@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.
@@ -1,55 +0,0 @@
1
- # Automatic measurement in ordinary sessions
2
-
3
- Inspect the live read schema first. If it advertises `effectTask`, use the installed local MCP bridge; do not run shell prepare/run alongside it. The bridge cannot infer the original information question or when information acquisition is finished. The host supplies only those boundaries; the installer owns preparation, tracking and execution.
4
-
5
- 1. Before the first index/TL;DR/search/content read for a new information question, pass `effectTask: {taskId, question, knownContext, criteria, host}` with the same brief constraints below. Use the trusted SessionStart host object (or the current CODEX_THREAD_ID); never choose another session or a guessed model. Do not send an answer or reconstruct a brief after exposure.
6
- 2. On every subsequent read/cursor/chunk, pass `effectTask: {taskId}`. Do not supply effectPreparationId yourself. The bridge checks policy, reads installation consent, freezes original sources and identifies the working model BEFORE forwarding the first read. OFF or unsupported/unconsented preparation continues ordinary reads with a diagnostic, never a replacement model.
7
- 3. Evaluate each actual content retrieval normally, adding `effectTaskId: taskId`. Index entries, candidate previews and skipped candidates have no retrieval to evaluate. For a supported batch use the same UUID for taskId and effectTaskId. On the final successful batch (or single evaluation) after all information reads/evaluations, add `effectTaskComplete: true`. This is the explicit information-acquisition boundary, not an individual useful read. The bridge automatically executes at most once in the background after a successful final evaluation. Never keep reading the same question under a new task ID to create a second sample. If evaluation is incomplete, finish the missing evaluations and mark the final one.
8
- 4. The bridge persists normalized status and reports skip/failure reasons for Insights. Reconnection flushes observed reports/status only; it never respawns interrupted probes. A host process shutdown can interrupt a comparison; missing usage stays unknown. Do not claim an MCP evaluation response means the comparison has completed.
9
-
10
- ## One-time installation consent and readiness
11
-
12
- Project policy ON is not local installation consent. At installation, explain that the allowlisted original sources and actually delivered Foundocs text are sent to the current model provider (OpenAI/Codex or Anthropic/Claude), and two independent probes incur additional usage. Obtain explicit consent and a relative source allowlist once, then persist through `measure configure --root ABSOLUTE_ROOT` with private stdin JSON:
13
-
14
- ```json
15
- {"enabled":true,"consentVersion":1,"shareProjectDataWithWorkingModel":true,"additionalModelUsage":true,"allowlist":["src"],"excludePaths":[]}
16
- ```
17
-
18
- Use actual approved source paths, not this example blindly. Existing setup can configure without a new code; new install input may include the same object as `effectMeasurement`. `{"enabled":false}` revokes local consent; the running coordinator checks it before each arm and heartbeat. `measure status` with `{}` diagnoses consent, supported CLI/login and remote connection without inference. Host MCP/process/filesystem/network permissions are independent. Never disable sandboxing, bypass approval rejection, or claim installation consent grants OS/host permissions. Explain actual restrictions and obtain only needed host approval. Ordinary access remains available when declined. MCP reconnect loads updated runtime/schema; SessionStart supplies current session metadata.
19
-
20
- ## Legacy CLI procedure (only without automatic fields)
21
-
22
-
23
- This is a host-agent procedure, not a request for the user to type commands. Run it automatically on a supported shell-capable host when the project's policy is ON. Never enable the project's policy yourself. Normal Foundocs work continues if a sample is unavailable, with the reason reported. Do not silently fall back to another model/runner.
24
-
25
- At the start of each information-acquisition task, before its first index, TL;DR, search or content exposure, call `get_effect_measurement_policy` once with the explicit configured project_id. Reuse this response throughout that task. OFF means no `measure prepare`, no `measure run`, no evaluation child and no probe inference. The policy response still consumes ordinary main-task context.
26
-
27
- For ON, use a fresh lowercase UUID taskId once per information question. Before any Foundocs exposure, form a short brief from the user's current question and context already known: question (1–2,000 characters), knownContext (0–4,000), criteria (1–10 unique `{id,description}`). Do not include expected answers, full conversation, Foundocs answers, later conclusions or reconstructed history. If this task already saw Foundocs content before preparation, skip measurement; do not relabel it with a new taskId.
28
-
29
- Automatically execute the installed CLI with stdin JSON (never include credentials):
30
-
31
- ```
32
- foundocs-setup measure prepare --root /absolute/governing/project
33
- ```
34
-
35
- Input is `{policy, host, brief:{taskId,question,knownContext,criteria}, allowlist:["src","README.md"], excludePaths:["path/to/known-foundocs-export"]}`. Pass the exact policy response's data object. `host` is the session object emitted by the installed SessionStart hook: `{client:"claude_code", sessionId, transcriptPath}` or `{client:"codex", sessionId, transcriptPath?}`. On Codex, omitting host lets the installer use the current process CODEX_THREAD_ID and locate only that exact thread’s rollout filename. It never reads other threads or chooses a model from config. Use only the current host-provided session identity/path; never search other sessions, infer a model, or ask the user to enter a model ID. If neither current hook identity nor CODEX_THREAD_ID is available, report `working_model_unavailable` and continue normal reads without tracking. The installer reads only the current session's latest assistant model metadata (not conversation text into the brief/server), freezes that exact model with the pre-exposure brief, and uses it for both arms. The old `policy.model` is ignored. A returned skipped reason is not a preparation and must not trigger probes. Use the installed `foundocs-setup` executable or `npx --yes @foundocs/foundocs-setup@latest` if that is the configured launcher. Do not put interpolated user text into shell command syntax: use a quoted heredoc or a private temporary input file and remove it afterward. Choose only user-authorized local original-source paths relative to the governing root; inspect provenance locally before selecting them. Do not use `.`/absolute/parent paths. Ordinary local user docs and extensionless UTF-8 sources are allowed. Explicitly exclude any known exported Foundocs docs/knowledge and already generated answers. Mandatory exclusions include `.git`, dependencies, credentials, `.env`, Foundocs config, installation/skills/session folders, AGENTS.md/CLAUDE.md, and legacy artifacts docs/knowledge/history. Symlink/hardlink sources and binary files are excluded. File/byte limits fail the entire snapshot, never silently truncate it. Unrecognized copied knowledge remains a source-provenance limitation.
36
-
37
- Only `status:"prepared"` authorizes measurement tracking. Save its `effectPreparationId` and the same taskId. Include BOTH on every subsequent `get_project_context` (including view:index), `search_docs`, `explore_docs`, `get_doc` and `get_docs`, retaining them across cursors/chunks. Gather all task retrievalIds, not only helpful ones. Do not retrieve extra content for the experiment or replace the captured response with a full document.
38
-
39
- When that question's information acquisition is finished, report each retrieval's usual beneficial/not_beneficial evaluation. If at least one is beneficial, automatically invoke ONCE:
40
-
41
- ```
42
- foundocs-setup measure run --root /absolute/governing/project
43
- ```
44
-
45
- stdin: `{taskId,retrievalIds:["all-task-retrieval-uuids"]}`. Multiple useful reads belong to this one run. The server chooses sampling/admission and arm order; the coordinator uses the exact captured text only for the with arm. Never call the model manually to reproduce a failed or uncertain run. A duplicate, crash or lost response must not create another probe or taskId. If the coordinator was interrupted or crashed, automatically invoke `measure flush` with the SAME taskId on resumption: it recovers only normalized observed costs after the old owner has exited and never spawns a probe. Do not call prepare with another taskId to reproduce it. For `report_pending`, use `measure flush --root ...` with `{taskId}` to resend only the identical report. A definite rejection requires investigation; it is not an uncertain transport retry, and changed payloads need a new requestId.
46
-
47
- Supported on macOS: authenticated Claude Code 2.1.312 and Codex CLI 0.166.0, including shell-capable Codex Desktop sessions with a current thread rollout. Claude uses fresh assistant metadata; Codex reads only the matching thread's session identity and latest turn_context model/effort, checks project boundaries and a freshly updated rollout. Paginated-only histories without current rollout metadata skip as working_model_unavailable. A user-facing model override is never accepted. Both arms use the working model; neither client substitutes the other provider. Missing/stale/unknown model metadata is working_model_unavailable. Missing CLI/login/isolation, Linux/Windows pending platform verification, shell-less hosts and external network sources skip. Preparation/model discovery does not run inference.
48
-
49
- Claude uses fresh sibling snapshots and restricted Read/Glob/Grep with empty MCP/settings/skills. Codex starts an ephemeral app-server thread with no environments, shell, apps, plugins, browser, web search or delegation, in a fresh empty HOME/cwd. The host serves only Read/Glob/Grep against the exact frozen manifest, with canonical-path, regular-file and hash checks; no model-visible filesystem/auth access. Provider authentication is copied privately for the CLI and removed at exit; Foundocs credentials remain only in the coordinator. Current Codex model and reasoning effort are shared between arms. Codex reports cumulative input+output tokens (cached/reasoning tokens are already included); in-flight usage stays partial. No USD estimate is fabricated: Codex does not provide one, so its estimated USD cutoff cannot be enforced. Token admission, timeout and bounded tool/response steps apply; the CLI may already have an in-flight request when stopped.
50
-
51
- Each arm starts at most once. The coordinator checks server permission before spawn and every 5 seconds; network failure, OFF, changed revision or lease expiry stops the child and prevents the next arm. Termination is SIGINT, 3 seconds later SIGTERM, then 2 seconds later SIGKILL. An already in-flight provider request can still incur cost. Max turns is not an API request count; token reservations and estimated USD thresholds are admission/observation limits, not hard billing caps.
52
-
53
- The comparison is a signed sampled information-acquisition token difference, not whole-task savings. Only actual usage is reported, including failed/cancelled costs; missing fields stay null. Without enough original information, the baseline records a question and the difference is null. Evidence verification checks literal source/quote presence; satisfied criteria are agent self-assessment, not objective semantic equivalence. No judge model is used.
54
-
55
- Raw snapshots, brief, prepareInput and captured context expire 24 hours after preparation. Normalized probes, report outbox and run/lease/hash metadata have a separate 24-hour settlement lifetime after observed completion. An unobserved crash uses the last recorded reservation/usage time + two (per-probe timeout +5s signal-grace) windows +24 hours; recovery and retry never extend it. The next measure command or MCP startup deletes expired local data; a live coordinator also aborts and purges only raw data on expiry. Journal writes serialize with cleanup and cannot restore expired raw fields. Reports can flush without raw data. A non-model watchdog kills the CLI process group on coordinator disconnect, including SIGKILL, and enforces its own timeout. An offline machine cannot guarantee an exact physical deletion time. Raw CLI transcripts are never saved by default. No automatic cleanup changes the original project.
@@ -1,190 +0,0 @@
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 evaluationTools = new Set(['report_retrieval_evaluation', 'report_retrieval_evaluations']);
9
- 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']);
10
- const safeReason = e => reasons.has(e?.reason ?? e?.code?.toLowerCase()) ? (e.reason ?? e.code.toLowerCase()) : ['EACCES', 'EPERM'].includes(e?.code) ? 'permission_denied' : 'local_failure';
11
- const dataOf = r => r?.structuredContent ?? (() => { try { return JSON.parse(r?.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
12
- function retrievalIds(value, found = new Set()) {
13
- if (!value || typeof value !== 'object') return found;
14
- if (Array.isArray(value.retrievals)) for (const r of value.retrievals) if (UUID.test(r?.retrievalId)) found.add(r.retrievalId);
15
- for (const [key, child] of Object.entries(value)) if (key !== 'retrievals' && child && typeof child === 'object') retrievalIds(child, found);
16
- return found;
17
- }
18
- export function automaticTool(tool) {
19
- if (!effectReads.has(tool.name) && !evaluationTools.has(tool.name)) return tool;
20
- const properties = { ...tool.inputSchema.properties };
21
- if (effectReads.has(tool.name)) properties.effectTask = { type: 'object', additionalProperties: false,
22
- 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.',
23
- required: ['taskId'], properties: { taskId: { type: 'string', format: 'uuid' },
24
- question: { type: 'string', minLength: 1, maxLength: 2000 }, knownContext: { type: 'string', maxLength: 4000 },
25
- 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 } } } },
26
- host: { type: 'object', additionalProperties: false, required: ['client', 'sessionId'], properties: { client: { type: 'string', enum: ['codex', 'claude_code'] }, sessionId: { type: 'string', format: 'uuid' }, transcriptPath: { type: 'string' } } },
27
- } };
28
- else {
29
- properties.effectTaskId = { type: 'string', format: 'uuid', description: 'Same automatic information task identity.' };
30
- 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.' };
31
- }
32
- return { ...tool, description: tool.description + ' Installed automatic measurement accepts local task metadata; no shell prepare/run is needed.', inputSchema: { ...tool.inputSchema, properties },
33
- annotations: { ...tool.annotations, readOnlyHint: false, openWorldHint: true } };
34
- }
35
-
36
- /** Serializes calls for this bridge; persistent coordinator locks prevent duplicate probes across bridges/restarts. */
37
- export class AutomaticMeasurement {
38
- constructor({ projectId, remote, factory, store, warn = () => {} }) { Object.assign(this, { projectId, remote, factory, store, warn }); this.queue = Promise.resolve(); this.jobs = new Set(); }
39
- call(params) {
40
- const next = this.queue.then(() => this.handle(params));
41
- this.queue = next.catch(() => {}); return next;
42
- }
43
- async recover() {
44
- for (const state of await this.store.list?.() ?? []) {
45
- if (state.diagnostic) {
46
- try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
47
- catch { this.warn('Foundocs measurement status is pending; no inference was repeated.'); }
48
- }
49
- if (!state.closed || state.settled || !state.preparationId) continue;
50
- try {
51
- const { coordinator } = await this.factory({ recovery: true });
52
- const result = await coordinator.flush(state.taskId);
53
- if (result.reason === 'coordinator_active') continue;
54
- if (result.status === 'report_pending') {
55
- await this.diagnostic(state, 'failed', 'report_pending');
56
- continue;
57
- }
58
- state.settled = true;
59
- if (['reported', 'already_reported'].includes(result.status)) {
60
- const failed = result.result && result.result.status !== 'completed';
61
- await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
62
- }
63
- else await this.diagnostic(state, 'failed', result.status === 'nothing_pending' ? 'local_failure' : safeReason(result));
64
- } catch { this.warn('Foundocs measurement recovery pending; no inference was repeated.'); }
65
- }
66
- }
67
- async diagnostic(state, status, reason = null) {
68
- state.sequence = (state.sequence ?? 0) + 1;
69
- state.diagnostic = { requestId: randomUUID(), taskId: state.taskId, sequence: state.sequence, status, reason };
70
- try { await this.store.save(state); } catch { this.warn('Foundocs measurement status could not be saved locally.'); }
71
- try { await this.remote('report_effect_diagnostic', state.diagnostic); state.diagnostic = null; await this.store.save(state); }
72
- catch { this.warn('Foundocs measurement status could not be delivered; local status retained.'); }
73
- }
74
- async handle(params) {
75
- const { effectTask, effectTaskId, effectTaskComplete, ...args } = params.arguments ?? {};
76
- const forward = () => this.remote(params.name, args, true);
77
- if (args.project_id !== this.projectId) {
78
- if (effectTask || effectTaskId || effectTaskComplete) throw new Error('Automatic measurement project mismatch');
79
- return forward();
80
- }
81
- if (effectReads.has(params.name)) {
82
- // Explicit legacy tracking stays under its existing coordinator. Never attach two tasks.
83
- if (!effectTask) return forward();
84
- const taskId = effectTask?.taskId ?? (UUID.test(args.taskId ?? '') ? args.taskId : UUID.test(args.readId ?? '') ? args.readId : randomUUID());
85
- if (!UUID.test(taskId) || (args.taskId && args.taskId !== taskId) || (effectTask && args.effectPreparationId)) throw new Error('Conflicting measurement task');
86
- let state;
87
- try { state = await this.store.load(taskId); }
88
- catch (e) {
89
- args.taskId = taskId;
90
- try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
91
- return forward();
92
- }
93
- if (!state) {
94
- state = { taskId, retrievals: [], evaluated: [], exposed: false, closed: false, expiresAt: new Date(Date.now() + 86400000).toISOString() };
95
- // Persist before preparation; a crash must never create a new baseline after exposure.
96
- try { await this.store.save(state); }
97
- catch (e) {
98
- args.taskId = taskId;
99
- try { await this.remote('report_effect_diagnostic', { requestId: randomUUID(), taskId, sequence: 0, status: 'skipped', reason: safeReason(e) }); } catch { this.warn('Foundocs measurement storage unavailable.'); }
100
- return forward();
101
- }
102
- try {
103
- const policy = await this.remote('get_effect_measurement_policy', {});
104
- if (!policy.enabled) state.skipped = 'disabled';
105
- else if (!effectTask?.question || !effectTask?.criteria) state.skipped = 'missing_preparation';
106
- else {
107
- const brief = { taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria };
108
- validateBrief(brief); state.briefHash = hash(brief);
109
- const { coordinator, config } = await this.factory();
110
- if (!config?.enabled) state.skipped = 'consent_required';
111
- else {
112
- const result = await coordinator.prepare({ policy, brief, allowlist: config.allowlist, excludePaths: config.excludePaths, host: effectTask.host });
113
- if (result.status === 'prepared') { state.preparationId = result.effectPreparationId; state.consentHash = hash(config); }
114
- else state.skipped = safeReason(result);
115
- }
116
- }
117
- } catch (e) { state.skipped = safeReason(e); }
118
- await this.diagnostic(state, state.preparationId ? 'prepared' : 'skipped', state.preparationId ? null : state.skipped);
119
- } else if (effectTask?.question && state.briefHash !== hash({ taskId, question: effectTask.question, knownContext: effectTask.knownContext ?? '', criteria: effectTask.criteria })) {
120
- throw new Error('Do not change a frozen information task');
121
- }
122
- if (!state.preparationId && !state.skipped) state.skipped = 'missing_preparation'; // interrupted preparation stays unmeasured
123
- if (state.closed && effectTask) throw new Error('Information task is closed; never add later context or relabel the same question.');
124
- if (state.closed || Date.parse(state.expiresAt) <= Date.now()) {
125
- // Continue ordinary reads, but never silently add post-completion context to an existing sample.
126
- delete args.effectPreparationId; args.taskId = taskId;
127
- return forward();
128
- }
129
- args.taskId = taskId;
130
- if (state.preparationId) args.effectPreparationId = state.preparationId;
131
- // Mark exposure before the remote request: a lost reply must not re-prepare.
132
- state.exposed = true;
133
- try { await this.store.save(state); }
134
- catch (e) { delete args.effectPreparationId; await this.diagnostic(state, 'skipped', safeReason(e)); return forward(); }
135
- const result = await forward(), body = dataOf(result);
136
- if (body?.ok) {
137
- state.retrievals = [...new Set([...state.retrievals, ...retrievalIds(body.data)])];
138
- try { await this.store.save(state); } catch { this.warn('Foundocs retrieval tracking could not be saved; no extra reads were requested.'); }
139
- }
140
- return result;
141
- }
142
- const isBatch = params.name === 'report_retrieval_evaluations';
143
- if (isBatch && effectTaskId && args.taskId !== effectTaskId) throw new Error('Conflicting measurement task');
144
- const result = await forward();
145
- if (!evaluationTools.has(params.name) || !effectTaskId || !dataOf(result)?.ok) return result;
146
- if (!UUID.test(effectTaskId)) return result;
147
- let state;
148
- try { state = await this.store.load(effectTaskId); } catch { this.warn('Foundocs evaluation tracking unavailable.'); return result; }
149
- if (!state || state.closed) return result;
150
- const submitted = isBatch ? args.items : [args];
151
- const tracked = submitted.filter(item => state.retrievals.includes(item.retrievalId));
152
- if (!tracked.length) return result;
153
- state.evaluated = [...new Set([...state.evaluated, ...tracked.map(item => item.retrievalId)])];
154
- if (tracked.some(item => item.verdict === 'beneficial')) state.beneficial = true;
155
- try { await this.store.save(state); } catch { this.warn('Foundocs evaluation tracking could not be saved; no comparison started.'); return result; }
156
- if (!effectTaskComplete) return result;
157
- if (state.retrievals.some(id => !state.evaluated.includes(id))) {
158
- await this.diagnostic(state, 'skipped', 'incomplete_evaluation'); return result;
159
- }
160
- state.closed = true;
161
- try { await this.store.save(state); } catch { this.warn('Foundocs task closure could not be saved; no comparison started.'); return result; }
162
- if (!state.preparationId || !state.beneficial) { state.settled = true; await this.diagnostic(state, 'skipped', state.skipped ?? 'no_beneficial_retrieval'); return result; }
163
- // No long-running model call inside the MCP response timeout. The bridge owns and settles the task.
164
- const job = this.run(state).catch(() => this.warn('Foundocs automatic measurement failed; ordinary work continues.'));
165
- this.jobs.add(job); void job.finally(() => this.jobs.delete(job));
166
- return result;
167
- }
168
- async run(state) {
169
- try {
170
- const { coordinator, config } = await this.factory();
171
- if (!config?.enabled || state.consentHash !== hash(config)) { state.settled = true; await this.diagnostic(state, 'skipped', 'consent_required'); return; }
172
- await this.diagnostic(state, 'running');
173
- const result = await coordinator.run({ taskId: state.taskId, retrievalIds: state.retrievals });
174
- state.settled = !['report_pending'].includes(result.status);
175
- if (result.status === 'reported' || result.status === 'already_reported') {
176
- const failed = result.result && result.result.status !== 'completed';
177
- await this.diagnostic(state, failed ? 'failed' : 'completed', failed ? 'local_failure' : null);
178
- } else await this.diagnostic(state, result.status === 'report_pending' ? 'failed' : 'skipped', result.status === 'report_pending' ? 'report_pending' : safeReason(result));
179
- } catch (e) { await this.diagnostic(state, 'failed', safeReason(e)); }
180
- }
181
- async drain() { await this.queue; await Promise.allSettled([...this.jobs]); }
182
- }
183
- export function automaticStore(base) {
184
- const path = taskId => { if (!UUID.test(taskId)) throw new Error('Invalid task'); return join(base, taskId, 'automatic.json'); };
185
- return {
186
- 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; },
187
- async load(taskId) { try { return await readJson(path(taskId)); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
188
- async save(state) { await privateDir(join(base, state.taskId)); await saveJson(path(state.taskId), state); },
189
- };
190
- }
@@ -1,31 +0,0 @@
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
- }
@@ -1,86 +0,0 @@
1
- import { open, realpath, readdir } from 'node:fs/promises';
2
- import { constants } from 'node:fs';
3
- import { basename, isAbsolute, relative, join } from 'node:path';
4
- import { UUID } from './effect-core.mjs';
5
-
6
- const exactModel = /^claude-(haiku|sonnet|opus)-\d+(?:-\d+)*$/;
7
- const maxTail = 1024 * 1024;
8
- const within = (root, path) => { const r = relative(root, path); return r === '' || (!r.startsWith('..') && !isAbsolute(r)); };
9
-
10
- /** Read only model metadata from the current host transcript; never return/persist conversation text. */
11
- export async function workingSessionModel(host, root, now = Date.now()) {
12
- if (host?.client === 'codex' || (!host && process.env.CODEX_THREAD_ID)) return codexSessionModel(host ?? { client: 'codex', sessionId: process.env.CODEX_THREAD_ID }, root, now);
13
- if (!host || host.client !== 'claude_code') return { status: 'skipped', reason: host?.client ? 'unsupported_runner' : 'working_model_unavailable' };
14
- if (typeof host.sessionId !== 'string' || !UUID.test(host.sessionId) || typeof host.transcriptPath !== 'string' || !isAbsolute(host.transcriptPath) || basename(host.transcriptPath) !== `${host.sessionId}.jsonl`) return { status: 'skipped', reason: 'working_model_unavailable' };
15
- let file;
16
- try {
17
- file = await open(host.transcriptPath, constants.O_RDONLY | constants.O_NOFOLLOW);
18
- const stat = await file.stat();
19
- if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
20
- const start = Math.max(0, stat.size - maxTail), buffer = Buffer.alloc(Math.min(stat.size, maxTail));
21
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
22
- const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n');
23
- if (start) lines.shift(); // Never parse a truncated leading record.
24
- for (const line of lines.reverse()) {
25
- if (!line.trim()) continue;
26
- let event; try { event = JSON.parse(line); } catch { throw new Error(); } // An incomplete latest record must not select an older model.
27
- if (event.type !== 'assistant' || event.isSidechain || event.parent_tool_use_id) continue;
28
- // Stop at the latest assistant record; never fall back to an older/different model.
29
- if (event.sessionId !== host.sessionId || typeof event.cwd !== 'string' || !within(await realpath(root), await realpath(event.cwd))) throw new Error();
30
- const timestamp = Date.parse(event.timestamp);
31
- if (!Number.isFinite(timestamp) || now - timestamp > 5 * 60_000 || timestamp > now + 60_000 || !exactModel.test(event.message?.model ?? '')) throw new Error();
32
- return { status: 'identified', model: event.message.model, modelSource: 'working_session' };
33
- }
34
- } catch { /* Missing, stale, inaccessible or unsupported metadata never chooses a default. */ }
35
- finally { await file?.close(); }
36
- return { status: 'skipped', reason: 'working_model_unavailable' };
37
- }
38
-
39
-
40
- /** Resolve only this host's exact thread ID, never another thread's contents. */
41
- export async function codexSessionModel(host, root, now = Date.now(), env = process.env) {
42
- if (!UUID.test(host.sessionId ?? '') || (env.CODEX_THREAD_ID && env.CODEX_THREAD_ID !== host.sessionId)) return { status: 'skipped', reason: 'working_model_unavailable' };
43
- let file;
44
- try {
45
- let path = host.transcriptPath;
46
- if (!path) {
47
- const base = join(env.CODEX_HOME || join(env.HOME, '.codex'), 'sessions');
48
- const matches = [];
49
- async function find(dir, depth = 0) {
50
- for (const entry of await readdir(dir, { withFileTypes: true })) {
51
- if (entry.isDirectory() && depth < 3 && /^\d{2,4}$/.test(entry.name)) await find(join(dir, entry.name), depth + 1);
52
- else if (entry.isFile() && entry.name.endsWith(`-${host.sessionId}.jsonl`)) matches.push(join(dir, entry.name));
53
- }
54
- }
55
- await find(base); if (matches.length !== 1) throw new Error(); path = matches[0];
56
- }
57
- if (typeof path !== 'string' || !isAbsolute(path) || !basename(path).endsWith(`-${host.sessionId}.jsonl`)) throw new Error();
58
- file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
59
- const stat = await file.stat();
60
- if (!stat.isFile() || now - stat.mtimeMs > 5 * 60_000 || stat.mtimeMs > now + 60_000) throw new Error();
61
- // Identity is in the first record. A long active Codex turn can emit several
62
- // MiB after turn_context; inspect a bounded 16 MiB tail, returning metadata only.
63
- const head = Buffer.alloc(Math.min(stat.size, 64 * 1024)); await file.read(head, 0, head.length, 0);
64
- const meta = JSON.parse(head.toString('utf8').split('\n')[0]);
65
- if (meta.type !== 'session_meta' || meta.payload.id !== host.sessionId || meta.payload.model_provider !== 'openai') throw new Error();
66
- const canonicalRoot = await realpath(root);
67
- if (!within(canonicalRoot, await realpath(meta.payload.cwd))) throw new Error();
68
- const start = Math.max(0, stat.size - 16 * maxTail), buffer = Buffer.alloc(Math.min(stat.size, 16 * maxTail));
69
- const { bytesRead } = await file.read(buffer, 0, buffer.length, start);
70
- const lines = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); if (start) lines.shift();
71
- for (const line of lines.reverse()) {
72
- if (!line.trim()) continue;
73
- const event = JSON.parse(line);
74
- if (event.type !== 'turn_context') continue;
75
- const p = event.payload;
76
- if (!within(canonicalRoot, await realpath(p.cwd)) || !/^gpt-\d[\w.-]{0,150}$/.test(p.model) || /(?:latest|auto)$/.test(p.model)) throw new Error();
77
- const timestamp = Date.parse(event.timestamp);
78
- if (!Number.isFinite(timestamp) || timestamp > now + 60_000) throw new Error();
79
- // A long active turn can outlive five minutes. Freshness is the current
80
- // transcript's mtime; never select an older turn after malformed metadata.
81
- return { status: 'identified', model: p.model, modelSource: 'working_session', runner: 'codex_read_tools_v1', ...(typeof p.effort === 'string' && ['none','minimal','low','medium','high','xhigh','max','ultra'].includes(p.effort) ? { reasoningEffort: p.effort } : {}) };
82
- }
83
- } catch { /* Never infer a model from config/defaults or another thread. */ }
84
- finally { await file?.close(); }
85
- return { status: 'skipped', reason: 'working_model_unavailable' };
86
- }
@@ -1,28 +0,0 @@
1
- import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
2
- import { readCredential } from './auth.mjs';
3
- import { EffectError } from './effect-core.mjs';
4
- export async function connectEffectRemote(manifest) {
5
- const url = new URL(manifest.mcpUrl);
6
- const key = await readCredential(manifest.credentialPath, manifest.projectId, manifest.workspaceId);
7
- const client = new Client({ name: 'foundocs-effect-coordinator', version: '1' });
8
- const transport = new StreamableHTTPClientTransport(url, {
9
- requestInit: { headers: { Authorization: `Bearer ${key}` } },
10
- fetch: (target, init) => {
11
- if (new URL(typeof target === 'string' || target instanceof URL ? target : target.url).origin !== url.origin) throw new EffectError('origin_changed');
12
- return fetch(target, { ...init, redirect: 'error', signal: init?.signal ? AbortSignal.any([init.signal, AbortSignal.timeout(5000)]) : AbortSignal.timeout(5000) });
13
- },
14
- });
15
- try { await client.connect(transport, { timeout: 5000 }); await client.listTools(); } catch { await client.close().catch(() => {}); throw new EffectError('connection_unavailable'); }
16
- return {
17
- close: () => client.close(),
18
- async call(name, args) {
19
- let result;
20
- try { result = await client.callTool({ name, arguments: { ...args, project_id: manifest.projectId } }, undefined, { timeout: 5000 }); }
21
- catch { throw new EffectError('transport_uncertain', 'Request outcome is uncertain; no inference will be repeated.', true); }
22
- const body = result.structuredContent ?? (() => { try { return JSON.parse(result.content?.find(c => c.type === 'text')?.text); } catch { return null; } })();
23
- if (!body || typeof body.ok !== 'boolean') throw new EffectError('invalid_response', 'Request outcome is uncertain.', true);
24
- if (!body.ok || result.isError) throw new EffectError(body.error?.code ?? 'request_failed', 'Server rejected the measurement request.');
25
- return body.data;
26
- },
27
- };
28
- }