@foundocs/foundocs-setup 0.3.24 → 0.3.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -3
- package/dist/bridge.mjs +740 -261
- package/package.json +3 -3
- package/skills/foundocs/SKILL.md +18 -8
- package/skills/foundocs/references/documents.md +13 -3
- package/skills/foundocs/references/dreaming.md +15 -7
- package/skills/foundocs/references/effect-measurement.md +21 -1
- package/skills/foundocs/scripts/session-start.mjs +1 -1
- package/skills/foundocs-capture-knowledge/SKILL.md +9 -9
- package/skills/foundocs-capture-knowledge/references/writing-guide.md +6 -4
- package/src/bridge.mjs +76 -24
- package/src/cli.mjs +2 -2
- package/src/effect-automatic.mjs +184 -0
- package/src/effect-config.mjs +31 -0
- package/src/effect-storage.mjs +2 -0
- package/src/effect.mjs +12 -3
- package/src/runtime.mjs +23 -1
- package/src/setup.mjs +12 -4
- package/templates/knowledge-policy.md +2 -2
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { readdir } from 'node:fs/promises';
|
|
2
|
+
import { randomUUID } from 'node:crypto';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { readJson, saveJson, privateDir } from './effect-storage.mjs';
|
|
5
|
+
import { UUID, hash, validateBrief } from './effect-core.mjs';
|
|
6
|
+
|
|
7
|
+
export const effectReads = new Set(['get_project_context', 'search_docs', 'explore_docs', 'get_doc', 'get_docs']);
|
|
8
|
+
const reasons = new Set(['consent_required', 'missing_preparation', 'late_preparation', 'working_model_unavailable', 'unsupported_runner', 'runner_not_configured', 'isolation_unavailable', 'connection_unavailable', 'permission_denied', 'snapshot_unavailable', 'context_unavailable', 'budget_admission_denied', 'concurrency_limit', 'daily_run_limit', 'not_sampled', 'disabled', 'no_beneficial_retrieval', 'expired_preparation', 'duplicate_task', 'report_pending', 'local_failure', 'incomplete_evaluation']);
|
|
9
|
+
const safeReason = e => reasons.has(e?.reason ?? e?.code?.toLowerCase()) ? (e.reason ?? e.code.toLowerCase()) : ['EACCES', 'EPERM'].includes(e?.code) ? 'permission_denied' : 'local_failure';
|
|
10
|
+
const dataOf = r => r?.structuredContent ?? (() => { try { return JSON.parse(r?.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
|
|
11
|
+
function retrievalIds(value, found = new Set()) {
|
|
12
|
+
if (!value || typeof value !== 'object') return found;
|
|
13
|
+
if (Array.isArray(value.retrievals)) for (const r of value.retrievals) if (UUID.test(r?.retrievalId)) found.add(r.retrievalId);
|
|
14
|
+
for (const [key, child] of Object.entries(value)) if (key !== 'retrievals' && child && typeof child === 'object') retrievalIds(child, found);
|
|
15
|
+
return found;
|
|
16
|
+
}
|
|
17
|
+
export function automaticTool(tool) {
|
|
18
|
+
if (!effectReads.has(tool.name) && tool.name !== 'report_retrieval_evaluation') return tool;
|
|
19
|
+
const properties = { ...tool.inputSchema.properties };
|
|
20
|
+
if (effectReads.has(tool.name)) properties.effectTask = { type: 'object', additionalProperties: false,
|
|
21
|
+
description: 'Local automatic measurement. First read: pre-exposure brief and current trusted host identity; following reads: same taskId only. Never reconstruct a brief after exposure. Source allowlist and consent come from installation, not this call.',
|
|
22
|
+
required: ['taskId'], properties: { taskId: { type: 'string', format: 'uuid' },
|
|
23
|
+
question: { type: 'string', minLength: 1, maxLength: 2000 }, knownContext: { type: 'string', maxLength: 4000 },
|
|
24
|
+
criteria: { type: 'array', minItems: 1, maxItems: 10, items: { type: 'object', additionalProperties: false, required: ['id', 'description'], properties: { id: { type: 'string', maxLength: 80 }, description: { type: 'string', maxLength: 500 } } } },
|
|
25
|
+
host: { type: 'object', additionalProperties: false, required: ['client', 'sessionId'], properties: { client: { type: 'string', enum: ['codex', 'claude_code'] }, sessionId: { type: 'string', format: 'uuid' }, transcriptPath: { type: 'string' } } },
|
|
26
|
+
} };
|
|
27
|
+
else {
|
|
28
|
+
properties.effectTaskId = { type: 'string', format: 'uuid', description: 'Same automatic information task identity.' };
|
|
29
|
+
properties.effectTaskComplete = { type: 'boolean', description: 'True only on the final evaluation after ALL information reads and evaluations for this question. The installer starts at most one comparison automatically, after saved consent. Do not issue measure run.' };
|
|
30
|
+
}
|
|
31
|
+
return { ...tool, description: tool.description + ' Installed automatic measurement accepts local task metadata; no shell prepare/run is needed.', inputSchema: { ...tool.inputSchema, properties },
|
|
32
|
+
annotations: { ...tool.annotations, readOnlyHint: false, openWorldHint: true } };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Serializes calls for this bridge; persistent coordinator locks prevent duplicate probes across bridges/restarts. */
|
|
36
|
+
export class AutomaticMeasurement {
|
|
37
|
+
constructor({ projectId, remote, factory, store, warn = () => {} }) { Object.assign(this, { projectId, remote, factory, store, warn }); this.queue = Promise.resolve(); this.jobs = new Set(); }
|
|
38
|
+
call(params) {
|
|
39
|
+
const next = this.queue.then(() => this.handle(params));
|
|
40
|
+
this.queue = next.catch(() => {}); return next;
|
|
41
|
+
}
|
|
42
|
+
async recover() {
|
|
43
|
+
for (const state of await this.store.list?.() ?? []) {
|
|
44
|
+
if (state.diagnostic) {
|
|
45
|
+
try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
|
|
46
|
+
catch { this.warn('Foundocs measurement status is pending; no inference was repeated.'); }
|
|
47
|
+
}
|
|
48
|
+
if (!state.closed || state.settled || !state.preparationId) continue;
|
|
49
|
+
try {
|
|
50
|
+
const { coordinator } = await this.factory({ recovery: true });
|
|
51
|
+
const result = await coordinator.flush(state.taskId);
|
|
52
|
+
if (result.reason === 'coordinator_active') continue;
|
|
53
|
+
if (result.status === 'report_pending') {
|
|
54
|
+
await this.diagnostic(state, 'failed', 'report_pending');
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
state.settled = true;
|
|
58
|
+
if (['reported', 'already_reported'].includes(result.status)) {
|
|
59
|
+
const failed = result.result && result.result.status !== 'completed';
|
|
60
|
+
await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
|
|
61
|
+
}
|
|
62
|
+
else await this.diagnostic(state, 'failed', result.status === 'nothing_pending' ? 'local_failure' : safeReason(result));
|
|
63
|
+
} catch { this.warn('Foundocs measurement recovery pending; no inference was repeated.'); }
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async diagnostic(state, status, reason = null) {
|
|
67
|
+
state.sequence = (state.sequence ?? 0) + 1;
|
|
68
|
+
state.diagnostic = { requestId: randomUUID(), taskId: state.taskId, sequence: state.sequence, status, reason };
|
|
69
|
+
try { await this.store.save(state); } catch { this.warn('Foundocs measurement status could not be saved locally.'); }
|
|
70
|
+
try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
|
|
71
|
+
catch { this.warn('Foundocs measurement status could not be delivered; local status retained.'); }
|
|
72
|
+
}
|
|
73
|
+
async handle(params) {
|
|
74
|
+
const { effectTask, effectTaskId, effectTaskComplete, ...args } = params.arguments ?? {};
|
|
75
|
+
const forward = () => this.remote(params.name, args, true);
|
|
76
|
+
if (args.project_id !== this.projectId) {
|
|
77
|
+
if (effectTask || effectTaskId || effectTaskComplete) throw new Error('Automatic measurement project mismatch');
|
|
78
|
+
return forward();
|
|
79
|
+
}
|
|
80
|
+
if (effectReads.has(params.name)) {
|
|
81
|
+
// Explicit legacy tracking stays under its existing coordinator. Never attach two tasks.
|
|
82
|
+
if (!effectTask) return forward();
|
|
83
|
+
const taskId = effectTask?.taskId ?? (UUID.test(args.taskId ?? '') ? args.taskId : UUID.test(args.readId ?? '') ? args.readId : randomUUID());
|
|
84
|
+
if (!UUID.test(taskId) || (args.taskId && args.taskId !== taskId) || (effectTask && args.effectPreparationId)) throw new Error('Conflicting measurement task');
|
|
85
|
+
let state;
|
|
86
|
+
try { state = await this.store.load(taskId); }
|
|
87
|
+
catch (e) {
|
|
88
|
+
args.taskId = taskId;
|
|
89
|
+
try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
|
|
90
|
+
return forward();
|
|
91
|
+
}
|
|
92
|
+
if (!state) {
|
|
93
|
+
state = { taskId, retrievals: [], evaluated: [], exposed: false, closed: false, expiresAt: new Date(Date.now() + 86400000).toISOString() };
|
|
94
|
+
// Persist before preparation; a crash must never create a new baseline after exposure.
|
|
95
|
+
try { await this.store.save(state); }
|
|
96
|
+
catch (e) {
|
|
97
|
+
args.taskId = taskId;
|
|
98
|
+
try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
|
|
99
|
+
return forward();
|
|
100
|
+
}
|
|
101
|
+
try {
|
|
102
|
+
const policy = await this.remote('get_effect_measurement_policy', {});
|
|
103
|
+
if (!policy.enabled) state.skipped = 'disabled';
|
|
104
|
+
else if (!effectTask?.question || !effectTask?.criteria) state.skipped = 'missing_preparation';
|
|
105
|
+
else {
|
|
106
|
+
const brief = { taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria };
|
|
107
|
+
validateBrief(brief); state.briefHash = hash(brief);
|
|
108
|
+
const { coordinator, config } = await this.factory();
|
|
109
|
+
if (!config?.enabled) state.skipped = 'consent_required';
|
|
110
|
+
else {
|
|
111
|
+
const result = await coordinator.prepare({ policy, brief, allowlist: config.allowlist, excludePaths: config.excludePaths, host: effectTask.host });
|
|
112
|
+
if (result.status === 'prepared') { state.preparationId = result.effectPreparationId; state.consentHash = hash(config); }
|
|
113
|
+
else state.skipped = safeReason(result);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
} catch (e) { state.skipped = safeReason(e); }
|
|
117
|
+
await this.diagnostic(state, state.preparationId ? 'prepared' : 'skipped', state.preparationId ? null : state.skipped);
|
|
118
|
+
} else if (effectTask?.question && state.briefHash !== hash({ taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria })) {
|
|
119
|
+
throw new Error('Do not change a frozen information task');
|
|
120
|
+
}
|
|
121
|
+
if (!state.preparationId && !state.skipped) state.skipped = 'missing_preparation'; // interrupted preparation stays unmeasured
|
|
122
|
+
if (state.closed && effectTask) throw new Error('Information task is closed; never add later context or relabel the same question.');
|
|
123
|
+
if (state.closed || Date.parse(state.expiresAt) <= Date.now()) {
|
|
124
|
+
// Continue ordinary reads, but never silently add post-completion context to an existing sample.
|
|
125
|
+
delete args.effectPreparationId; args.taskId = taskId;
|
|
126
|
+
return forward();
|
|
127
|
+
}
|
|
128
|
+
args.taskId = taskId;
|
|
129
|
+
if (state.preparationId) args.effectPreparationId = state.preparationId;
|
|
130
|
+
// Mark exposure before the remote request: a lost reply must not re-prepare.
|
|
131
|
+
state.exposed = true;
|
|
132
|
+
try { await this.store.save(state); }
|
|
133
|
+
catch (e) { delete args.effectPreparationId; await this.diagnostic(state, 'skipped', safeReason(e)); return forward(); }
|
|
134
|
+
const result = await forward(), body = dataOf(result);
|
|
135
|
+
if (body?.ok) {
|
|
136
|
+
state.retrievals = [...new Set([...state.retrievals, ...retrievalIds(body.data)])];
|
|
137
|
+
try { await this.store.save(state); } catch { this.warn('Foundocs retrieval tracking could not be saved; no extra reads were requested.'); }
|
|
138
|
+
}
|
|
139
|
+
return result;
|
|
140
|
+
}
|
|
141
|
+
const result = await forward();
|
|
142
|
+
if (params.name !== 'report_retrieval_evaluation' || !effectTaskId || !dataOf(result)?.ok) return result;
|
|
143
|
+
if (!UUID.test(effectTaskId)) return result;
|
|
144
|
+
let state;
|
|
145
|
+
try { state = await this.store.load(effectTaskId); } catch { this.warn('Foundocs evaluation tracking unavailable.'); return result; }
|
|
146
|
+
if (!state || state.closed || !state.retrievals.includes(args.retrievalId)) return result;
|
|
147
|
+
state.evaluated = [...new Set([...state.evaluated, args.retrievalId])];
|
|
148
|
+
if (args.verdict === 'beneficial') state.beneficial = true;
|
|
149
|
+
try { await this.store.save(state); } catch { this.warn('Foundocs evaluation tracking could not be saved; no comparison started.'); return result; }
|
|
150
|
+
if (!effectTaskComplete) return result;
|
|
151
|
+
if (state.retrievals.some(id => !state.evaluated.includes(id))) {
|
|
152
|
+
await this.diagnostic(state, 'skipped', 'incomplete_evaluation'); return result;
|
|
153
|
+
}
|
|
154
|
+
state.closed = true;
|
|
155
|
+
try { await this.store.save(state); } catch { this.warn('Foundocs task closure could not be saved; no comparison started.'); return result; }
|
|
156
|
+
if (!state.preparationId || !state.beneficial) { state.settled = true; await this.diagnostic(state, 'skipped', state.skipped ?? 'no_beneficial_retrieval'); return result; }
|
|
157
|
+
// No long-running model call inside the MCP response timeout. The bridge owns and settles the task.
|
|
158
|
+
const job = this.run(state).catch(() => this.warn('Foundocs automatic measurement failed; ordinary work continues.'));
|
|
159
|
+
this.jobs.add(job); void job.finally(() => this.jobs.delete(job));
|
|
160
|
+
return result;
|
|
161
|
+
}
|
|
162
|
+
async run(state) {
|
|
163
|
+
try {
|
|
164
|
+
const { coordinator, config } = await this.factory();
|
|
165
|
+
if (!config?.enabled || state.consentHash !== hash(config)) { state.settled = true; await this.diagnostic(state, 'skipped', 'consent_required'); return; }
|
|
166
|
+
await this.diagnostic(state, 'running');
|
|
167
|
+
const result = await coordinator.run({ taskId: state.taskId, retrievalIds: state.retrievals });
|
|
168
|
+
state.settled = !['report_pending'].includes(result.status);
|
|
169
|
+
if (result.status === 'reported' || result.status === 'already_reported') {
|
|
170
|
+
const failed = result.result && result.result.status !== 'completed';
|
|
171
|
+
await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
|
|
172
|
+
} else await this.diagnostic(state, result.status === 'report_pending' ? 'failed' : 'skipped', result.status === 'report_pending' ? 'report_pending' : safeReason(result));
|
|
173
|
+
} catch (e) { await this.diagnostic(state, 'failed', safeReason(e)); }
|
|
174
|
+
}
|
|
175
|
+
async drain() { await this.queue; await Promise.allSettled([...this.jobs]); }
|
|
176
|
+
}
|
|
177
|
+
export function automaticStore(base) {
|
|
178
|
+
const path = taskId => { if (!UUID.test(taskId)) throw new Error('Invalid task'); return join(base, taskId, 'automatic.json'); };
|
|
179
|
+
return {
|
|
180
|
+
async list() { await privateDir(base); const result = []; for (const id of await readdir(base)) if (UUID.test(id)) { const state = await this.load(id); if (state) result.push(state); } return result; },
|
|
181
|
+
async load(taskId) { try { return await readJson(path(taskId)); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
|
|
182
|
+
async save(state) { await privateDir(join(base, state.taskId)); await saveJson(path(state.taskId), state); },
|
|
183
|
+
};
|
|
184
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { readJson, saveJson } from './effect-storage.mjs';
|
|
3
|
+
import { EffectError } from './effect-core.mjs';
|
|
4
|
+
export function validateAutomaticConsent(input) {
|
|
5
|
+
if (input?.enabled === false && Object.keys(input).length === 1) return { enabled: false };
|
|
6
|
+
if (!input || input.enabled !== true || input.consentVersion !== 1 || input.shareProjectDataWithWorkingModel !== true || input.additionalModelUsage !== true) throw new EffectError('consent_required');
|
|
7
|
+
const paths = value => Array.isArray(value) && value.length > 0 && value.length <= 100 && value.every(p => typeof p === 'string' && p.length <= 500 && p !== '.' && !p.startsWith('/') && !p.includes('\\') && !p.split('/').some(s => !s || s === '..' || s === '.'));
|
|
8
|
+
if (!paths(input.allowlist) || !Array.isArray(input.excludePaths) || (input.excludePaths.length && !paths(input.excludePaths))) throw new EffectError('snapshot_unavailable');
|
|
9
|
+
return { enabled: true, consentVersion: 1, shareProjectDataWithWorkingModel: true, additionalModelUsage: true, allowlist: input.allowlist, excludePaths: input.excludePaths };
|
|
10
|
+
}
|
|
11
|
+
export async function saveAutomaticConsent(directory, input) {
|
|
12
|
+
const config = validateAutomaticConsent(input);
|
|
13
|
+
await saveJson(join(directory, 'measurement-consent.json'), { ...config, acceptedAt: new Date().toISOString() });
|
|
14
|
+
return { status: config.enabled ? 'consent_saved' : 'disabled', hostPermissions: 'unchanged', reconnectRequired: false };
|
|
15
|
+
}
|
|
16
|
+
export async function readAutomaticConsent(directory) {
|
|
17
|
+
try { const value = await readJson(join(directory, 'measurement-consent.json')); return validateAutomaticConsent(value.enabled ? value : { enabled: false }); }
|
|
18
|
+
catch (e) { if (e.code === 'ENOENT') return { enabled: false }; throw e; }
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Readiness is a non-inference check, not proof that a later provider request will succeed. */
|
|
22
|
+
export async function automaticReadiness({ config, checkCli, checkConnection, identify }) {
|
|
23
|
+
const issues = [];
|
|
24
|
+
if (!config.enabled) issues.push('consent_required');
|
|
25
|
+
try { await checkCli(); } catch { issues.push('unsupported_runner'); }
|
|
26
|
+
try { await checkConnection(); } catch { issues.push('connection_unavailable'); }
|
|
27
|
+
try { if ((await identify()).status !== 'identified') issues.push('working_model_unavailable'); }
|
|
28
|
+
catch { issues.push('working_model_unavailable'); }
|
|
29
|
+
return { config, ready: issues.length === 0, issues, hostPermissions: 'unchanged', inferenceExecuted: false,
|
|
30
|
+
note: 'Checks installation storage, supported CLI/login, current model metadata and Foundocs connectivity. Host approval and provider inference permissions remain independent.' };
|
|
31
|
+
}
|
package/src/effect-storage.mjs
CHANGED
|
@@ -74,6 +74,8 @@ export async function cleanExpired(base, now = Date.now()) {
|
|
|
74
74
|
if (!UUID.test(name)) continue;
|
|
75
75
|
const path = join(base, name), st = await lstat(path);
|
|
76
76
|
if (!st.isDirectory() || st.isSymbolicLink()) throw new EffectError('unsafe_storage');
|
|
77
|
+
const automatic = await readJson(join(path, 'automatic.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
78
|
+
if (automatic && Date.parse(automatic.expiresAt) <= now) await rm(join(path, 'automatic.json'), { force: true });
|
|
77
79
|
const state = await readJson(join(path, 'state.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
78
80
|
if (!state) { if (st.mtimeMs + 86400000 <= now) await rm(path, { recursive: true, force: true }); continue; }
|
|
79
81
|
const retention = Date.parse(state.settlementExpiresAt ?? state.expiresAt);
|
package/src/effect.mjs
CHANGED
|
@@ -70,7 +70,7 @@ export class EffectCoordinator {
|
|
|
70
70
|
const outbox = await readJson(join(dir, 'outbox.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
71
71
|
if (!outbox) {
|
|
72
72
|
const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
73
|
-
if (receipt) return { status: 'already_reported', requestId: receipt.requestId };
|
|
73
|
+
if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
|
|
74
74
|
if (state.reservation && state.probes) {
|
|
75
75
|
const owner = await readJson(join(dir, 'run-lock.json'));
|
|
76
76
|
let alive = true; try { process.kill(owner.pid, 0); } catch (error) { if (error.code === 'ESRCH') alive = false; }
|
|
@@ -84,7 +84,7 @@ export class EffectCoordinator {
|
|
|
84
84
|
if (outbox.rejected) return { status: 'report_rejected', reason: outbox.rejected };
|
|
85
85
|
try {
|
|
86
86
|
const result = await this.remote.call('report_effect_measurement', outbox.payload);
|
|
87
|
-
await saveJson(join(dir, 'receipt.json'), { reportedAt: new Date().toISOString(), requestId: outbox.payload.requestId });
|
|
87
|
+
await saveJson(join(dir, 'receipt.json'), { reportedAt: new Date().toISOString(), requestId: outbox.payload.requestId, result });
|
|
88
88
|
await rm(join(dir, 'outbox.json'));
|
|
89
89
|
// Raw sources/context/brief are no longer needed after settlement.
|
|
90
90
|
await rm(join(dir, 'snapshot'), { recursive: true, force: true });
|
|
@@ -111,7 +111,7 @@ export class EffectCoordinator {
|
|
|
111
111
|
if (state.policy.enabled !== true) return { status: 'skipped', reason: 'disabled' };
|
|
112
112
|
if (state.workingModel?.modelSource !== 'working_session') return { status: 'skipped', reason: 'working_model_unavailable' };
|
|
113
113
|
const receipt = await readJson(join(dir, 'receipt.json')).catch(e => { if (e.code !== 'ENOENT') throw e; return null; });
|
|
114
|
-
if (receipt) return { status: 'already_reported', requestId: receipt.requestId };
|
|
114
|
+
if (receipt) return { status: 'already_reported', requestId: receipt.requestId, result: receipt.result };
|
|
115
115
|
const lock = join(dir, 'run-lock.json');
|
|
116
116
|
try { await saveJson(lock, { pid: process.pid, attemptId: randomUUID() }, true); }
|
|
117
117
|
catch (e) {
|
|
@@ -188,6 +188,15 @@ export class EffectCoordinator {
|
|
|
188
188
|
export async function measure(action, rootPath, input) {
|
|
189
189
|
const installation = await measurementInstallation(rootPath);
|
|
190
190
|
await cleanExpired(installation.base);
|
|
191
|
+
if (action === 'configure' || action === 'status') {
|
|
192
|
+
const { saveAutomaticConsent, readAutomaticConsent, automaticReadiness } = await import('./effect-config.mjs');
|
|
193
|
+
if (action === 'configure') return saveAutomaticConsent(dirname(installation.base), input);
|
|
194
|
+
return automaticReadiness({ config: await readAutomaticConsent(dirname(installation.base)),
|
|
195
|
+
checkCli: () => installation.manifest.client === 'codex' ? codexCapabilities() : capabilities(),
|
|
196
|
+
identify: () => workingSessionModel(input.host, installation.root),
|
|
197
|
+
checkConnection: async () => { const remote = await connectEffectRemote(installation.manifest); try { await remote.call('get_effect_measurement_policy', {}); } finally { await remote.close(); } },
|
|
198
|
+
});
|
|
199
|
+
}
|
|
191
200
|
if (action === 'prepare' && input.policy?.enabled === false) return { status: 'skipped', reason: 'disabled' };
|
|
192
201
|
const remote = await connectEffectRemote(installation.manifest);
|
|
193
202
|
try {
|
package/src/runtime.mjs
CHANGED
|
@@ -72,5 +72,27 @@ export async function startRuntime(projectId, options = {}) {
|
|
|
72
72
|
// Optional measurement cleanup must not disable ordinary authenticated MCP.
|
|
73
73
|
process.stderr.write('Foundocs measurement cleanup unavailable; ordinary MCP continues. Run measure diagnostics before another sample.\n');
|
|
74
74
|
}
|
|
75
|
-
await
|
|
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
|
+
} });
|
|
76
98
|
}
|
package/src/setup.mjs
CHANGED
|
@@ -12,6 +12,7 @@ import { readCredential, windowsPrivateAcl } from './auth.mjs';
|
|
|
12
12
|
import { legacy, legacyInstructions } from './legacy-compat.mjs';
|
|
13
13
|
import { knowledgePolicy, skillAssets } from './skill-assets.mjs';
|
|
14
14
|
import { newer } from '../skills/foundocs/scripts/check-update.mjs';
|
|
15
|
+
import { validateAutomaticConsent, saveAutomaticConsent, readAutomaticConsent } from './effect-config.mjs';
|
|
15
16
|
import { episodeDiagnostics } from '../skills/foundocs/scripts/episode-checkpoint.mjs';
|
|
16
17
|
|
|
17
18
|
const exec = promisify(execFile);
|
|
@@ -35,6 +36,7 @@ export function validateInput(input) {
|
|
|
35
36
|
if (!plainObject(input) || input.version !== 1 || !['claude', 'codex'].includes(input.client)) fail('input', 'Unsupported installation input.');
|
|
36
37
|
for (const key of ['projectId', 'workspaceId', 'attemptId']) if (!UUID.test(input[key])) fail('input', `A UUID ${key} is required.`);
|
|
37
38
|
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);
|
|
38
40
|
validateUrl(input.exchangeUrl); validateUrl(input.mcpUrl);
|
|
39
41
|
return input;
|
|
40
42
|
}
|
|
@@ -80,6 +82,10 @@ export function instructions(client) {
|
|
|
80
82
|
return `## Foundocs\n\n${knowledgePolicy(client)}`;
|
|
81
83
|
}
|
|
82
84
|
|
|
85
|
+
function claudeInstructions(configName) {
|
|
86
|
+
return `Read and follow @AGENTS.md in this directory before using Foundocs. Use its document tree and knowledge capture guidance. The governing configuration is the ${configName} beside that AGENTS.md.`;
|
|
87
|
+
}
|
|
88
|
+
|
|
83
89
|
export function markedBlock(existing, content, oldFormat = false) {
|
|
84
90
|
const targetStart = oldFormat ? legacy.start : START, targetEnd = oldFormat ? legacy.end : END;
|
|
85
91
|
const block = `${targetStart}\n${content}\n${targetEnd}`;
|
|
@@ -466,7 +472,7 @@ export async function plan(root, input, credentialPath, helperPath, { oldFormat
|
|
|
466
472
|
}
|
|
467
473
|
const instructionText = oldFormat ? legacyInstructions(instructions(includeSkills ? input.client : undefined)) : instructions(includeSkills ? input.client : undefined);
|
|
468
474
|
await add('AGENTS.md', text => markedBlock(text ?? '', instructionText, oldFormat));
|
|
469
|
-
if (input.client === 'claude') await add('CLAUDE.md', text => markedBlock(text ?? '',
|
|
475
|
+
if (input.client === 'claude') await add('CLAUDE.md', text => markedBlock(text ?? '', claudeInstructions(configName), oldFormat));
|
|
470
476
|
// Delete the historical config last: until all clients/instructions are switched,
|
|
471
477
|
// interrupted migrations retain the file the old instructions still reference.
|
|
472
478
|
if (historical !== null) await add(legacy.config, () => null);
|
|
@@ -649,7 +655,7 @@ async function skillInstructionEntries(root, manifest, oldFormat) {
|
|
|
649
655
|
const configName = oldFormat ? legacy.config : 'foundocs.json';
|
|
650
656
|
const policy = instructions(manifest.client);
|
|
651
657
|
const targets = [['AGENTS.md', oldFormat ? legacyInstructions(policy) : policy]];
|
|
652
|
-
if (manifest.client === 'claude') targets.push(['CLAUDE.md',
|
|
658
|
+
if (manifest.client === 'claude') targets.push(['CLAUDE.md', claudeInstructions(configName)]);
|
|
653
659
|
const entries = [];
|
|
654
660
|
for (const [name, content] of targets) {
|
|
655
661
|
const path = join(root, name); await safeParent(root, path);
|
|
@@ -834,8 +840,9 @@ export async function install(rootPath, rawInput, options = {}) {
|
|
|
834
840
|
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 });
|
|
835
841
|
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 });
|
|
836
842
|
}
|
|
843
|
+
if (input.effectMeasurement !== undefined) await saveAutomaticConsent(rootDirectory, input.effectMeasurement);
|
|
837
844
|
const diagnostic = await (options.diagnose ?? diagnose)(manifest, credentialPath, options);
|
|
838
|
-
return { ok: true, status: 'configured', root, client, changedFiles: changes.map((entry) => entry.path), reusedCredential, diagnostic, skills: skillsInstalled() };
|
|
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() };
|
|
839
846
|
});
|
|
840
847
|
}
|
|
841
848
|
|
|
@@ -857,6 +864,7 @@ export async function doctor(rootPath, options = {}) {
|
|
|
857
864
|
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')] : [])];
|
|
858
865
|
for (const path of runtimeFiles) if (await textFile(path) === null) fail('diagnostic', 'A durable authentication helper is missing. Rerun install to repair it.', { path });
|
|
859
866
|
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 };
|
|
860
868
|
const skills = await checkSkills(root, directory, manifest, oldFormat);
|
|
861
869
|
{
|
|
862
870
|
let servers;
|
|
@@ -878,7 +886,7 @@ export async function doctor(rootPath, options = {}) {
|
|
|
878
886
|
if (entries.some((entry) => entry.before !== entry.after)) fail('diagnostic', 'Installation files are incomplete or modified. Rerun install to repair them.');
|
|
879
887
|
const client = await (options.probeClient ?? probeClient)(manifest.client);
|
|
880
888
|
const diagnostic = await (options.diagnose ?? diagnose)(manifest, manifest.credentialPath, options);
|
|
881
|
-
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.' }) } };
|
|
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.' }) } };
|
|
882
890
|
}
|
|
883
891
|
|
|
884
892
|
export async function rollback(rootPath, options = {}) {
|
|
@@ -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
|
|
3
|
-
-
|
|
2
|
+
- Write requested or approved documents under `docs/`. Ask before adding others.
|
|
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
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.
|
|
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.
|