@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.
@@ -30,7 +30,7 @@ Use these 1-based numbers when explaining stages or reporting progress. The serv
30
30
  - **1 — Memory Consolidation:** Distinguish byte-identical, same-scope duplicates from similar assertions. Assess topical placement using the folder review below, including knowledge still stored directly under a category root. Submit justified moves through the permitted Dreaming path; related links do not replace folder organization. Differences in environment, exceptions, provenance, metadata, or applicability disqualify automatic duplicate linking. A semantic merge is a reviewed rewrite; preserve every unique condition and source.
31
31
  - **2 — Conflict Resolution:** Compare matching subjects, scope, environment, and time period. Distinguish historical evolution from contradiction. Cite both sources and recommend a reviewed replacement, narrower scopes, or retaining the current state. A newer date never outranks an explicit rule by itself.
32
32
  - **3 — Knowledge Abstraction:** Identify recurring causes across independent experiences. Cite supporting cases, shared conditions, counterexamples, and limits. Prefer at least two independent cases; copied retellings count as one. Observations may describe patterns; activating generalized knowledge requires a reviewed create mutation.
33
- - **4 — Forgetting & Decay:** Require concrete evidence of obsolescence, lost applicability or repeated unnecessary retrieval after current-body and counterevidence review. Age and low retrieval frequency alone do not justify archival or lower importance, especially for rules and decisions. Explain retrieval impact and reversibility. Propose recoverable archive or importance changes for review; never permanent deletion.
33
+ - **4 — Forgetting & Decay:** Review the current body and project context for obsolescence, lost applicability, repeated unnecessary retrieval, or low future reuse value. A factually correct knowledge item can still be unnecessary; concrete content-based reasons can justify an archive proposal even without retrieval history. Age and low retrieval frequency alone do not justify archival or lower importance, especially for rules and decisions. Explain retrieval impact and reversibility. Propose recoverable archive or importance changes for review; never permanent deletion.
34
34
  - **5 — Memory Linking:** Link supported shared subject matter without claiming causality or authority. Deduplicate existing relations. Only related_to and eligible duplicate_of are auto candidates. supersedes, contradicts, supports, and derived_from need review and source evidence.
35
35
  - **6 — Reflection:** State documented outcome, supported explanation, useful next action, and applicability. Positive retrieval feedback measures retrieval usefulness, not task success. One incident can support a bounded lesson, never an unsupported universal rule.
36
36
 
@@ -40,9 +40,17 @@ Use `get_archive_candidates` with `{project_id, runId}` from this run, then foll
40
40
 
41
41
  For every relevant candidate, read all `retrievals` by continuing with `{project_id, runId, contentId, evidenceOffset: nextEvidenceOffset, evidenceVersion}` until nextEvidenceOffset is null. Continue the list separately with nextCursor. On VERSION_CONFLICT after an evaluation correction, content edit, archival, deletion or leaving the candidate set, discard the old evidence snapshot and restart the candidate/evidence read from the beginning. Do not splice evidenceVersion snapshots together.
42
42
 
43
- Read the current complete body with get_doc/get_docs at the returned versionToken. Compare counts.currentVersionNotBeneficial and counts.olderVersionNotBeneficial, actual evaluation reasons, purpose/task context, and beneficial records. An old problem already fixed in the current body is not a reason to propose again. Still-valid content can merit review for repeated unnecessary retrieval, but explain its useful applications and counterevidence. Four negative ratings do not cancel beneficial uses. Direct evidence of a retired feature, ended experiment or replaced policy can justify a proposal without retrieval counts; cite the relevant replacement or decision. Age and non-use alone never justify archive or importance reduction. Do not re-propose a rejected finding with the same evidence under a new title or explanation.
43
+ Read the current complete body with get_doc/get_docs at the returned versionToken. Compare counts.currentVersionNotBeneficial and counts.olderVersionNotBeneficial, actual evaluation reasons, purpose/task context, and beneficial records. An old problem already fixed in the current body is not a reason to propose again. Still-valid content can merit review for repeated unnecessary retrieval, but explain its useful applications and counterevidence. Four negative ratings do not cancel beneficial uses. Direct evidence of a retired feature, ended experiment or replaced policy can justify a proposal without retrieval counts; cite the relevant replacement or decision. The candidate list is a retrieval-signal shortlist, not the boundary of review: also assess low future reuse value in the other frozen knowledge targets you inspect, even when that list is empty. Age and non-use alone never justify archive or importance reduction. Do not re-propose a rejected finding with the same evidence under a new title or explanation.
44
44
 
45
- Submit archive-only `review_candidate` proposals with `{type: "archive", contentId}`, current targets/versionTokens and contiguous current-body excerpts in evidence. Keep retrieval statistics separate: `retrievalEvidence: [{contentId, versionToken, retrievalId, evaluationId, currentContentReason}]` references actual delivered retrieval/evaluation IDs and explains why that evaluated problem still applies to the current content. Never invent IDs or put an evaluation paraphrase into body evidence. The server verifies references and saves a fixed archiveReview snapshot, including beneficial counterevidence and the impact of exclusion from default retrieval. Explain the target, reason, counts and reasons or direct invalidation evidence, useful uses, and reversible retrieval impact for the human. Documents allow archive only; knowledge's other reviewed operations do not extend to documents.
45
+ ### Future reuse value
46
+
47
+ Assess whether the knowledge will help a future decision, recurring task, incident response or explanation of a still-relevant decision. Factual correctness alone does not require keeping an item in default retrieval. For example, a completed one-time task's incidental UI arrangement, temporary progress note or task-local observation with no reusable lesson can be unnecessary even though it remains true and has no negative evaluations. Explain the specific content and project context that limit its future use; do not invent retirement, replacement or retrieval statistics to justify it.
48
+
49
+ Before proposing, check plausible counteruses: rare incident recovery, current rules and constraints, reasons behind active decisions, audit or historical context, and useful unique conditions. Low frequency is not low value. If a useful reusable lesson is mixed with incidental detail, preserve it or propose a reviewed consolidation instead of archiving the whole item. If the future value is uncertain or project context is missing, retain the item and record the uncertainty; speculation that it will never be used is insufficient. This criterion does not expand frozen run scope or document mutation permissions.
50
+
51
+ For a low-reuse-value archive proposal, cite exact current-body excerpts and explain (1) why it is unlikely to help future work, (2) the counteruses checked and any remaining uncertainty, and (3) the reversible effect of removing it from default retrieval. Put these assessments in reason, alternatives, uncertainty and impact, not in fabricated source excerpts. No retrieval threshold applies to this content-grounded route; omit retrievalEvidence when there are no qualifying delivered retrieval references. Keep the proposal pending for specific human approval, just like other archive proposals.
52
+
53
+ Submit archive-only `review_candidate` proposals with `{type: "archive", contentId}`, current targets/versionTokens and contiguous current-body excerpts in evidence. Keep retrieval statistics separate: `retrievalEvidence: [{contentId, versionToken, retrievalId, evaluationId, currentContentReason}]` references actual delivered retrieval/evaluation IDs and explains why that evaluated problem still applies to the current content. Never invent IDs or put an evaluation paraphrase into body evidence. The server verifies references and saves a fixed archiveReview snapshot, including beneficial counterevidence and the impact of exclusion from default retrieval. Explain the target, reason, counts and reasons, direct invalidation evidence or content-grounded low future reuse value, useful uses, and reversible retrieval impact for the human. Documents allow archive only; knowledge's other reviewed operations do not extend to documents.
46
54
 
47
55
  ## Specific human chat approval
48
56
 
@@ -1,6 +1,6 @@
1
1
  # Optional effect measurement: automatic host procedure
2
2
 
3
- This is a host-agent procedure, not a request for the user to type commands. Run it automatically on a shell-capable Codex or Claude Code host when the project's policy is ON. Never enable the project's policy yourself. Normal Foundocs work continues if a sample is unavailable, with the reason reported. Do not silently fall back to another model/runner.
3
+ This is a host-agent procedure, not a request for the user to type commands. Run it automatically on a supported shell-capable host when the project's policy is ON. Never enable the project's policy yourself. Normal Foundocs work continues if a sample is unavailable, with the reason reported. Do not silently fall back to another model/runner.
4
4
 
5
5
  At the start of each information-acquisition task, before its first index, TL;DR, search or content exposure, call `get_effect_measurement_policy` once with the explicit configured project_id. Reuse this response throughout that task. OFF means no `measure prepare`, no `measure run`, no evaluation child and no probe inference. The policy response still consumes ordinary main-task context.
6
6
 
@@ -12,7 +12,7 @@ Automatically execute the installed CLI with stdin JSON (never include credentia
12
12
  foundocs-setup measure prepare --root /absolute/governing/project
13
13
  ```
14
14
 
15
- Input is `{policy, brief:{taskId,question,knownContext,criteria}, allowlist:["src","README.md"], excludePaths:["path/to/known-foundocs-export"]}`. Pass the exact policy response's data object. Use the installed `foundocs-setup` executable or `npx --yes @foundocs/foundocs-setup@latest` if that is the configured launcher. Do not put interpolated user text into shell command syntax: use a quoted heredoc or a private temporary input file and remove it afterward. Choose only user-authorized local original-source paths relative to the governing root; inspect provenance locally before selecting them. Do not use `.`/absolute/parent paths. Ordinary local user docs and extensionless UTF-8 sources are allowed. Explicitly exclude any known exported Foundocs docs/knowledge and already generated answers. Mandatory exclusions include `.git`, dependencies, credentials, `.env`, Foundocs config, installation/skills/session folders, AGENTS.md/CLAUDE.md, and legacy artifacts docs/knowledge/history. Symlink/hardlink sources and binary files are excluded. File/byte limits fail the entire snapshot, never silently truncate it. Unrecognized copied knowledge remains a source-provenance limitation.
15
+ Input is `{policy, host, brief:{taskId,question,knownContext,criteria}, allowlist:["src","README.md"], excludePaths:["path/to/known-foundocs-export"]}`. Pass the exact policy response's data object. `host` is the session object emitted by the installed SessionStart hook: `{client:"claude_code", sessionId, transcriptPath}` or `{client:"codex", sessionId, transcriptPath?}`. On Codex, omitting host lets the installer use the current process CODEX_THREAD_ID and locate only that exact thread’s rollout filename. It never reads other threads or chooses a model from config. Use only the current host-provided session identity/path; never search other sessions, infer a model, or ask the user to enter a model ID. If neither current hook identity nor CODEX_THREAD_ID is available, report `working_model_unavailable` and continue normal reads without tracking. The installer reads only the current session's latest assistant model metadata (not conversation text into the brief/server), freezes that exact model with the pre-exposure brief, and uses it for both arms. The old `policy.model` is ignored. A returned skipped reason is not a preparation and must not trigger probes. Use the installed `foundocs-setup` executable or `npx --yes @foundocs/foundocs-setup@latest` if that is the configured launcher. Do not put interpolated user text into shell command syntax: use a quoted heredoc or a private temporary input file and remove it afterward. Choose only user-authorized local original-source paths relative to the governing root; inspect provenance locally before selecting them. Do not use `.`/absolute/parent paths. Ordinary local user docs and extensionless UTF-8 sources are allowed. Explicitly exclude any known exported Foundocs docs/knowledge and already generated answers. Mandatory exclusions include `.git`, dependencies, credentials, `.env`, Foundocs config, installation/skills/session folders, AGENTS.md/CLAUDE.md, and legacy artifacts docs/knowledge/history. Symlink/hardlink sources and binary files are excluded. File/byte limits fail the entire snapshot, never silently truncate it. Unrecognized copied knowledge remains a source-provenance limitation.
16
16
 
17
17
  Only `status:"prepared"` authorizes measurement tracking. Save its `effectPreparationId` and the same taskId. Include BOTH on every subsequent `get_project_context` (including view:index), `search_docs`, `explore_docs`, `get_doc` and `get_docs`, retaining them across cursors/chunks. Gather all task retrievalIds, not only helpful ones. Do not retrieve extra content for the experiment or replace the captured response with a full document.
18
18
 
@@ -24,7 +24,9 @@ foundocs-setup measure run --root /absolute/governing/project
24
24
 
25
25
  stdin: `{taskId,retrievalIds:["all-task-retrieval-uuids"]}`. Multiple useful reads belong to this one run. The server chooses sampling/admission and arm order; the coordinator uses the exact captured text only for the with arm. Never call the model manually to reproduce a failed or uncertain run. A duplicate, crash or lost response must not create another probe or taskId. If the coordinator was interrupted or crashed, automatically invoke `measure flush` with the SAME taskId on resumption: it recovers only normalized observed costs after the old owner has exited and never spawns a probe. Do not call prepare with another taskId to reproduce it. For `report_pending`, use `measure flush --root ...` with `{taskId}` to resend only the identical report. A definite rejection requires investigation; it is not an uncertain transport retry, and changed payloads need a new requestId.
26
26
 
27
- Supported: local authenticated Claude Code 2.1.312 with safe-mode/restricted, on macOS shell hosts. Host and probe are different: Codex can coordinate Claude probes. Exact provider model IDs are required (for example `claude-haiku-5-5`); aliases, Codex-native probes, shell-less MCP/Chat/Desktop hosts, missing CLI/login/required isolation, Linux or Windows pending platform canary verification, external network sources and fallback models are unsupported. No preparation/model-discovery inference is used. Each arm is a fresh process in an independent sibling snapshot, Read/Glob/Grep only, empty MCP and settings sources, no persisted sessions, no shell/write/network/delegation. Foundocs credentials stay in the coordinator. The provider's existing local auth is needed; an execution sandbox that hides Keychain may make the runner unavailable.
27
+ Supported on macOS: authenticated Claude Code 2.1.312 and Codex CLI 0.166.0, including shell-capable Codex Desktop sessions with a current thread rollout. Claude uses fresh assistant metadata; Codex reads only the matching thread's session identity and latest turn_context model/effort, checks project boundaries and a freshly updated rollout. Paginated-only histories without current rollout metadata skip as working_model_unavailable. A user-facing model override is never accepted. Both arms use the working model; neither client substitutes the other provider. Missing/stale/unknown model metadata is working_model_unavailable. Missing CLI/login/isolation, Linux/Windows pending platform verification, shell-less hosts and external network sources skip. Preparation/model discovery does not run inference.
28
+
29
+ Claude uses fresh sibling snapshots and restricted Read/Glob/Grep with empty MCP/settings/skills. Codex starts an ephemeral app-server thread with no environments, shell, apps, plugins, browser, web search or delegation, in a fresh empty HOME/cwd. The host serves only Read/Glob/Grep against the exact frozen manifest, with canonical-path, regular-file and hash checks; no model-visible filesystem/auth access. Provider authentication is copied privately for the CLI and removed at exit; Foundocs credentials remain only in the coordinator. Current Codex model and reasoning effort are shared between arms. Codex reports cumulative input+output tokens (cached/reasoning tokens are already included); in-flight usage stays partial. No USD estimate is fabricated: Codex does not provide one, so its estimated USD cutoff cannot be enforced. Token admission, timeout and bounded tool/response steps apply; the CLI may already have an in-flight request when stopped.
28
30
 
29
31
  Each arm starts at most once. The coordinator checks server permission before spawn and every 5 seconds; network failure, OFF, changed revision or lease expiry stops the child and prevents the next arm. Termination is SIGINT, 3 seconds later SIGTERM, then 2 seconds later SIGKILL. An already in-flight provider request can still incur cost. Max turns is not an API request count; token reservations and estimated USD thresholds are admission/observation limits, not hard billing caps.
30
32
 
@@ -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
+ }
@@ -44,23 +44,35 @@ export async function autoUpdate(root, options = {}) {
44
44
  }
45
45
  }
46
46
 
47
- export async function sessionStart(args) {
47
+ export async function sessionStart(args, hookInput = {}) {
48
48
  try {
49
49
  if (args.length !== 2 || args[0] !== '--root' || !isAbsolute(args[1])) return null;
50
50
  const root = await realpath(args[1]);
51
51
  const script = fileURLToPath(import.meta.url);
52
52
  if (!['.agents', '.claude'].some(client => script === join(root, client, 'skills/foundocs/scripts/session-start.mjs'))) return null;
53
53
  const result = await autoUpdate(root);
54
- if (result.status !== 'updated') return null;
54
+ const isClaude = script.includes('/.claude/') || script.includes('\\.claude\\');
55
+ const host = !isClaude && typeof hookInput.session_id === 'string' && /^[0-9a-f-]{36}$/.test(hookInput.session_id)
56
+ ? { client: 'codex', sessionId: hookInput.session_id, ...(typeof hookInput.transcript_path === 'string' && isAbsolute(hookInput.transcript_path) ? { transcriptPath: hookInput.transcript_path } : {}) }
57
+ : isClaude && typeof hookInput.session_id === 'string' && /^[0-9a-f-]{36}$/.test(hookInput.session_id) && typeof hookInput.transcript_path === 'string' && isAbsolute(hookInput.transcript_path)
58
+ ? { client: 'claude_code', sessionId: hookInput.session_id, transcriptPath: hookInput.transcript_path } : null;
59
+ if (result.status !== 'updated' && !host) return null;
60
+ const context = [result.status === 'updated' ? `Foundocs skills updated to ${result.version}. Read the installed SKILL.md before using Foundocs; already loaded instructions may need a host reload.` : '', host ? `Foundocs effect measurement host session: ${JSON.stringify(host)}. Pass this host object to measure prepare; the installer reads only current model metadata. Never supply a guessed model.` : ''].filter(Boolean).join('\n');
55
61
  return { hookSpecificOutput: {
56
62
  hookEventName: 'SessionStart',
57
- additionalContext: `Foundocs skills updated to ${result.version}. Read the installed SKILL.md before using Foundocs; already loaded instructions may need a host reload.`,
58
- ...(script.includes('/.claude/') || script.includes('\\.claude\\') ? { reloadSkills: true } : {}),
63
+ additionalContext: context,
64
+ ...(isClaude && result.status === 'updated' ? { reloadSkills: true } : {}),
59
65
  } };
60
66
  } catch { return null; }
61
67
  }
62
68
 
63
69
  if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
64
- const output = await sessionStart(process.argv.slice(2));
70
+ let hookInput = {};
71
+ if (!process.stdin.isTTY) {
72
+ const timer = setTimeout(() => process.stdin.destroy(), 500);
73
+ try { let raw = ''; for await (const chunk of process.stdin) { raw += chunk; if (raw.length > 1024 * 1024) { process.stdin.destroy(); throw new Error(); } } hookInput = JSON.parse(raw); } catch { /* No host metadata: update still works. */ }
74
+ finally { clearTimeout(timer); }
75
+ }
76
+ const output = await sessionStart(process.argv.slice(2), hookInput);
65
77
  if (output) process.stdout.write(`${JSON.stringify(output)}\n`);
66
78
  }
@@ -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) {
@@ -0,0 +1,41 @@
1
+ import { open, realpath } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { join, relative } from 'node:path';
4
+ import { sha256 } from './effect-core.mjs';
5
+
6
+ // The model has no environment. These host tools are its only source access;
7
+ // exact manifest membership, canonical path and hash checks precede every read.
8
+ export async function snapshotTool(name, args, cwd, files) {
9
+ const paths = new Map(files.map(f => [f.path, f]));
10
+ const str = s => typeof s === 'string' && s.length <= 500 && !s.includes('\0');
11
+ async function read(path) {
12
+ if (!str(path) || !paths.has(path) || path.split('/').some(p => !p || p === '.' || p === '..') || path.includes('\\')) throw new Error('unavailable source');
13
+ const target = join(cwd, path);
14
+ if (relative(await realpath(cwd), await realpath(target)) !== path) throw new Error('unavailable source');
15
+ const handle = await open(target, constants.O_RDONLY | constants.O_NOFOLLOW);
16
+ try {
17
+ const st = await handle.stat(), expected = paths.get(path);
18
+ if (!st.isFile() || st.nlink !== 1 || st.size !== expected.bytes || st.size > 1024 * 1024) throw new Error('unavailable source');
19
+ const bytes = await handle.readFile();
20
+ if (sha256(bytes) !== expected.sha256) throw new Error('changed source');
21
+ return bytes.toString('utf8');
22
+ } finally { await handle.close(); }
23
+ }
24
+ if (!args || typeof args !== 'object' || Array.isArray(args)) throw new Error('invalid tool input');
25
+ let result;
26
+ if (name === 'Glob' && str(args.query)) result = [...paths.keys()].filter(p => p.includes(args.query)).slice(0, 200).join('\n');
27
+ else if (name === 'Read' && Number.isSafeInteger(args.offset) && args.offset >= 1 && Number.isSafeInteger(args.limit) && args.limit >= 1 && args.limit <= 200) {
28
+ result = (await read(args.path)).split('\n').slice(args.offset - 1, args.offset - 1 + args.limit).map((line, i) => `${args.offset + i}: ${line}`).join('\n');
29
+ } else if (name === 'Grep' && str(args.query) && args.query && str(args.path)) {
30
+ if (args.path && !paths.has(args.path)) throw new Error('unavailable source');
31
+ const matches = [];
32
+ for (const path of args.path ? [args.path] : paths.keys()) {
33
+ for (const [i, line] of (await read(path)).split('\n').entries()) if (line.includes(args.query)) {
34
+ matches.push(`${path}:${i + 1}: ${line}`); if (matches.length >= 100) break;
35
+ }
36
+ if (matches.length >= 100) break;
37
+ }
38
+ result = matches.join('\n');
39
+ } else throw new Error('unsupported tool');
40
+ return result.slice(0, 16000);
41
+ }