@foundocs/foundocs-setup 0.4.1 → 0.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -20
- package/dist/bridge.mjs +241 -702
- package/package.json +3 -3
- package/skills/foundocs/SKILL.md +5 -9
- package/skills/foundocs/references/documents.md +8 -5
- package/skills/foundocs/references/dreaming.md +13 -1
- package/skills/foundocs/scripts/episode-checkpoint.mjs +1 -1
- package/skills/foundocs/scripts/session-start.mjs +5 -15
- package/skills/foundocs-capture-episode/SKILL.md +8 -2
- package/skills/foundocs-capture-episode/references/capture.md +14 -6
- package/skills/foundocs-capture-knowledge/SKILL.md +1 -1
- package/skills/foundocs-capture-knowledge/references/writing-guide.md +1 -1
- package/src/bridge.mjs +4 -27
- package/src/cli.mjs +7 -8
- package/src/dream-models.mjs +67 -0
- package/src/dream-sessions.mjs +212 -0
- package/src/dream-transcripts.mjs +151 -0
- package/src/effect-codex-worker.mjs +5 -2
- package/src/effect-storage.mjs +1 -1
- package/src/global.mjs +10 -3
- package/src/runtime.mjs +7 -29
- package/src/setup.mjs +13 -6
- package/src/skill-assets.mjs +1 -1
- package/templates/knowledge-policy.md +2 -2
- package/templates/workspace-skill.md +5 -2
- package/skills/foundocs/references/effect-measurement.md +0 -55
- package/src/effect-automatic.mjs +0 -190
- package/src/effect-config.mjs +0 -31
- package/src/effect-host.mjs +0 -86
- package/src/effect-remote.mjs +0 -28
- package/src/effect.mjs +0 -209
package/src/effect.mjs
DELETED
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
import { join, dirname, isAbsolute } from 'node:path';
|
|
2
|
-
import { readFile, rm, realpath } from 'node:fs/promises';
|
|
3
|
-
import { randomUUID } from 'node:crypto';
|
|
4
|
-
import { loadInstallation } from './setup.mjs';
|
|
5
|
-
import { validateInstallation } from './runtime.mjs';
|
|
6
|
-
import { RUNNER, CLI_VERSION, UUID, EffectError, hash, missingObservation, normalizeProbe, toolPolicy, validateBrief } from './effect-core.mjs';
|
|
7
|
-
import { privateDir, readJson, saveJson, cleanExpired, purgeRaw, freezeSnapshot, copySnapshot } from './effect-storage.mjs';
|
|
8
|
-
import { capabilities, runProbe } from './effect-runner.mjs';
|
|
9
|
-
import { workingSessionModel } from './effect-host.mjs';
|
|
10
|
-
import { CODEX_RUNNER, CODEX_VERSION, codexCapabilities, codexToolPolicy } from './effect-codex.mjs';
|
|
11
|
-
import { connectEffectRemote } from './effect-remote.mjs';
|
|
12
|
-
|
|
13
|
-
export async function measurementInstallation(rootPath, options = {}) {
|
|
14
|
-
if (!isAbsolute(rootPath)) throw new EffectError('invalid_root');
|
|
15
|
-
const { root, directory, manifest } = await loadInstallation(rootPath, options);
|
|
16
|
-
// Exact governing file; no ancestor/alternate config fallback.
|
|
17
|
-
const config = JSON.parse(await readFile(join(root, 'foundocs.json'), 'utf8'));
|
|
18
|
-
if (config.project_id !== manifest.projectId) throw new EffectError('project_mismatch');
|
|
19
|
-
await validateInstallation(root, directory, manifest);
|
|
20
|
-
return { root, base: join(directory, 'effects'), manifest };
|
|
21
|
-
}
|
|
22
|
-
// Unobserved crash: finite upper allowance for two timeout/grace windows, never renewed by recovery.
|
|
23
|
-
export const crashSettlementDeadline = (policy, now = Date.now()) => new Date(now + 2 * (policy.perProbeTimeoutMs + 5000) + 86400000).toISOString();
|
|
24
|
-
|
|
25
|
-
export class EffectCoordinator {
|
|
26
|
-
constructor({ root, base, remote, probe = runProbe, check = options => options?.runner === CODEX_RUNNER ? codexCapabilities() : capabilities(), identify = workingSessionModel }) { Object.assign(this, { root, base, remote, probe, check, identify }); }
|
|
27
|
-
async initialize() { await cleanExpired(this.base); }
|
|
28
|
-
path(taskId) { if (!UUID.test(taskId)) throw new EffectError('invalid_task_id'); return join(this.base, taskId); }
|
|
29
|
-
async state(taskId) {
|
|
30
|
-
const dir = this.path(taskId); await privateDir(dir);
|
|
31
|
-
const s = await readJson(join(dir, 'state.json'));
|
|
32
|
-
if (Date.parse(s.settlementExpiresAt ?? s.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
|
|
33
|
-
return s;
|
|
34
|
-
}
|
|
35
|
-
async prepare({ policy, brief, allowlist, excludePaths = [], host }) {
|
|
36
|
-
// Host fetched policy exactly once, before any exposure. OFF must not inspect/spawn CLI.
|
|
37
|
-
if (policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
|
|
38
|
-
if (policy?.enabled !== true || ![RUNNER, CODEX_RUNNER].includes(policy.runner)) return { status: 'skipped', reason: 'unsupported_runner' };
|
|
39
|
-
const workingModel = await this.identify(host, this.root);
|
|
40
|
-
if (workingModel.status !== 'identified') return workingModel;
|
|
41
|
-
const runner = workingModel.runner ?? RUNNER;
|
|
42
|
-
validateBrief(brief);
|
|
43
|
-
const dir = this.path(brief.taskId); await privateDir(dir);
|
|
44
|
-
let state = await readJson(join(dir, 'state.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
45
|
-
if (state) {
|
|
46
|
-
if (state.workingModel?.model !== workingModel.model || state.workingModel?.modelSource !== 'working_session' || (state.policy.runner ?? RUNNER) !== runner || state.workingModel?.reasoningEffort !== workingModel.reasoningEffort) throw new EffectError('task_conflict');
|
|
47
|
-
if (state.briefSha256 !== hash(brief) || state.sourceSelectionHash !== hash({ allowlist, excludePaths })) throw new EffectError('task_conflict');
|
|
48
|
-
if (Date.parse(state.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
|
|
49
|
-
if (state.prepared) return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
|
|
50
|
-
if (!state.prepareInput) throw new EffectError('incomplete_preparation', 'A prior snapshot attempt was interrupted. Do not recreate this task after exposure.');
|
|
51
|
-
} else {
|
|
52
|
-
let runnerVersion;
|
|
53
|
-
try { runnerVersion = await this.check({ runner }); } catch (e) { if (e.code === 'unsupported_runner') return { status: 'skipped', reason: e.code }; throw e; }
|
|
54
|
-
state = { taskId: brief.taskId, criterionIds: brief.criteria.map(c => c.id), brief, briefSha256: hash(brief), sourceSelectionHash: hash({ allowlist, excludePaths }), policy: { ...policy, runner, model: workingModel.model }, workingModel, runnerVersion, expiresAt: new Date(Date.now() + 86400000).toISOString() };
|
|
55
|
-
await saveJson(join(dir, 'state.json'), state, true);
|
|
56
|
-
state.snapshot = await freezeSnapshot(this.root, join(dir, 'snapshot'), allowlist, excludePaths);
|
|
57
|
-
state.prepareInput = { requestId: randomUUID(), brief, briefSha256: state.briefSha256, snapshot: state.snapshot, runner, runnerVersion, model: workingModel.model, modelSource: workingModel.modelSource };
|
|
58
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
59
|
-
}
|
|
60
|
-
state.prepared = await this.remote.call('prepare_effect_measurement', state.prepareInput);
|
|
61
|
-
state.expiresAt = state.prepared.expiresAt;
|
|
62
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
63
|
-
return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
|
|
64
|
-
}
|
|
65
|
-
baseProbe(state, arm) {
|
|
66
|
-
return { arm, status: 'not_started', runner: state.policy.runner, runnerVersion: state.runnerVersion, provider: state.policy.runner === CODEX_RUNNER ? 'openai' : 'anthropic', model: state.policy.model, tokenUnit: 'provider_input_output_tokens', briefSha256: state.briefSha256, snapshotSha256: state.snapshot.sha256, criteriaSha256: hash(state.brief.criteria), toolPolicySha256: hash(state.policy.runner === CODEX_RUNNER ? codexToolPolicy({ ...state.policy, reasoningEffort: state.workingModel.reasoningEffort }) : toolPolicy(state.policy)), protocolVersion: 1, contextSha256: arm === 'with_foundocs' ? state.reservation.deliveredContextSha256 : null, isolationVerified: false, evidenceVerified: false, startedAt: null, finishedAt: null, observation: missingObservation(), output: null };
|
|
67
|
-
}
|
|
68
|
-
async flush(taskId) {
|
|
69
|
-
const dir = this.path(taskId); const state = await this.state(taskId);
|
|
70
|
-
const outbox = await readJson(join(dir, 'outbox.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
71
|
-
if (!outbox) {
|
|
72
|
-
const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
73
|
-
if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
|
|
74
|
-
if (state.reservation && state.probes) {
|
|
75
|
-
const owner = await readJson(join(dir, 'run-lock.json'));
|
|
76
|
-
let alive = true; try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
|
|
77
|
-
if (alive) return { status: 'report_pending', reason: 'coordinator_active' };
|
|
78
|
-
state.recovered = true;
|
|
79
|
-
for (const probe of Object.values(state.probes)) if (probe.startedAt && !probe.finishedAt) { probe.status = 'failed'; probe.finishedAt = new Date().toISOString(); }
|
|
80
|
-
return this.report(state, dir);
|
|
81
|
-
}
|
|
82
|
-
return { status: 'nothing_pending' };
|
|
83
|
-
}
|
|
84
|
-
if (outbox.rejected) return { status: 'report_rejected', reason: outbox.rejected };
|
|
85
|
-
try {
|
|
86
|
-
const result = await this.remote.call('report_effect_measurement', outbox.payload);
|
|
87
|
-
await saveJson(join(dir, 'receipt.json'), { reportedAt: new Date().toISOString(), requestId: outbox.payload.requestId, result });
|
|
88
|
-
await rm(join(dir, 'outbox.json'));
|
|
89
|
-
// Raw sources/context/brief are no longer needed after settlement.
|
|
90
|
-
await rm(join(dir, 'snapshot'), { recursive: true, force: true });
|
|
91
|
-
for (const arm of ['with_foundocs', 'without_foundocs']) await rm(join(dir, arm), { recursive: true, force: true });
|
|
92
|
-
return { status: 'reported', result };
|
|
93
|
-
} catch (e) {
|
|
94
|
-
if (!e.uncertain) { outbox.rejected = e.code ?? 'request_failed'; await saveJson(join(dir, 'outbox.json'), outbox); return { status: 'report_rejected', reason: outbox.rejected }; }
|
|
95
|
-
return { status: 'report_pending', reason: 'transport_uncertain' };
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
async report(state, dir) {
|
|
99
|
-
const payload = { requestId: randomUUID(), runId: state.reservation.runId, leaseToken: state.reservation.leaseToken, withFoundocs: normalizeProbe(state.probes.with_foundocs, { criteria: state.criterionIds.map(id => ({ id })) }), withoutFoundocs: normalizeProbe(state.probes.without_foundocs, { criteria: state.criterionIds.map(id => ({ id })) }) };
|
|
100
|
-
if (Buffer.byteLength(JSON.stringify(payload)) > 96 * 1024) throw new EffectError('report_too_large');
|
|
101
|
-
// This outbox has report fields only: never snapshot bytes, delivered context, API keys or raw transcript.
|
|
102
|
-
if (!state.recovered) state.settlementExpiresAt = new Date(Math.max(Date.now(), ...Object.values(state.probes).map(p => Date.parse(p.finishedAt ?? p.startedAt)).filter(Number.isFinite)) + 86400000).toISOString();
|
|
103
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
104
|
-
await saveJson(join(dir, 'outbox.json'), { payload }, true);
|
|
105
|
-
return this.flush(state.taskId);
|
|
106
|
-
}
|
|
107
|
-
async run({ taskId, retrievalIds }) {
|
|
108
|
-
if (!Array.isArray(retrievalIds) || !retrievalIds.every(v => UUID.test(v))) throw new EffectError('invalid_retrieval_ids');
|
|
109
|
-
const dir = this.path(taskId); let state = await this.state(taskId);
|
|
110
|
-
if (!state.prepared) throw new EffectError('missing_preparation');
|
|
111
|
-
if (state.policy.enabled !== true) return { status: 'skipped', reason: 'disabled' };
|
|
112
|
-
if (state.workingModel?.modelSource !== 'working_session') return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
113
|
-
const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
114
|
-
if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
|
|
115
|
-
const lock = join(dir, 'run-lock.json');
|
|
116
|
-
try { await saveJson(lock, { pid: process.pid, attemptId: randomUUID() }, true); }
|
|
117
|
-
catch (e) {
|
|
118
|
-
if (e.code !== 'EEXIST') throw e;
|
|
119
|
-
const owner = await readJson(lock);
|
|
120
|
-
let alive = true; try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
|
|
121
|
-
// Existing owner (or PID reuse) is conservatively treated as active.
|
|
122
|
-
if (alive) return { status: 'skipped', reason: 'duplicate_task' };
|
|
123
|
-
const pending = await this.flush(taskId);
|
|
124
|
-
if (pending.status !== 'nothing_pending') return pending;
|
|
125
|
-
if (state.reservation && state.probes) {
|
|
126
|
-
state.recovered = true;
|
|
127
|
-
for (const p of Object.values(state.probes)) if (p.startedAt && !p.finishedAt) { p.status = 'failed'; p.finishedAt = new Date().toISOString(); }
|
|
128
|
-
return this.report(state, dir);
|
|
129
|
-
}
|
|
130
|
-
return { status: 'skipped', reason: 'duplicate_task' }; // Never recreate an uncertain reservation/spawn.
|
|
131
|
-
}
|
|
132
|
-
const controller = new AbortController();
|
|
133
|
-
const abort = () => controller.abort();
|
|
134
|
-
process.once('SIGINT', abort); process.once('SIGTERM', abort);
|
|
135
|
-
let purging = Promise.resolve();
|
|
136
|
-
const expiration = setTimeout(() => { controller.abort(); purging = purgeRaw(dir, state); }, Math.max(1, Date.parse(state.expiresAt) - Date.now()));
|
|
137
|
-
let stopped = false;
|
|
138
|
-
try {
|
|
139
|
-
if (state.rawExpired) throw new EffectError('expired_preparation');
|
|
140
|
-
const version = await this.check({ runner: state.policy.runner });
|
|
141
|
-
if (version !== state.runnerVersion || version !== (state.policy.runner === CODEX_RUNNER ? CODEX_VERSION : CLI_VERSION)) throw new EffectError('unsupported_runner');
|
|
142
|
-
const { sha256: ignored, ...manifest } = state.snapshot;
|
|
143
|
-
if (hash(manifest) !== state.snapshot.sha256 || hash(state.brief) !== state.briefSha256) throw new EffectError('unsafe_snapshot');
|
|
144
|
-
state.reserveInput = { requestId: randomUUID(), preparationId: state.prepared.id, retrievalIds: [...new Set(retrievalIds)] };
|
|
145
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
146
|
-
const reserved = await this.remote.call('reserve_effect_measurement', state.reserveInput);
|
|
147
|
-
if (reserved.status !== 'reserved') return reserved;
|
|
148
|
-
state.reservation = reserved.reservation;
|
|
149
|
-
if (state.reservation.policy.revision !== state.prepared.policyRevision || hash(state.reservation.policy) !== hash(state.policy)) throw new EffectError('policy_changed');
|
|
150
|
-
state.probes = Object.fromEntries(['with_foundocs', 'without_foundocs'].map(arm => [arm, this.baseProbe(state, arm)]));
|
|
151
|
-
state.settlementExpiresAt = crashSettlementDeadline(state.policy);
|
|
152
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
153
|
-
const control = async (action, arm, probe) => {
|
|
154
|
-
const args = { requestId: randomUUID(), runId: state.reservation.runId, leaseToken: state.reservation.leaseToken, policyRevision: state.policy.revision, action, ...(arm ? { arm } : {}), ...(probe ? { probe } : {}) };
|
|
155
|
-
if (action === 'start_arm') { state.lastStart = args; await saveJson(join(dir, 'state.json'), state); }
|
|
156
|
-
try { const result = await this.remote.call('control_effect_measurement', args); if (result.action !== 'continue' || result.policyRevision !== state.policy.revision) stopped = true; }
|
|
157
|
-
catch { stopped = true; }
|
|
158
|
-
return !stopped;
|
|
159
|
-
};
|
|
160
|
-
const first = state.reservation.firstArm;
|
|
161
|
-
if (!['with_foundocs', 'without_foundocs'].includes(first)) throw new EffectError('invalid_response');
|
|
162
|
-
for (const arm of [first, first === 'with_foundocs' ? 'without_foundocs' : 'with_foundocs']) {
|
|
163
|
-
if (stopped || controller.signal.aborted) break;
|
|
164
|
-
const cwd = join(dir, arm);
|
|
165
|
-
await copySnapshot(join(dir, 'snapshot'), cwd, state.snapshot);
|
|
166
|
-
// Durable consumed marker BEFORE start_arm request: even a lost grant must not re-spawn.
|
|
167
|
-
await saveJson(join(dir, `${arm}.consumed.json`), { consumedAt: new Date().toISOString() }, true);
|
|
168
|
-
if (!(await control('start_arm', arm)) || controller.signal.aborted) break;
|
|
169
|
-
const probe = state.probes[arm]; probe.startedAt = new Date().toISOString(); probe.status = 'failed';
|
|
170
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
171
|
-
state.probes[arm] = await this.probe({ cwd, brief: state.brief, snapshot: state.snapshot, context: arm === 'with_foundocs' ? state.reservation.deliveredContext : [], policy: { ...state.policy, ...(state.workingModel.reasoningEffort ? { reasoningEffort: state.workingModel.reasoningEffort } : {}) }, probe, signal: controller.signal, heartbeat: () => control('heartbeat'), observe: async observation => { probe.observation = observation; state.settlementExpiresAt = crashSettlementDeadline(state.policy); await saveJson(join(dir, 'state.json'), state); } });
|
|
172
|
-
state.probes[arm] = normalizeProbe(state.probes[arm], { criteria: state.criterionIds.map(id => ({ id })) });
|
|
173
|
-
await saveJson(join(dir, 'state.json'), state);
|
|
174
|
-
if (!(await control('heartbeat', undefined, state.probes[arm]))) break;
|
|
175
|
-
}
|
|
176
|
-
await purging;
|
|
177
|
-
return await this.report(state, dir);
|
|
178
|
-
} catch (e) {
|
|
179
|
-
if (state.reservation && state.probes) {
|
|
180
|
-
for (const p of Object.values(state.probes)) if (p.startedAt && !p.finishedAt) { p.status = 'failed'; p.finishedAt = new Date().toISOString(); }
|
|
181
|
-
await purging;
|
|
182
|
-
return await this.report(state, dir);
|
|
183
|
-
}
|
|
184
|
-
throw e;
|
|
185
|
-
} finally { clearTimeout(expiration); process.removeListener('SIGINT', abort); process.removeListener('SIGTERM', abort); }
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
export async function measure(action, rootPath, input) {
|
|
189
|
-
const installation = await measurementInstallation(rootPath);
|
|
190
|
-
await cleanExpired(installation.base);
|
|
191
|
-
if (action === 'configure' || action === 'status') {
|
|
192
|
-
const { saveAutomaticConsent, readAutomaticConsent, automaticReadiness } = await import('./effect-config.mjs');
|
|
193
|
-
if (action === 'configure') return saveAutomaticConsent(dirname(installation.base), input);
|
|
194
|
-
return automaticReadiness({ config: await readAutomaticConsent(dirname(installation.base)),
|
|
195
|
-
checkCli: () => installation.manifest.client === 'codex' ? codexCapabilities() : capabilities(),
|
|
196
|
-
identify: () => workingSessionModel(input.host, installation.root),
|
|
197
|
-
checkConnection: async () => { const remote = await connectEffectRemote(installation.manifest); try { await remote.call('get_effect_measurement_policy', {}); } finally { await remote.close(); } },
|
|
198
|
-
});
|
|
199
|
-
}
|
|
200
|
-
if (action === 'prepare' && input.policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
|
|
201
|
-
const remote = await connectEffectRemote(installation.manifest);
|
|
202
|
-
try {
|
|
203
|
-
const coordinator = new EffectCoordinator({ ...installation, remote });
|
|
204
|
-
if (action === 'prepare') return await coordinator.prepare(input);
|
|
205
|
-
if (action === 'run') return await coordinator.run(input);
|
|
206
|
-
if (action === 'flush') return await coordinator.flush(input.taskId);
|
|
207
|
-
throw new EffectError('invalid_command');
|
|
208
|
-
} finally { await remote.close(); }
|
|
209
|
-
}
|