@foundocs/foundocs-setup 0.3.18 → 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.
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+ // Local metadata/outbox only. Never persists prompts/transcripts or reads keys/endpoints.
3
+ import { constants } from 'node:fs';
4
+ import { open, mkdir, lstat, readFile, realpath, rename, rm } from 'node:fs/promises';
5
+ import { homedir } from 'node:os';
6
+ import { dirname, isAbsolute, join } from 'node:path';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { pathToFileURL } from 'node:url';
9
+
10
+ const hash = value => createHash('sha256').update(value).digest('hex');
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
12
+ const TTL = 14 * 86400000, MAX_CHECKPOINTS = 128, MAX_OUTBOX = 32, MAX_BYTES = 64 * 1024;
13
+ const safeId = value => typeof value === 'string' && value.length > 0 && value.length <= 200 && !/[\x00-\x1f]/.test(value);
14
+ const unavailable = () => { throw new Error('unavailable'); };
15
+ async function privateDirectory(path) {
16
+ // Fail closed on Windows until equivalent ACL verification is available here.
17
+ if (process.platform === 'win32') unavailable();
18
+ let ancestor = path;
19
+ while (dirname(ancestor) !== ancestor) {
20
+ const st = await lstat(ancestor).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
21
+ if (st && (!st.isDirectory() || st.isSymbolicLink())) unavailable();
22
+ ancestor = dirname(ancestor);
23
+ }
24
+ await mkdir(path, { recursive: true, mode: 0o700 });
25
+ const st = await lstat(path);
26
+ if (st.mode & 0o077 || st.uid !== process.getuid()) unavailable();
27
+ }
28
+ async function readState(path) {
29
+ let file;
30
+ try {
31
+ file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
32
+ const st = await file.stat();
33
+ if (!st.isFile() || st.nlink !== 1 || st.mode & 0o077 || st.uid !== process.getuid() || st.size > 3 * 1024 * 1024) unavailable();
34
+ return JSON.parse(await file.readFile('utf8'));
35
+ } catch (e) { if (e.code === 'ENOENT') return { checkpoints: [], outbox: [] }; throw e; }
36
+ finally { await file?.close(); }
37
+ }
38
+ async function writeState(path, state) {
39
+ const temporary = `${path}.${randomUUID()}.tmp`;
40
+ let file;
41
+ try {
42
+ file = await open(temporary, 'wx', 0o600);
43
+ await file.writeFile(JSON.stringify(state)); await file.sync(); await file.close(); file = null;
44
+ await rename(temporary, path);
45
+ } finally { await file?.close(); await rm(temporary, { force: true }); }
46
+ }
47
+ async function locked(directory, action) {
48
+ const lock = join(directory, 'checkpoint.lock');
49
+ const file = await open(lock, 'wx', 0o600); // Contention/crash: soft failure, never steal a live lock.
50
+ try { await file.writeFile(String(process.pid)); return await action(); } finally { await file.close(); await rm(lock, { force: true }); }
51
+ }
52
+ function prune(state, now) {
53
+ state.outbox = state.outbox.filter(c => Number.isFinite(c.createdAt) && c.createdAt + TTL > now).slice(-MAX_OUTBOX);
54
+ const needed = new Set(state.outbox.map(e => e.checkpoint));
55
+ const valid = state.checkpoints.filter(c => Number.isFinite(c.createdAt) && (c.createdAt + TTL > now || needed.has(c.id)));
56
+ const kept = valid.filter(c => needed.has(c.id));
57
+ state.checkpoints = [...kept, ...valid.filter(c => !needed.has(c.id)).slice(-(MAX_CHECKPOINTS - kept.length))].sort((a, b) => a.createdAt - b.createdAt);
58
+
59
+ }
60
+ function reminder(checkpoint, client, fallback = false) {
61
+ const prefix = client === 'codex' ? '.agents' : '.claude';
62
+ return `${fallback ? 'One bounded Foundocs checkpoint follow-up. ' : ''}Foundocs episode checkpoint: ${checkpoint.id}. Read ${prefix}/skills/foundocs-capture-episode/SKILL.md. During this task, retain only confirmed important decisions, verified results/discoveries, concrete blockers or milestones. Routine lookup/no new fact: local skip only. Before the final response, acknowledge via local MCP episode_checkpoint (operation skip for routine) or the installed episode-checkpoint.mjs helper; do not upload prompts/transcripts or start another model. Missing tools, opt-out or failure must not delay the user task. ${fallback ? 'Do this once; do not repeat the user answer or continue just for bookkeeping.' : ''}`;
63
+ }
64
+ function captureInput(input, checkpoint, slot, projectId, now) {
65
+ const capture = structuredClone(input);
66
+ if (!capture || typeof capture !== 'object' || Array.isArray(capture)) unavailable();
67
+ // Preserve only the public capture contract. Unknown fields never enter a private journal.
68
+ const allowed = ['event', 'candidateId', 'sourceChangeId', 'judgment', 'episode', 'expectedEpisodeVersion', 'expectedCandidateVersion', 'correction'];
69
+ if (Object.keys(capture).some(key => !allowed.includes(key))) unavailable();
70
+ if (Boolean(capture.event) === Boolean(capture.candidateId)) unavailable();
71
+ if (!Number.isInteger(capture.expectedEpisodeVersion) || capture.expectedEpisodeVersion < 0) unavailable();
72
+ if (capture.event) {
73
+ if (!safeId(capture.event.taskKey) || !safeId(capture.event.boundaryKey)) unavailable();
74
+ const eventAllowed = ['taskKey', 'boundaryKey', 'kind', 'observation', 'occurredAt', 'evidence', 'links'];
75
+ if (Object.keys(capture.event).some(key => !eventAllowed.includes(key))) unavailable();
76
+ capture.event.sourceEventId = `host:${checkpoint.id}:${slot}`;
77
+ capture.event.sessionId = checkpoint.sessionId;
78
+ capture.event.occurredAt ??= new Date(now).toISOString();
79
+ if (typeof capture.event.observation !== 'string' || capture.event.observation.length > 3000 || !Array.isArray(capture.event.evidence) || capture.event.evidence.length > 20 || !Array.isArray(capture.event.links) || capture.event.links.length > 20) unavailable();
80
+ if (capture.event.evidence.some(e => typeof e.detail !== 'string' || e.detail.length > 1000)) unavailable();
81
+ }
82
+ return { ...capture, project_id: projectId, requestId: randomUUID() };
83
+ }
84
+
85
+ /** Read-only operational status. Never returns payloads, prompts or credentials. */
86
+ export async function episodeDiagnostics(rootPath, options = {}) {
87
+ try {
88
+ const root = await realpath(rootPath), config = JSON.parse(await readFile(join(root, 'foundocs.json'), 'utf8'));
89
+ if (config.episodes?.enabled === false || process.env.FOUNDOCS_EPISODES === 'off') return { status: 'disabled' };
90
+ if (process.platform === 'win32') return { status: 'unsupported_platform' };
91
+ const base = options.storageDir ?? process.env.FOUNDOCS_SETUP_HOME ?? join(homedir(), '.local/share/foundocs/setup');
92
+ const directory = join(base, 'episodes', hash(root)), lockPath = join(directory, 'checkpoint.lock');
93
+ const lock = await open(lockPath, constants.O_RDONLY | constants.O_NOFOLLOW).catch(e => { if (e.code === 'ENOENT') return null; throw e; });
94
+ if (lock) {
95
+ let pid;
96
+ try { const st = await lock.stat(); if (!st.isFile() || st.size > 32 || st.mode & 0o077 || st.uid !== process.getuid()) unavailable(); pid = Number(await lock.readFile('utf8')); } finally { await lock.close(); }
97
+ let alive = true;
98
+ if (Number.isInteger(pid) && pid > 0) { try { process.kill(pid, 0); } catch (e) { if (e.code === 'ESRCH') alive = false; } }
99
+ return { status: alive ? 'busy' : 'stale_lock', lockPath, next: alive ? 'A helper may be running. Do not remove its lock.' : 'After confirming no episode helper is running, remove only this stale lock and retry. Preserve checkpoints.json and credentials.' };
100
+ }
101
+ const state = await readState(join(directory, 'checkpoints.json'));
102
+ return { status: 'ready', pendingCount: state.outbox?.length ?? 0, hostVerification: 'required' };
103
+ } catch { return { status: 'unavailable', next: 'Inspect private storage permissions without changing host approvals. Primary work may continue.' }; }
104
+ }
105
+
106
+ /** Host hooks and agent commands share a bounded private journal; no network/model work. */
107
+ export async function episodeCheckpoint(command, rootPath, input, options = {}) {
108
+ if (Buffer.byteLength(JSON.stringify(input)) > 1024 * 1024) unavailable();
109
+ const root = await realpath(rootPath);
110
+ if (!isAbsolute(rootPath)) unavailable();
111
+ const config = JSON.parse(await readFile(join(root, 'foundocs.json'), 'utf8'));
112
+ if (!UUID.test(config.project_id) || (options.projectId && config.project_id !== options.projectId)) unavailable();
113
+ if (config.episodes?.enabled === false || process.env.FOUNDOCS_EPISODES === 'off') return { status: 'disabled' };
114
+ const client = options.client;
115
+ if (!['codex', 'claude'].includes(client)) return { status: 'unsupported_host' };
116
+ const base = options.storageDir ?? process.env.FOUNDOCS_SETUP_HOME ?? join(homedir(), '.local/share/foundocs/setup');
117
+ if (!isAbsolute(base)) unavailable();
118
+ const directory = join(base, 'episodes', hash(root));
119
+ await privateDirectory(directory);
120
+ return locked(directory, async () => {
121
+ const path = join(directory, 'checkpoints.json'), state = await readState(path), now = options.now ?? Date.now();
122
+ if (!Array.isArray(state.checkpoints) || !Array.isArray(state.outbox)) unavailable();
123
+ const counts = [state.checkpoints.length, state.outbox.length];
124
+ prune(state, now);
125
+ if (state.checkpoints.length !== counts[0] || state.outbox.length !== counts[1]) await writeState(path, state);
126
+ let output;
127
+ if (command === 'hook') {
128
+ if (!safeId(input.session_id) || input.agent_id || input.agent_type || input.stop_hook_active) return null;
129
+ if (!['UserPromptSubmit', 'Stop'].includes(input.hook_event_name)) return null;
130
+ let checkpoint = state.checkpoints.findLast(c => c.sessionId === input.session_id);
131
+ if (input.hook_event_name === 'UserPromptSubmit') {
132
+ // Codex's own Stop continuation is a synthetic UserPromptSubmit. Keep the
133
+ // original checkpoint and guard instead of creating a bookkeeping loop.
134
+ if (checkpoint?.fallbackIssued && typeof input.prompt === 'string' && input.prompt.startsWith('One bounded Foundocs checkpoint follow-up. ')) return null;
135
+ const id = client === 'codex' && safeId(input.turn_id) ? hash(`${input.session_id}:${input.turn_id}`).slice(0, 40) : randomUUID();
136
+ checkpoint = state.checkpoints.find(c => c.id === id);
137
+ if (!checkpoint) {
138
+ checkpoint = { id, sessionId: input.session_id, ...(safeId(input.turn_id) ? { turnId: input.turn_id } : {}), client, createdAt: now, acknowledged: false, fallbackIssued: false };
139
+ state.checkpoints.push(checkpoint);
140
+ }
141
+ output = { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: reminder(checkpoint, client) } };
142
+ } else {
143
+ if (!checkpoint || checkpoint.acknowledged || checkpoint.fallbackIssued || (client === 'codex' && checkpoint.turnId !== input.turn_id)) return null;
144
+ checkpoint.fallbackIssued = true;
145
+ const context = reminder(checkpoint, client, true);
146
+ output = client === 'claude' ? { hookSpecificOutput: { hookEventName: 'Stop', additionalContext: context } } : { decision: 'block', reason: context };
147
+ }
148
+ } else {
149
+ const checkpoint = state.checkpoints.find(c => c.id === input.checkpoint);
150
+ if (!checkpoint) return { status: 'checkpoint_unavailable' };
151
+ if (command === 'skip') {
152
+ checkpoint.acknowledged = true;
153
+ output = { status: 'acknowledged', pending: state.outbox.filter(e => e.checkpoint === checkpoint.id).length };
154
+ } else if (command === 'prepare') {
155
+ if (typeof input.slot !== 'string' || !/^[a-z0-9_-]{1,40}$/.test(input.slot)) unavailable();
156
+ const settled = checkpoint.settled?.find(entry => entry.slot === input.slot);
157
+ if (settled) return { status: settled.inputHash === hash(JSON.stringify(input.capture)) ? 'already_acknowledged' : 'payload_conflict', requestId: settled.requestId, disposition: settled.disposition };
158
+ if ((checkpoint.settled ?? []).length >= 32) return { status: 'checkpoint_full' };
159
+ const previous = state.outbox.find(e => e.checkpoint === checkpoint.id && e.slot === input.slot);
160
+ if (previous) {
161
+ if (previous.inputHash !== hash(JSON.stringify(input.capture))) return { status: 'payload_conflict', requestId: previous.payload.requestId };
162
+ output = { status: 'prepared', payload: previous.payload };
163
+ } else {
164
+ if (checkpoint.createdAt + TTL <= now) return { status: 'checkpoint_expired' };
165
+ if (state.outbox.length >= MAX_OUTBOX) return { status: 'outbox_full' };
166
+ const payload = captureInput(input.capture, checkpoint, input.slot, config.project_id, now);
167
+ if (Buffer.byteLength(JSON.stringify(payload)) > MAX_BYTES) unavailable();
168
+ state.outbox.push({ checkpoint: checkpoint.id, slot: input.slot, inputHash: hash(JSON.stringify(input.capture)), payload, createdAt: now });
169
+ output = { status: 'prepared', payload };
170
+ }
171
+ // A transport failure cannot induce repeated Stop continuations. Pending
172
+ // payload stays available for exact replay on a later ordinary task.
173
+ checkpoint.acknowledged = true;
174
+ } else if (command === 'ack') {
175
+ const entry = state.outbox.find(e => e.checkpoint === checkpoint.id && e.payload.requestId === input.requestId);
176
+ if (!entry) return { status: 'request_unavailable' };
177
+ if (!['created', 'updated', 'corrected', 'deferred', 'skipped', 'unchanged'].includes(input.result?.disposition) || !UUID.test(input.result?.candidate?.id)) unavailable();
178
+ checkpoint.settled ??= [];
179
+ checkpoint.settled.push({ slot: entry.slot, inputHash: entry.inputHash, requestId: entry.payload.requestId, disposition: input.result.disposition });
180
+ state.outbox = state.outbox.filter(e => e !== entry); checkpoint.acknowledged = true;
181
+ output = { status: 'acknowledged', disposition: input.result.disposition };
182
+ } else if (command === 'pending') {
183
+ output = { status: 'pending', items: state.outbox.slice(0, 3).map(e => ({ checkpoint: e.checkpoint, slot: e.slot, payload: e.payload })) };
184
+ } else if (command === 'discard') {
185
+ // Only for a definitive rejection after reconciliation; never after an uncertain response.
186
+ state.outbox = state.outbox.filter(e => e.payload.requestId !== input.requestId || e.checkpoint !== checkpoint.id);
187
+ checkpoint.acknowledged = true; output = { status: 'discarded' };
188
+ } else unavailable();
189
+ }
190
+ prune(state, now); await writeState(path, state); return output;
191
+ });
192
+ }
193
+
194
+ if (process.argv[1]?.endsWith('episode-checkpoint.mjs') && pathToFileURL(process.argv[1]).href === import.meta.url) {
195
+ const [command, flag, root] = process.argv.slice(2);
196
+ let output;
197
+ try {
198
+ if (flag !== '--root' || !isAbsolute(root)) unavailable();
199
+ const script = await realpath(process.argv[1]), canonical = await realpath(root);
200
+ const client = ['codex', 'claude'].find(c => script === join(canonical, c === 'codex' ? '.agents' : '.claude', 'skills/foundocs/scripts/episode-checkpoint.mjs'));
201
+ let text = '';
202
+ for await (const chunk of process.stdin) { text += chunk; if (Buffer.byteLength(text) > 1024 * 1024) unavailable(); }
203
+ output = await episodeCheckpoint(command, root, JSON.parse(text), { client });
204
+ } catch { output = command === 'hook' ? null : { status: 'unavailable' }; }
205
+ if (command === 'hook' && !output?.hookSpecificOutput && !output?.decision) output = null;
206
+ if (output) process.stdout.write(`${JSON.stringify(output)}\n`);
207
+ }
@@ -0,0 +1,22 @@
1
+ ---
2
+ name: foundocs-capture-episode
3
+ description: Automatically retain concise important work events during ordinary tasks: confirmed decisions, verified results or discoveries, concrete blockers and meaningful milestones. Skip routine lookups, chatter, duplicate reports and bookkeeping. Uses the current host context, without a separate model or a request to remember.
4
+ ---
5
+
6
+ # Selective episode capture
7
+
8
+ Use the current task context during normal work. The user need not ask to remember. Before finishing, assess the latest installed-hook checkpoint once. Read [the capture contract](references/capture.md) for a worthwhile event. Do not create a remote candidate for every turn. Routine lookup, greeting, unchanged status, repeated result, planned work or episode bookkeeping: acknowledge locally with `skip` and continue the task. Never invent a milestone just to satisfy a hook.
9
+
10
+ A confirmed decision, verified discovery, concrete blocker or material milestone can be worth keeping before the whole task completes. An ordinary proposed approach is not a confirmed decision. Result unknown means defer, not success. A PR submitted with tests passing but review/CI/release remaining is **in_progress**, with remainingWork; never mark the implementation completed. Use 2–4 short sentences, normally 150–300 Korean characters total or similarly concise text in the user's language. Keep facts, significance and actual remaining work. No full transcript, private reasoning, raw logs, secrets or speculative conclusions.
11
+
12
+ First follow [Foundocs configuration](../foundocs/references/configuration.md) for the exact governing project. Inspect live episode tool schemas. If disabled (`foundocs.json` has `"episodes":{"enabled":false}` or `FOUNDOCS_EPISODES=off`), no trusted checkpoint is available, the host is unsupported, or required remote tools are absent: skip honestly. Do not enable hooks, change trust/permissions or start external models. Never substitute documents or knowledge for an episode. Document consent and explicit Dreaming consent remain unchanged. Knowledge capture is a separate operation; link useful existing knowledge rather than duplicating its body.
13
+
14
+ The hook provides a checkpoint ID, not a task identity. Discover and use the installed local MCP `episode_checkpoint` tool when advertised; do not choose shell instead: pass the configured project_id, operation `skip|prepare|ack|pending|discard`, checkpoint and the corresponding fields described below. It performs private local bookkeeping in the existing MCP process, avoiding extra shell filesystem permissions. Its result.data is the helper result. It never substitutes for remote capture_episode. Confirm this tool is absent before considering a shell fallback. If absent, the shell helper is an optional fallback within existing permissions; never widen sandbox access or request permissions just for routine bookkeeping. The helper is `../foundocs/scripts/episode-checkpoint.mjs` relative to this skill; invoke it with Node and `--root ABSOLUTE_GOVERNING_ROOT`, supplying JSON through stdin. For routine local MCP acknowledgment, pass `{project_id: CONFIGURED_PROJECT, operation: "skip", checkpoint: CHECKPOINT_FROM_HOOK}`; no project index/search or remote capture is needed. Shell fallback only when the local MCP tool is unavailable (replace path/root/checkpoint with actual values):
15
+
16
+ ```sh
17
+ node .agents/skills/foundocs/scripts/episode-checkpoint.mjs skip --root /absolute/project <<'JSON'
18
+ {"checkpoint":"CHECKPOINT_FROM_HOOK"}
19
+ JSON
20
+ ```
21
+
22
+ Claude Code uses `.claude/skills/` instead of `.agents/skills/`. For important events, `prepare` persists a private retry payload **before** the host calls `capture_episode`, then `ack` settles the server-confirmed result. All details and examples are in the capture contract. Use normal host tools; no additional model API keys. A local failure must not block the primary response or cause repeated continuations. A Stop reminder is a single bounded fallback: assess/ack once, do not repeat the answer or continue just for bookkeeping. Do not mention routine skipping to the user.
@@ -0,0 +1,60 @@
1
+ # Capture, retry and continuity
2
+
3
+ Read current live tool schemas. Every remote call uses the exact configured project_id. Tools are `capture_episode`, `search_episodes`, `get_episode`, `get_episode_candidates`, `get_episode_candidate`, `get_episode_revisions`. If capture or recall is unavailable, locally skip; do not write another content kind. Authentication/access/configuration failures stop Foundocs calls.
4
+
5
+ ## Select and ground
6
+
7
+ The host supplies semantic judgments from current task context; the server validates structure, evidence references, state, novelty, versions and authority. It does not independently verify a conversation. No keyword or message-length heuristic decides importance.
8
+
9
+ - `judgment`: significance `important|routine|uncertain`, novelty `new|duplicate|uncertain`, grounding `confirmed|proposed|uncertain`, outcome `succeeded|failed|partial|unknown`, reason (<=1000), evidenceRefs (matching submitted evidence sourceRef). Routine/duplicate host events stay local. Use null or uncertain for a worthwhile event that cannot yet be judged; the server defers it.
10
+ - `event`: taskKey, boundaryKey, kind (`result|decision|discovery|blocker|milestone`), observation (<=3000), evidence and links. The helper assigns sourceEventId, sessionId and occurredAt. Supply occurredAt only for an observed past event, never guess a completion time.
11
+ - `episode`: title <=120; summary array of 2–4 sentences (each <=600); kind; status `in_progress|completed|blocked|cancelled`; tags; remainingWork (<=1000 or null); optional previousEpisodeId. Prefer substantially shorter content.
12
+ - `completed` requires `outcome:succeeded` and `remainingWork:null`. A completed decision means the choice is settled, not its implementation. State remaining implementation in the summary. `result` with outcome unknown must defer. Confirmed decision/discovery/blocker/milestone may record while overall outcome is unknown.
13
+ - Evidence: kind `user_statement|artifact|verification|observation`, stable sourceRef, label, detail <=1000, optional safe HTTP(S) URL. Decision needs explicit user_statement; result/discovery and ordinary completion need artifact or verification. Keep only brief supported facts, never source dumps. Input evidence/links <=20 each.
14
+ - Links: `{contentId,relation:"related|used|produced|supports",observedVersion?}` from observed same-project content. Do not invent IDs, permissions or old document bodies.
15
+
16
+ ## Stable goals and phases
17
+
18
+ Reuse taskKey across turns and sessions for the same explicit user goal: use a known card/task ID, or mint a persistent goal identity once and reuse the server record. Search a focused goal/topic before creating another identity when continuity is plausible. A session, date or checkpoint is **not** a goal or phase. One session can contain several goals.
19
+
20
+ Use an explicit boundaryKey for the goal's phase. Read the matching episode and current version before updating. Set expectedEpisodeVersion:0 only for a new boundary; positive observed version for an existing one. Add genuinely new evidence/links; wording-only changes are not progress. Completed/cancelled phases require a new boundaryKey and previousEpisodeId for later activity. Explicit factual corrections use correction:true, observed version and preserve prior status/timestamps/previousEpisodeId. On VERSION_CONFLICT or NOVELTY_REQUIRED, reread and reassess; do not blindly increment versions.
21
+
22
+ ## Private prepare → remote call → acknowledgment
23
+
24
+ Prefer local MCP episode_checkpoint with operation set to the command below and the configured project_id; its other arguments are the shown helper input. If unavailable, invoke the installed shell helper as in SKILL.md. The helper and local MCP tool share the same private state. Send `prepare` this shape (illustrative values must be replaced with actual facts):
25
+
26
+ ```json
27
+ {
28
+ "checkpoint":"CHECKPOINT_FROM_HOOK",
29
+ "slot":"verified-result",
30
+ "capture":{
31
+ "event":{
32
+ "taskKey":"TASK-STABLE-ID",
33
+ "boundaryKey":"implementation",
34
+ "kind":"milestone",
35
+ "observation":"Focused tests passed; the PR is awaiting review.",
36
+ "evidence":[{"kind":"verification","sourceRef":"test:OBSERVED-RUN-ID","label":"Focused tests","detail":"The observed test command passed."}],
37
+ "links":[]
38
+ },
39
+ "judgment":{"significance":"important","novelty":"new","grounding":"confirmed","outcome":"partial","reason":"Verified implementation milestone with review remaining.","evidenceRefs":["test:OBSERVED-RUN-ID"]},
40
+ "episode":{"title":"Implementation ready for review","summary":["The requested change passes its focused tests.","Review and integration checks remain."],"kind":"milestone","status":"in_progress","tags":[],"remainingWork":"Review and integration checks"},
41
+ "expectedEpisodeVersion":0
42
+ }
43
+ }
44
+ ```
45
+
46
+ `slot` is a stable short lowercase operation label within the checkpoint. Different meaningful events may use different slots. Never supply requestId/project_id/sourceEventId/sessionId yourself; the helper fills them once. `already_acknowledged` means this slot is already settled: do not call capture again. `prepared` returns `payload`: call the live `capture_episode` tool with **that exact object**. The helper does not call the server or make a meaning judgment. It marks the checkpoint acknowledged immediately so a lost response cannot cause a Stop loop.
47
+
48
+ After a successful server response, run `ack` with `{checkpoint,requestId,result:DATA_FROM_SUCCESSFUL_CAPTURE}`. Only a server-confirmed disposition (created/updated/corrected/deferred/skipped/unchanged) is success; inspect isError and ok. A deferred candidate is not a visible episode.
49
+
50
+ After timeout/unknown response, leave the outbox entry intact. On the next relevant ordinary task, `pending` with the current checkpoint returns at most 3 oldest outstanding payloads with their original checkpoint IDs. Replay the identical payload/requestId; ack against its original checkpoint. Do not reconstruct, change timestamps, make a new requestId or claim success. There is no background model or repeated retry loop. After definitive rejection, reconcile current server state; `discard` with original checkpoint/requestId removes only the rejected entry before a revised assessment uses a new slot. Never discard an uncertain write just to bypass a conflict. `payload_conflict` requires reusing pending original payload or explicit reconciliation.
51
+
52
+ Private state is outside the project under the setup storage directory, owner-only, bounded to 128 checkpoints/32 requests. Each prepared request expires 14 days after preparation; retries never extend it. Unreferenced checkpoints expire 14 days after creation. A live request retains only its required checkpoint metadata until acknowledgment or request expiry (at most 28 days after checkpoint creation). An expired checkpoint can retry/ack existing requests but cannot prepare new slots. It retains only minimal checkpoint metadata and brief submitted capture payloads, never prompts/transcripts/credentials. A crashed helper can leave checkpoint.lock; after confirming no helper process is running, remove only that private lock and retry. Never delete an outbox to repair a lock. Cleanup runs on helper use; an idle installation does not run a deletion daemon. Expiry removes local retry data, not server candidates. POSIX private storage is currently supported; Windows reports unavailable and capture skips. If local storage is unavailable/full, skip capture and continue primary work; do not change filesystem permissions or approvals.
53
+
54
+ ## Deferred and server-observed events
55
+
56
+ When new evidence settles a deferred event, read `get_episode_candidate` with version-pinned evidence/link pagination. Prepare a capture with candidateId and expectedCandidateVersion (no event), judgment, episode and expectedEpisodeVersion. This reassesses the stored original event, not a reconstructed/clipped inbox excerpt. Preserve the original goal/boundary.
57
+
58
+ For a current related document/knowledge change, `get_episode_candidates(source:"changes")` is a bounded recent inbox (24h default, at most14days, limit<=20). Do not scan old history on install. If meaning/goal is unclear, leave it unassessed. Assess a known source with sourceChangeId, event goal/boundary/kind and evidenceRefs `["change:SOURCE_ID"]`; the server substitutes canonical observation/evidence/time and deduplicates across actors. Unimportant *server inbox* changes may be submitted as routine to acknowledge them; ordinary trivial *host turns* must only skip locally. Already assessed source changes leave this inbox. `source:"pending"` finds deferred candidates.
59
+
60
+ Do not create episodes for reads, retrieval evaluation, checkpoint preparation, retry/ack or episode writes themselves. For recall, search recent task episodes first, widen query/time only as needed, read focused details and linked documents/knowledge. The compact list is not a complete evidence record.
package/src/bridge.mjs CHANGED
@@ -6,7 +6,8 @@ import { Server, ProtocolError, ProtocolErrorCode } from '@modelcontextprotocol/
6
6
  import { StdioServerTransport } from '@modelcontextprotocol/server/stdio';
7
7
  import { readCredential } from './auth.mjs';
8
8
  import { pathToFileURL } from 'node:url';
9
- import { resolve } from 'node:path';
9
+ import { resolve, dirname } from 'node:path';
10
+ import { episodeCheckpoint } from '../skills/foundocs/scripts/episode-checkpoint.mjs';
10
11
 
11
12
  // Forward only a stable category and safe context, never raw remote messages or data.
12
13
  function requestError(error, name) {
@@ -45,8 +46,18 @@ function requestError(error, name) {
45
46
  { code, retryable, ...(tool ? { tool } : {}), ...(httpStatus !== undefined ? { httpStatus } : {}), ...(remoteCode !== undefined ? { remoteCode } : {}) });
46
47
  }
47
48
 
48
- export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint }) {
49
- let remote, local;
49
+ export async function runBridge({ credentialPath, projectId, workspaceId, mcpUrl: endpoint, root, client }) {
50
+ let remote, local, checkpointRoute = 'remote', checkpointWasLocal = false;
51
+ const checkpointTool = {
52
+ name: 'episode_checkpoint',
53
+ description: 'Local installer checkpoint bookkeeping, not remote capture. Use the ID delivered by the trusted UserPromptSubmit/Stop hook. Routine turns: skip only. Important event: prepare persists an exact private payload, call remote capture_episode with returned payload, then ack the successful result. Pending returns at most 3 exact retries. Never use this as semantic evidence or put transcripts/secrets in capture. No model/network invocation; failures never block the primary task.',
54
+ inputSchema: { type: 'object', additionalProperties: false, required: ['project_id', 'operation', 'checkpoint'], properties: {
55
+ project_id: { type: 'string', format: 'uuid' }, operation: { type: 'string', enum: ['prepare', 'ack', 'skip', 'pending', 'discard'] },
56
+ checkpoint: { type: 'string', maxLength: 200 }, slot: { type: 'string', pattern: '^[a-z0-9_-]{1,40}$' },
57
+ capture: { type: 'object' }, requestId: { type: 'string', format: 'uuid' }, result: { type: 'object' },
58
+ } },
59
+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false, idempotentHint: false },
60
+ };
50
61
  async function close() {
51
62
  await remote?.close().catch(() => {});
52
63
  await local?.close().catch(() => {});
@@ -66,11 +77,45 @@ try {
66
77
  await remote.connect(transport, { timeout: 20000 });
67
78
  local = new Server({ name: 'foundocs', version: '0.2.0' }, { capabilities: { tools: {} }, instructions: remote.getInstructions() });
68
79
  local.setRequestHandler('tools/list', async (request) => {
69
- try { return await remote.listTools(request.params); }
80
+ try {
81
+ // Assemble a bounded complete inventory before adding a local name. Never
82
+ // infer absence from the first remote page or shadow a later-page tool.
83
+ const tools = [], seen = new Set(); let cursor;
84
+ for (let page = 0; page < 20; page++) {
85
+ const result = await remote.listTools(cursor ? { cursor } : undefined);
86
+ tools.push(...result.tools);
87
+ if (tools.length > 2000) throw new Error('tool inventory exceeds bound');
88
+ if (!result.nextCursor) {
89
+ const collision = tools.some(tool => tool.name === checkpointTool.name);
90
+ const supported = !!root && ['codex', 'claude'].includes(client) && tools.some(tool => tool.name === 'capture_episode') && !collision;
91
+ checkpointRoute = supported ? 'local' : checkpointWasLocal ? 'blocked' : 'remote';
92
+ if (supported) { checkpointWasLocal = true; tools.push(checkpointTool); }
93
+ // Once advertised locally, this name can never start forwarding private
94
+ // checkpoint payloads to a changing remote inventory.
95
+ return { tools: checkpointRoute === 'blocked' ? tools.filter(tool => tool.name !== checkpointTool.name) : tools };
96
+ }
97
+ if (seen.has(result.nextCursor)) throw new Error('tool cursor loop');
98
+ seen.add(result.nextCursor); cursor = result.nextCursor;
99
+ }
100
+ throw new Error('tool inventory exceeds page bound');
101
+ }
70
102
  catch (error) { throw requestError(error, 'tools_list'); }
71
103
  });
72
104
  local.setRequestHandler('tools/call', async (request) => {
73
105
  if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.params.arguments?.project_id)) throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Read and pass the explicit project_id from the governing foundocs.json.');
106
+ if (checkpointRoute !== 'remote' && request.params.name === checkpointTool.name) {
107
+ const args = request.params.arguments;
108
+ if (args.project_id !== projectId) throw new ProtocolError(ProtocolErrorCode.InvalidParams, 'Local checkpoint project differs from this installation.');
109
+ let data;
110
+ try {
111
+ if (checkpointRoute !== 'local' || !['prepare', 'ack', 'skip', 'pending', 'discard'].includes(args.operation)) throw new Error();
112
+ // Credential layout is validated by resolveRuntime; use that same private base.
113
+ const storageDir = dirname(dirname(dirname(dirname(dirname(credentialPath)))));
114
+ data = await episodeCheckpoint(args.operation, root, args, { client, storageDir, projectId });
115
+ } catch { data = { status: 'unavailable' }; }
116
+ const response = { ok: true, data };
117
+ return { structuredContent: response, content: [{ type: 'text', text: JSON.stringify(response) }], isError: false };
118
+ }
74
119
  try { return await remote.callTool(request.params); }
75
120
  catch (error) { throw requestError(error, request.params.name); }
76
121
  });
package/src/cli.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { install, doctor, rollback, updateSkills, migrate, SetupError } from './setup.mjs';
2
+ import { install, doctor, rollback, updateSkills, migrate, upgradeRuntime, SetupError } from './setup.mjs';
3
3
 
4
4
  const [command, ...args] = process.argv.slice(2);
5
5
  try {
6
6
  if (command === '--help' || command === '-h') {
7
- process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nfoundocs-setup measure prepare|run|flush --root ABSOLUTE_PATH < private-task.json\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
7
+ process.stdout.write('foundocs-setup install --root ABSOLUTE_PATH < private-input.json\nfoundocs-setup doctor --root ABSOLUTE_PATH\nfoundocs-setup update-skills --root ABSOLUTE_PATH\nfoundocs-setup rollback --root ABSOLUTE_PATH\nfoundocs-setup migrate --root ABSOLUTE_PATH\nfoundocs-setup upgrade-runtime --root ABSOLUTE_PATH\nfoundocs-setup mcp --project-id UUID\nfoundocs-setup measure prepare|run|flush --root ABSOLUTE_PATH < private-task.json\nInstall reads the one-time code from private stdin only. Never put credentials in argv or shell command text.\n');
8
8
  } else if (command === 'measure') {
9
9
  if (args.length !== 3 || !['prepare', 'run', 'flush'].includes(args[0]) || args[1] !== '--root') throw new SetupError('input', 'Use measure prepare|run|flush --root ABSOLUTE_PATH with JSON on stdin.');
10
10
  let input = '';
@@ -18,7 +18,7 @@ try {
18
18
  const { startRuntime } = await import('./runtime.mjs');
19
19
  await startRuntime(args[1]);
20
20
  } else {
21
- if (!['install', 'doctor', 'rollback', 'update-skills', 'migrate'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, migrate, or update-skills with --root ABSOLUTE_PATH.');
21
+ if (!['install', 'doctor', 'rollback', 'update-skills', 'migrate', 'upgrade-runtime'].includes(command) || args.length !== 2 || args[0] !== '--root') throw new SetupError('input', 'Use install, doctor, rollback, migrate, upgrade-runtime, or update-skills with --root ABSOLUTE_PATH.');
22
22
  let result;
23
23
  if (command === 'install') {
24
24
  if (process.stdin.isTTY) throw new SetupError('input', 'Supply installation JSON through private stdin.');
@@ -29,7 +29,7 @@ try {
29
29
  }
30
30
  try { input = JSON.parse(input); } catch { throw new SetupError('input', 'Installation input must be JSON.'); }
31
31
  result = await install(args[1], input);
32
- } else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : command === 'migrate' ? migrate : rollback)(args[1]);
32
+ } else result = await (command === 'doctor' ? doctor : command === 'update-skills' ? updateSkills : command === 'migrate' ? migrate : command === 'upgrade-runtime' ? upgradeRuntime : rollback)(args[1]);
33
33
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
34
34
  }
35
35
  } catch (error) {
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;
@@ -68,6 +69,12 @@ export function sessionHookCommand(client, projectId) {
68
69
  return helperCommand(['node', '-e', code]);
69
70
  }
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{}`;
75
+ return helperCommand(['node', '-e', code]);
76
+ }
77
+
71
78
  export function instructions(client) {
72
79
  if (!client) return '## Foundocs\n\nRead foundocs.json beside this governing AGENTS.md, validate its UUID project_id and pass it to every Foundocs call. If that exact configuration is missing or invalid, stop and ask; never search for a replacement. Run update-skills before document or knowledge work to install the Foundocs procedures.';
73
80
  return `## Foundocs\n\n${knowledgePolicy(client)}`;
@@ -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 groups = config.hooks.SessionStart ?? [];
531
- if (!Array.isArray(groups) || groups.some(group => !plainObject(group) || !Array.isArray(group.hooks) || group.hooks.some(hook => !plainObject(hook)))) fail('preflight', 'SessionStart hooks must be matcher groups.', { path });
532
- const command = sessionHookCommand(client, projectId);
533
- const desired = { matcher: '^(startup|resume|clear|fork)$', hooks: [{ type: 'command', command, timeout: 60 }] };
534
- const owned = state.sessionHook;
535
- if (owned && owned.file !== hookFile) fail('preflight', 'Session hook ownership differs from this client.', { path });
536
- const matches = groups.filter(group => [owned?.installedHash, owned?.pendingHash].includes(digest(JSON.stringify(group))) || group.hooks.some(hook => hook.command === command));
537
- const modified = matches.some(group => owned
538
- ? ![owned.installedHash, owned.pendingHash].includes(digest(JSON.stringify(group)))
539
- : JSON.stringify(group) !== JSON.stringify(desired));
540
- if (matches.length > 1 || (owned?.installedHash && matches.length !== 1) || modified) {
541
- fail('preflight', 'The Foundocs session hook was modified or removed. Preserve and reconcile the hook before updating.', { path, skills: { status: 'conflict' } });
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
- if (!matches.length) groups.push(desired);
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 hook in the host (Codex: /hooks). Reconnect or restart if needed and confirm it discovers foundocs-capture-knowledge and foundocs. Installed files do not prove host discovery or execution.' };
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.sessionHook && restored.includes(join(root, state.sessionHook.file))) delete state.sessionHook;
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
  });
@@ -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.