@foundocs/foundocs-setup 0.3.16 → 0.3.19
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 +73 -1
- package/dist/bridge.mjs +319 -61
- package/package.json +3 -3
- package/skills/foundocs/SKILL.md +5 -1
- package/skills/foundocs/references/dreaming.md +11 -3
- package/skills/foundocs/references/effect-measurement.md +5 -3
- package/skills/foundocs/scripts/episode-checkpoint.mjs +207 -0
- package/skills/foundocs/scripts/session-start.mjs +17 -5
- package/skills/foundocs-capture-episode/SKILL.md +22 -0
- package/skills/foundocs-capture-episode/references/capture.md +60 -0
- package/src/bridge.mjs +49 -4
- package/src/cli.mjs +4 -4
- package/src/effect-codex-tools.mjs +41 -0
- package/src/effect-codex-worker.mjs +112 -0
- package/src/effect-codex.mjs +45 -0
- package/src/effect-host.mjs +86 -0
- package/src/effect-runner.mjs +13 -3
- package/src/effect-storage.mjs +1 -1
- package/src/effect.mjs +18 -10
- package/src/setup.mjs +80 -24
- package/src/skill-assets.mjs +3 -1
- package/templates/knowledge-policy.md +1 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// Non-model supervisor. Only normalized observations leave this process.
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { mkdtemp, mkdir, open, writeFile, rm } from 'node:fs/promises';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { join, dirname } from 'node:path';
|
|
6
|
+
import { CODEX_CONFIG, CODEX_TOOLS, codexUsage } from './effect-codex.mjs';
|
|
7
|
+
import { snapshotTool } from './effect-codex-tools.mjs';
|
|
8
|
+
import { SYSTEM, missingObservation } from './effect-core.mjs';
|
|
9
|
+
const policy = JSON.parse(process.argv[2]);
|
|
10
|
+
let child, temporary, stopping = false, closed = false, input = '', line = '', threadId, turnId, output = null, usage = null, steps = 0, calls = 0, sequence = 0;
|
|
11
|
+
const pending = new Map(), timers = [];
|
|
12
|
+
const emit = value => process.stdout.write(JSON.stringify(value) + '\n');
|
|
13
|
+
const observation = complete => usage ? { completeness: complete ? 'complete' : 'partial', source: complete ? 'codex_turn_completed' : 'codex_token_usage', usage, estimatedCostUsd: null, models: [policy.model] } : missingObservation();
|
|
14
|
+
function signal(name) { if (!child?.pid || closed) return; try { process.kill(-child.pid, name); } catch { child.kill(name); } }
|
|
15
|
+
function stop() {
|
|
16
|
+
if (stopping) return; stopping = true;
|
|
17
|
+
if (!child) return;
|
|
18
|
+
signal('SIGINT'); timers.push(setTimeout(() => signal('SIGTERM'), 3000), setTimeout(() => signal('SIGKILL'), 5000));
|
|
19
|
+
}
|
|
20
|
+
process.on('disconnect', stop);
|
|
21
|
+
process.on('message', message => { if (message?.type === 'stop') stop(); });
|
|
22
|
+
for (const name of ['SIGINT', 'SIGTERM']) process.on(name, stop);
|
|
23
|
+
process.stdout.on('error', stop);
|
|
24
|
+
const send = value => { if (!stopping && !closed) child.stdin.write(JSON.stringify(value) + '\n'); };
|
|
25
|
+
const call = (method, params) => new Promise((resolve, reject) => {
|
|
26
|
+
const id = ++sequence; pending.set(id, { resolve, reject }); send({ id, method, params });
|
|
27
|
+
});
|
|
28
|
+
async function accept(event, payload) {
|
|
29
|
+
if (event.id !== undefined && pending.has(event.id)) {
|
|
30
|
+
const p = pending.get(event.id); pending.delete(event.id); if (event.error) p.reject(new Error('codex request failed')); else p.resolve(event.result); return;
|
|
31
|
+
}
|
|
32
|
+
const p = event.params;
|
|
33
|
+
if (!p || stopping) return;
|
|
34
|
+
if (p.threadId && p.threadId !== threadId) throw new Error('unexpected thread');
|
|
35
|
+
if (event.method === 'turn/started') { if (turnId && turnId !== p.turn.id) throw new Error('unexpected turn'); turnId = p.turn.id; }
|
|
36
|
+
if (p.turnId && turnId && p.turnId !== turnId) throw new Error('unexpected turn');
|
|
37
|
+
if (event.method === 'thread/settings/updated') {
|
|
38
|
+
const settings = p.threadSettings;
|
|
39
|
+
if (!settings || settings.model !== policy.model || settings.modelProvider !== 'openai' || settings.approvalPolicy !== 'never' || settings.sandboxPolicy?.type !== 'readOnly' || settings.sandboxPolicy.networkAccess !== false) throw new Error('settings changed');
|
|
40
|
+
}
|
|
41
|
+
if (event.method === 'item/tool/call') {
|
|
42
|
+
if (!CODEX_TOOLS.some(t => t.name === p.tool) || p.namespace || ++calls > policy.perProbeMaxTurns) throw new Error('tool limit');
|
|
43
|
+
let text, success = true;
|
|
44
|
+
try { text = await snapshotTool(p.tool, p.arguments, process.cwd(), payload.snapshotFiles); }
|
|
45
|
+
catch { text = 'Source unavailable: only frozen snapshot paths and supported read operations are allowed.'; success = false; }
|
|
46
|
+
send({ id: event.id, result: { success, contentItems: [{ type: 'inputText', text }] } });
|
|
47
|
+
} else if (event.id !== undefined) {
|
|
48
|
+
// No approvals, network, MCP, delegation or user interaction in probes.
|
|
49
|
+
throw new Error('unexpected server request');
|
|
50
|
+
}
|
|
51
|
+
if (event.method === 'item/started' && !['userMessage', 'agentMessage', 'reasoning', 'dynamicToolCall'].includes(p.item?.type)) throw new Error('unexpected tool');
|
|
52
|
+
if (event.method === 'item/completed' && p.item?.type === 'agentMessage') {
|
|
53
|
+
try { output = Buffer.byteLength(p.item.text) <= 40 * 1024 ? JSON.parse(p.item.text) : null; } catch { output = null; }
|
|
54
|
+
}
|
|
55
|
+
if (event.method === 'thread/tokenUsage/updated') {
|
|
56
|
+
const next = codexUsage(p.tokenUsage?.total);
|
|
57
|
+
if (!next || (usage && next.totalTokens < usage.totalTokens)) throw new Error('invalid usage');
|
|
58
|
+
usage = next; steps++; emit({ type: 'effect_observation', observation: observation(false) });
|
|
59
|
+
if (steps >= policy.perProbeMaxTurns && output === null) throw new Error('turn limit');
|
|
60
|
+
}
|
|
61
|
+
if (event.method === 'turn/completed') {
|
|
62
|
+
emit({ type: 'effect_observation', observation: observation(p.turn.status === 'completed') });
|
|
63
|
+
emit({ type: 'effect_result', success: p.turn.status === 'completed', output });
|
|
64
|
+
stop();
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
async function run(payload) {
|
|
68
|
+
try {
|
|
69
|
+
temporary = await mkdtemp(join(dirname(process.cwd()), 'codex-runtime-'));
|
|
70
|
+
const home = join(temporary, 'home'), empty = join(temporary, 'empty');
|
|
71
|
+
await mkdir(home, { mode: 0o700 }); await mkdir(empty, { mode: 0o700 });
|
|
72
|
+
if (!process.env.OPENAI_API_KEY) {
|
|
73
|
+
const auth = await open(join(process.env.CODEX_HOME || join(process.env.HOME, '.codex'), 'auth.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
74
|
+
try {
|
|
75
|
+
const stat = await auth.stat(); if (!stat.isFile() || stat.size > 1024 * 1024) throw new Error('auth unavailable');
|
|
76
|
+
await writeFile(join(home, 'auth.json'), await auth.readFile(), { mode: 0o600 });
|
|
77
|
+
} finally { await auth.close(); }
|
|
78
|
+
}
|
|
79
|
+
await writeFile(join(home, 'config.toml'), CODEX_CONFIG, { mode: 0o600 });
|
|
80
|
+
if (stopping || !process.connected) return;
|
|
81
|
+
// No source files, personal instructions, MCP configuration or skills in the CLI's HOME/cwd.
|
|
82
|
+
child = spawn('codex', ['app-server'], { cwd: empty, env: { PATH: process.env.PATH, HOME: temporary, CODEX_HOME: home, ...(process.env.OPENAI_API_KEY ? { OPENAI_API_KEY: process.env.OPENAI_API_KEY } : {}) }, detached: true, stdio: ['pipe', 'pipe', 'ignore'] });
|
|
83
|
+
child.stdin.on('error', stop);
|
|
84
|
+
const finished = new Promise(resolve => { child.once('error', resolve); child.once('close', () => { closed = true; for (const p of pending.values()) p.reject(new Error('closed')); pending.clear(); resolve(); }); });
|
|
85
|
+
let queue = Promise.resolve();
|
|
86
|
+
child.stdout.setEncoding('utf8'); child.stdout.on('data', chunk => {
|
|
87
|
+
line += chunk; let i;
|
|
88
|
+
while ((i = line.indexOf('\n')) !== -1) {
|
|
89
|
+
const entry = line.slice(0, i); line = line.slice(i + 1);
|
|
90
|
+
if (entry) { try { const e = JSON.parse(entry); queue = queue.then(() => accept(e, payload)).catch(() => { emit({ type: 'effect_invalid' }); stop(); }); } catch { stop(); } }
|
|
91
|
+
}
|
|
92
|
+
if (Buffer.byteLength(line) > 4 * 1024 * 1024) { line = ''; stop(); }
|
|
93
|
+
});
|
|
94
|
+
timers.push(setTimeout(stop, policy.perProbeTimeoutMs));
|
|
95
|
+
try {
|
|
96
|
+
await call('initialize', { clientInfo: { name: 'foundocs_effect', version: '1' }, capabilities: { experimentalApi: true } }); send({ method: 'initialized' });
|
|
97
|
+
const t = await call('thread/start', { model: policy.model, modelProvider: 'openai', allowProviderModelFallback: false, cwd: empty, environments: [], ephemeral: true, approvalPolicy: 'never', sandbox: 'read-only', baseInstructions: SYSTEM, dynamicTools: CODEX_TOOLS });
|
|
98
|
+
if (t.model !== policy.model || t.modelProvider !== 'openai' || t.thread.ephemeral !== true || !Array.isArray(t.thread.environments) || t.thread.environments.length || !Array.isArray(t.instructionSources) || t.instructionSources.length || t.approvalPolicy !== 'never' || t.sandbox.type !== 'readOnly' || t.sandbox.networkAccess !== false) throw new Error('isolation unavailable');
|
|
99
|
+
threadId = t.thread.id;
|
|
100
|
+
emit({ type: 'effect_init', model: t.model, verified: true });
|
|
101
|
+
const prompt = { ...payload, snapshotFiles: payload.snapshotFiles.map(f => f.path) };
|
|
102
|
+
await call('turn/start', { threadId, model: policy.model, ...(policy.reasoningEffort ? { effort: policy.reasoningEffort } : {}), input: [{ type: 'text', text: JSON.stringify(prompt) }] });
|
|
103
|
+
} catch { stop(); }
|
|
104
|
+
await finished; await queue;
|
|
105
|
+
} finally { timers.forEach(clearTimeout); if (temporary) await rm(temporary, { recursive: true, force: true }); }
|
|
106
|
+
}
|
|
107
|
+
process.stdin.setEncoding('utf8');
|
|
108
|
+
process.stdin.on('data', chunk => { input += chunk; if (Buffer.byteLength(input) > 2 * 1024 * 1024) stop(); });
|
|
109
|
+
process.stdin.on('end', async () => {
|
|
110
|
+
try { if (!stopping) await run(JSON.parse(input)); } catch { stop(); }
|
|
111
|
+
process.exit(0);
|
|
112
|
+
});
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { execFile, fork } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { EffectError, missingObservation, SYSTEM } from './effect-core.mjs';
|
|
4
|
+
|
|
5
|
+
export const CODEX_RUNNER = 'codex_read_tools_v1';
|
|
6
|
+
export const CODEX_VERSION = '0.166.0';
|
|
7
|
+
export const CODEX_FEATURES = ['shell_tool', 'apps', 'plugins', 'multi_agent', 'multi_agent_v2', 'view_image', 'browser_use', 'browser_use_external', 'computer_use', 'in_app_browser', 'code_mode', 'skill_search', 'shell_snapshot', 'sleep_tool'];
|
|
8
|
+
export const CODEX_CONFIG = `web_search = "disabled"\nproject_doc_max_bytes = 0\n[features]\n${CODEX_FEATURES.map(k => `${k} = false`).join('\n')}\n`;
|
|
9
|
+
export const CODEX_TOOLS = [{
|
|
10
|
+
type: 'function', name: 'Read', description: 'Read lines from a frozen source file. Only exact snapshot paths are accepted.',
|
|
11
|
+
inputSchema: { type: 'object', properties: { path: { type: 'string' }, offset: { type: 'integer', minimum: 1 }, limit: { type: 'integer', minimum: 1, maximum: 200 } }, required: ['path', 'offset', 'limit'], additionalProperties: false },
|
|
12
|
+
}, {
|
|
13
|
+
type: 'function', name: 'Grep', description: 'Search literal text in frozen sources. Returns at most 100 matching lines.',
|
|
14
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, path: { type: 'string', description: 'Exact snapshot path, or empty string for all snapshot files.' } }, required: ['query', 'path'], additionalProperties: false },
|
|
15
|
+
}, {
|
|
16
|
+
type: 'function', name: 'Glob', description: 'List frozen source paths containing a literal substring (empty string lists all).',
|
|
17
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false },
|
|
18
|
+
}];
|
|
19
|
+
export const codexToolPolicy = policy => ({ system: SYSTEM, tools: CODEX_TOOLS, config: CODEX_CONFIG, environments: [], model: policy.model, reasoningEffort: policy.reasoningEffort ?? null, timeoutMs: policy.perProbeTimeoutMs, maxTurns: policy.perProbeMaxTurns, outputVersion: 1 });
|
|
20
|
+
export function codexEnvironment(env = process.env) {
|
|
21
|
+
return Object.fromEntries(['PATH', 'HOME', 'USER', 'LOGNAME', 'TMPDIR', 'LANG', 'LC_ALL', 'CODEX_HOME', 'OPENAI_API_KEY'].filter(k => typeof env[k] === 'string').map(k => [k, env[k]]));
|
|
22
|
+
}
|
|
23
|
+
export async function codexCapabilities({ execute = promisify(execFile), env = codexEnvironment(), platform = process.platform } = {}) {
|
|
24
|
+
if (platform !== 'darwin') throw new EffectError('unsupported_runner');
|
|
25
|
+
try {
|
|
26
|
+
if ((await execute('codex', ['--version'], { env, timeout: 10000 })).stdout.trim() !== `codex-cli ${CODEX_VERSION}`) throw new Error();
|
|
27
|
+
const auth = await execute('codex', ['login', 'status'], { env, timeout: 10000 });
|
|
28
|
+
if (!/Logged in/.test(auth.stdout + auth.stderr)) throw new Error();
|
|
29
|
+
return CODEX_VERSION;
|
|
30
|
+
} catch { throw new EffectError('unsupported_runner', 'Install and authenticate Codex CLI 0.166.0; no fallback model is used.'); }
|
|
31
|
+
}
|
|
32
|
+
export function spawnCodex(_file, _args, options) {
|
|
33
|
+
const child = fork(new URL('./effect-codex-worker.mjs', import.meta.url), [JSON.stringify(options.effectPolicy)], { cwd: options.cwd, env: codexEnvironment(), execArgv: [], stdio: ['pipe', 'pipe', 'pipe', 'ipc'] });
|
|
34
|
+
child.effectSupervised = true;
|
|
35
|
+
return child;
|
|
36
|
+
}
|
|
37
|
+
export class CodexObservation {
|
|
38
|
+
observed = missingObservation();
|
|
39
|
+
accept(event) { if (event.type === 'effect_observation') this.observed = event.observation; }
|
|
40
|
+
value() { return this.observed; }
|
|
41
|
+
}
|
|
42
|
+
export function codexUsage(value) {
|
|
43
|
+
if (!value || !['inputTokens', 'outputTokens', 'cachedInputTokens'].every(k => Number.isSafeInteger(value[k]) && value[k] >= 0) || value.cachedInputTokens > value.inputTokens || !Number.isSafeInteger(value.inputTokens + value.outputTokens)) return null;
|
|
44
|
+
return { inputTokens: value.inputTokens, outputTokens: value.outputTokens, cacheReadInputTokens: value.cachedInputTokens, cacheCreationInputTokens: null, totalTokens: value.inputTokens + value.outputTokens };
|
|
45
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { open, realpath, readdir } from 'node:fs/promises';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { basename, isAbsolute, relative, join } from 'node:path';
|
|
4
|
+
import { UUID } from './effect-core.mjs';
|
|
5
|
+
|
|
6
|
+
const exactModel = /^claude-(haiku|sonnet|opus)-\d+(?:-\d+)*$/;
|
|
7
|
+
const maxTail = 1024 * 1024;
|
|
8
|
+
const within = (root, path) => { const r = relative(root, path); return r === '' || (!r.startsWith('..') && !isAbsolute(r)); };
|
|
9
|
+
|
|
10
|
+
/** Read only model metadata from the current host transcript; never return/persist conversation text. */
|
|
11
|
+
export async function workingSessionModel(host, root, now = Date.now()) {
|
|
12
|
+
if (host?.client === 'codex' || (!host && process.env.CODEX_THREAD_ID)) return codexSessionModel(host ?? { client: 'codex', sessionId: process.env.CODEX_THREAD_ID }, root, now);
|
|
13
|
+
if (!host || host.client !== 'claude_code') return { status: 'skipped', reason: host?.client ? 'unsupported_runner' : 'working_model_unavailable' };
|
|
14
|
+
if (typeof host.sessionId !== 'string' || !UUID.test(host.sessionId) || typeof host.transcriptPath !== 'string' || !isAbsolute(host.transcriptPath) || basename(host.transcriptPath) !== `${host.sessionId}.jsonl`) return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
15
|
+
let file;
|
|
16
|
+
try {
|
|
17
|
+
file = await open(host.transcriptPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
18
|
+
const stat = await file.stat();
|
|
19
|
+
if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
|
|
20
|
+
const start = Math.max(0, stat.size - maxTail), buffer = Buffer.alloc(Math.min(stat.size, maxTail));
|
|
21
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
|
|
22
|
+
const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n');
|
|
23
|
+
if (start) lines.shift(); // Never parse a truncated leading record.
|
|
24
|
+
for (const line of lines.reverse()) {
|
|
25
|
+
if (!line.trim()) continue;
|
|
26
|
+
let event; try { event = JSON.parse(line); } catch { throw new Error(); } // An incomplete latest record must not select an older model.
|
|
27
|
+
if (event.type !== 'assistant' || event.isSidechain || event.parent_tool_use_id) continue;
|
|
28
|
+
// Stop at the latest assistant record; never fall back to an older/different model.
|
|
29
|
+
if (event.sessionId !== host.sessionId || typeof event.cwd !== 'string' || !within(await realpath(root), await realpath(event.cwd))) throw new Error();
|
|
30
|
+
const timestamp = Date.parse(event.timestamp);
|
|
31
|
+
if (!Number.isFinite(timestamp) || now - timestamp > 5 * 60_000 || timestamp > now + 60_000 || !exactModel.test(event.message?.model ?? '')) throw new Error();
|
|
32
|
+
return { status: 'identified', model: event.message.model, modelSource: 'working_session' };
|
|
33
|
+
}
|
|
34
|
+
} catch { /* Missing, stale, inaccessible or unsupported metadata never chooses a default. */ }
|
|
35
|
+
finally { await file?.close(); }
|
|
36
|
+
return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
/** Resolve only this host's exact thread ID, never another thread's contents. */
|
|
41
|
+
export async function codexSessionModel(host, root, now = Date.now(), env = process.env) {
|
|
42
|
+
if (!UUID.test(host.sessionId ?? '') || (env.CODEX_THREAD_ID && env.CODEX_THREAD_ID !== host.sessionId)) return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
43
|
+
let file;
|
|
44
|
+
try {
|
|
45
|
+
let path = host.transcriptPath;
|
|
46
|
+
if (!path) {
|
|
47
|
+
const base = join(env.CODEX_HOME || join(env.HOME, '.codex'), 'sessions');
|
|
48
|
+
const matches = [];
|
|
49
|
+
async function find(dir, depth = 0) {
|
|
50
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
51
|
+
if (entry.isDirectory() && depth < 3 && /^\d{2,4}$/.test(entry.name)) await find(join(dir, entry.name), depth + 1);
|
|
52
|
+
else if (entry.isFile() && entry.name.endsWith(`-${host.sessionId}.jsonl`)) matches.push(join(dir, entry.name));
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
await find(base); if (matches.length !== 1) throw new Error(); path = matches[0];
|
|
56
|
+
}
|
|
57
|
+
if (typeof path !== 'string' || !isAbsolute(path) || !basename(path).endsWith(`-${host.sessionId}.jsonl`)) throw new Error();
|
|
58
|
+
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
59
|
+
const stat = await file.stat();
|
|
60
|
+
if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
|
|
61
|
+
// Identity is in the first record. A long active Codex turn can emit several
|
|
62
|
+
// MiB after turn_context; inspect a bounded 16 MiB tail, returning metadata only.
|
|
63
|
+
const head = Buffer.alloc(Math.min(stat.size, 64 * 1024)); await file.read(head, 0, head.length, 0);
|
|
64
|
+
const meta = JSON.parse(head.toString('utf8').split('\n')[0]);
|
|
65
|
+
if (meta.type !== 'session_meta' || meta.payload.id !== host.sessionId || meta.payload.model_provider !== 'openai') throw new Error();
|
|
66
|
+
const canonicalRoot = await realpath(root);
|
|
67
|
+
if (!within(canonicalRoot, await realpath(meta.payload.cwd))) throw new Error();
|
|
68
|
+
const start = Math.max(0, stat.size - 16 * maxTail), buffer = Buffer.alloc(Math.min(stat.size, 16 * maxTail));
|
|
69
|
+
const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
|
|
70
|
+
const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); if (start) lines.shift();
|
|
71
|
+
for (const line of lines.reverse()) {
|
|
72
|
+
if (!line.trim()) continue;
|
|
73
|
+
const event = JSON.parse(line);
|
|
74
|
+
if (event.type !== 'turn_context') continue;
|
|
75
|
+
const p = event.payload;
|
|
76
|
+
if (!within(canonicalRoot, await realpath(p.cwd)) || !/^gpt-\d[\w.-]{0,150}$/.test(p.model) || /(?:latest|auto)$/.test(p.model)) throw new Error();
|
|
77
|
+
const timestamp = Date.parse(event.timestamp);
|
|
78
|
+
if (!Number.isFinite(timestamp) || timestamp > now + 60_000) throw new Error();
|
|
79
|
+
// A long active turn can outlive five minutes. Freshness is the current
|
|
80
|
+
// transcript's mtime; never select an older turn after malformed metadata.
|
|
81
|
+
return { status: 'identified', model: p.model, modelSource: 'working_session', runner: 'codex_read_tools_v1', ...(typeof p.effort === 'string' && ['none','minimal','low','medium','high','xhigh','max','ultra'].includes(p.effort) ? { reasoningEffort: p.effort } : {}) };
|
|
82
|
+
}
|
|
83
|
+
} catch { /* Never infer a model from config/defaults or another thread. */ }
|
|
84
|
+
finally { await file?.close(); }
|
|
85
|
+
return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
86
|
+
}
|
package/src/effect-runner.mjs
CHANGED
|
@@ -4,6 +4,8 @@ import { readFile } from 'node:fs/promises';
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { CLI_VERSION, BASE_ARGS, SYSTEM, Observation, EffectError, normalizeProbe, validOutput } from './effect-core.mjs';
|
|
6
6
|
|
|
7
|
+
import { CODEX_RUNNER, CodexObservation, spawnCodex } from './effect-codex.mjs';
|
|
8
|
+
|
|
7
9
|
const exec = promisify(execFile);
|
|
8
10
|
export function providerEnvironment(env = process.env) {
|
|
9
11
|
// No NODE_OPTIONS, shell hooks, provider routing overrides, or application keys.
|
|
@@ -45,7 +47,8 @@ export function spawnSupervised(_file, args, options) {
|
|
|
45
47
|
}
|
|
46
48
|
export async function runProbe({ cwd, brief, snapshot, context, policy, probe, heartbeat, observe, signal, spawnChild = spawnSupervised, heartbeatMs = 5000, grace = [3000, 2000] }) {
|
|
47
49
|
if (signal?.aborted) return { ...probe, status: 'not_started', startedAt: null, finishedAt: null };
|
|
48
|
-
const
|
|
50
|
+
const codex = policy.runner === CODEX_RUNNER;
|
|
51
|
+
const observation = codex ? new CodexObservation() : new Observation();
|
|
49
52
|
let child, line = '', init = false, invalid = false, output = null, resultSuccess = false, stopping = false, closed = false, status = null, heartbeating = false;
|
|
50
53
|
const timers = [];
|
|
51
54
|
const kill = sig => { if (closed || !child?.pid) return; try { process.kill(-child.pid, sig); } catch { child.kill(sig); } };
|
|
@@ -57,6 +60,13 @@ export async function runProbe({ cwd, brief, snapshot, context, policy, probe, h
|
|
|
57
60
|
}
|
|
58
61
|
async function accept(event) {
|
|
59
62
|
observation.accept(event);
|
|
63
|
+
if (codex) {
|
|
64
|
+
if (event.type === 'effect_invalid') { invalid = true; stop('failed'); }
|
|
65
|
+
if (event.type === 'effect_init') { init = event.verified === true && event.model === policy.model; if (!init) { invalid = true; stop('failed'); } }
|
|
66
|
+
if (event.type === 'effect_result') { resultSuccess = event.success === true; output = event.output; }
|
|
67
|
+
if (event.type === 'effect_observation') await observe?.(observation.value());
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
60
70
|
if (event.type === 'system' && event.subtype === 'init') { init = verifiedInit(event, policy.model); if (!init) { invalid = true; stop('failed'); } }
|
|
61
71
|
if (event.type === 'assistant') {
|
|
62
72
|
for (const b of event.message?.content ?? []) if (b.type === 'tool_use' && !['Read', 'Glob', 'Grep'].includes(b.name)) { invalid = true; stop('failed'); }
|
|
@@ -81,7 +91,7 @@ export async function runProbe({ cwd, brief, snapshot, context, policy, probe, h
|
|
|
81
91
|
let exit;
|
|
82
92
|
try {
|
|
83
93
|
if (signal?.aborted) return { ...probe, status: 'not_started', startedAt: null, finishedAt: null };
|
|
84
|
-
child = spawnChild('claude', probeArguments(policy), { cwd, env: providerEnvironment(), detached: true, effectTimeoutMs: policy.perProbeTimeoutMs, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
94
|
+
child = (codex && spawnChild === spawnSupervised ? spawnCodex : spawnChild)(codex ? 'codex' : 'claude', codex ? [] : probeArguments(policy), { cwd, env: providerEnvironment(), detached: true, effectTimeoutMs: policy.perProbeTimeoutMs, effectPolicy: policy, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
85
95
|
child.stdout.setEncoding('utf8');
|
|
86
96
|
child.stdout.on('data', chunk => {
|
|
87
97
|
line += chunk;
|
|
@@ -91,7 +101,7 @@ export async function runProbe({ cwd, brief, snapshot, context, policy, probe, h
|
|
|
91
101
|
});
|
|
92
102
|
child.stderr.resume(); // Never retain raw provider errors or transcripts.
|
|
93
103
|
child.stdin.on('error', () => {});
|
|
94
|
-
child.stdin.end(JSON.stringify({ brief, snapshotFiles: snapshot.files.map(f => f.path), ...(context.length ? { deliveredContext: context } : {}) }));
|
|
104
|
+
child.stdin.end(JSON.stringify({ brief, snapshotFiles: codex ? snapshot.files : snapshot.files.map(f => f.path), ...(context.length ? { deliveredContext: context } : {}) }));
|
|
95
105
|
if (signal?.aborted) stop();
|
|
96
106
|
exit = await new Promise(resolve => { child.once('error', () => resolve(-1)); child.once('close', code => { closed = true; resolve(code); }); });
|
|
97
107
|
if (line.trim()) parseLine(line);
|
package/src/effect-storage.mjs
CHANGED
|
@@ -65,7 +65,7 @@ export async function purgeRaw(path, state) {
|
|
|
65
65
|
// Reread under the same lock as usage writes: cleanup never overwrites newer observations.
|
|
66
66
|
const latest = await readJson(file);
|
|
67
67
|
await writeJson(file, stripRaw(latest));
|
|
68
|
-
for (const name of ['snapshot', 'with_foundocs', 'without_foundocs']) await rm(join(path, name), { recursive: true, force: true });
|
|
68
|
+
for (const name of ['snapshot', 'with_foundocs', 'without_foundocs', ...(await readdir(path)).filter(name => name.startsWith('codex-runtime-'))]) await rm(join(path, name), { recursive: true, force: true });
|
|
69
69
|
});
|
|
70
70
|
}
|
|
71
71
|
export async function cleanExpired(base, now = Date.now()) {
|
package/src/effect.mjs
CHANGED
|
@@ -6,6 +6,8 @@ import { validateInstallation } from './runtime.mjs';
|
|
|
6
6
|
import { RUNNER, CLI_VERSION, UUID, EffectError, hash, missingObservation, normalizeProbe, toolPolicy, validateBrief } from './effect-core.mjs';
|
|
7
7
|
import { privateDir, readJson, saveJson, cleanExpired, purgeRaw, freezeSnapshot, copySnapshot } from './effect-storage.mjs';
|
|
8
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';
|
|
9
11
|
import { connectEffectRemote } from './effect-remote.mjs';
|
|
10
12
|
|
|
11
13
|
export async function measurementInstallation(rootPath, options = {}) {
|
|
@@ -21,7 +23,7 @@ export async function measurementInstallation(rootPath, options = {}) {
|
|
|
21
23
|
export const crashSettlementDeadline = (policy, now = Date.now()) => new Date(now + 2 * (policy.perProbeTimeoutMs + 5000) + 86400000).toISOString();
|
|
22
24
|
|
|
23
25
|
export class EffectCoordinator {
|
|
24
|
-
constructor({ root, base, remote, probe = runProbe, check = capabilities }) { Object.assign(this, { root, base, remote, probe, check }); }
|
|
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 }); }
|
|
25
27
|
async initialize() { await cleanExpired(this.base); }
|
|
26
28
|
path(taskId) { if (!UUID.test(taskId)) throw new EffectError('invalid_task_id'); return join(this.base, taskId); }
|
|
27
29
|
async state(taskId) {
|
|
@@ -30,24 +32,29 @@ export class EffectCoordinator {
|
|
|
30
32
|
if (Date.parse(s.settlementExpiresAt ?? s.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
|
|
31
33
|
return s;
|
|
32
34
|
}
|
|
33
|
-
async prepare({ policy, brief, allowlist, excludePaths = [] }) {
|
|
35
|
+
async prepare({ policy, brief, allowlist, excludePaths = [], host }) {
|
|
34
36
|
// Host fetched policy exactly once, before any exposure. OFF must not inspect/spawn CLI.
|
|
35
37
|
if (policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
|
|
36
|
-
if (policy?.enabled !== true || policy.runner
|
|
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;
|
|
37
42
|
validateBrief(brief);
|
|
38
43
|
const dir = this.path(brief.taskId); await privateDir(dir);
|
|
39
44
|
let state = await readJson(join(dir, 'state.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
40
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');
|
|
41
47
|
if (state.briefSha256 !== hash(brief) || state.sourceSelectionHash !== hash({ allowlist, excludePaths })) throw new EffectError('task_conflict');
|
|
42
48
|
if (Date.parse(state.expiresAt) <= Date.now()) throw new EffectError('expired_preparation');
|
|
43
49
|
if (state.prepared) return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
|
|
44
50
|
if (!state.prepareInput) throw new EffectError('incomplete_preparation', 'A prior snapshot attempt was interrupted. Do not recreate this task after exposure.');
|
|
45
51
|
} else {
|
|
46
|
-
|
|
47
|
-
|
|
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() };
|
|
48
55
|
await saveJson(join(dir, 'state.json'), state, true);
|
|
49
56
|
state.snapshot = await freezeSnapshot(this.root, join(dir, 'snapshot'), allowlist, excludePaths);
|
|
50
|
-
state.prepareInput = { requestId: randomUUID(), brief, briefSha256: state.briefSha256, snapshot: state.snapshot, runner
|
|
57
|
+
state.prepareInput = { requestId: randomUUID(), brief, briefSha256: state.briefSha256, snapshot: state.snapshot, runner, runnerVersion, model: workingModel.model, modelSource: workingModel.modelSource };
|
|
51
58
|
await saveJson(join(dir, 'state.json'), state);
|
|
52
59
|
}
|
|
53
60
|
state.prepared = await this.remote.call('prepare_effect_measurement', state.prepareInput);
|
|
@@ -56,7 +63,7 @@ export class EffectCoordinator {
|
|
|
56
63
|
return { status: 'prepared', ...state.prepared, effectPreparationId: state.prepared.id };
|
|
57
64
|
}
|
|
58
65
|
baseProbe(state, arm) {
|
|
59
|
-
return { arm, status: 'not_started', runner:
|
|
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 };
|
|
60
67
|
}
|
|
61
68
|
async flush(taskId) {
|
|
62
69
|
const dir = this.path(taskId); const state = await this.state(taskId);
|
|
@@ -102,6 +109,7 @@ export class EffectCoordinator {
|
|
|
102
109
|
const dir = this.path(taskId); let state = await this.state(taskId);
|
|
103
110
|
if (!state.prepared) throw new EffectError('missing_preparation');
|
|
104
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' };
|
|
105
113
|
const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
106
114
|
if (receipt) return { status: 'already_reported', requestId: receipt.requestId };
|
|
107
115
|
const lock = join(dir, 'run-lock.json');
|
|
@@ -129,8 +137,8 @@ export class EffectCoordinator {
|
|
|
129
137
|
let stopped = false;
|
|
130
138
|
try {
|
|
131
139
|
if (state.rawExpired) throw new EffectError('expired_preparation');
|
|
132
|
-
const version = await this.check();
|
|
133
|
-
if (version !== state.runnerVersion || version !== CLI_VERSION) throw new EffectError('unsupported_runner');
|
|
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');
|
|
134
142
|
const { sha256: ignored, ...manifest } = state.snapshot;
|
|
135
143
|
if (hash(manifest) !== state.snapshot.sha256 || hash(state.brief) !== state.briefSha256) throw new EffectError('unsafe_snapshot');
|
|
136
144
|
state.reserveInput = { requestId: randomUUID(), preparationId: state.prepared.id, retrievalIds: [...new Set(retrievalIds)] };
|
|
@@ -160,7 +168,7 @@ export class EffectCoordinator {
|
|
|
160
168
|
if (!(await control('start_arm', arm)) || controller.signal.aborted) break;
|
|
161
169
|
const probe = state.probes[arm]; probe.startedAt = new Date().toISOString(); probe.status = 'failed';
|
|
162
170
|
await saveJson(join(dir, 'state.json'), state);
|
|
163
|
-
state.probes[arm] = await this.probe({ cwd, brief: state.brief, snapshot: state.snapshot, context: arm === 'with_foundocs' ? state.reservation.deliveredContext : [], policy: state.policy, 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); } });
|
|
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); } });
|
|
164
172
|
state.probes[arm] = normalizeProbe(state.probes[arm], { criteria: state.criterionIds.map(id => ({ id })) });
|
|
165
173
|
await saveJson(join(dir, 'state.json'), state);
|
|
166
174
|
if (!(await control('heartbeat', undefined, state.probes[arm]))) break;
|
package/src/setup.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { readCredential, windowsPrivateAcl } from './auth.mjs';
|
|
|
12
12
|
import { legacy, legacyInstructions } from './legacy-compat.mjs';
|
|
13
13
|
import { knowledgePolicy, skillAssets } from './skill-assets.mjs';
|
|
14
14
|
import { newer } from '../skills/foundocs/scripts/check-update.mjs';
|
|
15
|
+
import { episodeDiagnostics } from '../skills/foundocs/scripts/episode-checkpoint.mjs';
|
|
15
16
|
|
|
16
17
|
const exec = promisify(execFile);
|
|
17
18
|
const PACKAGE_VERSION = JSON.parse(await readFile(new URL('../package.json', import.meta.url), 'utf8')).version;
|
|
@@ -64,7 +65,13 @@ export function helperCommand(args, platform = process.platform) {
|
|
|
64
65
|
// configured project at execution time, stop at Git boundaries, and guard its ID.
|
|
65
66
|
export function sessionHookCommand(client, projectId) {
|
|
66
67
|
const prefix = client === 'codex' ? '.agents' : '.claude';
|
|
67
|
-
const code = `const fs=require('node:fs'),p=require('node:path'),{spawnSync}=require('node:child_process');try{let r=fs.realpathSync(process.cwd());for(;;){const a=p.join(r,'foundocs.json'),b=p.join(r,'steerdocs.json');if(fs.existsSync(a)||fs.existsSync(b)){const c=JSON.parse(fs.readFileSync(fs.existsSync(a)?a:b,'utf8'));if(c.project_id!==${JSON.stringify(projectId)})break;spawnSync(process.execPath,[p.join(r,${JSON.stringify(prefix)},'skills/foundocs/scripts/session-start.mjs'),'--root',r],{cwd:r,stdio:['
|
|
68
|
+
const code = `const fs=require('node:fs'),p=require('node:path'),{spawnSync}=require('node:child_process');try{let r=fs.realpathSync(process.cwd());for(;;){const a=p.join(r,'foundocs.json'),b=p.join(r,'steerdocs.json');if(fs.existsSync(a)||fs.existsSync(b)){const c=JSON.parse(fs.readFileSync(fs.existsSync(a)?a:b,'utf8'));if(c.project_id!==${JSON.stringify(projectId)})break;spawnSync(process.execPath,[p.join(r,${JSON.stringify(prefix)},'skills/foundocs/scripts/session-start.mjs'),'--root',r],{cwd:r,stdio:['inherit','inherit','ignore'],timeout:55000});break;}if(fs.existsSync(p.join(r,'.git'))||p.dirname(r)===r)break;r=p.dirname(r);}}catch{}`;
|
|
69
|
+
return helperCommand(['node', '-e', code]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function episodeHookCommand(client, projectId) {
|
|
73
|
+
const prefix = client === 'codex' ? '.agents' : '.claude';
|
|
74
|
+
const code = `const fs=require('node:fs'),p=require('node:path'),{spawnSync}=require('node:child_process');try{let r=fs.realpathSync(process.cwd());for(;;){const a=p.join(r,'foundocs.json');if(fs.existsSync(a)){const c=JSON.parse(fs.readFileSync(a,'utf8'));if(c.project_id!==${JSON.stringify(projectId)})break;spawnSync(process.execPath,[p.join(r,${JSON.stringify(prefix)},'skills/foundocs/scripts/episode-checkpoint.mjs'),'hook','--root',r],{cwd:r,stdio:['inherit','inherit','ignore'],timeout:3000});break;}if(fs.existsSync(p.join(r,'.git'))||p.dirname(r)===r)break;r=p.dirname(r);}}catch{}`;
|
|
68
75
|
return helperCommand(['node', '-e', code]);
|
|
69
76
|
}
|
|
70
77
|
|
|
@@ -207,7 +214,7 @@ function sameConfig(a, b) {
|
|
|
207
214
|
return JSON.stringify(canonical(a)) === JSON.stringify(canonical(b));
|
|
208
215
|
}
|
|
209
216
|
|
|
210
|
-
export const RUNTIME_ENV = ['FOUNDOCS_SETUP_HOME', 'FOUNDOCS_API_KEY', 'FOUNDOCS_PROJECT_ID', 'FOUNDOCS_WORKSPACE_ID', 'STEERDOCS_SETUP_HOME', 'STEERDOCS_API_KEY', 'STEERDOCS_PROJECT_ID', 'STEERDOCS_WORKSPACE_ID'];
|
|
217
|
+
export const RUNTIME_ENV = ['FOUNDOCS_SETUP_HOME', 'FOUNDOCS_EPISODES', 'FOUNDOCS_API_KEY', 'FOUNDOCS_PROJECT_ID', 'FOUNDOCS_WORKSPACE_ID', 'STEERDOCS_SETUP_HOME', 'STEERDOCS_API_KEY', 'STEERDOCS_PROJECT_ID', 'STEERDOCS_WORKSPACE_ID'];
|
|
211
218
|
|
|
212
219
|
export function portableTransport(projectId, version = PACKAGE_VERSION, client = 'codex') {
|
|
213
220
|
if (client === 'claude') return { type: 'stdio', command: 'npx', args: ['--yes', `@foundocs/foundocs-setup@${version}`, 'mcp', '--project-id', projectId] };
|
|
@@ -343,6 +350,38 @@ export async function migrate(rootPath, options = {}) {
|
|
|
343
350
|
});
|
|
344
351
|
}
|
|
345
352
|
|
|
353
|
+
// Explicit opt-in only: startup/update-skills continue preserving runtime pins.
|
|
354
|
+
export async function upgradeRuntime(rootPath, options = {}) {
|
|
355
|
+
const { root, directory, manifest } = await loadInstallation(rootPath, options);
|
|
356
|
+
await checkGitRoot(root);
|
|
357
|
+
return withLock(directory, async () => {
|
|
358
|
+
if (await installedFormat(root, manifest)) fail('preflight', 'Migrate the historical project configuration first.');
|
|
359
|
+
const { validateInstallation } = await import('./runtime.mjs');
|
|
360
|
+
await validateInstallation(root, directory, manifest);
|
|
361
|
+
const path = join(root, clientConfigName(manifest.client)), before = await textFile(path);
|
|
362
|
+
const previousText = await textFile(join(directory, 'runtime-upgrade.json'));
|
|
363
|
+
const previous = previousText ? parseJson(previousText, 'runtime-upgrade.json') : null;
|
|
364
|
+
const server = clientServers(before, manifest.client).foundocs;
|
|
365
|
+
const version = portableVersion(server, manifest.projectId, manifest.client);
|
|
366
|
+
// Resume only an exactly journaled interrupted upgrade, never edited config.
|
|
367
|
+
if (previous?.root === root && before === previous.afterConfig && sameConfig(manifest, previous.beforeManifest)) {
|
|
368
|
+
await atomicWrite(join(directory, 'installation.json'), json(previous.afterManifest));
|
|
369
|
+
return { ok: true, status: 'runtime_upgraded', version: previous.afterManifest.runtimeVersion, hostVerification: 'required' };
|
|
370
|
+
}
|
|
371
|
+
if (!version || version !== manifest.runtimeVersion) fail('preflight', 'Runtime configuration is not the recorded portable transport. Preserve edits; migrate legacy transports or reconcile the conflict first.');
|
|
372
|
+
if (!newer(PACKAGE_VERSION, version)) return { ok: true, status: 'runtime_current', version };
|
|
373
|
+
const desired = portableTransport(manifest.projectId, PACKAGE_VERSION, manifest.client);
|
|
374
|
+
let after;
|
|
375
|
+
if (manifest.client === 'codex') after = replaceTransport(before, 'foundocs', 'foundocs', desired, path);
|
|
376
|
+
else { const config = parseJson(before, path); config.mcpServers.foundocs = { ...server, ...desired }; after = json(config); }
|
|
377
|
+
const updated = { ...manifest, runtimeVersion: PACKAGE_VERSION };
|
|
378
|
+
await atomicWrite(join(directory, 'runtime-upgrade.json'), json({ root, configPath: path, beforeConfig: before, afterConfig: after, beforeManifest: manifest, afterManifest: updated }));
|
|
379
|
+
await applyProjectChanges(root, directory, [{ path, before, after, mode: (await lstat(path)).mode & 0o777 }]);
|
|
380
|
+
await atomicWrite(join(directory, 'installation.json'), json(updated));
|
|
381
|
+
return { ok: true, status: 'runtime_upgraded', version: PACKAGE_VERSION, credentialRetained: true, hostVerification: 'required', next: 'Reconnect MCP, run update-skills, and review exact hook definitions in the host. Verify episode_checkpoint and capture_episode are advertised; installation does not activate host trust.' };
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
|
|
346
385
|
export async function plan(root, input, credentialPath, helperPath, { oldFormat = false, owned = false, includeSkills = false, ownedTransport = null } = {}) {
|
|
347
386
|
const entries = [];
|
|
348
387
|
const add = async (name, transform) => {
|
|
@@ -527,26 +566,31 @@ async function skillPlan(root, client, directory, projectId) {
|
|
|
527
566
|
const config = before === null ? {} : parseJson(before, path);
|
|
528
567
|
if (config.hooks !== undefined && !plainObject(config.hooks)) fail('preflight', 'Hooks must be an object.', { path });
|
|
529
568
|
config.hooks ??= {};
|
|
530
|
-
const
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
569
|
+
const desiredHooks = [
|
|
570
|
+
['SessionStart', 'sessionHook', { matcher: '^(startup|resume|clear|fork)$', hooks: [{ type: 'command', command: sessionHookCommand(client, projectId), timeout: 60 }] }],
|
|
571
|
+
...['UserPromptSubmit', 'Stop'].map(event => [event, `episode${event}Hook`, { hooks: [{ type: 'command', command: episodeHookCommand(client, projectId), timeout: 5 }] }]),
|
|
572
|
+
];
|
|
573
|
+
let changed = false;
|
|
574
|
+
for (const [event, stateKey, desired] of desiredHooks) {
|
|
575
|
+
const groups = config.hooks[event] ?? [];
|
|
576
|
+
if (!Array.isArray(groups) || groups.some(group => !plainObject(group) || !Array.isArray(group.hooks) || group.hooks.some(hook => !plainObject(hook)))) fail('preflight', `${event} hooks must be matcher groups.`, { path });
|
|
577
|
+
const command = desired.hooks[0].command, owned = state[stateKey];
|
|
578
|
+
if (owned && owned.file !== hookFile) fail('preflight', `${event} hook ownership differs from this client.`, { path });
|
|
579
|
+
const matches = groups.filter(group => [owned?.installedHash, owned?.pendingHash].includes(digest(JSON.stringify(group))) || group.hooks.some(hook => hook.command === command));
|
|
580
|
+
const modified = matches.some(group => owned
|
|
581
|
+
? ![owned.installedHash, owned.pendingHash].includes(digest(JSON.stringify(group)))
|
|
582
|
+
: JSON.stringify(group) !== JSON.stringify(desired));
|
|
583
|
+
if (matches.length > 1 || (owned?.installedHash && matches.length !== 1) || modified) {
|
|
584
|
+
fail('preflight', `The Foundocs ${event === 'SessionStart' ? 'session' : event} hook was modified or removed. Preserve and reconcile the hook before updating.`, { path, skills: { status: 'conflict' } });
|
|
585
|
+
}
|
|
586
|
+
if (!matches.length) { groups.push(desired); changed = true; }
|
|
587
|
+
else { changed ||= JSON.stringify(matches[0]) !== JSON.stringify(desired); groups[groups.indexOf(matches[0])] = desired; }
|
|
588
|
+
config.hooks[event] = groups;
|
|
589
|
+
const hookHash = digest(JSON.stringify(desired));
|
|
590
|
+
pending[stateKey] = { file: hookFile, installedHash: owned?.installedHash ?? null, pendingHash: hookHash };
|
|
591
|
+
complete[stateKey] = { file: hookFile, installedHash: hookHash };
|
|
542
592
|
}
|
|
543
|
-
|
|
544
|
-
else groups[groups.indexOf(matches[0])] = desired;
|
|
545
|
-
config.hooks.SessionStart = groups;
|
|
546
|
-
const after = matches.length && JSON.stringify(matches[0]) === JSON.stringify(desired) ? before : json(config);
|
|
547
|
-
const hookHash = digest(JSON.stringify(desired));
|
|
548
|
-
pending.sessionHook = { file: hookFile, installedHash: owned?.installedHash ?? null, pendingHash: hookHash };
|
|
549
|
-
complete.sessionHook = { file: hookFile, installedHash: hookHash };
|
|
593
|
+
const after = changed ? json(config) : before;
|
|
550
594
|
entries.push({ path, before, after, mode: before === null ? 0o644 : (await lstat(path)).mode & 0o777 });
|
|
551
595
|
return { entries, statePath, stateText, pending, complete };
|
|
552
596
|
}
|
|
@@ -585,7 +629,7 @@ async function applyProjectChanges(root, directory, entries) {
|
|
|
585
629
|
}
|
|
586
630
|
|
|
587
631
|
function skillsInstalled() {
|
|
588
|
-
return { status: 'installed', hostVerification: 'required', next: 'Review and trust the SessionStart
|
|
632
|
+
return { status: 'installed', hostVerification: 'required', next: 'Review and trust the SessionStart, UserPromptSubmit and Stop hooks in the host (Codex: /hooks). Reconnect or restart if needed and confirm it discovers foundocs, foundocs-capture-knowledge and foundocs-capture-episode. Installed files do not prove host discovery or execution.' };
|
|
589
633
|
}
|
|
590
634
|
|
|
591
635
|
async function installedFormat(root, manifest) {
|
|
@@ -757,7 +801,7 @@ export async function doctor(rootPath, options = {}) {
|
|
|
757
801
|
if (entries.some((entry) => entry.before !== entry.after)) fail('diagnostic', 'Installation files are incomplete or modified. Rerun install to repair them.');
|
|
758
802
|
const client = await (options.probeClient ?? probeClient)(manifest.client);
|
|
759
803
|
const diagnostic = await (options.diagnose ?? diagnose)(manifest, manifest.credentialPath, options);
|
|
760
|
-
return { ok: true, status: 'configured', root, client, diagnostic, skills };
|
|
804
|
+
return { ok: true, status: 'configured', root, client, diagnostic, skills, episodes: { ...await episodeDiagnostics(root, { storageDir: dirname(dirname(directory)) }), runtimeSupport: manifest.runtimeVersion && !newer('0.3.19', manifest.runtimeVersion) ? 'local_checkpoint_available_after_reconnect' : 'upgrade_required', ...(manifest.runtimeVersion && !newer('0.3.19', manifest.runtimeVersion) ? {} : { next: 'Run the current package upgrade-runtime command explicitly, reconnect MCP and review the host hooks. Skill updates preserve existing runtime pins.' }) } };
|
|
761
805
|
}
|
|
762
806
|
|
|
763
807
|
export async function rollback(rootPath, options = {}) {
|
|
@@ -782,7 +826,7 @@ export async function rollback(rootPath, options = {}) {
|
|
|
782
826
|
const skillStateText = await textFile(skillStatePath);
|
|
783
827
|
if (skillStateText !== null) {
|
|
784
828
|
const state = parseJson(skillStateText, skillStatePath);
|
|
785
|
-
if (state
|
|
829
|
+
for (const key of ['sessionHook', 'episodeUserPromptSubmitHook', 'episodeStopHook']) if (state[key] && restored.includes(join(root, state[key].file))) delete state[key];
|
|
786
830
|
if (state.root !== root || state.version !== 1 || !plainObject(state.files)) fail('rollback', 'Invalid skill installation metadata.');
|
|
787
831
|
for (const entry of journal.entries) {
|
|
788
832
|
const name = relative(root, entry.path).split(sep).join('/');
|
|
@@ -794,6 +838,18 @@ export async function rollback(rootPath, options = {}) {
|
|
|
794
838
|
}
|
|
795
839
|
if (json(state) !== skillStateText) await atomicWrite(skillStatePath, json(state));
|
|
796
840
|
}
|
|
841
|
+
const upgradePath = join(directory, 'runtime-upgrade.json'), upgradeText = await textFile(upgradePath);
|
|
842
|
+
if (upgradeText !== null) {
|
|
843
|
+
const upgrade = parseJson(upgradeText, upgradePath);
|
|
844
|
+
if (upgrade.root !== root || upgrade.configPath !== join(root, clientConfigName(upgrade.beforeManifest?.client))) fail('rollback', 'Invalid runtime upgrade journal.');
|
|
845
|
+
const currentConfig = await textFile(upgrade.configPath);
|
|
846
|
+
if (!conflicts.includes(upgrade.configPath) && (currentConfig === upgrade.beforeConfig || restored.includes(upgrade.configPath))) {
|
|
847
|
+
const manifestPath = join(directory, 'installation.json'), currentManifest = parseJson(await textFile(manifestPath), manifestPath);
|
|
848
|
+
if (sameConfig(currentManifest, upgrade.afterManifest) || sameConfig(currentManifest, upgrade.beforeManifest)) {
|
|
849
|
+
await atomicWrite(manifestPath, json(upgrade.beforeManifest)); await rm(upgradePath);
|
|
850
|
+
} else conflicts.push(manifestPath);
|
|
851
|
+
}
|
|
852
|
+
}
|
|
797
853
|
if (!conflicts.length) await rm(join(directory, 'rollback.json'));
|
|
798
854
|
return { ok: conflicts.length === 0, status: conflicts.length ? 'rollback_conflicts' : 'rolled_back', restored, conflicts, credentialRetained: true, next: 'The private installation key is retained for retry. Revoke it from the web key manager if no longer needed.' };
|
|
799
855
|
});
|
package/src/skill-assets.mjs
CHANGED
|
@@ -11,14 +11,16 @@ export function skillDirectory(client) {
|
|
|
11
11
|
export function knowledgePolicy(client) {
|
|
12
12
|
return readFileSync(new URL('../templates/knowledge-policy.md', import.meta.url), 'utf8')
|
|
13
13
|
.replaceAll('{{SKILL_PATH}}', `${skillDirectory(client)}/SKILL.md`)
|
|
14
|
+
.replaceAll('{{EPISODE_SKILL_PATH}}', `${skillDirectory(client).slice(0, -SKILL_NAME.length)}foundocs-capture-episode/SKILL.md`)
|
|
14
15
|
.replaceAll('{{FOUNDOCS_SKILL_PATH}}', `${skillDirectory(client).slice(0, -SKILL_NAME.length)}foundocs/SKILL.md`).trim();
|
|
15
16
|
}
|
|
16
17
|
|
|
17
18
|
export function skillAssets(client) {
|
|
18
19
|
const prefix = skillDirectory(client).slice(0, -SKILL_NAME.length);
|
|
19
20
|
return [
|
|
21
|
+
...['SKILL.md', 'references/capture.md'].map(name => ({ name: `foundocs-capture-episode/${name}` })),
|
|
20
22
|
...SKILL_FILES.map(name => ({ name: `${SKILL_NAME}/${name}` })),
|
|
21
|
-
...['SKILL.md', 'references/configuration.md', 'references/documents.md', 'references/dreaming.md', 'references/updates.md', 'references/effect-measurement.md', 'scripts/check-update.mjs', 'scripts/session-start.mjs'].map(name => ({ name: `foundocs/${name}` })),
|
|
23
|
+
...['SKILL.md', 'references/configuration.md', 'references/documents.md', 'references/dreaming.md', 'references/updates.md', 'references/effect-measurement.md', 'scripts/check-update.mjs', 'scripts/session-start.mjs', 'scripts/episode-checkpoint.mjs'].map(name => ({ name: `foundocs/${name}` })),
|
|
22
24
|
].map(({ name }) => ({
|
|
23
25
|
name: `${prefix}${name}`,
|
|
24
26
|
content: readFileSync(new URL(`../skills/${name}`, import.meta.url), 'utf8'),
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
- Before project context lookup, document management, or any Foundocs MCP call, read and follow [foundocs]({{FOUNDOCS_SKILL_PATH}}).
|
|
2
2
|
- Write Foundocs documents only when requested or approved by the user. Otherwise propose the purpose/content and wait; do not reconfirm the same approved scope.
|
|
3
3
|
- When the user provides durable project context, or lasting rules, confirmed decisions or verified reusable learnings arise (including after correcting your own mistakes), follow [foundocs-capture-knowledge]({{SKILL_PATH}}) in the same turn, even without a request to save. Skip when there is nothing new to keep.
|
|
4
|
+
- Keep only important confirmed episodes with [foundocs-capture-episode]({{EPISODE_SKILL_PATH}}); skip routine turns locally.
|
|
4
5
|
- Run Dreaming only on an explicit user request (including “꿈꾸자” or “꿈구자”); follow the foundocs skill. Quoted triggers and ordinary capture do not start Dreaming.
|
|
5
6
|
- Project configuration: `foundocs.json` beside this governing AGENTS.md; resolve it from that directory, including when working in nested directories.
|