@foundocs/foundocs-setup 0.4.1 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,212 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, realpath } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import { join, isAbsolute } from 'node:path';
5
+ import { randomUUID } from 'node:crypto';
6
+ import { UUID, hash } from './effect-core.mjs';
7
+ import { storageBase } from './setup.mjs';
8
+ import { privateDir, readJson, saveJson, withStateLock } from './effect-storage.mjs';
9
+ import { analyze, DREAM_MODEL } from './dream-models.mjs';
10
+ import { INPUT_CHARS, WINDOW, boundDirectory, readMessages, safeText, transcripts } from './dream-transcripts.mjs';
11
+
12
+ async function binding(root) {
13
+ const f = await open(join(root, 'foundocs.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
14
+ try {
15
+ const s = await f.stat();
16
+ if (!s.isFile() || s.size > 64 * 1024) throw Error('invalid_binding');
17
+ const cfg = JSON.parse(await f.readFile('utf8'));
18
+ if (!UUID.test(cfg.project_id)) throw Error('invalid_binding');
19
+ return cfg;
20
+ } finally { await f.close(); }
21
+ }
22
+
23
+ function findings(value, messages) {
24
+ if (!value || !Array.isArray(value.findings) || value.findings.length > 60) throw Error('invalid_findings');
25
+ const refs = new Map(messages.map(m => [m.id, m]));
26
+ return value.findings.map(item => {
27
+ if (!['agreed', 'started', 'open', 'withdrawn'].includes(item?.state) || typeof item.summary !== 'string' || !item.summary.trim() || item.summary.length > 1200 || !Array.isArray(item.evidence) || !item.evidence.length || item.evidence.length > 16) throw Error('invalid_finding');
28
+ const summary = safeText(item.summary.trim());
29
+ if (!summary || summary !== item.summary.trim()) throw Error('unsafe_finding');
30
+ const evidence = item.evidence.map(ref => {
31
+ const msg = refs.get(ref?.id);
32
+ if (!msg || typeof ref.quote !== 'string' || !ref.quote.trim() || ref.quote.length > 640 || !msg.text.includes(ref.quote) || safeText(ref.quote) !== ref.quote) throw Error('unverified_evidence');
33
+ return { id: msg.id, session: msg.session, source: msg.source, timestamp: msg.timestamp, line: msg.line, role: msg.role, quote: ref.quote };
34
+ });
35
+ const state = evidence.some(m => m.role === 'user') ? item.state : 'open';
36
+ return { summary, state, evidence };
37
+ });
38
+ }
39
+
40
+ function emptyState() { return { seen: {}, pending: {}, receipts: {}, scanId: null, coverage: null }; }
41
+
42
+ function serverStart(value, now) {
43
+ if (value === undefined) return undefined;
44
+ // get_dream serializes UTC instants; reject local dates and Date.parse's
45
+ // silent normalization of impossible dates before creating a checkpoint.
46
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/.test(value)) throw Error('invalid_initial_since');
47
+ const ms = Date.parse(value);
48
+ if (!Number.isFinite(ms) || ms > now || new Date(ms).toISOString() !== (value.includes('.') ? value : value.replace('Z', '.000Z'))) throw Error('invalid_initial_since');
49
+ return ms;
50
+ }
51
+
52
+ function prune(state, cutoff) {
53
+ for (const key of ['seen', 'receipts']) for (const [id, time] of Object.entries(state[key])) if (time < cutoff) delete state[key][id];
54
+ for (const [id, group] of Object.entries(state.pending)) {
55
+ // Findings spanning the cutoff must be re-evaluated against the surviving
56
+ // messages. Never surface quotes or claims based on expired evidence.
57
+ if (group.messages.some(m => m.timestamp < cutoff)) delete state.pending[id];
58
+ }
59
+ }
60
+
61
+ function page(state, after = '') {
62
+ const groups = Object.values(state.pending).sort((a, b) => a.id.localeCompare(b.id));
63
+ if (after && !groups.some(group => group.id === after)) throw Error('invalid_page');
64
+ const start = after ? groups.findIndex(group => group.id === after) + 1 : 0;
65
+ const items = [];
66
+ let bytes = 0;
67
+ for (const entry of groups.slice(start, start + 10)) {
68
+ const item = { id: entry.id, session: entry.session, source: entry.source, findings: entry.findings };
69
+ const size = Buffer.byteLength(JSON.stringify(item));
70
+ if (items.length && bytes + size > 40_000) break;
71
+ bytes += size; items.push(item);
72
+ }
73
+ return { scanId: state.scanId, coverage: state.coverage, groups: items, pendingGroups: groups.length, next: start + items.length < groups.length ? items.at(-1).id : null };
74
+ }
75
+
76
+ async function scan(options, state, persist) {
77
+ const { now, since, config, projectId, runModel, recheck, home, codexHome, claudeHome } = options;
78
+ const eligibility = { preBindingMessages: 0, unprocessedMessages: 0 };
79
+ const failures = [], sessions = new Set(), unavailable = new Set(), bindings = new Map();
80
+ const known = new Set([...Object.keys(state.seen), ...Object.values(state.pending).flatMap(g => g.messages.map(m => m.id))]);
81
+ let analyzedMessages = 0, reusedMessages = 0;
82
+ async function processBatch(source, session, messages) {
83
+ if (!messages.length) return;
84
+ if (unavailable.has(source)) { eligibility.unprocessedMessages += messages.length; return; }
85
+ const dates = new Map();
86
+ for (const m of messages) dates.set(m.cwd, Math.min(m.timestamp, dates.get(m.cwd) ?? Infinity));
87
+ const origins = Array.from(dates, ([cwd, first]) => ({ cwd, first }));
88
+ async function checkOrigins() {
89
+ await recheck();
90
+ for (const { cwd, first } of origins) {
91
+ const current = await boundDirectory(cwd, config);
92
+ if (!current || first < current.since) throw Object.assign(Error('binding_changed'), { code: 'binding_changed' });
93
+ }
94
+ }
95
+ await checkOrigins();
96
+ let output, items;
97
+ try { output = await runModel(source, messages); }
98
+ catch {
99
+ // No receipt for failed/unattempted messages. Back off an unavailable
100
+ // provider without blocking another host's history.
101
+ unavailable.add(source);
102
+ eligibility.unprocessedMessages += messages.length;
103
+ failures.push({ source, session, reason: 'provider_unavailable' });
104
+ return;
105
+ }
106
+ try { items = findings(output, messages); }
107
+ catch {
108
+ eligibility.unprocessedMessages += messages.length;
109
+ failures.push({ source, session, reason: 'unverified_model_output' });
110
+ return;
111
+ }
112
+ await checkOrigins();
113
+ const refs = messages.map(({ id, timestamp }) => ({ id, timestamp }));
114
+ if (items.length) {
115
+ const id = hash([projectId, source, session, refs]);
116
+ state.pending[id] = { id, session, source, origins, messages: refs, findings: items };
117
+ } else {
118
+ for (const m of refs) state.seen[m.id] = m.timestamp;
119
+ }
120
+ await persist();
121
+ for (const m of refs) known.add(m.id);
122
+ analyzedMessages += messages.length;
123
+ }
124
+ for await (const f of transcripts({ home, codexHome, claudeHome, failures })) {
125
+ let messages = [], chars = 0;
126
+ try {
127
+ for await (const msg of readMessages(f.path, f.source, f.session, config, since, now, bindings, eligibility)) {
128
+ sessions.add(f.source + '/' + f.session);
129
+ if (known.has(msg.id)) { reusedMessages++; continue; }
130
+ if (messages.length && chars + msg.text.length + 300 > INPUT_CHARS) {
131
+ await processBatch(f.source, f.session, messages);
132
+ messages = []; chars = 0;
133
+ }
134
+ messages.push(msg);
135
+ chars += msg.text.length + 300;
136
+ }
137
+ await processBatch(f.source, f.session, messages);
138
+ } catch (error) {
139
+ if (error.code === 'binding_changed' || error.code === 'cannot_save_review') throw error;
140
+ const identified = sessions.has(f.source + '/' + f.session);
141
+ failures.push({ source: f.source, ...(identified ? { session: f.session } : {}), reason: 'unreadable_session' });
142
+ }
143
+ }
144
+ state.scanId = randomUUID();
145
+ state.coverage = { since: new Date(since).toISOString(), through: new Date(now).toISOString(), sessions: sessions.size, ...eligibility, analyzedMessages, reusedMessages, failures, models: DREAM_MODEL };
146
+ await persist();
147
+ return page(state);
148
+ }
149
+
150
+ export async function dreamSessions(action, directory, input, options = {}) {
151
+ if (!isAbsolute(directory) || !UUID.test(input?.projectId)) throw Error('invalid_project');
152
+ const root = await realpath(directory);
153
+ const config = await binding(root);
154
+ const check = async () => {
155
+ const current = await binding(root);
156
+ if (current.project_id !== input.projectId || current.workspace_id !== config.workspace_id) throw Object.assign(Error('binding_changed'), { code: 'binding_changed' });
157
+ };
158
+ await check();
159
+ const home = options.home ?? homedir();
160
+ const base = options.storage ?? await storageBase({}, root);
161
+ const dir = join(base, 'dream-sessions', input.projectId);
162
+ await privateDir(dir);
163
+ const path = join(dir, 'review.json');
164
+ return withStateLock(path, async () => {
165
+ await check();
166
+ const now = options.now ?? Date.now();
167
+ const suppliedSince = serverStart(input.initialSince, now);
168
+ if (suppliedSince !== undefined && action !== 'scan') throw Error('invalid_initial_since');
169
+ const previous = await readJson(path).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
170
+ const state = previous ?? emptyState();
171
+ prune(state, now - WINDOW);
172
+ const bindings = new Map();
173
+ for (const entry of Object.values(state.pending)) {
174
+ for (const { cwd, first } of entry.origins) {
175
+ const current = await boundDirectory(cwd, config, bindings);
176
+ if (!current || first < current.since) { delete state.pending[entry.id]; break; }
177
+ }
178
+ }
179
+ const persist = async () => {
180
+ await check();
181
+ try { await saveJson(path, state); }
182
+ catch { throw Object.assign(Error('cannot_save_review'), { code: 'cannot_save_review' }); }
183
+ };
184
+ if (action === 'scan') {
185
+ if (state.initialSince === undefined) {
186
+ // Older journals may already contain unacknowledged or failed ranges.
187
+ // Preserve their effective lower bound instead of moving it to a newer server run.
188
+ const legacySince = previous ? Date.parse(state.coverage?.since) : NaN;
189
+ state.initialSince = previous ? (Number.isFinite(legacySince) ? legacySince : now - WINDOW) : (suppliedSince ?? now - WINDOW);
190
+ await persist(); // even a crash before the first model call must retain this baseline
191
+ }
192
+ if (!Number.isSafeInteger(state.initialSince) || state.initialSince > now) throw Error('invalid_initial_since');
193
+ const since = Math.max(state.initialSince, now - WINDOW);
194
+ return scan({ config, home, projectId: input.projectId, recheck: check, now, since, runModel: options.analyze ?? analyze, codexHome: options.codexHome ?? process.env.CODEX_HOME, claudeHome: options.claudeHome ?? process.env.CLAUDE_CONFIG_DIR }, state, persist);
195
+ }
196
+ if (!state.scanId || input.scanId !== state.scanId) throw Error('stale_scan');
197
+ if (action === 'page') return page(state, input.after);
198
+ if (action !== 'ack' || !Array.isArray(input.groups) || !input.groups.length || input.groups.length > 100) throw Error('invalid_ack');
199
+ for (const id of input.groups) {
200
+ if (!Object.hasOwn(state.pending, id) && !Object.hasOwn(state.receipts, id)) throw Error('unknown_group');
201
+ }
202
+ for (const id of input.groups) {
203
+ const entry = state.pending[id];
204
+ if (!entry) continue;
205
+ for (const m of entry.messages) state.seen[m.id] = m.timestamp;
206
+ state.receipts[id] = now;
207
+ delete state.pending[id];
208
+ }
209
+ await persist();
210
+ return { acknowledged: input.groups.length, pendingGroups: Object.keys(state.pending).length };
211
+ });
212
+ }
@@ -0,0 +1,151 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, realpath, readdir, lstat } from 'node:fs/promises';
3
+ import { createInterface } from 'node:readline';
4
+ import { basename, dirname, isAbsolute, join } from 'node:path';
5
+ import { UUID, sha256 } from './effect-core.mjs';
6
+
7
+ export const WINDOW = 30 * 24 * 60 * 60 * 1000;
8
+ export const INPUT_CHARS = 24_000;
9
+
10
+ async function* files(dir, failures, source, top = true) {
11
+ let entries;
12
+ try { entries = await readdir(dir, { withFileTypes: true }); }
13
+ catch (error) {
14
+ if (!top || error.code !== 'ENOENT') failures.push({ source, reason: 'unreadable_directory' });
15
+ return;
16
+ }
17
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
18
+ const path = join(dir, entry.name);
19
+ if (entry.isDirectory()) yield* files(path, failures, source, false);
20
+ else if (entry.isFile() && entry.name.endsWith('.jsonl')) yield path;
21
+ }
22
+ }
23
+
24
+ export function safeText(text) {
25
+ if (typeof text !== 'string' || /-----BEGIN [A-Z ]*PRIVATE KEY-----|<environment_context>|^# AGENTS\.md instructions|^<local-command|^<command-name>|^<system-reminder>|^<instructions>|^<INSTRUCTIONS>|^<environment_context>|^<user_instructions>|^<turn_aborted>|^<local-command-caveat>|^<subagent_notification>|^<permissions instructions>/i.test(text.trim())) return '';
26
+ return text.replace(/(\bauthorization\s*[:=]\s*)(?:bearer|basic)\s+[^\s,;]+/ig, '$1[redacted]')
27
+ .replace(/\b(?:sk-[\w-]{12,}|sd_(?:agent|setup|key)_[\w-]{8,}|gh[pousr]_[A-Za-z0-9]{16,}|github_pat_[\w]{16,}|AKIA[A-Z0-9]{16})\b/g, '[redacted]')
28
+ .replace(/\bBearer\s+[a-z0-9+/.=_-]+/ig, 'Bearer [redacted]')
29
+ .replace(/(\b(?:authorization|api[_-]?key|password|access[_-]?token|secret)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s,;]+)/ig, '$1[redacted]');
30
+ }
31
+
32
+ async function readBindingAt(path) {
33
+ let file;
34
+ try {
35
+ file = await open(join(path, 'foundocs.json'), constants.O_RDONLY | constants.O_NOFOLLOW);
36
+ const stat = await file.stat();
37
+ if (!stat.isFile() || stat.size > 64 * 1024) return null;
38
+ const cfg = JSON.parse(await file.readFile('utf8'));
39
+ // A folder may have been rebound or the config copied into a new checkout.
40
+ // Only trust messages after the current binding is known to have existed.
41
+ // ctime guards manual replacement or an in-place edit carrying an old epoch.
42
+ const stamp = Date.parse(cfg.session_history_since);
43
+ return { ...cfg, since: Math.max(Math.ceil(stat.ctimeMs), Number.isFinite(stamp) ? stamp : 0) };
44
+ } catch (e) { return e.code === 'ENOENT' ? undefined : null; }
45
+ finally { await file?.close(); }
46
+ }
47
+
48
+ // The destination always comes from the explicit invocation. These local
49
+ // bindings only prove attribution of transcript metadata, including another
50
+ // checkout linked to the same exact project. A Git boundary ends the search.
51
+ export async function boundDirectory(cwd, config, bindings = new Map()) {
52
+ if (typeof cwd !== 'string' || !isAbsolute(cwd)) return null;
53
+ if (bindings.has(cwd)) return bindings.get(cwd);
54
+ let path = await realpath(cwd).catch(() => null), found = null;
55
+ while (path) {
56
+ const cfg = await readBindingAt(path);
57
+ if (cfg !== undefined) {
58
+ if (cfg?.project_id === config.project_id && (!cfg.workspace_id || !config.workspace_id || cfg.workspace_id === config.workspace_id)) found = { root: path, since: cfg.since };
59
+ break;
60
+ }
61
+ try { await lstat(join(path, '.git')); break; }
62
+ catch (e) { if (e.code !== 'ENOENT') break; }
63
+ if (dirname(path) === path) break;
64
+ path = dirname(path);
65
+ }
66
+ bindings.set(cwd, found);
67
+ return found;
68
+ }
69
+
70
+ function spokenText(role, content) {
71
+ const types = role === 'user' ? ['text', 'input_text'] : ['text', 'output_text'];
72
+ if (typeof content === 'string') return safeText(content);
73
+ if (!Array.isArray(content)) return '';
74
+ return content.filter(part => types.includes(part?.type)).map(part => safeText(part.text)).filter(Boolean).join('\n');
75
+ }
76
+
77
+ export async function* readMessages(path, source, session, config, since, now, bindings, coverage) {
78
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
79
+ try {
80
+ const stat = await file.stat();
81
+ if (!stat.isFile() || stat.nlink !== 1 || !stat.size || stat.mtimeMs < since) return;
82
+ const input = file.createReadStream({ autoClose: false, end: stat.size - 1 });
83
+ const lines = createInterface({ input, crlfDelay: Infinity });
84
+ let position = 0, origin = null, cwd;
85
+ try {
86
+ for await (const line of lines) {
87
+ position++;
88
+ if (!line.trim()) continue;
89
+ // A concurrently appended, incomplete record is left for a later scan.
90
+ const event = JSON.parse(line);
91
+ if (source === 'codex') {
92
+ const p = event.payload;
93
+ if (position === 1) {
94
+ if (event.type !== 'session_meta' || p?.id !== session || p.source === 'subagent' || p.source?.subagent) return;
95
+ cwd = p.cwd;
96
+ origin = await boundDirectory(cwd, config, bindings);
97
+ if (!origin) return;
98
+ continue;
99
+ }
100
+ if (event.type === 'session_meta') return;
101
+ if (event.type === 'turn_context') { cwd = p?.cwd; origin = await boundDirectory(cwd, config, bindings); continue; }
102
+ if (!origin || event.type !== 'response_item' || p?.type !== 'message') continue;
103
+ if (p.channel && !['final', 'commentary'].includes(p.channel)) continue;
104
+ if (p.phase && !['final_answer', 'commentary'].includes(p.phase)) continue;
105
+ if (p.recipient && p.recipient !== 'all') continue;
106
+ } else {
107
+ if (event.type !== 'user' && event.type !== 'assistant') continue;
108
+ if (event.sessionId !== session || event.isMeta || event.isSidechain || event.parent_tool_use_id || event.isCompactSummary || event.isApiErrorMessage) continue;
109
+ const first = cwd === undefined;
110
+ cwd = event.cwd;
111
+ origin = await boundDirectory(cwd, config, bindings);
112
+ if (!origin) { if (first) return; continue; }
113
+ }
114
+ const msg = source === 'codex' ? event.payload : event.message;
115
+ if (!['user', 'assistant'].includes(msg?.role) || (source === 'claude' && msg.role !== event.type)) continue;
116
+ const timestamp = Date.parse(event.timestamp);
117
+ if (!Number.isFinite(timestamp) || timestamp < since || timestamp > now) continue;
118
+ if (timestamp < origin.since) { coverage.preBindingMessages++; continue; }
119
+ const text = spokenText(msg.role, msg.content);
120
+ if (!text.trim()) continue;
121
+ // Split very long messages instead of skipping their remaining content.
122
+ for (let start = 0; start < text.length; start += INPUT_CHARS - 1024) {
123
+ const part = text.slice(start, start + INPUT_CHARS - 1024);
124
+ const id = sha256(JSON.stringify([source, session, position, start, timestamp, part]));
125
+ yield { id, source, session, cwd, line: position, start, timestamp, role: msg.role, text: part };
126
+ }
127
+ }
128
+ } finally { lines.close(); input.destroy(); }
129
+ } finally { await file.close(); }
130
+ }
131
+
132
+ export async function* transcripts({ home, codexHome, claudeHome, failures }) {
133
+ const codex = codexHome || join(home, '.codex');
134
+ const claude = claudeHome || join(home, '.claude');
135
+ const directories = [{ source: 'codex', path: join(codex, 'sessions') }, { source: 'codex', path: join(codex, 'archived_sessions') }];
136
+ const projects = join(claude, 'projects');
137
+ let entries;
138
+ try { entries = await readdir(projects, { withFileTypes: true }); }
139
+ catch (error) { if (error.code !== 'ENOENT') failures.push({ source: 'claude', reason: 'unreadable_directory' }); }
140
+ // Claude project directory names are lossy encodings and can be truncated.
141
+ // Inspect per-session cwd metadata instead of inferring identity from a name.
142
+ for (const entry of entries ?? []) if (entry.isDirectory()) directories.push({ source: 'claude', path: join(projects, entry.name) });
143
+ for (const dir of directories) {
144
+ for await (const path of files(dir.path, failures, dir.source)) {
145
+ const name = basename(path, '.jsonl');
146
+ if (dir.source === 'codex' && !name.startsWith('rollout-')) continue;
147
+ const session = dir.source === 'codex' ? name.slice(-36) : name;
148
+ if (UUID.test(session)) yield { source: dir.source, session, path };
149
+ }
150
+ }
151
+ }
@@ -7,6 +7,9 @@ import { CODEX_CONFIG, CODEX_TOOLS, codexUsage } from './effect-codex.mjs';
7
7
  import { snapshotTool } from './effect-codex-tools.mjs';
8
8
  import { SYSTEM, missingObservation } from './effect-core.mjs';
9
9
  const policy = JSON.parse(process.argv[2]);
10
+ const sessionReview = policy.purpose === 'dream-session';
11
+ const instructions = sessionReview ? (await import('./dream-models.mjs')).DREAM_PROMPT : SYSTEM;
12
+ const availableTools = sessionReview ? [] : CODEX_TOOLS;
10
13
  let child, temporary, stopping = false, closed = false, input = '', line = '', threadId, turnId, output = null, usage = null, steps = 0, calls = 0, sequence = 0;
11
14
  const pending = new Map(), timers = [];
12
15
  const emit = value => process.stdout.write(JSON.stringify(value) + '\n');
@@ -39,7 +42,7 @@ async function accept(event, payload) {
39
42
  if (!settings || settings.model !== policy.model || settings.modelProvider !== 'openai' || settings.approvalPolicy !== 'never' || settings.sandboxPolicy?.type !== 'readOnly' || settings.sandboxPolicy.networkAccess !== false) throw new Error('settings changed');
40
43
  }
41
44
  if (event.method === 'item/tool/call') {
42
- if (!CODEX_TOOLS.some(t => t.name === p.tool) || p.namespace || ++calls > policy.perProbeMaxTurns) throw new Error('tool limit');
45
+ if (!availableTools.some(t => t.name === p.tool) || p.namespace || ++calls > policy.perProbeMaxTurns) throw new Error('tool limit');
43
46
  let text, success = true;
44
47
  try { text = await snapshotTool(p.tool, p.arguments, process.cwd(), payload.snapshotFiles); }
45
48
  catch { text = 'Source unavailable: only frozen snapshot paths and supported read operations are allowed.'; success = false; }
@@ -94,7 +97,7 @@ async function run(payload) {
94
97
  timers.push(setTimeout(stop, policy.perProbeTimeoutMs));
95
98
  try {
96
99
  await call('initialize', { clientInfo: { name: 'foundocs_effect', version: '1' }, capabilities: { experimentalApi: true } }); send({ method: 'initialized' });
97
- const t = await call('thread/start', { model: policy.model, modelProvider: 'openai', allowProviderModelFallback: false, cwd: empty, environments: [], ephemeral: true, approvalPolicy: 'never', sandbox: 'read-only', baseInstructions: SYSTEM, dynamicTools: CODEX_TOOLS });
100
+ const t = await call('thread/start', { model: policy.model, modelProvider: 'openai', allowProviderModelFallback: false, cwd: empty, environments: [], ephemeral: true, approvalPolicy: 'never', sandbox: 'read-only', baseInstructions: instructions, dynamicTools: availableTools });
98
101
  if (t.model !== policy.model || t.modelProvider !== 'openai' || t.thread.ephemeral !== true || !Array.isArray(t.thread.environments) || t.thread.environments.length || !Array.isArray(t.instructionSources) || t.instructionSources.length || t.approvalPolicy !== 'never' || t.sandbox.type !== 'readOnly' || t.sandbox.networkAccess !== false) throw new Error('isolation unavailable');
99
102
  threadId = t.thread.id;
100
103
  emit({ type: 'effect_init', model: t.model, verified: true });
@@ -32,7 +32,7 @@ function stripRaw(state) {
32
32
  if (value.reservation) { value.reservation = { ...value.reservation }; delete value.reservation.deliveredContext; }
33
33
  return value;
34
34
  }
35
- async function withStateLock(path, operation) {
35
+ export async function withStateLock(path, operation) {
36
36
  const lock = `${path}.write-lock`; let handle;
37
37
  for (let attempt = 0; !handle && attempt < 500; attempt++) {
38
38
  try { handle = await open(lock, 'wx', 0o600); await handle.writeFile(String(process.pid)); }
package/src/global.mjs CHANGED
@@ -64,6 +64,13 @@ async function requestProjects(dir, client, ws, input, fetcher = fetch) {
64
64
  return body;
65
65
  }
66
66
 
67
+ // Unmodified 0.4.0 global descriptors predate installation receipts.
68
+ const legacyDescriptorHashes = new Map([
69
+ ['foundocs/SKILL.md', 'f94766dbc91c8e87a749f40f2af64994e516053c225cf454b2288ae6274129e6'],
70
+ ['foundocs-capture-episode/SKILL.md', 'be15feb8a06682cc4025ebc16355be7a597984b13209abc104917f681666c791'],
71
+ ['foundocs-capture-knowledge/SKILL.md', '13dd143183a608d6a5fb37002f16de71473a21a63bca0903a9a8217812968f25'],
72
+ ]);
73
+
67
74
  async function prepareHost(input, dir) {
68
75
  const { client, workspaceId } = input;
69
76
  const home = homedir();
@@ -125,8 +132,8 @@ async function prepareHost(input, dir) {
125
132
  const legacy = join(skillRoot, name);
126
133
  await safeParent(dirname(configHome), legacy);
127
134
  const descriptor = await textFile(legacy);
128
- if (descriptor !== null && descriptor !== content) fail('Global skill has local edits: ' + legacy);
129
- if (descriptor !== null) legacySkills.push({ path: legacy, content });
135
+ if (descriptor !== null && descriptor !== content && digest(descriptor) !== legacyDescriptorHashes.get(name)) fail('Global skill has local edits: ' + legacy);
136
+ if (descriptor !== null) legacySkills.push({ path: legacy, content: descriptor });
130
137
  }
131
138
  }
132
139
  return async () => {
@@ -248,7 +255,7 @@ export async function bindProject(action, args, options = {}) {
248
255
  }
249
256
  if (await textFile(configPath) !== previous) fail('The folder binding changed during this request. Review it before retrying.');
250
257
  const mode = previous === null ? 0o644 : (await lstat(configPath)).mode & 0o777;
251
- await atomicWrite(configPath, json({ ...binding, workspace_id: ws.id, project_id: project.id }), mode);
258
+ await atomicWrite(configPath, json({ ...binding, workspace_id: ws.id, project_id: project.id, session_history_since: new Date().toISOString() }), mode);
252
259
  if (pending) await unlink(journal);
253
260
  return { status: 'linked', workspace: catalog.workspace, project: { id: project.id, name: project.name }, server: serverName(ws.id) };
254
261
  });
package/src/runtime.mjs CHANGED
@@ -1,11 +1,10 @@
1
- import { lstat, realpath } from 'node:fs/promises';
1
+ import { lstat, realpath, rm } from 'node:fs/promises';
2
2
  import { dirname, join, isAbsolute } from 'node:path';
3
3
  import { createHash } from 'node:crypto';
4
4
  import { isDeepStrictEqual } from 'node:util';
5
5
  import { legacy } from './legacy-compat.mjs';
6
6
  import { readCredential, windowsPrivateAcl } from './auth.mjs';
7
7
  import { loadInstallation, textFile, parseJson, validateUrl, SetupError } from './setup.mjs';
8
- import { cleanExpired } from './effect-storage.mjs';
9
8
  import { runBridge } from './bridge.mjs';
10
9
 
11
10
  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;
@@ -65,34 +64,13 @@ export async function resolveRuntime(projectId, options = {}) {
65
64
 
66
65
  export async function startRuntime(projectId, options = {}) {
67
66
  const manifest = await resolveRuntime(projectId, options);
67
+ const { directory } = await loadInstallation(manifest.root, options);
68
+ // Earlier runtimes kept temporary copies of source files in this private directory.
68
69
  try {
69
- const { directory } = await loadInstallation(manifest.root, options);
70
- await cleanExpired(join(directory, 'effects'));
70
+ await rm(join(directory, 'effects'), { recursive: true, force: true });
71
+ await rm(join(directory, 'measurement-consent.json'), { force: true });
71
72
  } catch {
72
- // Optional measurement cleanup must not disable ordinary authenticated MCP.
73
- process.stderr.write('Foundocs measurement cleanup unavailable; ordinary MCP continues. Run measure diagnostics before another sample.\n');
73
+ process.stderr.write('Foundocs could not remove retired measurement files from private installation storage.\n');
74
74
  }
75
- const { directory } = await loadInstallation(manifest.root, options);
76
- await runBridge({ ...manifest, automaticBase: join(directory, 'effects'), automaticFactory: async ({ recovery = false } = {}) => {
77
- const { EffectCoordinator } = await import('./effect.mjs');
78
- const { readAutomaticConsent } = await import('./effect-config.mjs');
79
- const { connectEffectRemote } = await import('./effect-remote.mjs');
80
- // A fresh remote is scoped to this installation. Coordinator run owns its lifetime.
81
- const config = await readAutomaticConsent(directory);
82
- if (!config.enabled && !recovery) return { config };
83
- const remote = await connectEffectRemote(manifest);
84
- const scopedRemote = { call: async (name, args) => {
85
- if (name === 'control_effect_measurement' && ['start_arm', 'heartbeat'].includes(args.action)) {
86
- const current = await readAutomaticConsent(directory);
87
- if (!current.enabled || JSON.stringify(current) !== JSON.stringify(config)) return { action: 'stop', policyRevision: args.policyRevision, reason: 'cancelled' };
88
- }
89
- return remote.call(name, args);
90
- } };
91
- const coordinator = new EffectCoordinator({ root: manifest.root, base: join(directory, 'effects'), remote: scopedRemote });
92
- return { config, coordinator: {
93
- async prepare(input) { try { return await coordinator.prepare(input); } finally { await remote.close(); } },
94
- async flush(taskId) { try { return await coordinator.flush(taskId); } finally { await remote.close(); } },
95
- async run(input) { try { return await coordinator.run(input); } finally { await remote.close(); } },
96
- } };
97
- } });
75
+ await runBridge(manifest);
98
76
  }
package/src/setup.mjs CHANGED
@@ -12,7 +12,6 @@ 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 { validateAutomaticConsent, saveAutomaticConsent, readAutomaticConsent } from './effect-config.mjs';
16
15
  import { episodeDiagnostics } from '../skills/foundocs/scripts/episode-checkpoint.mjs';
17
16
 
18
17
  const exec = promisify(execFile);
@@ -36,7 +35,6 @@ export function validateInput(input) {
36
35
  if (!plainObject(input) || input.version !== 1 || !['claude', 'codex'].includes(input.client)) fail('input', 'Unsupported installation input.');
37
36
  for (const key of ['projectId', 'workspaceId', 'attemptId']) if (!UUID.test(input[key])) fail('input', `A UUID ${key} is required.`);
38
37
  if (typeof input.code !== 'string' || input.code.length < 16 || input.code.length > 512 || /\s/.test(input.code)) fail('input', 'A valid one-time connection code is required.');
39
- if (input.effectMeasurement !== undefined) validateAutomaticConsent(input.effectMeasurement);
40
38
  validateUrl(input.exchangeUrl); validateUrl(input.mcpUrl);
41
39
  return input;
42
40
  }
@@ -555,6 +553,17 @@ async function skillPlan(root, client, directory, projectId) {
555
553
  const state = stateText === null ? { version: 1, root, files: {} } : parseJson(stateText, statePath);
556
554
  if (state.version !== 1 || state.root !== root || !plainObject(state.files)) fail('preflight', 'Invalid skill installation metadata. Existing assets were preserved.');
557
555
  const entries = [], pending = { ...state, files: { ...state.files } }, complete = { ...state, files: { ...state.files } };
556
+ const retiredName = `${client === 'claude' ? '.claude' : '.agents'}/skills/foundocs/references/effect-measurement.md`;
557
+ const retired = state.files[retiredName];
558
+ if (retired) {
559
+ const path = join(root, retiredName);
560
+ await safeParent(root, path);
561
+ const before = await textFile(path);
562
+ if (before !== null && [retired.installedHash, retired.pendingHash].includes(digest(before))) {
563
+ entries.push({ path, before, after: null, mode: (await lstat(path)).mode & 0o777 });
564
+ }
565
+ delete complete.files[retiredName];
566
+ }
558
567
  for (const asset of skillAssets(client)) {
559
568
  const path = join(root, asset.name);
560
569
  await safeParent(root, path);
@@ -840,9 +849,8 @@ export async function install(rootPath, rawInput, options = {}) {
840
849
  if (error instanceof SetupError) fail('configuration', `${error.message} The installation key is saved; rerun with the same input, or run rollback to undo unchanged setup edits.`, { ...error.details, attemptId: saved.attemptId });
841
850
  fail('configuration', 'Configuration write failed. The credential was saved; rerun install with the same input, or run rollback to undo unchanged setup edits.', { attemptId: saved.attemptId });
842
851
  }
843
- if (input.effectMeasurement !== undefined) await saveAutomaticConsent(rootDirectory, input.effectMeasurement);
844
852
  const diagnostic = await (options.diagnose ?? diagnose)(manifest, credentialPath, options);
845
- return { ok: true, status: 'configured', root, client, changedFiles: changes.map((entry) => entry.path), reusedCredential, diagnostic, measurement: { consent: (await readAutomaticConsent(rootDirectory)).enabled ? 'accepted' : 'required', hostPermissions: 'unchanged', next: 'Review project data sharing and additional model usage before enabling automatic measurement. Host MCP/process/network permissions must allow the installed runner; the installer never weakens host security.' }, skills: skillsInstalled() };
853
+ return { ok: true, status: 'configured', root, client, changedFiles: changes.map((entry) => entry.path), reusedCredential, diagnostic, skills: skillsInstalled() };
846
854
  });
847
855
  }
848
856
 
@@ -864,7 +872,6 @@ export async function doctor(rootPath, options = {}) {
864
872
  const runtimeFiles = manifest.runtimeVersion ? [] : [manifest.helperPath, ...(manifest.brandingVersion === 2 ? [join(dirname(manifest.helperPath), 'legacy-compat.mjs')] : []), ...(manifest.client === 'codex' ? [join(dirname(manifest.helperPath), 'bridge-v1.mjs')] : [])];
865
873
  for (const path of runtimeFiles) if (await textFile(path) === null) fail('diagnostic', 'A durable authentication helper is missing. Rerun install to repair it.', { path });
866
874
  const oldFormat = await textFile(join(root, 'foundocs.json')) === null && await textFile(join(root, legacy.config)) !== null;
867
- const measurement = { consent: (await readAutomaticConsent(directory)).enabled ? 'accepted' : 'required', hostPermissions: 'unchanged', executionVerified: false };
868
875
  const skills = await checkSkills(root, directory, manifest, oldFormat);
869
876
  {
870
877
  let servers;
@@ -886,7 +893,7 @@ export async function doctor(rootPath, options = {}) {
886
893
  if (entries.some((entry) => entry.before !== entry.after)) fail('diagnostic', 'Installation files are incomplete or modified. Rerun install to repair them.');
887
894
  const client = await (options.probeClient ?? probeClient)(manifest.client);
888
895
  const diagnostic = await (options.diagnose ?? diagnose)(manifest, manifest.credentialPath, options);
889
- return { ok: true, status: 'configured', root, client, diagnostic, measurement, 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 update command, reconnect MCP and review the host hooks.' }) } };
896
+ 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 update command, reconnect MCP and review the host hooks.' }) } };
890
897
  }
891
898
 
892
899
  export async function rollback(rootPath, options = {}) {
@@ -20,7 +20,7 @@ export function skillAssets(client) {
20
20
  return [
21
21
  ...['SKILL.md', 'references/capture.md'].map(name => ({ name: `foundocs-capture-episode/${name}` })),
22
22
  ...SKILL_FILES.map(name => ({ name: `${SKILL_NAME}/${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}` })),
23
+ ...['SKILL.md', 'references/configuration.md', 'references/documents.md', 'references/dreaming.md', 'references/updates.md', 'scripts/check-update.mjs', 'scripts/session-start.mjs', 'scripts/episode-checkpoint.mjs'].map(name => ({ name: `foundocs/${name}` })),
24
24
  ].map(({ name }) => ({
25
25
  name: `${prefix}${name}`,
26
26
  content: readFileSync(new URL(`../skills/${name}`, import.meta.url), 'utf8'),
@@ -1,6 +1,6 @@
1
1
  - Before project context lookup, document management, or any Foundocs MCP call, read and follow [foundocs]({{FOUNDOCS_SKILL_PATH}}).
2
- - Write requested or approved documents under `docs/`. Ask before adding others.
2
+ - Capture project discussions under `docs/` when a topic closes. At implementation start, update the feature document. Ask if sharing intent is unclear.
3
3
  - For durable context, rules, confirmed decisions or verified reusable lessons (including corrections), write under `docs/knowledge/{rules,decisions,learnings}/` via [foundocs-capture-knowledge]({{SKILL_PATH}}) in the same turn, even without a request to save. Skip when there is nothing new to keep.
4
- - Batch small tasks via [foundocs-capture-episode]({{EPISODE_SKILL_PATH}}) at PR handoff or completed rollout, not each step/turn. Wait for the final intended boundary. Honor opt-out.
4
+ - Record each closed discussion in a brief [episode]({{EPISODE_SKILL_PATH}}). Batch implementation steps until delivery. Honor opt-out.
5
5
  - Run Dreaming only on an explicit user request (including “꿈꾸자” or “꿈구자”); follow the foundocs skill. Quoted triggers and ordinary capture do not start Dreaming.
6
6
  - Project configuration: `foundocs.json` beside this governing AGENTS.md; resolve it from that directory, including when working in nested directories.
@@ -1,6 +1,9 @@
1
1
  ---
2
2
  name: foundocs-workspace
3
- description: Use when the user explicitly asks to create or link a Foundocs project or manage a Foundocs workspace. For ordinary work, use only when the current project context already identifies a Foundocs binding. An unlinked folder needs no Foundocs lookup, capture, or setup prompt.
3
+ description: >-
4
+ Use only when asked to create a Foundocs project, link or switch a folder's project, list registered workspaces, or change the default workspace.
5
+ In an already connected project, go directly to its foundocs or capture skill. For a global binding, those guides are under {{GUIDES}}.
6
+ Ordinary work in an unlinked folder needs no Foundocs lookup, capture, or setup prompt.
4
7
  ---
5
8
 
6
9
  # Foundocs workspace
@@ -16,4 +19,4 @@ Use the selected {{CLIENT}} installation. Run the pinned CLI as an argument arra
16
19
  - A `project_installation` result means the folder has a separate project-scoped install. Show the previous project and requested target. Only after explicit approval to remove that installation, run its existing `rollback --root ABSOLUTE_PROJECT_ROOT` workflow. Proceed with the requested global link when rollback succeeds and the folder is clear. If rollback reports conflicts or restores an older binding, preserve it and report the conflict.
17
20
  - After binding, use the MCP server named in the CLI result. Call `get_project_context` for the exact project ID and report the workspace and project names. If the host cached an empty tool list before binding, reopen the chat in the linked folder; distinguish a saved folder binding from host verification.
18
21
  - For ordinary Foundocs work, use the exact governing project’s `foundocs.json`. A global binding contains `workspace_id` and `project_id`. Use this workspace's MCP server (use the server name returned by `workspace list` for that exact workspace ID). Use the project’s existing instructions and MCP connection when it has its own installation. Never guess a binding in an unlinked folder.
19
- - Once bound, read the appropriate guide under {{GUIDES}}: `foundocs/SKILL.md`, `foundocs-capture-knowledge/SKILL.md`, or `foundocs-capture-episode/SKILL.md` for the requested activity. For a global binding the explicit workspace and project in the governing folder are the configuration. Global setup installs no project-scoped update or checkpoint hooks. The private bootstrap CLI handles workspace registration and linking before any project is selected.
22
+ - Once bound, read the appropriate guide under {{GUIDES}}: `foundocs/SKILL.md`, `foundocs-capture-knowledge/SKILL.md`, or `foundocs-capture-episode/SKILL.md` for the requested activity. In a bound project, use these guides to record a closing discussion and its brief episode, or update the feature document when implementation starts. For a global binding the explicit workspace and project in the governing folder are the configuration. Global setup installs no project-scoped update or checkpoint hooks. The private bootstrap CLI handles workspace registration and linking before any project is selected.