@fatelabs/opencode-estelle 0.0.0-stage → 0.0.18

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.
Files changed (83) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +6 -0
  3. package/README.md +46 -2
  4. package/adapters/claude.mjs +17 -0
  5. package/adapters/codex.mjs +85 -0
  6. package/adapters/cursor.mjs +66 -0
  7. package/adapters/dsh-host.mjs +181 -0
  8. package/adapters/dsh-plugin.mjs +11 -0
  9. package/adapters/dsh.mjs +54 -0
  10. package/adapters/grok.mjs +63 -0
  11. package/adapters/host-bridge.mjs +85 -0
  12. package/adapters/kimi.mjs +135 -0
  13. package/adapters/opencode-mirror.mjs +103 -0
  14. package/adapters/opencode-plugin.mjs +143 -0
  15. package/adapters/opencode.mjs +15 -0
  16. package/adapters/pi-extension.mjs +107 -0
  17. package/adapters/pi.mjs +13 -0
  18. package/adapters/plugin-envelope.mjs +56 -0
  19. package/agents/estelle-grounder.md +34 -0
  20. package/agents/estelle-historian.md +28 -0
  21. package/agents/estelle-repair.md +29 -0
  22. package/agents/estelle-reviewer.md +32 -0
  23. package/commands/cloud.md +28 -0
  24. package/commands/code.md +6 -0
  25. package/commands/handoff.md +25 -0
  26. package/commands/monitor.md +6 -0
  27. package/commands/resume.md +6 -0
  28. package/commands/review.md +6 -0
  29. package/commands/rooms.md +7 -0
  30. package/instructions.md +19 -0
  31. package/package.json +34 -4
  32. package/runtime/auth.mjs +27 -0
  33. package/runtime/checkpoint.mjs +208 -0
  34. package/runtime/claude-setup.mjs +130 -0
  35. package/runtime/cli.mjs +112 -0
  36. package/runtime/codex-trust.mjs +68 -0
  37. package/runtime/credential.mjs +341 -0
  38. package/runtime/dsh-session.mjs +91 -0
  39. package/runtime/dsh-telemetry.mjs +31 -0
  40. package/runtime/hooks.mjs +234 -0
  41. package/runtime/identity.mjs +20 -0
  42. package/runtime/io.mjs +155 -0
  43. package/runtime/key-check.mjs +51 -0
  44. package/runtime/kimi-history.mjs +163 -0
  45. package/runtime/mailbox.mjs +46 -0
  46. package/runtime/migration.mjs +118 -0
  47. package/runtime/move.mjs +443 -0
  48. package/runtime/native-export.mjs +204 -0
  49. package/runtime/native-index.mjs +77 -0
  50. package/runtime/native-tree.mjs +117 -0
  51. package/runtime/queued-context.mjs +152 -0
  52. package/runtime/redact.mjs +74 -0
  53. package/runtime/reindex.mjs +259 -0
  54. package/runtime/setup.mjs +174 -0
  55. package/runtime/stream.mjs +755 -0
  56. package/runtime/version.mjs +2 -0
  57. package/runtime/write-warning.mjs +67 -0
  58. package/skills/abstain-right/SKILL.md +19 -0
  59. package/skills/api-call-ground/SKILL.md +19 -0
  60. package/skills/bug-hunt/SKILL.md +20 -0
  61. package/skills/chain-of-verification/SKILL.md +19 -0
  62. package/skills/change-impact/SKILL.md +19 -0
  63. package/skills/coding-workflow/SKILL.md +20 -0
  64. package/skills/commit-guard/SKILL.md +20 -0
  65. package/skills/context-checkpoint/SKILL.md +19 -0
  66. package/skills/continuity-brief/SKILL.md +19 -0
  67. package/skills/dead-code-sweep/SKILL.md +19 -0
  68. package/skills/deep-search/SKILL.md +19 -0
  69. package/skills/diff-review/SKILL.md +19 -0
  70. package/skills/estelle/SKILL.md +119 -0
  71. package/skills/estelle-loop/SKILL.md +19 -0
  72. package/skills/estelle-monitor-install/SKILL.md +20 -0
  73. package/skills/evidence-traceability-audit/SKILL.md +19 -0
  74. package/skills/grounded-generate/SKILL.md +19 -0
  75. package/skills/incident-rca/SKILL.md +20 -0
  76. package/skills/mutation-test/SKILL.md +19 -0
  77. package/skills/program-repair/SKILL.md +20 -0
  78. package/skills/prompt-injection-defense/SKILL.md +19 -0
  79. package/skills/property-based-test/SKILL.md +19 -0
  80. package/skills/refactor-rfc/SKILL.md +19 -0
  81. package/skills/root-cause-loop/SKILL.md +19 -0
  82. package/skills/test-first/SKILL.md +19 -0
  83. package/skills/threat-model-stride/SKILL.md +19 -0
@@ -0,0 +1,259 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdir, open, realpath, stat, unlink } from 'node:fs/promises';
4
+ import { constants } from 'node:fs';
5
+ import path from 'node:path';
6
+ import { hash, readJson, writeJson } from './io.mjs';
7
+ import { redact } from './redact.mjs';
8
+
9
+ // Extracted from public estelle-cli reindex_spool / checkout_identity contracts.
10
+ const LIMITS = Object.freeze({ paths: 500, batch: 100, fileBytes: 256_000,
11
+ bodyBytes: 2_000_000, patchLines: 10_000, debounceMs: 5_000,
12
+ repoIntervalMs: 20_000, lockAttempts: 20, lockDelayMs: 25, deadLockMs: 30_000 });
13
+ const EXTENSIONS = new Set('c cpp cs go h hpp java js jsx kt md php py rb rs scala swift ts tsx'.split(' '));
14
+ const SKIP_DIRS = new Set('.git build coverage dist node_modules target vendor'.split(' '));
15
+ const CREDENTIAL_NAMES = new Set(['.env', '.netrc', '.npmrc', '.pypirc', 'auth.json',
16
+ 'credentials.json', 'estelle_accounts.json', 'estelle_experience.json', 'stress_accounts.json',
17
+ 'id_ecdsa', 'id_ed25519', 'id_rsa']);
18
+ const CREDENTIAL_EXTENSIONS = new Set(['key', 'p12', 'pem', 'pfx']);
19
+ const GIT_KEYS = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR',
20
+ 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES', 'GIT_NAMESPACE', 'GIT_PREFIX'];
21
+ const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
22
+
23
+ function git(root, args) {
24
+ const env = { ...process.env, GIT_TERMINAL_PROMPT: '0' };
25
+ for (const key of GIT_KEYS) delete env[key];
26
+ const result = spawnSync('git', ['--literal-pathspecs', '-C', root, ...args], {
27
+ env, encoding: 'utf8', timeout: 1_500, maxBuffer: LIMITS.bodyBytes,
28
+ stdio: ['ignore', 'pipe', 'ignore'],
29
+ });
30
+ return result.status === 0 ? result.stdout : undefined;
31
+ }
32
+
33
+ function within(child, root) {
34
+ const relative = path.relative(root, child);
35
+ return relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`)
36
+ && !path.isAbsolute(relative);
37
+ }
38
+
39
+ function credentialPath(key) {
40
+ const name = path.basename(key).toLowerCase();
41
+ return CREDENTIAL_NAMES.has(name) || name.startsWith('.env.') || /^id_(rsa|ed25519)/.test(name)
42
+ || CREDENTIAL_EXTENSIONS.has(path.extname(name).slice(1));
43
+ }
44
+
45
+ function editedPaths(n) {
46
+ const input = n.toolInput;
47
+ if (!input || typeof input !== 'object') return [];
48
+ const paths = new Set();
49
+ for (const key of ['file_path', 'path', 'filePath', 'notebook_path']) {
50
+ if (typeof input[key] === 'string' && input[key].trim()) paths.add(input[key]);
51
+ }
52
+ const patch = ['input', 'patch', 'diff', 'arguments', 'command']
53
+ .map(key => input[key]).find(value => typeof value === 'string' && value.includes('*** Begin Patch'));
54
+ if (patch) {
55
+ const lines = patch.split('\n');
56
+ if (lines.length > LIMITS.patchLines) throw new Error('reindex_patch_bound');
57
+ for (const line of lines) {
58
+ const match = /^\*\*\* (?:Update File|Add File|Delete File|Move to): (.+)$/.exec(line);
59
+ if (match) paths.add(match[1]);
60
+ if (paths.size > LIMITS.batch) throw new Error('reindex_path_bound');
61
+ }
62
+ }
63
+ return [...paths];
64
+ }
65
+
66
+ async function admit(root, cwd, offered) {
67
+ if (!offered || /[\0\r\n]/.test(offered)) return null;
68
+ const full = path.resolve(cwd, offered);
69
+ if (!within(full, root)) return null;
70
+ const key = path.relative(root, full).split(path.sep).join('/');
71
+ if (credentialPath(key) || key.split('/').some(part => SKIP_DIRS.has(part))) return null;
72
+ if (!EXTENSIONS.has(path.extname(key).slice(1))) return null;
73
+ let canonical;
74
+ try { canonical = await realpath(full); }
75
+ catch (error) {
76
+ if (error.code !== 'ENOENT') throw error;
77
+ // Resolve the existing parent before accepting a deletion.
78
+ canonical = path.join(await realpath(path.dirname(full)), path.basename(full));
79
+ }
80
+ if (!within(canonical, root) || canonical !== full) return null;
81
+ const ignored = git(root, ['check-ignore', '-q', '--', key]);
82
+ if (ignored !== undefined) return null;
83
+ const inventory = git(root, ['ls-files', '-z', '--cached', '--others', '--exclude-standard', '--', key]);
84
+ if (inventory === undefined || !inventory.split('\0').includes(key)) return null;
85
+ return key;
86
+ }
87
+
88
+ async function lock(file) {
89
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
90
+ for (let attempt = 0; attempt < LIMITS.lockAttempts; attempt++) {
91
+ try {
92
+ const handle = await open(file, 'wx', 0o600);
93
+ const token = randomUUID();
94
+ try { await handle.writeFile(JSON.stringify({ pid: process.pid, token })); }
95
+ catch (error) { await unlink(file).catch(() => {}); throw error; }
96
+ finally { await handle.close(); }
97
+ return async () => {
98
+ const item = await readJson(file, 1024);
99
+ if (item.token === token) await unlink(file);
100
+ };
101
+ } catch (error) {
102
+ if (error.code !== 'EEXIST') throw error;
103
+ await clearDeadLock(file);
104
+ await sleep(LIMITS.lockDelayMs);
105
+ }
106
+ }
107
+ throw new Error('reindex_locked');
108
+ }
109
+
110
+ async function clearDeadLock(file) {
111
+ try {
112
+ if (Date.now() - (await stat(file)).mtimeMs < LIMITS.deadLockMs) return;
113
+ const item = await readJson(file, 1024);
114
+ if (!Number.isSafeInteger(item.pid) || item.pid < 1) return;
115
+ try { process.kill(item.pid, 0); }
116
+ catch (error) { if (error.code === 'ESRCH') await unlink(file); }
117
+ } catch (error) { if (error.code !== 'ENOENT') throw error; }
118
+ }
119
+
120
+ async function load(file, initial) {
121
+ try { return await readJson(file, 128_000); }
122
+ catch (error) { if (error.code === 'ENOENT') return initial; throw error; }
123
+ }
124
+
125
+ async function enqueue(file, repo, keys, now) {
126
+ const release = await lock(`${file}.lock`);
127
+ try {
128
+ const state = await load(file, { repo: repo.name, root: repo.root, pending: {}, since: now, overflow: 0 });
129
+ if (state.repo !== repo.name || state.root !== repo.root || !state.pending || typeof state.pending !== 'object') {
130
+ throw new Error('reindex_spool_identity');
131
+ }
132
+ const pending = { ...state.pending };
133
+ let overflow = state.overflow || 0;
134
+ for (const key of keys) {
135
+ if (!Object.hasOwn(pending, key) && Object.keys(pending).length >= LIMITS.paths) { overflow++; continue; }
136
+ pending[key] = randomUUID();
137
+ }
138
+ const next = { ...state, pending, overflow, since: Object.keys(state.pending).length ? state.since : now };
139
+ await writeJson(file, next);
140
+ return next;
141
+ } finally { await release(); }
142
+ }
143
+
144
+ async function reserve(marker, now) {
145
+ const release = await lock(`${marker}.lock`);
146
+ try {
147
+ const previous = await load(marker, { at: 0 });
148
+ if (!Number.isFinite(previous.at) || now < previous.at + LIMITS.repoIntervalMs) return false;
149
+ await writeJson(marker, { at: now });
150
+ return true;
151
+ } finally { await release(); }
152
+ }
153
+
154
+ async function checkout(root) {
155
+ const branch = git(root, ['rev-parse', '--abbrev-ref', 'HEAD'])?.trim();
156
+ const originHead = git(root, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'])?.trim();
157
+ const gitDir = git(root, ['rev-parse', '--absolute-git-dir'])?.trim();
158
+ const commonDir = git(root, ['rev-parse', '--git-common-dir'])?.trim();
159
+ const linked = gitDir && commonDir
160
+ ? await realpath(gitDir) !== await realpath(path.resolve(root, commonDir)) : false;
161
+ return { linked_worktree: Boolean(linked),
162
+ ...(branch && branch !== 'HEAD' ? { branch } : {}),
163
+ ...(originHead?.startsWith('origin/') ? { default_branch: originHead.slice(7) } : {}),
164
+ };
165
+ }
166
+
167
+ async function filePayload(root, key) {
168
+ if (await admit(root, root, key) !== key) return null;
169
+ const full = path.join(root, key);
170
+ let handle;
171
+ try {
172
+ handle = await open(full, constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
173
+ const info = await handle.stat();
174
+ if (!info.isFile() || info.size > LIMITS.fileBytes) return null;
175
+ const actual = await realpath(full);
176
+ if (actual !== full || !within(actual, root)) return null;
177
+ const current = await stat(full);
178
+ if (current.dev !== info.dev || current.ino !== info.ino) return null;
179
+ const buffer = Buffer.alloc(info.size + 1);
180
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
181
+ if (bytesRead > info.size) return null;
182
+ const content = new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, bytesRead));
183
+ if (redact(content) !== content) return null;
184
+ return { path: key, content };
185
+ } catch (error) {
186
+ if (error.code === 'ENOENT') return { removed: key };
187
+ if (error instanceof TypeError) return null;
188
+ throw error;
189
+ } finally { await handle?.close(); }
190
+ }
191
+
192
+ async function batchBody(root, repo, pending, deadline) {
193
+ const files = [], removed = [], consumed = {};
194
+ let excluded = 0;
195
+ let bytes = 1000;
196
+ for (const [key, token] of Object.entries(pending).slice(0, LIMITS.batch)) {
197
+ // Leave room for two per-file Git checks and the four checkout-identity reads.
198
+ if (Date.now() + 9_500 > deadline) break;
199
+ const item = await filePayload(root, key);
200
+ if (item === null) { consumed[key] = token; excluded++; continue; }
201
+ const size = Buffer.byteLength(JSON.stringify(item));
202
+ if (bytes + size > LIMITS.bodyBytes) break;
203
+ bytes += size;
204
+ consumed[key] = token;
205
+ if (item.removed) removed.push(item.removed); else files.push(item);
206
+ }
207
+ const body = { repo, files, ...(removed.length ? { removed } : {}), checkout: await checkout(root) };
208
+ if (Buffer.byteLength(JSON.stringify(body)) > LIMITS.bodyBytes) throw new Error('request_size');
209
+ return { consumed, excluded, body };
210
+ }
211
+
212
+ async function acknowledge(file, consumed) {
213
+ const release = await lock(`${file}.lock`);
214
+ try {
215
+ const state = await readJson(file, 128_000);
216
+ const pending = { ...state.pending };
217
+ for (const [key, token] of Object.entries(consumed)) if (pending[key] === token) delete pending[key];
218
+ await writeJson(file, { ...state, pending });
219
+ return Object.keys(pending).length;
220
+ } finally { await release(); }
221
+ }
222
+
223
+ /** Synchronous debounced flush. Pending paths retry on later hook calls; no background worker. */
224
+ export async function queueReindex({ normalized, repo, stateDir, request, now = Date.now(),
225
+ deadline = Date.now() + 12_000 }) {
226
+ if (!repo || typeof repo.name !== 'string' || !/^[\w.-]+\/[\w.-]+$/.test(repo.name)) throw new Error('reindex_repo');
227
+ if (typeof request !== 'function' || !Number.isFinite(now) || now <= 0) throw new Error('reindex_arguments');
228
+ const root = await realpath(repo.root);
229
+ const identity = { name: repo.name, root };
230
+ const directory = path.join(stateDir, 'reindex');
231
+ const file = path.join(directory, `${hash(`${repo.name}\0${root}`)}.json`);
232
+ const keys = [];
233
+ const cwd = await realpath(normalized.cwd || root);
234
+ for (const offered of editedPaths(normalized)) {
235
+ if (Date.now() + 3_000 > deadline) {
236
+ // Queue only a lexical path here; filePayload revalidates inventory and real paths before
237
+ // reading any content. A slow Git process must not lose the remaining edit references.
238
+ const full = path.resolve(cwd, offered);
239
+ const key = path.relative(root, full).split(path.sep).join('/');
240
+ if (within(full, root) && !credentialPath(key) && EXTENSIONS.has(path.extname(key).slice(1))
241
+ && !key.split('/').some(part => SKIP_DIRS.has(part))) keys.push(key);
242
+ continue;
243
+ }
244
+ const key = await admit(root, cwd, offered);
245
+ if (key) keys.push(key);
246
+ }
247
+ const state = await enqueue(file, identity, keys, now);
248
+ if (!Object.keys(state.pending).length) return { pending: false, sent: 0, skipped: keys.length === 0 };
249
+ if (now < state.since + LIMITS.debounceMs) return { pending: true, sent: 0, overflow: state.overflow };
250
+ if (!await reserve(path.join(directory, `repo-${hash(repo.name)}.json`), now)) return { pending: true, sent: 0 };
251
+ const { body, consumed, excluded } = await batchBody(root, repo.name, state.pending, deadline);
252
+ const sent = body.files.length + (body.removed?.length || 0);
253
+ const response = sent ? await request('/reindex', body) : {};
254
+ const remaining = await acknowledge(file, consumed);
255
+ // A lane skip is consumed, never reported as current. No freshness stamp is written here.
256
+ return { pending: remaining > 0, sent, accepted: sent > 0 && response.skipped_off_default !== true,
257
+ skippedOffDefault: response.skipped_off_default === true, overflow: state.overflow,
258
+ excluded, incomplete: excluded > 0 || state.overflow > 0 };
259
+ }
@@ -0,0 +1,174 @@
1
+ /** Explicit native setup; no install callback, hook-trust edit, credential-store or cache migration. */
2
+ import { execFile } from 'node:child_process';
3
+ import { request as httpsRequest } from 'node:https';
4
+ import { homedir } from 'node:os';
5
+ import { join, resolve } from 'node:path';
6
+ import { open } from 'node:fs/promises';
7
+ import { constants } from 'node:fs';
8
+ import { createHash } from 'node:crypto';
9
+ import { launchCredential } from './auth.mjs';
10
+ import { UNREADABLE, codexHookTrust } from './codex-trust.mjs';
11
+ import { inspectHooks, planHooks, commitHooks } from './migration.mjs';
12
+ import { VERSION } from './version.mjs';
13
+
14
+ const CAP=16384, BUDGET_MS=45000, CALL_MS=8000;
15
+ const BASE='https://api.fatelabs.ca';
16
+ const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
17
+ const hash=x=>createHash('sha256').update(x).digest('hex');
18
+ const COMMANDS=Object.freeze({plugin:['plugin','list','--marketplace','estelle-plugins','--json'],
19
+ legacy:['mcp','get','estelle'],remove:['mcp','remove','estelle']});
20
+ const remaining=deadline=>{const value=Math.min(CALL_MS,deadline-Date.now());if(value<=0)throw Error('setup_deadline');return value;};
21
+
22
+ export function nativeCodex(operation,deadline=Date.now()+BUDGET_MS) {
23
+ if(!Object.hasOwn(COMMANDS,operation))throw Error('setup_operation');
24
+ return new Promise(resolveResult=>{
25
+ execFile('codex',COMMANDS[operation],{timeout:remaining(deadline),maxBuffer:CAP,windowsHide:true},(error,stdout,stderr)=>{
26
+ if(error){
27
+ const missing=operation==='legacy'&&stderr.trim()==="Error: No MCP server named 'estelle' found.";
28
+ resolveResult(missing?{missing:true}:{ok:false});return;
29
+ }
30
+ resolveResult({ok:true,text:stdout});
31
+ });
32
+ });
33
+ }
34
+
35
+ /** Fixed authenticated read-only MCP initialization, not an account/key-presence substitute. */
36
+ export function probeMcp(key,{request=httpsRequest,deadline=Date.now()+BUDGET_MS}={}) {
37
+ const body=JSON.stringify({jsonrpc:'2.0',id:1,method:'initialize',params:{protocolVersion:'2025-11-25',
38
+ capabilities:{prompts:{}},clientInfo:{name:'estelle-plugin-setup',version:VERSION}}});
39
+ return new Promise(resolveResult=>{
40
+ let settled=false;
41
+ const done=value=>{if(!settled){settled=true;resolveResult(value);}};
42
+ const req=request(BASE+'/mcp',{method:'POST',agent:false,headers:{Authorization:`Bearer ${key}`,
43
+ 'Content-Type':'application/json','Content-Length':Buffer.byteLength(body)},signal:AbortSignal.timeout(remaining(deadline))},res=>{
44
+ if(res.statusCode!==200){res.destroy();done(false);return;}
45
+ const chunks=[];let bytes=0;
46
+ res.on('data',chunk=>{bytes+=chunk.length;if(bytes>CAP){res.destroy();done(false);}else chunks.push(chunk);});
47
+ res.on('error',()=>done(false));res.on('aborted',()=>done(false));
48
+ res.on('end',()=>{
49
+ try{
50
+ const value=JSON.parse(Buffer.concat(chunks).toString('utf8')),result=value.result;
51
+ done(value.jsonrpc==='2.0'&&value.id===1&&!Object.hasOwn(value,'error')&&object(result)
52
+ &&result.protocolVersion==='2025-11-25'&&object(result.capabilities)&&object(result.capabilities.tools));
53
+ }catch{done(false);}
54
+ });
55
+ });
56
+ req.on('error',()=>done(false));req.end(body);
57
+ });
58
+ }
59
+
60
+ export function parseLegacyMcp(text) {
61
+ if(typeof text!=='string'||Buffer.byteLength(text)>CAP)return 'unavailable';
62
+ const lines=text.trim().split(/\r?\n/);if(lines.shift()!=='estelle')return 'unavailable';
63
+ const fields=Object.create(null);
64
+ for(const line of lines){
65
+ const match=/^\s+([a-z_]+): (.*)$/.exec(line);if(!match || Object.hasOwn(fields,match[1]))return 'unavailable';
66
+ fields[match[1]]=match[2];
67
+ }
68
+ const allowed=['enabled','transport','url','bearer_token_env_var','http_headers','env_http_headers','http_headers_helper','remove'];
69
+ if(Object.keys(fields).some(k=>!allowed.includes(k)))return 'unavailable';
70
+ if(fields.enabled!=='true'||fields.transport!=='streamable_http')return 'unavailable';
71
+ if(fields.url!==BASE+'/mcp'||fields.bearer_token_env_var!=='ESTELLE_API_KEY')return 'preserved';
72
+ if(['http_headers','env_http_headers','http_headers_helper'].some(k=>fields[k]!=='-'))return 'unavailable';
73
+ if(fields.remove!==undefined&&fields.remove!=='codex mcp remove estelle')return 'unavailable';
74
+ return 'duplicate';
75
+ }
76
+
77
+ async function packageJson(path) {
78
+ const file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW|constants.O_NONBLOCK);
79
+ try{
80
+ const info=await file.stat();if(!info.isFile()||info.size>CAP)throw Error('package_bound');
81
+ const bytes=Buffer.alloc(CAP+1),read=await file.read(bytes,0,bytes.length,0);
82
+ if(read.bytesRead>CAP)throw Error('package_bound');
83
+ if(read.bytesRead!==info.size)throw Error('package_incomplete');
84
+ return JSON.parse(bytes.subarray(0,read.bytesRead).toString('utf8'));
85
+ }finally{await file.close();}
86
+ }
87
+
88
+ async function packageReady(bundleRoot,native) {
89
+ try{
90
+ const paths=['.codex-plugin/plugin.json','.mcp.json'];const docs=[];
91
+ for(const path of paths)docs.push(await packageJson(join(bundleRoot,path)));
92
+ const [manifest,mcp]=docs;
93
+ if(manifest.name!=='estelle'||manifest.version!==VERSION||manifest.mcpServers!=='./.mcp.json')return false;
94
+ const server=mcp.mcpServers?.Estelle;
95
+ if(!object(server)||Object.keys(server).sort().join(',')!=='bearer_token_env_var,url'
96
+ ||server.url!==BASE+'/mcp'||server.bearer_token_env_var!=='ESTELLE_API_KEY')return false;
97
+ const listing=await native('plugin');if(listing.ok!==true||Buffer.byteLength(listing.text)>CAP)return false;
98
+ const items=JSON.parse(listing.text).installed;if(!Array.isArray(items)||items.length>64)return false;
99
+ const own=items.filter(x=>x?.pluginId==='estelle@estelle-plugins');
100
+ return own.length===1&&own[0].name==='estelle'&&own[0].marketplaceName==='estelle-plugins'
101
+ &&own[0].version===VERSION&&own[0].installed===true&&own[0].enabled===true;
102
+ }catch{return false;}
103
+ }
104
+
105
+ const projection=(status,extra={})=>({status,host:'codex',version:VERSION,...extra,
106
+ capture_auth:'unavailable_or_unproven',mcp_auth:'not_probed',hook_execution:'not_observed',
107
+ trust:'not_changed_not_measured',reload:'fresh_session_required',active_cache:'not_migrated'});
108
+ const authenticated=(status,extra={})=>({...projection(status,extra),
109
+ capture_auth:'canonical_environment_available',mcp_auth:'initialized'});
110
+ const same=(a,b)=>a===null?b===null:b!==null&&a.hash===b.hash&&a.identity===b.identity;
111
+
112
+ async function applyPlan(file,snapshot,legacy,native) {
113
+ if(!same(snapshot,await inspectHooks(file)))return authenticated('pending_conflict');
114
+ if(legacy==='duplicate'){
115
+ const fresh=await native('legacy');if(fresh.ok!==true||parseLegacyMcp(fresh.text)!=='duplicate')return authenticated('pending_conflict');
116
+ const removed=await native('remove');
117
+ if(removed.ok!==true||removed.text.trim()!=="Removed global MCP server 'estelle'.")return authenticated('unknown',{mcp:'unknown',hooks:'not_started'});
118
+ const readback=await native('legacy');if(readback.missing!==true)return authenticated('unknown',{mcp:'unknown',hooks:'not_started'});
119
+ }
120
+ const mcp=legacy==='duplicate'?'removed':legacy;
121
+ try{
122
+ const hooks=snapshot?await commitHooks(file,snapshot):{status:'unchanged',removed:0};
123
+ return authenticated(hooks.status==='unknown'?'unknown':hooks.status==='unchanged'&&mcp!=='removed'?'unchanged':'applied',
124
+ {mcp,hooks:hooks.status,hook_removals:hooks.removed,...(hooks.cleanup?{cleanup:hooks.cleanup}:{})});
125
+ }catch{return authenticated(mcp==='removed'?'partial':'pending_conflict',{mcp,hooks:'not_applied'});}
126
+ }
127
+
128
+ export async function runSetup({host,apply=false,expect,env=process.env,home=homedir(),
129
+ bundleRoot=resolve(import.meta.dirname,'..')}={},ports={}) {
130
+ if(host==='claude'){
131
+ const {runClaudeSetup}=await import('./claude-setup.mjs');
132
+ return runClaudeSetup({apply,expect,env,home},ports);
133
+ }
134
+ if(host!=='codex')return {status:'pending_unsupported_host',host:typeof host==='string'&&/^[a-z-]{1,20}$/.test(host)?host:'unknown'};
135
+ if(apply&&(ports.platform||process.platform)==='win32')return projection('pending_unsupported_platform');
136
+ // Do not invoke the legacy auth-file fallback. Hooks and MCP must share this one canonical variable.
137
+ if(!env.ESTELLE_API_KEY)return projection('pending_auth');
138
+ const key=await launchCredential({ESTELLE_API_KEY:env.ESTELLE_API_KEY}).catch(()=>null);
139
+ if(!key)return projection('pending_auth');
140
+ const deadline=Date.now()+BUDGET_MS,native=ports.native||(op=>nativeCodex(op,deadline));
141
+ if(!await packageReady(bundleRoot,native))return projection('pending_package');
142
+ const authenticate=ports.authenticate||(k=>probeMcp(k,{deadline}));
143
+ try{if(await authenticate(key)!==true)return projection('pending_auth');}
144
+ catch{return projection('pending_auth');}
145
+ const review=await(ports.hookTrust||(()=>codexHookTrust(process.cwd(),{env})))().catch(()=>UNREADABLE);
146
+ return withReview(await migrateCodex({home,env,native,expect,apply}),review);
147
+ }
148
+
149
+ // Setup measures hook review so it can say the next step. Approving stays with the person, in Codex.
150
+ const withReview=(result,review)=>({...result,hook_review:review.status,trust:'not_changed',
151
+ ...(review.next_step?{next_step:review.next_step}:{})});
152
+
153
+ async function migrateCodex({home,env,native,expect,apply}) {
154
+ try{
155
+ const codexHome=env.CODEX_HOME?resolve(env.CODEX_HOME):join(home,'.codex'),file=join(codexHome,'hooks.json');
156
+ const snapshot=await inspectHooks(file),plan=snapshot?planHooks(snapshot.bytes):{removed:0};
157
+ const result=await native('legacy'),legacy=result.missing===true?'absent':result.ok===true?parseLegacyMcp(result.text):'unavailable';
158
+ if(legacy==='unavailable')return authenticated('pending_mcp_lookup');
159
+ const planHash=hash(JSON.stringify({before:snapshot?.hash||null,removed:plan.removed,mcp:legacy,version:VERSION}));
160
+ if(expect!==undefined&&expect!==planHash)return authenticated('pending_conflict');
161
+ if(!apply)return authenticated('planned',{hook_removals:plan.removed,mcp:legacy,plan_sha256:planHash});
162
+ return await applyPlan(file,snapshot,legacy,native);
163
+ }catch{return authenticated('pending_configuration');}
164
+ }
165
+
166
+ export async function runSetupArgs(args) {
167
+ const [host,...flags]=args;let apply=false,expect;
168
+ for(let i=0;i<flags.length;i++){
169
+ if(flags[i]==='--apply'&&!apply)apply=true;
170
+ else if(flags[i]==='--expect'&&expect===undefined&&/^[a-f0-9]{64}$/.test(flags[i+1]||''))expect=flags[++i];
171
+ else return {status:'pending_arguments'};
172
+ }
173
+ return runSetup({host,apply,expect});
174
+ }