salvage 2026-11-06: uncommitted work from scratch/darkwing-proxy-precheck-1961 (disk cleanup #824)
This commit is contained in:
1 parent
c91bd3787b
commit
4b5fd01499
16 files changed
+354
-60
No files matched your search
@@ -5857,3 +5857,23 @@ Fethry stopped under Mos mos-1630/Jason's T3 crash instruction. No production im
|
||||
2026-10-26 — Fethry Mos1961 P3/P2 actual join on09a847ed: metadata-first/one actual modelPreflight key through harness,private spawn,binding and stall;explicit provider-identity mapping preserves existing zai/anthropic;proxy strict route. TDD new RED→GREEN plus117/117 targeted wholefile checks,zero skips;original653/655 bodies/assertions/deadlines and runtime/process/modelkeys unchanged. Preserved nonproxy fixture-key RED and exact127 /usr wrapper→unmounted /opt ELF failure;minimal approved fake-key prerequisite/proper executable pin,focused andwholefile recheck. No P5 overlap,#662,fullgate,push or live-provider claim. Full evidence agents/fethry/work/queue-332/join1961/.
|
||||
|
||||
2026-10-26T23:10:42.967773+00:00 — Sage corrective journal integration: P3 carry ee1f926ce accidentally committed unresolved journal markers after an append-only resolver failed and the shell continued staging. Removed only marker lines; restored exact prior parent journal prefixes and appended every incoming Fethry block byte-for-byte instead of inserting historical entries. No history rewrite or product change; source trees unchanged. Corrected before any candidate freeze/full gate. P5 independent R1 CHANGES preserved and sent for actual RED-first fixes; no approval or landing claimed.
|
||||
|
||||
|
||||
### 2026-10-26 — Mos1961 proxy precheck source repair: before (Darkwing)
|
||||
|
||||
Base09a847ed in isolated darkwing/proxy-precheck-1961. F8 requires legacy claude-session.env; precheck invokes Claude directly. P2 modelPreflight is bus-private; no preboot replacement-prompt probe interface found. Authorized new localfake TDD only, no full gate/host/provider turn/push/queue. Preserve nonproxy checks, marker AND2000-token ceiling, uid boundaries and supervisor budgets. Plan: agents/darkwing/work/proxy-precheck-1961/PLAN.md. Parent owns final independent review and combined integration.
|
||||
|
||||
### 2026-10-26T22:52:59Z — Mos1961 proxy precheck negative/source controls: after (Darkwing)
|
||||
|
||||
New isolated controls observed RED5/GREEN11 (six controls already passed on base). Corrected initial scratch-fixture project/launch validation before recording RED. Raw final11/11: agents/darkwing/work/proxy-precheck-1961/green-11.log; two selected original acceptance tests pass in legacy-f8.log. Original tests, marker arithmetic and both supervisor blocks byte-identical (preserved-invariants.json). F8 and precheck now explicitly refuse proxy-managed-probe-required instead of treating legacy credentials/direct probe as proxy evidence; this is NOT acceptance or a host fix. Factory input proposes providerproxy/routeanthropic/accountcredentialproxy, awaiting332 validator join and explicit reconciliation of old template expectation. PROBE-PROPOSAL.md is one unimplemented Mos-selection request for human-gated/private managed probe+caller order; source pins include16 unchanged files. No full gate, host/provider/secret reads, live turn, push, queue, cross-owner source edit or commit. Parent independent review/combinedgreen remain required.
|
||||
|
||||
2026-10-26T22:53:51Z — Mos1961 validation addendum (Darkwing): one selected original row323 loader test was run locally and is RED at unsupported launch.models.claude-opus-5-5 key "route" (base-validator-join.log). The explicit332 validator dependency is now reproduced; no schema/old-assertion edit or commit follows this failure. New source controls remain11/11, selected legacy acceptance2/2; no fullgate or standalone-green business claim.
|
||||
|
||||
|
||||
### 2026-10-26T23:01:33Z — Mos1966 selected managed acceptance probe: before (Darkwing)
|
||||
|
||||
Exactproposal63cb9caf/5624selected; Codexgpt6.1/high verified before code. Independentauth/probe modules+TDD first; actualhumanproof, P2launch/bind/nativecleanup required. Shared332 and P5runtime joins remain ownership-coordinated; no fullgate outside1014, liveaction, secrets, push, queue or delegation. Plan agents/darkwing/work/proxy-probe-1966/PLAN.md.
|
||||
|
||||
2026-10-26T23:29:09.044152+00:00 — Mos1971 validation correction (Darkwing): all pre-1971 local nice19 logs remain raw functional observations only; actual own driver/direct-child priorities were not independently sampled, so strict19 acceptance is UNVERIFIED. New runtime validation is STOPPED for admitted1014; no scheduler edit, local correction, strict19 relaxation or rerun. Source/regression authoring continues. Native pre-1971 localfake proof and human-proof refusal do not establish live human/provider acceptance.
|
||||
|
||||
2026-10-26T23:40:13.419108+00:00 — Mos1966/1971 Case1 source candidate handoff (Darkwing): parent c91bd3787b0c670f5ffcac3197b062078f740e1b joined, original changes/history preserved. Human-only acceptance.authorize/private one-use consume, fixed P2/native launch/marker/actual summed usage/own cleanup, typed host evidence and bounded dropped-uid consumers authored. Original exact nonproxy model assertion retained on compatibility input; no weakened marker/ceiling/deadline or shared case2-unit change. Static source comparisons13/13 byte-identical for protected blocks/files, not runtime acceptance.19 source mutant patches prepared without execution. New consumers and native-negative/actual180s controls UNRUN after1971; earlier logs functional-only, strict19 and current-byte acceptance UNVERIFIED. P5 createUsage/createLimits/tick/close unchanged. Review/runner packet agents/darkwing/work/proxy-probe-1966/REVIEW.md. Admitted1014,334 same-active-unit human caller/200-210 envelope and parent independent Codex review remain. No host/provider/fullgate, scheduler correction/retry, commit/push/queue.
|
||||
@@ -1920,3 +1920,9 @@ are never rewritten or removed; corrections are new entries.
|
||||
2026-10-26 | fethry (65673bd9-3bfa-412b-85d5-9b364187d8b6) | Mos1961 completed targeted P3/P2 join |117pass/0fail/0skip across11wholefiles incl6535/0,65518/0,launcher35/0;newsamekey/privateenv/nativeprovider+explicitroute controls7/0;REDs preserved,fixture-only fake-key/nativebinary prerequisite fixes,no runtime/P5 changes;local commit/no push,owned cleanup0,serial SLOTBACK for227;parent owns integration/review/fullgate.
|
||||
|
||||
2026-10-26T23:10:42.967773+00:00 | Sage | Mos1961 local P3 carry journal correction and P5 R1 repair delegation | Removed accidentally committed merge markers, exact prior parent prefix and all peer blocks retained; product unchanged, no gate/push/landing.
|
||||
|
||||
2026-10-26T22:52:59Z | darkwing | Mos1961 isolated proxy-precheck source controls and bounded probe proposal | branch darkwing/proxy-precheck-1961 at09a847ed; new localfake11/11green, selected original acceptance2/2green, source invariants unchanged. No actual proxy acceptance; one human-gated host-private probe proposal for Mos selection. Factory input depends332; sharedcase2-unit.test untouched. No fullgate/host/provider/secret work, push/queue/commit/delegation.
|
||||
|
||||
2026-10-26T22:53:51Z | darkwing | Mos1961 base schema dependency receipt | One selected original row323 loader test RED on unsupported proxy route key at09a847ed; deferred to332 owner/combined parent gate, no cross-owner edit or commit. Raw11/11 controls and2/2 selected legacy acceptance remain separately recorded.
|
||||
|
||||
2026-10-26T23:40:13.419108+00:00 | Darkwing (Codex) | Mos1966 Case1 native source/control integration on c91; Mos1971 hold | source candidate +19 prepared mutant patches; no runtime rerun or commit; acceptance UNVERIFIED; admitted1014/334 caller join/independent review pending.
|
||||
@@ -38,10 +38,15 @@
|
||||
"launch": {
|
||||
"by": "chief",
|
||||
"instances": ["assistant"],
|
||||
"account": {
|
||||
"name": "factory",
|
||||
"credential": "proxy"
|
||||
},
|
||||
"models": {
|
||||
"claude-opus-5-5": {
|
||||
"provider": "anthropic",
|
||||
"model": "claude-opus-5-5"
|
||||
"provider": "proxy",
|
||||
"model": "claude-opus-5-5",
|
||||
"route": "anthropic"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -422,6 +422,7 @@ export class Broker {
|
||||
#credentialVerbs;
|
||||
#proxyInit;
|
||||
#proxyPage;
|
||||
#acceptanceAuthorize;
|
||||
#project;
|
||||
#library;
|
||||
// C2-06 (design 5.2, B7): cap -> the session's kept web.fetch pages, in a library business only.
|
||||
@@ -480,7 +481,7 @@ export class Broker {
|
||||
#clock = 0;
|
||||
#processing;
|
||||
// credentialStatus is the runtime's metadata-only Credentials.status(); the broker never gets use().
|
||||
constructor({ store, businesses, secretCheck = () => {}, credentialStatus = () => [], organization = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyPage = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, giteaKeys = null, access = null, accessStamp = null, compactions = null }) {
|
||||
constructor({ store, businesses, secretCheck = () => {}, credentialStatus = () => [], organization = null, project = null, library = null, usage = null, limits = null, harnessOn = null, credentialVerbs = null, proxyInit = null, proxyPage = null, acceptanceAuthorize = null, hostGrant = null, hostKeys = null, processing = null, testerOn = null, grantScope = null, roleFile = null, giteaGrant = null, giteaKeys = null, access = null, accessStamp = null, compactions = null }) {
|
||||
if (!object(businesses) || !Object.keys(businesses).length) fail('invalid-business');
|
||||
// Row 194 b15 (sage-2501): the function-argument checks come before anything reads the store.
|
||||
if (harnessOn !== null && typeof harnessOn !== 'function') throw new TypeError('harnessOn must be a function');
|
||||
@@ -490,6 +491,7 @@ export class Broker {
|
||||
if (access !== null && typeof access !== 'function') throw new TypeError('access must be a function');
|
||||
if (accessStamp !== null && typeof accessStamp !== 'function') throw new TypeError('accessStamp must be a function');
|
||||
if (compactions !== null && typeof compactions !== 'function') throw new TypeError('compactions must be a function');
|
||||
if (acceptanceAuthorize !== null && typeof acceptanceAuthorize !== 'function') throw new TypeError('acceptanceAuthorize must be a function');
|
||||
this.#businesses = structuredClone(businesses);
|
||||
this.#store = store;
|
||||
// A Broker is a trusted host startup, including in-process hosts. Never repair an existing state as off.
|
||||
@@ -506,6 +508,7 @@ export class Broker {
|
||||
this.#credentialVerbs = credentialVerbs;
|
||||
this.#proxyInit = proxyInit;
|
||||
this.#proxyPage = proxyPage;
|
||||
this.#acceptanceAuthorize = acceptanceAuthorize;
|
||||
this.#hostGrant = hostGrant;
|
||||
this.#hostKeys = hostKeys;
|
||||
this.#giteaGrant = giteaGrant;
|
||||
@@ -4818,6 +4821,27 @@ export class Broker {
|
||||
try {
|
||||
keys(request, ['verb', 'args'], ['verb']);
|
||||
string(request.verb, 64);
|
||||
// Mos1966: the only public probe operation is human authorization.
|
||||
// Runtime authenticated this CLI principal through verifyPrincipal;
|
||||
// no tester/agent/Console or supplied readiness flag can mint a ticket.
|
||||
if (request.verb === 'acceptance.authorize') {
|
||||
this.#human(s);
|
||||
if (s.human !== this.#business(s.business).human) fail('human-required');
|
||||
if (!this.#acceptanceAuthorize) fail('not-configured');
|
||||
const args = request.args ?? {};
|
||||
keys(args, ['challenge'], ['challenge']);
|
||||
if (typeof args.challenge !== 'string' || !/^[a-f0-9]{64}$/.test(args.challenge)) fail('invalid-request');
|
||||
return Promise.resolve().then(() => this.#acceptanceAuthorize(args, { business: s.business, human: s.human })).then(result => {
|
||||
keys(result, ['authorization'], ['authorization']);
|
||||
if (typeof result.authorization !== 'string' || !/^[a-f0-9]{64}$/.test(result.authorization)) fail('acceptance-authorization-refused');
|
||||
this.#store.transaction(() => this.#event(s, 'action.allowed', { call: 'acceptance.authorize', probe: 'case1-claude-marker-v1' }, null));
|
||||
return result;
|
||||
}).catch(error => {
|
||||
const code = ['acceptance-authorization-refused', 'acceptance-probe-busy'].includes(error?.code)
|
||||
? error.code : 'acceptance-authorization-refused';
|
||||
throw this.#refused(s, new BusError(code), { verb: request.verb });
|
||||
});
|
||||
}
|
||||
// P4: this boundary precedes the generic user/tester gates so every
|
||||
// nonhuman caller gets human-required. Never secret-check, clone or trail
|
||||
// a write-only API key or a callback URL as request content.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// never command arguments, stdout or service-token-bearing environment variables.
|
||||
import { startBroker } from './runtime.mjs';
|
||||
import { BusError } from './broker.mjs';
|
||||
import { startTimeOf } from '../../seat/src/proc.mjs';
|
||||
const LAUNCH_OPS = new Set([
|
||||
'identity',
|
||||
'authorizeLaunch',
|
||||
@@ -10,6 +11,9 @@ const LAUNCH_OPS = new Set([
|
||||
'recoverLaunch',
|
||||
'credentialStatus',
|
||||
'modelPreflight',
|
||||
'acceptancePrepare',
|
||||
'acceptanceConsume',
|
||||
'acceptanceClose',
|
||||
'modelStall',
|
||||
'checkPush',
|
||||
'recordPush',
|
||||
@@ -81,6 +85,9 @@ function launchOp(m) {
|
||||
if (m.op === 'sessionClearStart') return runtime.sessionClearStart(m.record);
|
||||
if (m.op === 'credentialStatus') return runtime.credentialStatus(m.business, m.role);
|
||||
if (m.op === 'modelPreflight') return runtime.modelPreflight(m);
|
||||
if (m.op === 'acceptancePrepare') return runtime.prepareAcceptance(m.context);
|
||||
if (m.op === 'acceptanceConsume') return runtime.consumeAcceptance(m.context);
|
||||
if (m.op === 'acceptanceClose') { runtime.closeAcceptance(); return { closed: true }; }
|
||||
if (m.op === 'modelStall') return runtime.modelStall(m);
|
||||
// Every LAUNCH_OPS name has its line above. A missing one used to answer as credentialStatus,
|
||||
// whose [] for an unknown role read as "no holders" for landHolders (row 156 mutant P02).
|
||||
@@ -139,6 +146,8 @@ if (!process.send) {
|
||||
// Row 199: publishTls is the tests' scratch CA, for an in-process runtime only. The host's boot
|
||||
// config never carries it, so a boot that does is refused rather than trusted.
|
||||
const { trackers, ...config } = message.config ?? {};
|
||||
if (config.acceptanceHost && (config.acceptanceHost.pid !== process.ppid
|
||||
|| config.acceptanceHost.startTime !== startTimeOf(process.ppid))) throw new BusError('invalid-host-request');
|
||||
if (Object.hasOwn(config, 'publishTls')) throw new BusError('invalid-host-request');
|
||||
if (trackers) {
|
||||
const { tasksAdapter } = await import('../../tasks/src/adapter.mjs');
|
||||
|
||||
@@ -5,6 +5,7 @@ import { Store } from './store.mjs';
|
||||
import * as projectModule from '../../project/src/index.mjs';
|
||||
import * as libraryModule from '../../library/src/index.mjs';
|
||||
import { Broker, BusError, LIBRARY_FETCH_FIX } from './broker.mjs';
|
||||
import { AcceptanceAuthority } from './acceptance-authority.mjs';
|
||||
import { Credentials } from './credentials.mjs';
|
||||
import { serve } from './server.mjs';
|
||||
import { launchSettings } from '../../business/src/launch-settings.mjs';
|
||||
@@ -253,7 +254,17 @@ export async function startBroker({
|
||||
consoleOwners = [],
|
||||
// P1 validated sidecar from the trusted host; never a socket request setting.
|
||||
proxy = null,
|
||||
// Mos1966: trusted host boot metadata only, never a socket setting.
|
||||
acceptanceHost = null,
|
||||
}) {
|
||||
let acceptance = null;
|
||||
if (acceptanceHost !== null) {
|
||||
if (!acceptanceHost || Object.keys(acceptanceHost).sort().join(',') !== 'business,copy,pid,startTime'
|
||||
|| !Object.hasOwn(businesses, acceptanceHost.business)) throw new BusError('invalid-host-request');
|
||||
const { business, ...host } = acceptanceHost;
|
||||
try { acceptance = new AcceptanceAuthority({ host, business, owner: businesses[business].human }); }
|
||||
catch { throw new BusError('invalid-host-request'); }
|
||||
}
|
||||
if (!Array.isArray(consoleOwners) || consoleOwners.length > 512 || consoleOwners.some((o) => o === null || typeof o !== 'object' || Array.isArray(o) ||
|
||||
Object.keys(o).length !== 3 || ['provider', 'iss', 'sub'].some((k) => typeof o[k] !== 'string' || !o[k] || o[k].length > 512)))
|
||||
throw new BusError('invalid-host-request');
|
||||
@@ -469,6 +480,7 @@ export async function startBroker({
|
||||
}
|
||||
}
|
||||
broker = new Broker({
|
||||
acceptanceAuthorize: acceptance ? (args, principal) => acceptance.authorize(args, principal) : null,
|
||||
// FED R3: the access file is read per user request; a refusal leaves the user no grant.
|
||||
access: access ? () => loadAccess(access.file, access.context) : null,
|
||||
// FED R4 (#1801, design 3.7 trigger 1): a request stats the file and reads it only when this
|
||||
@@ -858,6 +870,15 @@ export async function startBroker({
|
||||
credentials,
|
||||
// P2 consumes this inside the bus only. No process IPC/verb returns it.
|
||||
get modelProxy() { return modelProxyClient; },
|
||||
prepareAcceptance: context => {
|
||||
if (!acceptance) throw new BusError('acceptance-authorization-refused');
|
||||
return acceptance.prepare(context);
|
||||
},
|
||||
consumeAcceptance: context => {
|
||||
if (!acceptance) throw new BusError('acceptance-authorization-refused');
|
||||
return acceptance.consume(context);
|
||||
},
|
||||
closeAcceptance: () => acceptance?.close(),
|
||||
path,
|
||||
bindLaunch,
|
||||
recoverLaunch: ({ modelKeyId, ...record }) => broker.recoverLaunch(record),
|
||||
|
||||
@@ -73,7 +73,8 @@ test("row 323: committed Case 1 document loads unchanged through the business lo
|
||||
assert.equal(b.launch.by, "chief");
|
||||
assert.deepEqual(b.launch.instances, ["assistant"]);
|
||||
assert.deepEqual(b.arbiters, { delivery: "chief", technical: "chief" });
|
||||
assert.deepEqual(b.launch.models["claude-opus-5-5"], { provider: "anthropic", model: "claude-opus-5-5" });
|
||||
assert.deepEqual(b.launch.models["claude-opus-5-5"], { provider: "proxy", model: "claude-opus-5-5", route: "anthropic" });
|
||||
assert.deepEqual(b.launch.account, { name: "factory", credential: "proxy" });
|
||||
for (const role of Object.values(b.roles)) {
|
||||
assert.equal(role.vars.harness, "claude-code");
|
||||
assert.equal(role.vars.model, "claude-opus-5-5");
|
||||
@@ -83,6 +84,18 @@ test("row 323: committed Case 1 document loads unchanged through the business lo
|
||||
}
|
||||
});
|
||||
|
||||
// Mos1966 changes the shipped factory route. Preserve the original exact
|
||||
// nonproxy loader assertion on an explicit direct-provider input as well.
|
||||
test("row 323: original direct Anthropic input remains valid with its original exact model assertion", (t) => {
|
||||
const x = world(t);
|
||||
x.doc.launch.models["claude-opus-5-5"] = { provider: "anthropic", model: "claude-opus-5-5" };
|
||||
delete x.doc.launch.account;
|
||||
writeJson(x.business, x.doc);
|
||||
const b = loadBusiness("mosaic-stack", { dir: x.configDir, rolesDir: REPO_ROLES });
|
||||
assert.deepEqual(b.launch.models["claude-opus-5-5"], { provider: "anthropic", model: "claude-opus-5-5" });
|
||||
assert.equal(b.launch.account, undefined);
|
||||
});
|
||||
|
||||
test("row 323: real business validate accepts the Case 1 fixture without tracker credentials", (t) => {
|
||||
const x = world(t);
|
||||
configure(x);
|
||||
|
||||
@@ -34,6 +34,7 @@ import { busExit, humanTransport, refuseInsideAgent, testerTransport } from "./t
|
||||
import { formatAgents, formatDecision, formatInbox, formatTasks, formatTrail, shortId } from "./format.mjs";
|
||||
import { hostStatus, readHostState, startHost, stopHost } from "./host.mjs";
|
||||
import { createLauncher } from "./launcher.mjs";
|
||||
import { pinnedAcceptanceCopy, writeAcceptanceRecord } from './acceptance-record.mjs';
|
||||
import { quitLine, runApp } from "./app.mjs";
|
||||
import { readSessions, stopSession } from "../../seat/src/session.mjs";
|
||||
import { SeatError } from "../../seat/src/seat.mjs";
|
||||
@@ -546,13 +547,27 @@ async function launches(rest, io, deps) {
|
||||
async function bus(rest, io, deps) {
|
||||
const [sub, ...args] = rest;
|
||||
if (sub === "start") {
|
||||
const parsed = parse(args, { flags: ["--pm", "--no-launch"] });
|
||||
const parsed = parse(args, { flags: ["--pm", "--no-launch", "--acceptance-probe"] });
|
||||
const acceptanceProbe = parsed.flags.has('--acceptance-probe');
|
||||
if (acceptanceProbe) refuseInsideAgent(io.env);
|
||||
if (acceptanceProbe && (!io.stdin.isTTY || !io.stdout.isTTY))
|
||||
throw new CliError('acceptance-human-terminal-required', 3);
|
||||
if (parsed.positional.length !== 1) throw usage("bus start takes one business");
|
||||
// Row 163: --no-launch is the D2 rehearsal's host. No unit passes it.
|
||||
const launches = !parsed.flags.has("--no-launch");
|
||||
if (acceptanceProbe && !launches) throw new CliError('acceptance-context-invalid', 3);
|
||||
if (!launches && parsed.flags.has("--pm")) throw usage("bus start takes --pm or --no-launch, not both");
|
||||
const businessId = parsed.positional[0];
|
||||
const system = deps.system ?? loadSystem({ env: io.env });
|
||||
let acceptanceCopy = null;
|
||||
if (acceptanceProbe) {
|
||||
if (!system.proxy) throw new CliError('acceptance-proxy-required', 3);
|
||||
try { acceptanceCopy = pinnedAcceptanceCopy(fileURLToPath(new URL('../../../', import.meta.url)).replace(/\/$/, '')); }
|
||||
catch { throw new CliError('acceptance-copy-required', 3); }
|
||||
const previous = readSessions(system.dataRoot).filter(s => s.business === businessId);
|
||||
if (previous.some(s => s.instance === 'chief' && s.live)) throw new CliError('instance-running', 3);
|
||||
if (previous.length) throw new CliError('acceptance-runs-live', 3);
|
||||
}
|
||||
// Fail closed, and say so (vikunja:19/302): a refused load is recorded where the Console and
|
||||
// `bus status` can read it, then thrown as before. No retry.
|
||||
const file = businessFilePath(businessId, configDir(io.env));
|
||||
@@ -565,11 +580,17 @@ async function bus(rest, io, deps) {
|
||||
}
|
||||
try { recordBootOk(system.dataRoot, { business: businessId, file }); } catch { /* status is advisory */ }
|
||||
const binding = readNotifyConfig(system.dataRoot, businessId);
|
||||
const host = await startHost({ boot, business: businessId, notifier: binding ? { binding } : null });
|
||||
const host = await startHost({ boot, business: businessId, notifier: binding ? { binding } : null, acceptanceCopy });
|
||||
try {
|
||||
const launcher = createLauncher({ host, system, env: io.env, tracker: Boolean(boot.trackers?.[businessId]), launches, ...(deps.launcher ?? {}) });
|
||||
const launcher = createLauncher({ host, system, env: io.env, tracker: Boolean(boot.trackers?.[businessId]), launches, acceptanceWindow: acceptanceProbe, ...(deps.launcher ?? {}) });
|
||||
await launcher.listen();
|
||||
io.stdout.write(`bus host up: business ${businessId}, socket ${host.path}, notifier ${binding ?? "off"}${launches ? "" : ", launches disabled"}\n`);
|
||||
if (acceptanceProbe) {
|
||||
const call = humanTransport({ socket: host.path, business: businessId, env: io.env });
|
||||
const result = await launcher.probeFactory(args => call('acceptance.authorize', args));
|
||||
writeAcceptanceRecord(system.dataRoot, result);
|
||||
io.stdout.write(JSON.stringify(result) + '\n');
|
||||
}
|
||||
if (parsed.flags.has("--pm")) {
|
||||
try {
|
||||
const pm = await launcher.launchPm();
|
||||
@@ -581,6 +602,11 @@ async function bus(rest, io, deps) {
|
||||
}
|
||||
} catch (e) {
|
||||
await host.close(1);
|
||||
if (acceptanceProbe) {
|
||||
const code = /^acceptance-[a-z-]+$/.test(e?.code ?? '') || ['human-required', 'instance-running'].includes(e?.code)
|
||||
? e.code : 'acceptance-probe-failed';
|
||||
throw new CliError(code, 3);
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
const stop = () => host.close(0);
|
||||
|
||||
@@ -168,8 +168,11 @@ export function watchChildren(children, onDeath) {
|
||||
// {binding, base?, pollMs?}; base and pollMs exist for the tests, and the
|
||||
// command line never sets them, nor requestTimeoutMs. Resolves once both
|
||||
// children are up.
|
||||
export async function startHost({ boot, business, notifier = null, bootTimeoutMs = BOOT_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS, log = (l) => process.stderr.write(`mosaic-bus: ${l}\n`) }) {
|
||||
export async function startHost({ boot, business, notifier = null, acceptanceCopy = null, bootTimeoutMs = BOOT_TIMEOUT_MS, requestTimeoutMs = REQUEST_TIMEOUT_MS, log = (l) => process.stderr.write(`mosaic-bus: ${l}\n`) }) {
|
||||
const dataRoot = boot.dataRoot;
|
||||
if (acceptanceCopy !== null && (typeof acceptanceCopy !== 'string' || !/^[a-f0-9]{40}$/.test(acceptanceCopy)))
|
||||
throw new CliError('acceptance-copy-required', 3);
|
||||
const acceptanceIdentity = acceptanceCopy === null ? null : { pid: process.pid, startTime: startTimeOf(process.pid), copy: acceptanceCopy };
|
||||
// A host started before host.lock existed holds only host.json.
|
||||
const prior = readHostState(dataRoot);
|
||||
if (prior?.live) throw new CliError(`a bus host already runs for ${prior.business} (pid ${prior.pid})`, 3);
|
||||
@@ -214,7 +217,7 @@ export async function startHost({ boot, business, notifier = null, bootTimeoutMs
|
||||
try {
|
||||
broker = fork(BROKER, [], { stdio: ["ignore", "inherit", "inherit", "ipc"] });
|
||||
broker.on("error", onChildError("broker"));
|
||||
broker.send({ op: "boot", config: boot });
|
||||
broker.send({ op: "boot", config: acceptanceIdentity ? { ...boot, acceptanceHost: { ...acceptanceIdentity, business } } : boot });
|
||||
ready = await firstReply(broker, bootTimeoutMs, "broker");
|
||||
} catch (e) {
|
||||
if (broker) {
|
||||
@@ -363,7 +366,8 @@ export async function startHost({ boot, business, notifier = null, bootTimeoutMs
|
||||
close(1);
|
||||
});
|
||||
|
||||
return Object.freeze({ path: ready.path, dataRoot, business, bindLaunch, op, beforeClose, close, done, pids: Object.freeze({ broker: broker.pid, notifier: notify?.pid ?? null }) });
|
||||
if (acceptanceIdentity) beforeClose(() => op({ op: 'acceptanceClose' }));
|
||||
return Object.freeze({ path: ready.path, dataRoot, business, acceptanceIdentity, bindLaunch, op, beforeClose, close, done, pids: Object.freeze({ broker: broker.pid, notifier: notify?.pid ?? null }) });
|
||||
}
|
||||
|
||||
// `mosaic bus stop`: SIGTERM to the recorded host, after checking that the
|
||||
|
||||
@@ -141,8 +141,9 @@
|
||||
import { createServer } from "node:net";
|
||||
import { createHash } from 'node:crypto';
|
||||
import { watchModelOutput } from './model-stall.mjs';
|
||||
import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { constants, closeSync, fstatSync, openSync, chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { configDir, loadBusiness, resolveInstance, systemVars } from "../../business/src/index.mjs";
|
||||
import { THREAD_DEFINITIONS } from "../../business/src/vocabulary.mjs";
|
||||
import { limitHit } from "../../business/src/launch.mjs";
|
||||
@@ -178,6 +179,7 @@ import { CliError } from "./errors.mjs";
|
||||
import { assertProcessing, processingStatus, ProcessingError } from "../../processing-control/src/state.mjs";
|
||||
import { registerRuntime, updateRuntime, runtime, unregisterRuntime, processIdentity, stopRun } from "../../processing-control/src/runtimes.mjs";
|
||||
import { withProcessing } from '../../processing-control/src/effects.mjs';
|
||||
import { createProbeContext, completeMeasuredProbe, PROBE_BUDGET } from './acceptance-probe.mjs';
|
||||
|
||||
const STOP_TIMEOUT_MS = 30000;
|
||||
const LINE_MAX = 4096;
|
||||
@@ -224,6 +226,7 @@ export function createLauncher({
|
||||
proxy = null,
|
||||
tracker = false,
|
||||
launches = true,
|
||||
acceptanceWindow = false,
|
||||
makeLoader = createLoader,
|
||||
bwrap = BWRAP,
|
||||
readOnly = [],
|
||||
@@ -265,6 +268,7 @@ export function createLauncher({
|
||||
const children = new Map();
|
||||
let chain = Promise.resolve();
|
||||
let closed = false;
|
||||
let probeAttempted = false, probePassed = false;
|
||||
let server = null;
|
||||
let ticker = null;
|
||||
let ticking = false;
|
||||
@@ -466,7 +470,7 @@ export function createLauncher({
|
||||
}
|
||||
|
||||
// Bundle, spawn, bind, register, hand over the capability.
|
||||
async function start({ instance, launchedBy, resolved, model, account = null, thread = null, session = null, legacy = false, legacyThread = legacy, human = false, admissionGeneration }) {
|
||||
async function start({ instance, launchedBy, resolved, model, account = null, thread = null, session = null, legacy = false, legacyThread = legacy, human = false, admissionGeneration, preparedProbe = null }) {
|
||||
admission(admissionGeneration);
|
||||
// Every launch path ends here, so a --no-launch host spawns nothing whichever path asked.
|
||||
if (!launches) throw new Refusal("launches-disabled", "this host was started with --no-launch");
|
||||
@@ -491,7 +495,10 @@ export function createLauncher({
|
||||
let workspace;
|
||||
let workspaceDest = null;
|
||||
let lock = null;
|
||||
if (thread) {
|
||||
if (preparedProbe) {
|
||||
workspace = join(preparedProbe.runDir, 'workspace');
|
||||
mkdirSync(workspace, { mode: 0o700 });
|
||||
} else if (thread) {
|
||||
try {
|
||||
const live = registry.sessions.filter((s) => s.business === b.id && s.workspace).map((s) => s.workspace);
|
||||
workspace = sessionWorkspace(dataRoot, b.id, instance, session, { live });
|
||||
@@ -506,7 +513,7 @@ export function createLauncher({
|
||||
mkdirSync(workspace, { recursive: true, mode: 0o700 });
|
||||
}
|
||||
try {
|
||||
return await startLocked({ instance, launchedBy, resolved, model, account, thread, session, human, admissionGeneration, store, credentials, workspace, workspaceDest, lock });
|
||||
return await startLocked({ instance, launchedBy, resolved, model, account, thread, session, human, admissionGeneration, store, credentials, workspace, workspaceDest, lock, preparedProbe });
|
||||
} catch (e) {
|
||||
// Every failure path in startLocked has proven the run's exit, or never spawned one.
|
||||
lock?.release();
|
||||
@@ -516,12 +523,12 @@ export function createLauncher({
|
||||
|
||||
// The rest of start(): clones, bundle, spawn, bind, register. The lock, when there is one, is
|
||||
// released at the run's close.
|
||||
async function startLocked({ instance, launchedBy, resolved, model, account, thread, session, human, admissionGeneration, store, credentials, workspace, workspaceDest, lock }) {
|
||||
async function startLocked({ instance, launchedBy, resolved, model, account, thread, session, human, admissionGeneration, store, credentials, workspace, workspaceDest, lock, preparedProbe }) {
|
||||
// What the session sees: a legacy session's workspace at the old instance path.
|
||||
const inSandbox = workspaceDest ?? workspace;
|
||||
let checkouts;
|
||||
try {
|
||||
checkouts = await withProcessing(dataRoot, () => {
|
||||
checkouts = preparedProbe ? [] : await withProcessing(dataRoot, () => {
|
||||
admission(admissionGeneration);
|
||||
return ensureCheckouts({ workspace, projects: Object.fromEntries(Object.entries(b.projects).filter(([, entry]) => entry.kind !== 'library')), env });
|
||||
});
|
||||
@@ -544,7 +551,7 @@ export function createLauncher({
|
||||
let harness, route, routeReason, sessionProxy;
|
||||
({resolved,model,account,harness,route,routeReason,sessionProxy}=await check(instance,{pm:instance===b.launch.by,thread,session,human,proxyContext:admittedProxy,proxyReady:true}));
|
||||
admission(admissionGeneration);
|
||||
const { run, runDir } = newRun(dataRoot, b.id);
|
||||
const { run, runDir } = preparedProbe ?? newRun(dataRoot, b.id);
|
||||
let modelKeyId;
|
||||
if (admittedProxy) {
|
||||
modelKeyId = createHash('sha256').update(sessionProxy.key).digest('hex').slice(0, 12);
|
||||
@@ -552,6 +559,8 @@ export function createLauncher({
|
||||
try { writeFileSync(join(runDir, 'proxy-first-turn-enabled'), 'enabled\n', { flag: 'wx', mode: 0o600 }); }
|
||||
catch { throw new Refusal('launch-failed', 'first-turn protocol setup failed'); }
|
||||
}
|
||||
const acceptanceProbe = preparedProbe ? createProbeContext({ business: b.id, role: instance, run,
|
||||
...host.acceptanceIdentity, modelKeyId }) : null;
|
||||
const sessionDir = store ? store.session : join(runDir, "session");
|
||||
if (!store) mkdirSync(sessionDir, { mode: 0o700 });
|
||||
if (store) compactions(store, model.harness, harness, { instance, thread, session, run });
|
||||
@@ -571,6 +580,7 @@ export function createLauncher({
|
||||
resolved,
|
||||
models: b.launch.models,
|
||||
proxy: sessionProxy,
|
||||
acceptanceProbe,
|
||||
contract: readFileSync(resolved.contract, "utf8"),
|
||||
arbiter: Object.values(b.arbiters).includes(instance),
|
||||
tracker,
|
||||
@@ -586,14 +596,14 @@ export function createLauncher({
|
||||
personaDir: join(configDir(env), "personas"),
|
||||
});
|
||||
const { manifest, ...files } = bundle.files;
|
||||
const adapter = call(model.harness, "adapter", () => harness.adapter());
|
||||
const adapter = acceptanceProbe ? fileURLToPath(new URL('../../../adapters/claude/acceptance-probe.sh', import.meta.url)) : call(model.harness, "adapter", () => harness.adapter());
|
||||
const turnEnd = call(model.harness, "turnEnd", () => harness.turnEnd());
|
||||
const transcript = call(model.harness, "transcript", () => harness.transcript({ runDir, store }));
|
||||
const harnessMounts = call(model.harness, "mounts", () => harness.mounts({ env }));
|
||||
// Row 93: the git socket, for a role that pushes work or reviews it. Row 137: or lands it.
|
||||
// Row 199 (D11): or publishes it, once a reviewed commit routes git.push.remote within-role.
|
||||
const held = [...resolved.limits.authority.withinRole, ...resolved.limits.authority.crossRole];
|
||||
const git = land || ["git.push.working", "review.verdict", "git.push.remote"].some((a) => held.includes(a)) ? gitSocketPath(dataRoot) : null;
|
||||
const git = !acceptanceProbe && (land || ["git.push.working", "review.verdict", "git.push.remote"].some((a) => held.includes(a))) ? gitSocketPath(dataRoot) : null;
|
||||
// Secrets go only to spawn, never session.json. Keep this split at the
|
||||
// actual serialization boundary, even if a harness adds another key.
|
||||
const harnessEnv = {}, transientEnv = {};
|
||||
@@ -621,6 +631,7 @@ export function createLauncher({
|
||||
turnEnd,
|
||||
toolSocket,
|
||||
turnMarker,
|
||||
...(acceptanceProbe ? { acceptanceProbe, turnTimeout: PROBE_BUDGET.turnSeconds } : {}),
|
||||
...(holding?.length ? { landing: holding.map(({ decision, task_ref }) => ({ decision, task_ref })) } : {}),
|
||||
});
|
||||
|
||||
@@ -630,7 +641,7 @@ export function createLauncher({
|
||||
adapter,
|
||||
harnessMounts,
|
||||
brokerSocket: host.path,
|
||||
launchSocket: resolved.launch ? launchSocketPath(dataRoot) : null,
|
||||
launchSocket: !acceptanceProbe && resolved.launch ? launchSocketPath(dataRoot) : null,
|
||||
gitSocket: git,
|
||||
threadStore: store,
|
||||
readOnly,
|
||||
@@ -689,7 +700,8 @@ export function createLauncher({
|
||||
children.set(run, exited);
|
||||
const outputWatch = admittedProxy ? watchModelOutput({ runDir, armAtFirstTurn: true, keyId: modelKeyId, seconds: system.proxy.firstOutputSeconds ?? 120,
|
||||
stop: () => host.op({ op: 'modelStall', business: b.id, role: instance, run, keyId: modelKeyId }), receipt: record }) : null;
|
||||
exited.then(async ({ code, signal }) => {
|
||||
const cleanupDone = exited.then(async ({ code, signal }) => {
|
||||
let cleanupConfirmed = true;
|
||||
outputWatch?.cancel();
|
||||
let receipt;
|
||||
try { receipt = runtime(dataRoot, managed.id); }
|
||||
@@ -704,10 +716,11 @@ export function createLauncher({
|
||||
record({ event: "end", instance, ...(thread ? { thread, session } : {}), run, reason, exitCode: code, signal, ...(haltGeneration ? { haltGeneration } : {}), ...(ended?.limit ? { limit: ended.limit } : {}) });
|
||||
log(`run ${run} (${instance}) ended: ${reason}`);
|
||||
} catch (e) {
|
||||
log(`run ${run}: ${e.message}`);
|
||||
cleanupConfirmed = false;
|
||||
log(acceptanceProbe ? `run ${run}: acceptance-cleanup-unknown` : `run ${run}: ${e.message}`);
|
||||
} finally {
|
||||
try { unregisterRuntime(dataRoot, managed.id); }
|
||||
catch { log(`run ${run}: processing receipt cleanup refused`); }
|
||||
catch { cleanupConfirmed = false; log(`run ${run}: processing receipt cleanup refused`); }
|
||||
if (store) compactions(store, model.harness, harness, { instance, thread, session, run });
|
||||
try { lock?.release(); }
|
||||
catch (e) { log(`run ${run}: workspace lock release: ${e.message}`); }
|
||||
@@ -717,8 +730,36 @@ export function createLauncher({
|
||||
landingOf.delete(run);
|
||||
refusedRelease.delete(run);
|
||||
}
|
||||
if (acceptanceProbe) {
|
||||
const gone = (pid, time) => !existsSync(`/proc/${pid}`) || (startTimeOf(pid) !== null && startTimeOf(pid) !== time);
|
||||
cleanupConfirmed = cleanupConfirmed && !registry.running(b.id, instance)
|
||||
&& gone(entry.pid, entry.startTime) && gone(entry.runnerPid, entry.runnerStartTime);
|
||||
}
|
||||
return { code, signal, confirmed: cleanupConfirmed };
|
||||
});
|
||||
record({ event: "launch", instance, ...(thread ? { thread, session } : {}), run, launchedBy, harness: model.harness, route, routeReason, model: model.model, provider: model.provider, modelKey: model.modelKey, account, pid: child.pid, runnerPid: entry.runnerPid, manifest });
|
||||
if (acceptanceProbe) {
|
||||
let clock;
|
||||
try {
|
||||
const cleanup = await Promise.race([cleanupDone, new Promise((_, reject) => {
|
||||
clock = setTimeout(() => reject(new Refusal('acceptance-cleanup-unknown')), PROBE_BUDGET.innerSeconds * 1000);
|
||||
})]);
|
||||
if (cleanup.code !== 0 || cleanup.signal) throw new Refusal('acceptance-probe-failed');
|
||||
// Read the same non-symlink inode we validate, after this bound native
|
||||
// run has exited. A worker path cannot redirect the host's read.
|
||||
const fd = openSync(join(runDir, 'acceptance.measurement.json'), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
||||
try {
|
||||
const st = fstatSync(fd);
|
||||
if (!st.isFile() || st.uid !== process.getuid() || (st.mode & 0o777) !== 0o600 || st.size > 65536)
|
||||
throw new Refusal('acceptance-measurement-invalid');
|
||||
const bytes = Buffer.alloc(65537), count = readSync(fd, bytes, 0, bytes.length, 0);
|
||||
if (count !== st.size || count > 65536) throw new Refusal('acceptance-measurement-invalid');
|
||||
return completeMeasuredProbe(acceptanceProbe, JSON.parse(bytes.subarray(0, count).toString('utf8')), cleanup);
|
||||
} finally { closeSync(fd); }
|
||||
} catch (error) {
|
||||
throw new Refusal(/^acceptance-[a-z-]+$/.test(error?.code ?? '') ? error.code : 'acceptance-measurement-invalid');
|
||||
} finally { clearTimeout(clock); }
|
||||
}
|
||||
return { run, instance, harness: model.harness, model: model.model };
|
||||
}
|
||||
|
||||
@@ -726,7 +767,7 @@ export function createLauncher({
|
||||
// landing pass. A tick that is still running when the next is due skips it.
|
||||
// Row 194 (D6): while row 191's switch is on, only the lifecycle pass runs.
|
||||
async function tick() {
|
||||
if (ticking || closed) return;
|
||||
if (ticking || closed || (acceptanceWindow && !probePassed)) return;
|
||||
let halted = false;
|
||||
try { admission(); } catch { halted = true; }
|
||||
ticking = true;
|
||||
@@ -1208,6 +1249,7 @@ export function createLauncher({
|
||||
// `bus start --pm`: the business's launcher instance, launched by the human.
|
||||
function launchPm() {
|
||||
return serialize(async () => {
|
||||
if (acceptanceWindow && !probePassed) throw new Refusal('acceptance-probe-pending');
|
||||
if (!b.launch) throw new CliError(`business ${b.id} has no launch block, so --pm has nothing to launch`, 3);
|
||||
try {
|
||||
return await start({ instance: b.launch.by, launchedBy: b.human, ...(await check(b.launch.by, { pm: true })) });
|
||||
@@ -1221,6 +1263,27 @@ export function createLauncher({
|
||||
});
|
||||
}
|
||||
|
||||
function probeFactory(authorize) {
|
||||
return serialize(async () => {
|
||||
if (!acceptanceWindow || !host.acceptanceIdentity || probeAttempted) throw new Refusal('acceptance-window-required');
|
||||
if (registry.running(b.id, 'chief') || [...leftover, ...survivors].some(s => s.business === b.id && s.instance === 'chief' && liveRun(s)))
|
||||
throw new Refusal('instance-running');
|
||||
if (!launches || closed || !system.proxy || b.launch?.by !== 'chief' || typeof authorize !== 'function') throw new Refusal('acceptance-context-invalid');
|
||||
const checked = await check('chief', { pm: true });
|
||||
if (checked.model.harness !== 'claude-code' || checked.model.provider !== 'proxy' || checked.model.proxyRoute !== 'anthropic' || hasFallback(checked.resolved))
|
||||
throw new Refusal('acceptance-context-invalid');
|
||||
probeAttempted = true;
|
||||
const allocation = newRun(dataRoot, b.id), context = { business: b.id, role: 'chief', run: allocation.run };
|
||||
const challenge = await host.op({ op: 'acceptancePrepare', context });
|
||||
const ticket = await authorize({ challenge });
|
||||
if (!ticket || Object.keys(ticket).join(',') !== 'authorization' || !/^[a-f0-9]{64}$/.test(ticket.authorization)) throw new Refusal('acceptance-authorization-refused');
|
||||
await host.op({ op: 'acceptanceConsume', context: { ...context, ...host.acceptanceIdentity, authorization: ticket.authorization } });
|
||||
const result = await start({ instance: 'chief', launchedBy: b.human, ...checked, preparedProbe: allocation });
|
||||
probePassed = true;
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
// The earlier host's sessions. Their capabilities died with its broker, so
|
||||
// one that still runs can do nothing: kill it (the namespace takes its
|
||||
// turn with it). Then end each run in the bus, which releases its role.
|
||||
@@ -1352,5 +1415,5 @@ export function createLauncher({
|
||||
}
|
||||
|
||||
host.beforeClose(close);
|
||||
return { business: b, registry, listen, launchPm, fromSession, tick, close };
|
||||
return { business: b, registry, listen, launchPm, probeFactory, fromSession, tick, close };
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import fs from 'node:fs';
|
||||
import http from 'node:http';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { fixture, fakeHarnesses } from './helpers.mjs';
|
||||
@@ -11,11 +11,13 @@ import { loadSystem, bootConfig } from '../src/config.mjs';
|
||||
import { createLauncher } from '../src/launcher.mjs';
|
||||
import { startBroker } from '../../bus/src/runtime.mjs';
|
||||
import { gitEnv } from '../../seat/src/checkout.mjs';
|
||||
import { startTimeOf } from '../../seat/src/proc.mjs';
|
||||
import { HUMAN_CLI } from '../src/transport.mjs';
|
||||
import { readSessions, runsDir, sessionsFile, SESSIONS_VERSION, launchLogFile } from '../../seat/src/session.mjs';
|
||||
export const waitFor = async (read, message, ms=15000) => { const end=Date.now()+ms;while(Date.now()<end){const value=await read();if(value)return value;await new Promise(r=>setTimeout(r,20));}throw Error(message); };
|
||||
export const pause = ms => new Promise(r=>setTimeout(r,ms));
|
||||
const id = value => createHash('sha256').update(value).digest('hex').slice(0,12);
|
||||
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false,harness='pi'}={}){
|
||||
export async function managedLaunchFixture(t,{proxy=true,launches=true,refuseProbe=false,harness='pi',acceptance=false,acceptanceCleanupRefused=false,acceptanceReply='valid'}={}){
|
||||
const root=fs.mkdtempSync(join(tmpdir(),'ml653-')),closers=[],history=new Set(['fx653-manage']),proxyReceipts=[],logs=[];
|
||||
let server,bus,launcher,stderr;const trace={preflightAttempts:0,successfulPreflights:0,enableBeforeSpawn:[],bindings:[],stalls:[]};
|
||||
const checkHistory=entries=>{const text=JSON.stringify(entries);for(const value of history)if(text.includes(value))throw Error('fixture credential leaked');};
|
||||
@@ -42,19 +44,30 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
|
||||
const git=(...args)=>{const result=spawnSync('git',['-c','user.name=test','-c','[email protected]','-C',f.doc.projects.stack.root,...args],{env:gitEnv(env),encoding:'utf8'});assert.equal(result.status,0,'owned local git fixture succeeds');};
|
||||
git('init','-q','-b','main');fs.writeFileSync(join(f.doc.projects.stack.root,'file.txt'),'one\n');git('add','file.txt');git('commit','-q','-m','one');
|
||||
const adapter=join(root,'adapter.sh');fs.writeFileSync(adapter,'case "$MOSAIC_REQUEST" in *SILENT*) exec /usr/bin/sleep 30;; *) printf %s fx653-private-output; printf "done\\n" > "$MOSAIC_TURN_MARKER";; esac\n',{mode:0o644});
|
||||
const system={...loadSystem({env}),...(proxy?{proxy:{port,binary:'/fixture-unused',firstOutputSeconds:1}}:{})};
|
||||
if(acceptance){
|
||||
env.MOSAIC_CLAUDE_BIN=join(root,'fixture-claude');
|
||||
assert.ok(['valid','marker','missing-usage','over-ceiling','hang'].includes(acceptanceReply));
|
||||
fs.writeFileSync(env.MOSAIC_CLAUDE_BIN,`#!${process.execPath}\nimport fs from 'node:fs';const a=process.argv.slice(2);if(a.includes('--version'))console.log('fixture Claude');else{const mode=${JSON.stringify(acceptanceReply)};const p=fs.readFileSync(a[a.indexOf('--system-prompt-file')+1],'utf8');const marker=p.trim().split(' ').at(-1);if(mode==='hang'){process.stdout.write(' ');setInterval(()=>{},1000);}else{const reply={result:mode==='marker'?'wrong':marker};if(mode!=='missing-usage')reply.usage={input_tokens:40,cache_creation_input_tokens:mode==='over-ceiling'?1000:0,cache_read_input_tokens:mode==='over-ceiling'?1000:0};process.stdout.write(JSON.stringify(reply));}}\n`,{mode:0o700});
|
||||
const path=join(root,'config/businesses/acme.json'),doc=JSON.parse(fs.readFileSync(path,'utf8'));doc.launch.models['claude-opus-5-5']={provider:'proxy',model:'claude-opus-5-5',route:'anthropic'};doc.launch.account={name:'factory',credential:'proxy'};fs.writeFileSync(path,JSON.stringify(doc));
|
||||
}
|
||||
const system={...loadSystem({env}),...(proxy?{proxy:{port,binary:'/fixture-unused',firstOutputSeconds:acceptance?120:1}}:{})};
|
||||
const {trackers,...boot}=bootConfig({system,businessId:'acme',env});assert.equal(trackers,undefined);
|
||||
stderr=process.stderr.write;process.stderr.write=function(chunk,...args){if(String(chunk).startsWith('model-proxy: ')){proxyReceipts.push(String(chunk));const callback=args.find(a=>typeof a==='function');callback?.();return true;}return stderr.call(this,chunk,...args);};
|
||||
bus=await startBroker(boot);closers.push(()=>bus.close());
|
||||
const acceptanceIdentity=acceptance?{pid:process.pid,startTime:startTimeOf(process.pid),copy:'a'.repeat(40)}:null;
|
||||
bus=await startBroker({...boot,...(acceptanceIdentity?{acceptanceHost:{...acceptanceIdentity,business:'acme'}}:{})});closers.push(()=>bus.close());
|
||||
const hooks=[];let expectedKeyId;
|
||||
const actualOp=async m=>{
|
||||
switch(m.op){
|
||||
case 'acceptancePrepare':return bus.prepareAcceptance(m.context);
|
||||
case 'acceptanceConsume':return bus.consumeAcceptance(m.context);
|
||||
case 'modelPreflight':return bus.modelPreflight(m);
|
||||
case 'modelStall':return bus.modelStall(m);
|
||||
case 'identity':return bus.identity(m.cap);
|
||||
case 'authorizeLaunch':return bus.authorizeLaunch(m.cap,m.instance);
|
||||
case 'refuse':return bus.refuse(m.cap,m.code,m.subject);
|
||||
case 'endLaunch':return bus.endLaunch(m.record);
|
||||
case 'endLaunch':
|
||||
if(acceptance&&acceptanceCleanupRefused)throw Object.assign(Error('owned-cleanup-refusal'),{code:'owned-cleanup-refusal'});
|
||||
return bus.endLaunch(m.record);
|
||||
case 'recoverLaunch':return bus.recoverLaunch(m.record);
|
||||
case 'credentialStatus':return bus.credentialStatus(m.business,m.role);
|
||||
case 'mayLaunch':return bus.mayLaunch(m);
|
||||
@@ -68,10 +81,10 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
|
||||
default:throw Error('fixture unrequested trusted operation');
|
||||
}
|
||||
};
|
||||
const host={business:'acme',path:bus.path,dataRoot:f.dataRoot,beforeClose:fn=>hooks.push(fn),
|
||||
const host={acceptanceIdentity,business:'acme',path:bus.path,dataRoot:f.dataRoot,beforeClose:fn=>hooks.push(fn),
|
||||
op:async m=>{
|
||||
if(m.op==='modelPreflight'){trace.preflightAttempts++;const value=await actualOp(m);if(value){trace.successfulPreflights++;expectedKeyId=id(value.key);}return value;}
|
||||
if(m.op==='landHolders'&&trace.successfulPreflights){
|
||||
if(m.op==='landHolders'&&trace.successfulPreflights&&!acceptance){
|
||||
// Existing trusted host call occurs after enable publication and BEFORE bundle,
|
||||
// registerRuntime/spawnSession/bind in the production startLocked sequence.
|
||||
const dirs=fs.readdirSync(runsDir(f.dataRoot,'acme'));assert.equal(dirs.length,1);const file=join(runsDir(f.dataRoot,'acme'),dirs[0],'proxy-first-turn-enabled');
|
||||
@@ -81,15 +94,23 @@ export async function managedLaunchFixture(t,{proxy=true,launches=true,refusePro
|
||||
return actualOp(m);
|
||||
},
|
||||
bindLaunch:async record=>{const result=bus.bindLaunch(record);trace.bindings.push({run:record.run,pid:record.pid,startTime:record.startTime,modelKeyId:record.modelKeyId});return result;}};
|
||||
const makeLoader=await fakeHarnesses({after:close=>closers.push(close)},{[harness]:adapter});
|
||||
launcher=createLauncher({host,system,env,launches,makeLoader,sessionDefaults:{pollInterval:50},harnessVersion:'0.85.1',log:line=>logs.push(line)});
|
||||
const makeLoader=acceptance?undefined:await fakeHarnesses({after:close=>closers.push(close)},{[harness]:adapter});
|
||||
launcher=createLauncher({host,system,env,launches,acceptanceWindow:acceptance,makeLoader,sessionDefaults:{pollInterval:50},harnessVersion:'0.85.1',log:line=>logs.push(line)});
|
||||
// The existing trusted host hook owns all launcher-created children. No registry
|
||||
// PID is signalled by fixture teardown; normal bounded launcher close is used.
|
||||
closers.push(async()=>{for(const close of hooks)await close(0);});await launcher.listen();
|
||||
const human=bus.broker.bindHuman({business:'acme',human:'jason',via:'cli',outsideAgent:true});
|
||||
const launchLog=()=>fs.existsSync(launchLogFile(f.dataRoot,'acme'))?fs.readFileSync(launchLogFile(f.dataRoot,'acme'),'utf8').trim().split('\n').filter(Boolean).map(l=>JSON.parse(l)):[];
|
||||
const valueFree=()=>checkHistory({logs,proxyReceipts,launch:launchLog(),trace});
|
||||
return {root,f,state,trace,proxyReceipts,logs,launcher,bus,launchLog,expectedKeyId:()=>expectedKeyId,valueFree,
|
||||
return {root,f,state,trace,
|
||||
authorizeProbe:args=>bus.broker.request(human,{verb:'acceptance.authorize',args}),
|
||||
authorizeThroughActualHumanProof:args=>new Promise((resolve,reject)=>{
|
||||
const child=spawn(process.execPath,[HUMAN_CLI,bus.path],{env:{...env,CODEX_THREAD_ID:'owned-agent-proof-test'},stdio:['pipe','pipe','pipe']});let out='',err='';
|
||||
const timer=setTimeout(()=>child.kill('SIGKILL'),6000);child.stdout.on('data',v=>{out+=v;});child.stderr.on('data',v=>{err+=v;});
|
||||
child.on('error',()=>{clearTimeout(timer);reject(Object.assign(Error('fixture-human-client-failed'),{code:'fixture-human-client-failed'}));});
|
||||
child.on('close',code=>{clearTimeout(timer);if(code!==0)return reject(Object.assign(Error('human-proof-refused'),{code:err.trim().split('\n').at(-1)}));try{resolve(JSON.parse(out));}catch{reject(Error('fixture-human-json'));}});
|
||||
child.stdin.end(JSON.stringify({business:'acme',verb:'acceptance.authorize',args})+'\n');
|
||||
}),proxyReceipts,logs,launcher,bus,launchLog,expectedKeyId:()=>expectedKeyId,valueFree,
|
||||
upstreamCredentialNames:Object.keys(env).filter(name=>['ANTHROPIC_API_KEY','ANTHROPIC_AUTH_TOKEN','CLAUDE_CODE_OAUTH_TOKEN','OPENAI_API_KEY','OPENROUTER_API_KEY','ZAI_API_KEY'].includes(name)),
|
||||
runDirectories:()=>fs.existsSync(runsDir(f.dataRoot,'acme'))?fs.readdirSync(runsDir(f.dataRoot,'acme')).map(name=>join(runsDir(f.dataRoot,'acme'),name)):[],
|
||||
sessions:()=>readSessions(f.dataRoot),send:body=>bus.broker.request(human,{verb:'message.send',args:{to:'chief',body,class:'REQUEST'}}),
|
||||
|
||||
@@ -16,6 +16,7 @@ import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { typedTools, untypedActions } from "./tools.mjs";
|
||||
import { CREATIVE_DEFINITIONS } from "../../business/src/vocabulary.mjs";
|
||||
import { probePrompt, validateProbeContext } from '../../cli/src/acceptance-probe.mjs';
|
||||
|
||||
export const BUNDLE_VERSION = 1;
|
||||
// The role file's "web" is a grant for the broker's typed web tools, not a harness built-in. The
|
||||
@@ -324,18 +325,23 @@ function prompt({ contract, resolved, session, tools, untyped, builtins, persona
|
||||
// Returns { manifest, files, policy, tools, env } with absolute paths; env is the module's
|
||||
// adapter variables. In proxy mode the host splits credentials into its
|
||||
// transient spawn environment before writing the remaining variables to session.json.
|
||||
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, library = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null, proxy = null }) {
|
||||
export function buildBundle({ dir, resolved, contract, arbiter = false, tracker = false, library = false, credentials = [], session, harness, route = "primary", routeReason = null, harnessVersion = null, models = null, land = false, skillsDir = null, personaDir = null, proxy = null, acceptanceProbe = null }) {
|
||||
if (acceptanceProbe) {
|
||||
validateProbeContext(acceptanceProbe);
|
||||
if (acceptanceProbe.business !== resolved.business || acceptanceProbe.role !== resolved.instance || acceptanceProbe.run !== session.run)
|
||||
throw new BundleError('acceptance-context-invalid');
|
||||
}
|
||||
if (route !== "primary" && route !== "fallback") throw new BundleError(`route ${JSON.stringify(route)} isn't primary or fallback`);
|
||||
const model = sessionModel(resolved, models, route, { proxy: Boolean(proxy) });
|
||||
if (model.provider === "proxy" && !proxy) throw new BundleError("proxy model needs its own session credential", "no-session-credential");
|
||||
if (proxy && (typeof proxy.key !== "string" || !proxy.key || typeof proxy.baseUrl !== "string"
|
||||
|| !/^http:\/\/127\.0\.0\.1:[0-9]+$/.test(proxy.baseUrl))) throw new BundleError("invalid session proxy context");
|
||||
const web = webPlan(resolved, model.harness, harness.builtinWeb());
|
||||
const tools = typedTools({ resolved, arbiter, tracker, library, projects: (session.checkouts ?? []).map((c) => c.project), webTyped: !web.builtin, land });
|
||||
const untyped = untypedActions(resolved, tools);
|
||||
const persona = readPersona(resolved, personaDir);
|
||||
const tools = acceptanceProbe ? [] : typedTools({ resolved, arbiter, tracker, library, projects: (session.checkouts ?? []).map((c) => c.project), webTyped: !web.builtin, land });
|
||||
const untyped = acceptanceProbe ? [] : untypedActions(resolved, tools);
|
||||
const persona = acceptanceProbe ? null : readPersona(resolved, personaDir);
|
||||
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
||||
const skills = copySkills(resolved.skills ?? [], skillsDir, dir);
|
||||
const skills = copySkills(acceptanceProbe ? [] : resolved.skills ?? [], skillsDir, dir);
|
||||
const write = (name, text) => {
|
||||
writeFileSync(join(dir, name), text, { mode: 0o600, flag: "wx" });
|
||||
return [name, sha256(text)];
|
||||
@@ -343,12 +349,12 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
|
||||
const policy = {
|
||||
harness: model.harness,
|
||||
workspace: session.workspace,
|
||||
tools: builtinTools(resolved.limits.tools),
|
||||
tools: acceptanceProbe ? [] : builtinTools(resolved.limits.tools),
|
||||
typed: tools.map((t) => t.name),
|
||||
network: resolved.limits.network,
|
||||
...(web.builtin ? { webBuiltin: true } : {}),
|
||||
needs: Object.keys(resolved.credentials ?? {}),
|
||||
credentials,
|
||||
needs: acceptanceProbe ? [] : Object.keys(resolved.credentials ?? {}),
|
||||
credentials: acceptanceProbe ? [] : credentials,
|
||||
};
|
||||
const files = {
|
||||
prompt: join(dir, "prompt.md"),
|
||||
@@ -358,7 +364,7 @@ export function buildBundle({ dir, resolved, contract, arbiter = false, tracker
|
||||
};
|
||||
const builtins = harness.builtins({ tools: policy.tools, webBuiltin: web.builtin });
|
||||
const digests = [
|
||||
write("prompt.md", prompt({ contract, resolved, session: { ...session, ...model, webBuiltin: web.builtin }, tools, untyped, builtins, persona }) + skillSection(skills)),
|
||||
write("prompt.md", acceptanceProbe ? probePrompt(acceptanceProbe) : prompt({ contract, resolved, session: { ...session, ...model, webBuiltin: web.builtin }, tools, untyped, builtins, persona }) + skillSection(skills)),
|
||||
write("policy.json", JSON.stringify(policy, null, 2) + "\n"),
|
||||
write("tools.json", JSON.stringify(tools, null, 2) + "\n"),
|
||||
];
|
||||
|
||||
@@ -39,6 +39,7 @@ import { join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { Client } from "../../bus/src/client.mjs";
|
||||
import { firstOutputMarker, firstTurnMarker } from './first-output.mjs';
|
||||
import { acceptanceTurn } from './acceptance-turn.mjs';
|
||||
import { GUARD_CODES, FIXED_TEXTS } from "../../library/src/reply-protocol.mjs";
|
||||
import { fetchReview, landWork, pushWorking } from "./git-tools.mjs";
|
||||
|
||||
@@ -385,7 +386,7 @@ function runTurn({ session, request, n, env, onChild }) {
|
||||
kill("SIGKILL");
|
||||
onChild(null);
|
||||
if (markerFailed) return resolve({ ok: false, markerFailed: true, reason: "first-turn marker publication failed" });
|
||||
if (timedOut) return resolve({ ok: false, reason: `turn passed its ${session.turnTimeout} s wall clock` });
|
||||
if (timedOut) return resolve({ ok: false, ...(session.acceptanceProbe ? { timedOut: true } : {}), reason: `turn passed its ${session.turnTimeout} s wall clock` });
|
||||
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
|
||||
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
|
||||
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
|
||||
@@ -490,6 +491,20 @@ export async function main(runDir, { stdin = process.stdin, env = process.env, l
|
||||
}
|
||||
log(`runner: ${session.business}/${session.instance} claimed by run ${session.run}`);
|
||||
|
||||
if (session.acceptanceProbe !== undefined) {
|
||||
let code = EXIT.stopped;
|
||||
try {
|
||||
await acceptanceTurn({ session, policy, env: adapterEnv(session, env), runTurn, onChild: p => { child = p; } });
|
||||
} catch (error) {
|
||||
code = EXIT.usage;
|
||||
log(`runner: ${/^acceptance-[a-z-]+$/.test(error?.code ?? '') ? error.code : 'acceptance-probe-failed'}`);
|
||||
} finally {
|
||||
try { await client.call('role.release'); }
|
||||
catch { code = EXIT.usage; log('runner: acceptance-release-refused'); }
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
const tools = JSON.parse(readFileSync(session.bundle.tools, "utf8"));
|
||||
const server = await toolServer({
|
||||
path: session.toolSocket,
|
||||
|
||||
@@ -51,6 +51,9 @@ export const RUNNER_FILES = Object.freeze([
|
||||
"packages/harness/src/runner.mjs",
|
||||
// Row 331: fixed output-exists marker; writes only within the existing run directory.
|
||||
"packages/harness/src/first-output.mjs",
|
||||
// Mos1966: fixed private probe parsing/measurement, read-only code only.
|
||||
"packages/harness/src/acceptance-turn.mjs",
|
||||
"packages/cli/src/acceptance-probe.mjs",
|
||||
"packages/harness/src/gate.mjs",
|
||||
"packages/harness/src/tools.mjs",
|
||||
"packages/harness/src/git-tools.mjs",
|
||||
|
||||
+22
-4
@@ -14,7 +14,7 @@
|
||||
# --node is the pinned path and it and every directory above it are root's with no group or other
|
||||
# write. The script changes nothing on the host but the message F3 sends and its reply, and it never
|
||||
# opens claude-session.env. A bounded config/target query imports the copy only as the stack
|
||||
# user, with sudo and an empty environment. Root parses its two facts in bash. P10 uses the
|
||||
# user, with sudo and an empty environment. Root parses only bounded metadata in bash. P10 uses the
|
||||
# fixed system Python, also as the stack user, for a read-only SO_PEERCRED observation.
|
||||
# The config/probe supervisor is fixed root-validated system Bash plus setsid
|
||||
# and sleep, after the uid drop: query inner/outer 5/7 s, probe 2/4 s. Root
|
||||
@@ -28,6 +28,9 @@
|
||||
# One line per check, `<id> <path> <mark> <evidence>`, then `count <mark> N` for each mark and a
|
||||
# result line. F checks are `pass` or `FAIL`. P checks are `closed`, `accepted <ruling>` or
|
||||
# `unnamed`, which means no Q182, Q183 or Mos ruling names the path; each unnamed line goes to Mos.
|
||||
# The config query also carries a proxy mode fact when configured. In proxy
|
||||
# mode F8 requires the same active unit host/copy typed managed marker/usage
|
||||
# record through a second dropped-uid query; it never substitutes a legacy token file.
|
||||
#
|
||||
# Exit 0 when every F check passes, 1 when one fails, 2 on usage or a refusal (a bad args file, or
|
||||
# --root misused). A P check never changes the exit.
|
||||
@@ -321,11 +324,11 @@ legacy_run() (
|
||||
)
|
||||
# row276-legacy-end
|
||||
|
||||
TESTER_QUERY='import {readFileSync} from "node:fs";import {pathToFileURL} from "node:url";const m=await import(pathToFileURL(process.argv[1]).href);const s=m.loadSystem();console.log(JSON.stringify({dataRoot:s.dataRoot,socket:readFileSync(process.argv[2],"utf8").includes("MOSAIC_TESTER_SOCKET_V1")}));'
|
||||
TESTER_QUERY='import {readFileSync} from "node:fs";import {pathToFileURL} from "node:url";const m=await import(pathToFileURL(process.argv[1]).href);const s=m.loadSystem();console.log(JSON.stringify({dataRoot:s.dataRoot,socket:readFileSync(process.argv[2],"utf8").includes("MOSAIC_TESTER_SOCKET_V1"),...(s.proxy?{proxy:true}:{})}));'
|
||||
tester_facts() {
|
||||
local LC_ALL=C pattern='^\{"dataRoot":"([A-Za-z0-9/._@+-]+)","socket":(true|false)\}$'
|
||||
local LC_ALL=C pattern='^\{"dataRoot":"([A-Za-z0-9/._@+-]+)","socket":(true|false)(,"proxy":(true))?\}$'
|
||||
[[ "$1" =~ $pattern ]] || return 1
|
||||
TS_DATA="${BASH_REMATCH[1]}" TS_MARKED="${BASH_REMATCH[2]}"
|
||||
TS_DATA="${BASH_REMATCH[1]}" TS_MARKED="${BASH_REMATCH[2]}" TS_PROXY="${BASH_REMATCH[4]:-false}"
|
||||
}
|
||||
tester_location() {
|
||||
local LC_ALL=C data="$1" home="$2" uid="$3" prefix="$4" part at="" st
|
||||
@@ -563,8 +566,23 @@ check_f7() {
|
||||
else ffail F7 pm-live "$(clean "${out#fail }")"; fi
|
||||
}
|
||||
|
||||
PROBE_QUERY='import{pathToFileURL}from"node:url";const m=await import(pathToFileURL(process.argv[1]).href);const r=m.readAcceptanceRecord(process.argv[2],process.argv[3],process.argv[4]);console.log([r.copy,r.hostPid,r.hostStartTime,r.run,r.modelKeyId,r.inputTokens].join(" "));'
|
||||
check_f8() {
|
||||
local s
|
||||
# This is a mode fact from the existing bounded, dropped-uid config query,
|
||||
# never a readiness assertion. P2's key stays inside managed launch. The
|
||||
# second bounded dropped-uid query reads typed host-owned evidence only.
|
||||
if [ "$TS_PROXY" = true ]; then
|
||||
local out rc=0 copy host_pid host_start run key tokens
|
||||
out="$(tester_capture 5 7 4096 "$S_USER" "$S_HOME" "$(dirname "$NODE"):/usr/local/bin:/usr/bin:/bin" "$NODE" --input-type=module -e "$PROBE_QUERY" "$COPY/packages/cli/src/acceptance-record.mjs" "$DATA_ROOT" "$BUSINESS" "$COPY_ID")" || rc=$?
|
||||
if [ "$rc" = 0 ] && [[ "$out" =~ ^[a-f0-9]{40}\ [1-9][0-9]*\ [0-9]+\ r[a-f0-9]{12}\ [a-f0-9]{12}\ (0|[1-9][0-9]*)$ ]]; then
|
||||
read -r copy host_pid host_start run key tokens <<<"$out"
|
||||
if [ "$copy" = "$COPY_ID" ] && [ "$host_pid" = "$(prop "$BUS_SHOW" MainPID)" ] && [ "$tokens" -le 2000 ]; then
|
||||
fpass F8 proxy-managed-probe "same-copy host $host_pid/$host_start run $run key id $key: literal marker, $tokens input tokens and confirmed native cleanup"
|
||||
else ffail F8 proxy-managed-probe "acceptance-record-invalid: copy, active bus host or token ceiling differs"; fi
|
||||
else ffail F8 proxy-managed-probe "proxy-managed-probe-required: no trusted managed marker/token result; legacy token metadata is not proxy evidence"; fi
|
||||
return
|
||||
fi
|
||||
s="$(stat -c '%U %a %F' -- "$ROOT$CRED" 2>/dev/null)" || s="missing"
|
||||
if [ ! -L "$ROOT$CRED" ] && [ "$s" = "$S_USER 600 regular file" ]; then fpass F8 credential-file "$CRED is '$s'"
|
||||
else ffail F8 credential-file "$CRED is '$s', not '$S_USER 600 regular file'"; fi
|
||||
|
||||
+51
-11
@@ -4,7 +4,7 @@
|
||||
# nothing. It runs every check, prints one line for each, and refuses if
|
||||
# any one failed.
|
||||
#
|
||||
# case2-precheck.sh --business ID [--profile factory|library]
|
||||
# case2-precheck.sh --business ID [--profile factory|library] [--static-only]
|
||||
# case2-precheck.sh --business ID --library-status
|
||||
#
|
||||
# Checks: the config and business file validate; `sudo -n true` fails and
|
||||
@@ -18,6 +18,13 @@
|
||||
# runs claude-code; and claude-session.env sets ZAI_API_KEY, when some
|
||||
# instance's provider is zai. It prints free memory and checks that HOME is
|
||||
# <home>. It never prints a value from claude-session.env.
|
||||
# Proxy mode consumes only the running host's same-copy typed managed probe
|
||||
# record, proving literal marker, actual aggregate input<=2000 and native cleanup.
|
||||
# Missing/invalid evidence refuses proxy-managed-probe-required; it invokes no
|
||||
# direct Claude path and imports no legacy env file. A proxy business route
|
||||
# without proxy configuration refuses proxy-route-needs-config.
|
||||
# --static-only runs the pre-start checks without a provider probe. Clean
|
||||
# static checks exit 3 with PROBEPENDING, never full acceptance (exit 0).
|
||||
#
|
||||
# C2-13b adds to the library profile: the business file is <user>'s with no
|
||||
# group or other bit; businesses/.history/<id>/ is 0700 and its changes.jsonl
|
||||
@@ -40,7 +47,7 @@
|
||||
# CASE2_PROC_SYS default /proc/sys
|
||||
# CASE2_GETENT the getent command, default getent
|
||||
#
|
||||
# Exit 0 every check passed, 1 refused, 4 usage.
|
||||
# Exit 0 every check passed, 1 refused, 3 static PROBEPENDING, 4 usage.
|
||||
set -uo pipefail
|
||||
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
UNIT_DIR="${CASE2_UNIT_DIR:-/etc/systemd/system}"
|
||||
@@ -52,18 +59,20 @@ WEBUI_UNIT="$UNIT_DIR/mosaic-webui.service"
|
||||
# Claude Code's own prompt is many times this.
|
||||
MARKER_TOKEN_CEILING=2000
|
||||
|
||||
usage() { echo 'usage: case2-precheck.sh --business ID [--profile factory|library] | --business ID --library-status' >&2; exit 4; }
|
||||
PROFILE=library PROFILE_SET=0 BUSINESS='' STATUS=0
|
||||
usage() { echo 'usage: case2-precheck.sh --business ID [--profile factory|library] [--static-only] | --business ID --library-status' >&2; exit 4; }
|
||||
PROFILE=library PROFILE_SET=0 BUSINESS='' STATUS=0 STATIC=0
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--profile) [ $# -ge 2 ] || usage; PROFILE="$2"; PROFILE_SET=1; shift 2 ;;
|
||||
--business) [ $# -ge 2 ] || usage; BUSINESS="$2"; shift 2 ;;
|
||||
--library-status) STATUS=1; shift ;;
|
||||
--static-only) [ "$STATIC" = 0 ] || usage; STATIC=1; shift ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
done
|
||||
[ -n "$BUSINESS" ] || usage
|
||||
[ "$STATUS" = 0 ] || [ "$PROFILE_SET" = 0 ] || usage
|
||||
[ "$STATUS" = 0 ] || [ "$STATIC" = 0 ] || usage
|
||||
case "$PROFILE" in factory|library) ;; *) echo "case2-precheck: --profile must be factory or library: $PROFILE" >&2; exit 4 ;; esac
|
||||
[[ "$BUSINESS" =~ ^[a-z0-9][a-z0-9._-]{0,63}$ ]] || { echo "case2-precheck: --business must be a business id: $BUSINESS" >&2; exit 4; }
|
||||
|
||||
@@ -80,7 +89,7 @@ private_dir() { [ ! -L "$1" ] && [ -d "$1" ] && [ "$(stat -c '%u' -- "$1")" = "$
|
||||
if [ "$STATUS" = 1 ]; then
|
||||
status="$(cd "$REPO" && node --input-type=module -e '
|
||||
import { lstatSync } from "node:fs";
|
||||
const [repo, id] = process.argv.slice(1);
|
||||
const [repo, id, staticOnly] = process.argv.slice(1);
|
||||
const { loadSystem, rolesDir } = await import(`${repo}/packages/cli/src/config.mjs`);
|
||||
const { loadBusiness } = await import(`${repo}/packages/business/src/index.mjs`);
|
||||
const { libraryStatus, mirrorPath } = await import(`${repo}/packages/library/src/index.mjs`);
|
||||
@@ -112,7 +121,7 @@ for (const project of projects) {
|
||||
for (const p of s.problems) say("PROBLEM", p.code, quote(p.path));
|
||||
say("PROBLEMS", project, s.problems.length);
|
||||
}
|
||||
' "$REPO" "$BUSINESS" 2>&1)" || true
|
||||
' "$REPO" "$BUSINESS" "$STATIC" 2>&1)" || true
|
||||
[ -n "$status" ] || refuse "library status: the check printed nothing"
|
||||
while IFS=$'\t' read -r kind a b c; do
|
||||
case "$kind" in
|
||||
@@ -166,13 +175,21 @@ HOME_DIR="${PW_HOME:-$HOME}"
|
||||
# The helper prints tab-separated facts and never a credential.
|
||||
facts="$(cd "$REPO" && node --input-type=module -e '
|
||||
import { readFileSync } from "node:fs";
|
||||
const [repo, id] = process.argv.slice(1);
|
||||
const [repo, id, staticOnly] = process.argv.slice(1);
|
||||
const { loadSystem, rolesDir } = await import(`${repo}/packages/cli/src/config.mjs`);
|
||||
const { businessFilePath, configDir, loadBusiness, resolveInstance, systemVars } = await import(`${repo}/packages/business/src/index.mjs`);
|
||||
const say = (...f) => console.log(f.join("\t"));
|
||||
let system;
|
||||
try { system = loadSystem(); } catch (e) { say("CONFIG", "bad", e.message.split("\n")[0]); process.exit(0); }
|
||||
say("CONFIG", "ok", system.dataRoot, configDir());
|
||||
if (system.proxy) {
|
||||
say("PROXY", "on");
|
||||
if (staticOnly !== "1") try {
|
||||
const { readAcceptanceRecord, pinnedAcceptanceCopy } = await import(`${repo}/packages/cli/src/acceptance-record.mjs`);
|
||||
const r = readAcceptanceRecord(system.dataRoot, id, pinnedAcceptanceCopy(repo));
|
||||
say("PROBE", "ok", r.run, r.modelKeyId, r.inputTokens);
|
||||
} catch { say("PROBE", "missing"); }
|
||||
}
|
||||
try {
|
||||
const { readNotifyConfig } = await import(`${repo}/packages/cli/src/cli.mjs`);
|
||||
readNotifyConfig(system.dataRoot, id);
|
||||
@@ -199,7 +216,7 @@ for (const instance of Object.keys(b.roles)) {
|
||||
say("ROUTE", instance, v[h], provider);
|
||||
}
|
||||
}
|
||||
' "$REPO" "$BUSINESS" 2>&1)" || true
|
||||
' "$REPO" "$BUSINESS" "$STATIC" 2>&1)" || true
|
||||
|
||||
line() { printf '%s\n' "$facts" | awk -F'\t' -v k="$1" '$1 == k' ; }
|
||||
cfg="$(line CONFIG)"
|
||||
@@ -322,6 +339,26 @@ elif [ "$floor" -le "$port" ]; then refuse "net.ipv4.ip_unprivileged_port_start
|
||||
else ok "net.ipv4.ip_unprivileged_port_start $floor is above the Console's port $port"; fi
|
||||
|
||||
routes="$(line ROUTE)"
|
||||
# P2 releases a key only inside a managed launch in the running bus. A
|
||||
# preboot process cannot substitute a host credential or a public ready flag.
|
||||
# Only same-copy/current-host typed probe evidence can complete BOTH properties;
|
||||
# static-only remains pending regardless of an earlier record.
|
||||
DIRECT_PROBE=1
|
||||
if [ "$STATIC" = 1 ]; then
|
||||
DIRECT_PROBE=0
|
||||
elif [ "$(line PROXY)" = $'PROXY\ton' ]; then
|
||||
DIRECT_PROBE=0
|
||||
probe="$(line PROBE)"
|
||||
if [[ "$probe" =~ ^PROBE$'\t'ok$'\t'r[a-f0-9]{12}$'\t'[a-f0-9]{12}$'\t'(0|[1-9][0-9]*)$ ]]; then
|
||||
IFS=$'\t' read -r _ _ probe_run probe_key probe_tokens <<<"$probe"
|
||||
if [ "$probe_tokens" -le "$MARKER_TOKEN_CEILING" ]; then
|
||||
ok "managed proxy replaces its prompt: run $probe_run key id $probe_key, $probe_tokens input tokens; same live host/copy and native cleanup recorded"
|
||||
else refuse "proxy-managed-probe-required: recorded token ceiling failed"; fi
|
||||
else refuse "proxy-managed-probe-required: no typed same-live-host/copy marker and token-ceiling result"; fi
|
||||
elif printf '%s\n' "$routes" | awk -F'\t' '$4 == "proxy" { f = 1 } END { exit !f }'; then
|
||||
refuse "proxy-route-needs-config: a proxy route cannot use the direct host credential/probe path"
|
||||
DIRECT_PROBE=0
|
||||
fi
|
||||
SESSION_ENV="${CONFIG_DIR:-$HOME_DIR/.config/mosaic-dev}/secrets/claude-session.env"
|
||||
# The session env file, checked as the bus unit's EnvironmentFile.
|
||||
env_file_ok() {
|
||||
@@ -329,7 +366,7 @@ env_file_ok() {
|
||||
}
|
||||
|
||||
# Claude Code replaces its prompt with --system-prompt-file.
|
||||
if printf '%s\n' "$routes" | awk -F'\t' '$3 == "claude-code" { f = 1 } END { exit !f }'; then
|
||||
if [ "$DIRECT_PROBE" = 1 ] && printf '%s\n' "$routes" | awk -F'\t' '$3 == "claude-code" { f = 1 } END { exit !f }'; then
|
||||
claude="$(unit_value "$BUS_UNIT" Environment | sed -n 's/^MOSAIC_CLAUDE_BIN=//p')"
|
||||
claude="${claude:-$(command -v claude || true)}"
|
||||
if [ -z "$claude" ] || [ ! -x "$claude" ]; then refuse "an instance runs claude-code and no claude is installed"
|
||||
@@ -367,7 +404,7 @@ if printf '%s\n' "$routes" | awk -F'\t' '$3 == "claude-code" { f = 1 } END { exi
|
||||
fi
|
||||
|
||||
# ZAI_API_KEY, when some instance's provider is zai (design 10 step 2d).
|
||||
if printf '%s\n' "$routes" | awk -F'\t' '$4 == "zai" { f = 1 } END { exit !f }'; then
|
||||
if [ "$DIRECT_PROBE" = 1 ] && printf '%s\n' "$routes" | awk -F'\t' '$4 == "zai" { f = 1 } END { exit !f }'; then
|
||||
if [ -L "$SESSION_ENV" ]; then refuse "$SESSION_ENV is a symlink"
|
||||
elif [ ! -f "$SESSION_ENV" ]; then refuse "an instance's provider is zai and $SESSION_ENV is missing"
|
||||
elif ! env_file_ok; then refuse "$SESSION_ENV must be owned by $ME at 0600 (mode $(stat -c '%a' -- "$SESSION_ENV"))"
|
||||
@@ -376,6 +413,9 @@ if printf '%s\n' "$routes" | awk -F'\t' '$4 == "zai" { f = 1 } END { exit !f }';
|
||||
fi
|
||||
|
||||
echo " free memory: $(awk '$1 == "MemAvailable:" { printf "%d MiB", $2 / 1024 }' /proc/meminfo)"
|
||||
if [ "$FAILED" = 0 ]; then echo "case2-precheck: every check passed"; exit 0; fi
|
||||
if [ "$FAILED" = 0 ]; then
|
||||
if [ "$STATIC" = 1 ]; then echo "case2-precheck: PROBEPENDING (static checks passed; trusted managed probe still required)"; exit 3; fi
|
||||
echo "case2-precheck: every check passed"; exit 0
|
||||
fi
|
||||
echo "case2-precheck: refused"
|
||||
exit 1
|
||||
Reference in new issue
Block a user