@foundocs/foundocs-setup 0.4.0 → 0.5.0

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
@@ -1,6 +1,7 @@
1
1
  import { execFile } from 'node:child_process';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { lstat, mkdir, readFile, unlink } from 'node:fs/promises';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { homedir } from 'node:os';
5
6
  import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
6
7
  import { isDeepStrictEqual, parseArgs, promisify } from 'node:util';
@@ -63,6 +64,13 @@ async function requestProjects(dir, client, ws, input, fetcher = fetch) {
63
64
  return body;
64
65
  }
65
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
+
66
74
  async function prepareHost(input, dir) {
67
75
  const { client, workspaceId } = input;
68
76
  const home = homedir();
@@ -72,35 +80,81 @@ async function prepareHost(input, dir) {
72
80
  const args = ['--yes', '@foundocs/foundocs-setup@' + version, 'mcp-global', '--client', client, '--workspace', workspaceId, '--storage', dirname(dir)];
73
81
  const configPath = client === 'codex' ? join(configHome, 'config.toml') : process.env.CLAUDE_CONFIG_DIR ? join(configHome, '.claude.json') : join(home, '.claude.json');
74
82
  const current = await textFile(configPath);
75
- const configured = client === 'codex' ? parseToml(current ?? '').mcp_servers?.[name] : JSON.parse(current ?? '{}').mcpServers?.[name];
76
- if (configured && (configured.command !== 'npx' || !isDeepStrictEqual(configured.args, args) ||
77
- Object.keys(configured).some(key => !['command', 'args', 'type'].includes(key)) || (configured.type && configured.type !== 'stdio'))) fail('Conflicting user MCP entry: ' + name);
83
+ const parseHost = text => client === 'codex' ? parseToml(text ?? '') : JSON.parse(text ?? '{}');
84
+ const entry = config => (client === 'codex' ? config.mcp_servers : config.mcpServers)?.[name];
85
+ const expected = parseHost(current);
86
+ const configured = entry(expected);
87
+ let updatedConfig;
88
+ if (configured) {
89
+ const oldPackage = configured.args?.[1];
90
+ const oldArgs = [...args];
91
+ oldArgs[1] = oldPackage;
92
+ if (configured.command !== 'npx' || !/^@foundocs\/foundocs-setup@\d+\.\d+\.\d+$/.test(oldPackage) ||
93
+ !isDeepStrictEqual(configured.args, oldArgs) || Object.keys(configured).some(key => !['command', 'args', 'type'].includes(key)) ||
94
+ (configured.type && configured.type !== 'stdio')) fail('Conflicting user MCP entry: ' + name);
95
+ if (oldPackage !== args[1]) {
96
+ // Keep comments, unrelated entries and formatting intact in either host format.
97
+ configured.args = args;
98
+ for (let i = current.indexOf(oldPackage); i >= 0; i = current.indexOf(oldPackage, i + oldPackage.length)) {
99
+ const candidate = current.slice(0, i) + args[1] + current.slice(i + oldPackage.length);
100
+ if (isDeepStrictEqual(parseHost(candidate), expected)) { updatedConfig = candidate; break; }
101
+ }
102
+ if (!updatedConfig) fail('Cannot safely update the MCP entry: ' + name);
103
+ }
104
+ }
78
105
  await execute(client, ['--version'], { cwd: dir, timeout: 15000 });
79
106
  const skillRoot = join(configHome, 'skills', 'foundocs-workspace');
107
+ const guideRoot = join(dir, 'guides', version, client);
108
+ const skillPath = join(skillRoot, 'SKILL.md');
109
+ const receipt = join(dir, client + '-workspace-skill.sha256');
80
110
  const source = await readFile(new URL('../templates/workspace-skill.md', import.meta.url), 'utf8');
81
- const files = [{ name: 'SKILL.md', content: source.replaceAll('{{CLIENT}}', client).replaceAll('{{VERSION}}', version).replaceAll('{{STORAGE}}', JSON.stringify(dirname(dir))) }];
111
+ const storageArg = JSON.stringify(dirname(dir));
112
+ const bootstrap = source.replaceAll('{{CLIENT}}', client).replaceAll('{{VERSION}}', version)
113
+ .replaceAll('{{STORAGE}}', storageArg).replaceAll('{{GUIDES}}', JSON.stringify(guideRoot));
114
+ await safeParent(dirname(configHome), skillPath);
115
+ const before = await textFile(skillPath);
116
+ // 0.4.0 predates receipts. Recognize only its exact template for this client and storage.
117
+ const legacyHash = client === 'codex' ? 'caeed0744464166dd0772882e965fd9b9464c06d160ffa9f002e5385276f5f91' : 'cccf248e38dbea2d0328dc29c403ef2baba3816250a58894f64754c92f621083';
118
+ if (before !== null && before !== bootstrap && digest(before) !== (await textFile(receipt))?.trim() &&
119
+ digest(before.replace(storageArg, '{{STORAGE}}')) !== legacyHash) fail('Global workspace skill has local edits: ' + skillPath);
120
+ const guides = [];
121
+ const legacySkills = [];
82
122
  for (const asset of skillAssets(client)) {
83
123
  const name = asset.name.split('/skills/')[1];
124
+ const path = join(guideRoot, name);
125
+ await safeParent(dir, path);
84
126
  const content = name === 'foundocs/references/configuration.md'
85
- ? await readFile(new URL('../templates/workspace-configuration.md', import.meta.url), 'utf8')
86
- : asset.content;
87
- files.push({ name, content });
88
- }
89
- const changes = [];
90
- for (const file of files) {
91
- const path = join(skillRoot, file.name);
92
- await safeParent(dirname(configHome), path);
93
- const before = await textFile(path);
94
- if (before === file.content) continue;
95
- if (before !== null) fail('A different global skill file already exists at ' + path);
96
- changes.push({ path, content: file.content });
127
+ ? await readFile(new URL('../templates/workspace-configuration.md', import.meta.url), 'utf8') : asset.content;
128
+ const existing = await textFile(path);
129
+ if (existing === null) guides.push({ path, content });
130
+ else if (existing !== content) fail('Global guide has local edits: ' + path);
131
+ if (name.endsWith('/SKILL.md')) {
132
+ const legacy = join(skillRoot, name);
133
+ await safeParent(dirname(configHome), legacy);
134
+ const descriptor = await textFile(legacy);
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 });
137
+ }
97
138
  }
98
139
  return async () => {
99
- for (const { path, content } of changes) {
140
+ for (const { path, content } of guides) {
100
141
  await mkdir(dirname(path), { recursive: true, mode: 0o700 });
101
- if (await textFile(path) !== null) fail('Global skill changed during installation.');
102
142
  await atomicWrite(path, content);
103
143
  }
144
+ if (before !== bootstrap) {
145
+ if (await textFile(skillPath) !== before) fail('Workspace skill changed during installation.');
146
+ await mkdir(skillRoot, { recursive: true, mode: 0o700 });
147
+ await atomicWrite(skillPath, bootstrap);
148
+ }
149
+ await atomicWrite(receipt, digest(bootstrap) + '\n');
150
+ for (const { path, content } of legacySkills) {
151
+ if (await textFile(path) !== content) fail('Global skill changed during migration: ' + path);
152
+ await unlink(path);
153
+ }
154
+ if (updatedConfig) {
155
+ if (await textFile(configPath) !== current) fail('Client configuration changed. Retry the update.');
156
+ await atomicWrite(configPath, updatedConfig, (await lstat(configPath)).mode & 0o777);
157
+ }
104
158
  if (!configured) {
105
159
  if (await textFile(configPath) !== current) fail('Client configuration changed. Rerun the same installation.');
106
160
  const command = client === 'codex' ? ['mcp', 'add', name, '--', 'npx', ...args] :
@@ -129,6 +183,10 @@ export async function installGlobal(input, options = {}) {
129
183
  if (catalog.workspace?.id !== ws.id) fail('Workspace identity mismatch.');
130
184
  ws.name = catalog.workspace.name;
131
185
  await finishHost();
186
+ for (const other of registry.workspaces.filter(item => item.id !== ws.id)) {
187
+ const update = await (options.prepareHost ?? prepareHost)({ client: input.client, workspaceId: other.id }, dir);
188
+ await update();
189
+ }
132
190
  registry.workspaces = [...registry.workspaces.filter(item => item.id !== ws.id), ws];
133
191
  await atomicWrite(path, json(registry));
134
192
  return { status: 'workspace_registered', workspace: catalog.workspace, server: serverName(ws.id), next: 'Reload the client, open your project folder and ask Foundocs to create or link its project.' };
@@ -197,12 +255,29 @@ export async function bindProject(action, args, options = {}) {
197
255
  }
198
256
  if (await textFile(configPath) !== previous) fail('The folder binding changed during this request. Review it before retrying.');
199
257
  const mode = previous === null ? 0o644 : (await lstat(configPath)).mode & 0o777;
200
- 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);
201
259
  if (pending) await unlink(journal);
202
260
  return { status: 'linked', workspace: catalog.workspace, project: { id: project.id, name: project.name }, server: serverName(ws.id) };
203
261
  });
204
262
  }
205
263
 
264
+ // Respect the host's selected folder. A default workspace is never a document binding.
265
+ async function folderProject(server, workspaceId) {
266
+ try {
267
+ let folder = process.cwd();
268
+ if (server.getClientCapabilities()?.roots) {
269
+ const { roots } = await server.listRoots({}, { timeout: 3000 });
270
+ if (roots.length !== 1) return null;
271
+ folder = fileURLToPath(roots[0].uri);
272
+ }
273
+ let root = folder;
274
+ try { root = (await execute('git', ['-C', folder, 'rev-parse', '--show-toplevel'], { timeout: 3000 })).stdout.trim(); }
275
+ catch { /* Plain folders are bound at the selected directory. */ }
276
+ const binding = await readJson(join(root, 'foundocs.json'));
277
+ return binding?.workspace_id === workspaceId && uuid.test(binding.project_id) ? binding.project_id : null;
278
+ } catch { return null; }
279
+ }
280
+
206
281
  export async function globalCommand(command, argv) {
207
282
  if (command === 'install-global') {
208
283
  if (argv.length || process.stdin.isTTY) fail('Provide the installation JSON on private stdin.');
@@ -219,6 +294,16 @@ export async function globalCommand(command, argv) {
219
294
  await privateDirectory(dir);
220
295
  const registry = await readJson(path);
221
296
  if (command === 'workspace' && action === 'list') return { defaultId: registry?.defaultId, workspaces: (registry?.workspaces ?? []).map(({ id, name }) => ({ id, name, server: serverName(id) })) };
297
+ if (command === 'workspace' && action === 'update') {
298
+ return withLock(dir, async () => {
299
+ const registered = (await readJson(path))?.workspaces ?? [];
300
+ for (const ws of registered) {
301
+ const update = await prepareHost({ client: values.client, workspaceId: ws.id }, dir);
302
+ await update();
303
+ }
304
+ return { status: 'updated', workspaces: registered.length, version };
305
+ });
306
+ }
222
307
  if (command === 'workspace' && action === 'default') {
223
308
  if (!values.workspace) fail('Choose --workspace NAME_OR_ID.');
224
309
  return withLock(dir, async () => {
@@ -232,5 +317,5 @@ export async function globalCommand(command, argv) {
232
317
  if (command !== 'mcp-global' || !uuid.test(values.workspace)) fail('Unknown workspace operation.');
233
318
  const ws = selectWorkspace(registry, values.workspace);
234
319
  const { runBridge } = await import('./bridge.mjs');
235
- await runBridge({ credentialPath: keyPath(dir, values.client, ws), projectId: null, workspaceId: ws.id, mcpUrl: ws.mcpUrl });
320
+ await runBridge({ credentialPath: keyPath(dir, values.client, ws), projectId: null, workspaceId: ws.id, mcpUrl: ws.mcpUrl, folderProject: server => folderProject(server, ws.id) });
236
321
  }
@@ -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,10 +1,15 @@
1
1
  ---
2
2
  name: foundocs-workspace
3
- description: Connect a folder to Foundocs, create a Foundocs project, select a registered workspace, or use Foundocs documents and knowledge in a globally linked folder. Use for “Foundocs 프로젝트 생성하자”, “프로젝트로 연결”, and explicit Foundocs requests. For ordinary work, use the document and capture guidance only in a Foundocs-bound project.
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
7
10
 
11
+ For ordinary chat or coding, stay silent when the governing folder has no valid `foundocs.json`. Do not search the filesystem for a binding during unrelated chat, call Foundocs tools, list workspaces, load the guides, ask for configuration, or suggest installing it. A registered global workspace alone never activates document lookup or capture. Explicit Foundocs creation and linking requests below work from an unlinked folder.
12
+
8
13
  Use the selected {{CLIENT}} installation. Run the pinned CLI as an argument array with prefix `npx --yes @foundocs/foundocs-setup@{{VERSION}}`. Append `--client {{CLIENT}}` and the two arguments `--storage` and {{STORAGE}} to the commands below. Treat names and folder paths as literal arguments.
9
14
 
10
15
  - On an explicit request to create a project, run `project create --root ABSOLUTE_PROJECT_ROOT`. Use the current governing project root. The folder name is the default. Pass `--name NAME` when requested.
@@ -12,6 +17,6 @@ Use the selected {{CLIENT}} installation. Run the pinned CLI as an argument arra
12
17
  - On a switch confirmation show both targets and wait for the user's decision. Once confirmed, repeat the same command with `--replace OLD_PROJECT_ID`. Retry interrupted creation with the same root and name.
13
18
  - `workspace list` shows registered workspaces. Use `workspace default --workspace ID_OR_NAME` only when asked to change the default.
14
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.
15
- - 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 server has just been installed and is unavailable, ask the user to reload the host; distinguish a saved folder binding from host verification.
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.
16
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.
17
- - Once bound, follow [Foundocs](foundocs/SKILL.md), [knowledge capture](foundocs-capture-knowledge/SKILL.md), and [episode capture](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.