@awebai/oats 0.45.0 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ /** Bounded, lossless native TOML editor. Unknown syntax is refused rather than
2
+ * interpreted by the deliberately permissive readiness reader. No dependencies. */
3
+ const bad = () => { throw new Error('unsupported or invalid native TOML configuration'); };
4
+ const object = (style = 'implicit') => ({ kind: 'object', style, fields: new Map() });
5
+ function scanner(text, offset = 0) {
6
+ let i = 0;
7
+ const space = () => { while (text[i] === ' ' || text[i] === '\t') i++; };
8
+ const quoted = () => {
9
+ const start = i, quote = text[i++];
10
+ if (text.slice(i, i + 2) === quote + quote) bad();
11
+ while (i < text.length) {
12
+ if (quote === '"' && text[i] === '\\') {
13
+ const point = text[i + 1] === 'u' ? Number.parseInt(text.slice(i + 2, i + 6), 16) : -1;
14
+ if (point >= 0xD800 && point <= 0xDFFF) bad();
15
+ i += 2; continue;
16
+ }
17
+ if (text[i++] === quote) {
18
+ const raw = text.slice(start, i);
19
+ let value;
20
+ try { value = quote === '"' ? JSON.parse(raw) : raw.slice(1, -1); } catch { bad(); }
21
+ if (/[\x00-\x08\x0a-\x1f\x7f]/.test(raw.slice(1, -1))) bad();
22
+ // JSON accepts escaped slash and lone surrogates; TOML does not.
23
+ if (quote === '"' && (/\\\//.test(raw) || /[\uD800-\uDFFF]/u.test(value))) bad();
24
+ return { kind: 'string', value, start: offset + start, end: offset + i };
25
+ }
26
+ }
27
+ bad();
28
+ };
29
+ const key = () => {
30
+ space(); const parts = [];
31
+ for (;;) {
32
+ if (text[i] === '"' || text[i] === "'") parts.push(quoted().value);
33
+ else { const m = /^[A-Za-z0-9_-]+/.exec(text.slice(i)); if (!m) bad(); parts.push(m[0]); i += m[0].length; }
34
+ space(); if (text[i] !== '.') break; i++; space();
35
+ }
36
+ return parts;
37
+ };
38
+ const put = (node, path, value) => {
39
+ for (const k of path.slice(0, -1)) {
40
+ if (!node.fields.has(k)) node.fields.set(k, object('dotted'));
41
+ node = node.fields.get(k); if (node.kind !== 'object' || ['inline', 'table'].includes(node.style)) bad();
42
+ }
43
+ const k = path.at(-1); if (node.fields.has(k)) bad(); node.fields.set(k, value);
44
+ };
45
+ const value = (depth = 0) => {
46
+ if (depth > 64) bad(); space(); const start = i;
47
+ if (text[i] === '"' || text[i] === "'") return quoted();
48
+ if (text[i] === '[') {
49
+ i++; space(); const items = [];
50
+ while (text[i] !== ']') {
51
+ items.push(value(depth + 1)); space();
52
+ if (text[i] !== ',') break; i++; space();
53
+ }
54
+ if (text[i++] !== ']') bad();
55
+ return { kind: 'array', items, start: offset + start, end: offset + i };
56
+ }
57
+ if (text[i] === '{') {
58
+ const node = object('inline'); node.start = offset + i++; space();
59
+ if (text[i] !== '}') for (;;) {
60
+ const path = key(); if (text[i++] !== '=') bad(); put(node, path, value(depth + 1)); space();
61
+ if (text[i] !== ',') break; i++; space(); if (text[i] === '}') bad();
62
+ }
63
+ if (text[i++] !== '}') bad(); node.end = offset + i; return node;
64
+ }
65
+ const token = /^[^\s,#\]}]+/.exec(text.slice(i))?.[0];
66
+ if (!token || !/^(?:true|false|[+-]?(?:0|[1-9](?:_?[0-9])*)(?:\.[0-9](?:_?[0-9])*)?(?:[eE][+-]?[0-9](?:_?[0-9])*)?)$/.test(token)) bad();
67
+ // TOML integers are signed 64-bit, unlike JSON's unrestricted numeric syntax.
68
+ if (/^[+-]?[0-9_]+$/.test(token)) { const n = BigInt(token.replaceAll('_', '')); if (n < -(2n ** 63n) || n > 2n ** 63n - 1n) bad(); }
69
+ // Reject integer forms TOML excludes (e.g. -01); preserve all numeric bytes.
70
+ i += token.length; return { kind: 'scalar', token, start: offset + start, end: offset + i };
71
+ };
72
+ return { key, value, space, get at() { return i; }, get char() { return text[i]; }, advance() { i++; }, put };
73
+ }
74
+ export function tomlDocument(text) {
75
+ const root = object(), tables = []; let table = root, offset = 0;
76
+ for (const raw of text.split(/(?<=\n)/)) {
77
+ const line = raw.replace(/\r?\n$/, '');
78
+ if (/[\x00-\x08\x0b-\x1f\x7f]/.test(line)) bad();
79
+ const scan = scanner(line, offset); scan.space();
80
+ if (scan.char !== undefined && scan.char !== '#') {
81
+ if (scan.char === '[') {
82
+ if (tables.length) tables.at(-1).end = offset;
83
+ scan.advance(); const path = scan.key(); if (scan.char !== ']') bad(); scan.advance();
84
+ table = root;
85
+ for (const k of path) {
86
+ if (!table.fields.has(k)) table.fields.set(k, object());
87
+ table = table.fields.get(k); if (table.kind !== 'object' || ['inline', 'dotted'].includes(table.style)) bad();
88
+ }
89
+ if (table.style === 'table') bad(); table.style = 'table'; table.path = path;
90
+ table.bodyStart = offset + raw.length; table.end = text.length; tables.push(table);
91
+ } else {
92
+ const path = scan.key(); if (scan.char !== '=') bad(); scan.advance(); const value = scan.value();
93
+ scan.put(table, path, value);
94
+ }
95
+ scan.space(); if (scan.char !== undefined && scan.char !== '#') bad();
96
+ }
97
+ offset += raw.length;
98
+ }
99
+ return { root, tables };
100
+ }
101
+ const semantic = (n) => n.kind === 'object' ? ['object', [...n.fields].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, semantic(v)])]
102
+ : n.kind === 'array' ? ['array', n.items.map(semantic)] : [n.kind, n.value ?? n.token];
103
+ export function editCodexTrust(text, rootPath) {
104
+ const { root, tables } = tomlDocument(text), projects = root.fields.get('projects');
105
+ if (projects && (projects.kind !== 'object' || projects.style === 'inline')) bad();
106
+ const project = projects?.fields.get(rootPath);
107
+ if (project && project.kind !== 'object') bad();
108
+ if (project?.style === 'inline' && [...project.fields.keys()].some(k => k !== 'trust_level')) bad();
109
+ const leaf = project?.fields.get('trust_level');
110
+ if (leaf && (leaf.kind !== 'string' || !['trusted', 'untrusted'].includes(leaf.value))) bad();
111
+ if (leaf?.value === 'trusted') return { text, current: 'trusted' };
112
+ let candidate;
113
+ const nl = text.includes('\r\n') ? '\r\n' : '\n';
114
+ const append = (at, line) => text.slice(0, at) + (at && text[at - 1] !== '\n' ? nl : '') + line + nl + text.slice(at);
115
+ if (leaf) candidate = text.slice(0, leaf.start) + '"trusted"' + text.slice(leaf.end);
116
+ else if (project?.style === 'inline') {
117
+ candidate = text.slice(0, project.end - 1) + (project.fields.size ? ', ' : '') + 'trust_level = "trusted"' + text.slice(project.end - 1);
118
+ } else if (project?.style === 'table') candidate = append(project.end, 'trust_level = "trusted"');
119
+ else if (!project && projects?.style !== 'dotted') candidate = append(text.length, `[projects.${JSON.stringify(rootPath)}]${nl}trust_level = "trusted"`);
120
+ else {
121
+ // Dotted-key tables cannot be reopened as headers. Add another dotted leaf
122
+ // in the nearest explicit enclosing table, or the document's root region.
123
+ const container = projects?.style === 'table' ? projects : null;
124
+ const at = container ? container.end : text.length;
125
+ const line = `${container ? '' : 'projects.'}${JSON.stringify(rootPath)}.trust_level = "trusted"`;
126
+ if (!container && tables.length) {
127
+ // The first header offset is derived from its body, not a bracket in a
128
+ // preceding string/comment.
129
+ const header = text.lastIndexOf('\n', tables[0].bodyStart - 2) + 1;
130
+ candidate = append(header, line);
131
+ } else candidate = append(at, line);
132
+ }
133
+ const expectedProjects = projects ?? object(); if (!projects) root.fields.set('projects', expectedProjects);
134
+ const expectedProject = project ?? object(); if (!project) expectedProjects.fields.set(rootPath, expectedProject);
135
+ expectedProject.fields.set('trust_level', { kind: 'string', value: 'trusted' });
136
+ if (JSON.stringify(semantic(root)) !== JSON.stringify(semantic(tomlDocument(candidate).root))) bad();
137
+ return { text: candidate, current: leaf ? 'untrusted' : null };
138
+ }
@@ -0,0 +1,221 @@
1
+ /** Explicit operator-only native trust writes. Never called from spawn/start.
2
+ * Native writers do not cooperate with our locks: compare-and-replace narrows,
3
+ * but cannot eliminate, the race immediately before rename. No rollback. */
4
+ import * as fs from 'node:fs';
5
+ import { join, dirname, basename, resolve, isAbsolute } from 'node:path';
6
+ import { homedir } from 'node:os';
7
+ import { createHash, randomUUID } from 'node:crypto';
8
+ import { execFileSync } from 'node:child_process';
9
+ import { editClaudeTrust } from './harness-trust-json.mjs';
10
+ import { editCodexTrust } from './harness-trust-toml.mjs';
11
+ import { claudeTrusts, codexTrustsRoot, codexTrustedDirs } from './harness-trust.mjs';
12
+ const digest = bytes => createHash('sha256').update(bytes).digest('hex');
13
+ const error = (code, message, details) => Object.assign(new Error(message), { code, details });
14
+ const broken = () => error('E_CONFIG_BROKEN', 'Native trust configuration is unreadable, unsafe, invalid, or outside the supported format; inspect the selected file before retrying.');
15
+ const identity = s => `${s.dev}:${s.ino}`;
16
+ function stat(path) { try { return fs.lstatSync(path); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } }
17
+ /** GNU ls uses '.' for a security context alone, '+' for an ACL. macOS
18
+ * '@' marks extended attributes. Refuse metadata we cannot preserve; a Linux
19
+ * context is checked on the same-directory candidate before any replacement. */
20
+ export function nativeSecurityContext(path, { platform = process.platform, run = execFileSync } = {}) {
21
+ const flags = platform === 'darwin' ? ['-lde', path] : ['-ld', '--', path];
22
+ const mode = run('ls', flags, { encoding: 'utf8' }).split(/\s/, 1)[0];
23
+ if (!/^-[-rwxStTs]{9}$/.test(mode)) {
24
+ if (platform !== 'linux' || !/^-[-rwxStTs]{9}\.$/.test(mode)) throw broken();
25
+ const context = run('ls', ['-Zd', '--', path], { encoding: 'utf8' }).trim().split(/\s/, 1)[0];
26
+ if (!context || context === '?' || context.split(':').length < 3) throw broken();
27
+ return context;
28
+ }
29
+ return null;
30
+ }
31
+ function regular(path, metadataProbe) {
32
+ const s = stat(path); if (!s) return null;
33
+ if (!s.isFile() || s.nlink !== 1 || s.uid !== process.getuid?.() || (s.mode & 0o7000)) throw broken();
34
+ s.securityContext = metadataProbe(path);
35
+ return s;
36
+ }
37
+ function canonicalMissingDirectory(path) {
38
+ let at = resolve(path), tail = [];
39
+ for (;;) {
40
+ const s = stat(at);
41
+ if (s) {
42
+ const real = fs.realpathSync.native(at); if (!fs.statSync(real).isDirectory()) throw broken();
43
+ return join(real, ...tail.reverse());
44
+ }
45
+ const parent = dirname(at); if (parent === at) throw broken(); tail.push(basename(at)); at = parent;
46
+ }
47
+ }
48
+ function snapshot(file, metadataProbe) {
49
+ const s = regular(file, metadataProbe); if (!s) return { bytes: null, digest: null, identity: null, mode: null, securityContext: null };
50
+ const fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
51
+ try {
52
+ if (identity(fs.fstatSync(fd)) !== identity(s)) throw broken();
53
+ const bytes = fs.readFileSync(fd); if (bytes.length > 8 * 1024 * 1024) throw broken();
54
+ if (identity(fs.lstatSync(file)) !== identity(s)) throw broken();
55
+ return { bytes, digest: digest(bytes), identity: identity(s), mode: s.mode & 0o777, uid: s.uid, gid: s.gid, securityContext: s.securityContext };
56
+ } finally { fs.closeSync(fd); }
57
+ }
58
+ const same = (a, b) => a.digest === b.digest && a.identity === b.identity && a.mode === b.mode && a.uid === b.uid && a.gid === b.gid && a.securityContext === b.securityContext;
59
+ function nativePath(harness, env) {
60
+ const home = env.HOME || homedir(); if (!isAbsolute(home)) throw broken();
61
+ const override = harness === 'claude' ? env.CLAUDE_CONFIG_DIR : env.CODEX_HOME;
62
+ if (override && !isAbsolute(override)) throw broken();
63
+ const dir = override || (harness === 'claude' ? home : join(home, '.codex'));
64
+ return join(canonicalMissingDirectory(dir), harness === 'claude' ? '.claude.json' : 'config.toml');
65
+ }
66
+ function validAudit(file, metadataProbe) {
67
+ const observed = snapshot(file, metadataProbe);
68
+ if (observed.bytes) {
69
+ const text = observed.bytes.toString('utf8');
70
+ if (text && !text.endsWith('\n')) throw broken();
71
+ for (const line of text.split('\n').slice(0, -1)) {
72
+ let row; try { row = JSON.parse(line); } catch { throw broken(); }
73
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw broken();
74
+ }
75
+ }
76
+ return observed;
77
+ }
78
+ function syncDirectory(path) { const fd = fs.openSync(path, 'r'); try { fs.fsyncSync(fd); } finally { fs.closeSync(fd); } }
79
+ function ensureDirectory(path) {
80
+ if (stat(path)) { if (!fs.lstatSync(path).isDirectory() || fs.realpathSync.native(path) !== path) throw broken(); return; }
81
+ ensureDirectory(dirname(path)); fs.mkdirSync(path, { mode: 0o700 }); syncDirectory(dirname(path));
82
+ }
83
+ /** Planning performs reads only, including when native directories do not exist. */
84
+ export function planHarnessTrust(root, { harness = 'all', env = process.env, metadataProbe = nativeSecurityContext } = {}) {
85
+ if (!['all', 'claude', 'codex'].includes(harness)) throw error('E_BAD_ARGS', '--harness must be claude, codex, or all');
86
+ // Native lookup preserves the on-disk casing on case-insensitive APFS; the
87
+ // JS realpath implementation can retain the caller's spelling as a wrong key.
88
+ root = fs.realpathSync.native(root);
89
+ const result = { operation: 'harness-trust', mode: 'plan', root, entries: [], audit: null, warnings: [] }, plans = [];
90
+ for (const name of harness === 'all' ? ['claude', 'codex'] : [harness]) {
91
+ const key = ['projects', root, name === 'claude' ? 'hasTrustDialogAccepted' : 'trust_level'];
92
+ const entry = { harness: name, file: null, key, current: null, desired: name === 'claude' ? true : 'trusted', beforeDigest: null, afterDigest: null, status: 'refused' };
93
+ result.entries.push(entry);
94
+ try {
95
+ const file = nativePath(name, env); entry.file = file;
96
+ const before = snapshot(file, metadataProbe); entry.beforeDigest = before.digest;
97
+ const text = before.bytes?.toString('utf8') ?? (name === 'claude' ? '{}' : '');
98
+ if (before.bytes && !Buffer.from(text).equals(before.bytes)) throw broken();
99
+ const edited = (name === 'claude' ? editClaudeTrust : editCodexTrust)(text, root);
100
+ // Preflight the existing reader's supported representation as well as
101
+ // native syntax; never discover a known compatibility gap after writing.
102
+ if (name === 'codex' && !codexTrustedDirs(edited.text).has(root)) throw broken();
103
+ const after = Buffer.from(edited.text);
104
+ entry.current = edited.current; entry.afterDigest = digest(after);
105
+ entry.status = before.bytes?.equals(after) ? 'unchanged' : 'change';
106
+ plans.push({ entry, before, after });
107
+ const overrideKey = name === 'claude' ? 'CLAUDE_CONFIG_DIR' : 'CODEX_HOME';
108
+ if (env[overrideKey]) result.warnings.push(`${overrideKey} selects ${env[overrideKey]}; effective file ${file}`);
109
+ } catch { /* Per-file refusal; never echo native content or parser exceptions. */ }
110
+ }
111
+ if (result.entries.some(e => e.status === 'refused')) throw error('E_CONFIG_BROKEN', broken().message, result);
112
+ return { result, plans };
113
+ }
114
+ export function harnessTrust(root, { harness = 'all', plan = false, env = process.env, checkpoint = () => {}, metadataProbe = nativeSecurityContext } = {}) {
115
+ let prepared;
116
+ try { prepared = planHarnessTrust(root, { harness, env, metadataProbe }); }
117
+ catch (e) { if (e.details?.operation === 'harness-trust') e.details.mode = plan ? 'plan' : 'apply'; throw e; }
118
+ const { result, plans } = prepared;
119
+ if (plan) return result;
120
+ result.mode = 'apply'; const operationId = randomUUID(), auditPath = join(result.root, '.agents', 'harness-trust.jsonl');
121
+ const locks = [], temps = new Map(), parents = new Map(); let mayHaveChanged = false, currentMayHaveChanged = false, reason = 'audit', current = null, auditSnapshot, failure, acquiringLock;
122
+ result.audit = { path: auditPath, operationId, status: 'incomplete' };
123
+ const checkParent = file => {
124
+ const dir = dirname(file);
125
+ if (fs.realpathSync.native(dir) !== dir || identity(fs.statSync(dir)) !== parents.get(dir)) throw new Error('parent changed');
126
+ };
127
+ const append = (entry, phase, status) => {
128
+ checkpoint('before-audit', { phase, entry });
129
+ checkParent(auditPath);
130
+ const now = validAudit(auditPath, metadataProbe); if (!same(now, auditSnapshot)) throw new Error('audit changed');
131
+ const row = Buffer.from(JSON.stringify({ version: 1, kind: 'harness-trust', at: new Date().toISOString(), operationId, phase, harness: entry.harness, root: result.root, file: entry.file, beforeDigest: entry.beforeDigest, afterDigest: entry.afterDigest, status }) + '\n');
132
+ const expected = digest(Buffer.concat([now.bytes ?? Buffer.alloc(0), row]));
133
+ const fd = fs.openSync(auditPath, fs.constants.O_WRONLY | fs.constants.O_APPEND | fs.constants.O_CREAT | fs.constants.O_NOFOLLOW | (now.identity === null ? fs.constants.O_EXCL : 0), 0o600);
134
+ let writtenIdentity;
135
+ try {
136
+ writtenIdentity = identity(fs.fstatSync(fd));
137
+ if (now.identity !== null && writtenIdentity !== now.identity) throw new Error('audit replaced');
138
+ fs.writeFileSync(fd, row);
139
+ fs.fsyncSync(fd);
140
+ } finally { fs.closeSync(fd); }
141
+ checkParent(auditPath); syncDirectory(dirname(auditPath));
142
+ const after = validAudit(auditPath, metadataProbe);
143
+ if (after.identity !== writtenIdentity || after.digest !== expected) throw new Error('audit changed after append');
144
+ auditSnapshot = after;
145
+ };
146
+ try {
147
+ // Validate the complete existing audit before creating any directories/locks.
148
+ auditSnapshot = validAudit(auditPath, metadataProbe);
149
+ checkpoint('before-locks', { result }); reason = 'locked';
150
+ const lockPaths = [auditPath, ...plans.map(p => p.entry.file)].map(f => `${f}.oats-trust.lock`).sort();
151
+ for (const lock of lockPaths) {
152
+ acquiringLock = lock;
153
+ ensureDirectory(dirname(lock));
154
+ const dir = dirname(lock), observed = identity(fs.statSync(dir));
155
+ if (parents.has(dir) && parents.get(dir) !== observed) throw new Error('parent changed');
156
+ parents.set(dir, observed);
157
+ const fd = fs.openSync(lock, 'wx', 0o600);
158
+ locks.push({ path: lock, identity: identity(fs.fstatSync(fd)) }); fs.closeSync(fd);
159
+ }
160
+ reason = 'changed';
161
+ for (const p of plans) { checkParent(p.entry.file); if (!same(snapshot(p.entry.file, metadataProbe), p.before)) throw new Error('configuration changed'); }
162
+ if (!same(validAudit(auditPath, metadataProbe), auditSnapshot)) { reason = 'audit'; throw new Error('audit changed'); }
163
+ for (const p of plans) {
164
+ current = p; currentMayHaveChanged = false; reason = 'audit';
165
+ if (p.entry.status === 'unchanged') {
166
+ reason = 'verify';
167
+ if (!(p.entry.harness === 'claude' ? claudeTrusts(result.root, { env }) : codexTrustsRoot(result.root, { env }))) throw new Error('verification failed');
168
+ reason = 'audit'; append(p.entry, 'outcome', 'unchanged'); current = null; continue;
169
+ }
170
+ append(p.entry, 'intent', 'planned'); reason = 'write';
171
+ checkParent(p.entry.file);
172
+ const tmp = join(dirname(p.entry.file), `.${basename(p.entry.file)}.oats-${operationId}.tmp`);
173
+ const parentIdentity = identity(fs.statSync(dirname(p.entry.file)));
174
+ const fd = fs.openSync(tmp, 'wx', p.before.mode ?? 0o600); temps.set(tmp, identity(fs.fstatSync(fd)));
175
+ try {
176
+ if (p.before.uid !== undefined) fs.fchownSync(fd, p.before.uid, p.before.gid);
177
+ fs.fchmodSync(fd, p.before.mode ?? 0o600); fs.writeFileSync(fd, p.after); fs.fsyncSync(fd);
178
+ } finally { fs.closeSync(fd); }
179
+ const candidate = snapshot(tmp, metadataProbe);
180
+ if (p.before.identity !== null && candidate.securityContext !== p.before.securityContext) throw new Error('candidate security context differs');
181
+ reason = 'changed'; checkpoint('before-replace', { entry: p.entry });
182
+ if (identity(fs.statSync(dirname(p.entry.file))) !== parentIdentity || fs.realpathSync.native(dirname(p.entry.file)) !== dirname(p.entry.file) || !same(snapshot(p.entry.file, metadataProbe), p.before)) throw new Error('configuration changed');
183
+ reason = 'write';
184
+ // Once rename is attempted, conservatively report uncertainty on any error.
185
+ mayHaveChanged = true; currentMayHaveChanged = true; fs.renameSync(tmp, p.entry.file); temps.delete(tmp); syncDirectory(dirname(p.entry.file));
186
+ reason = 'verify'; checkpoint('after-replace', { entry: p.entry });
187
+ const observed = snapshot(p.entry.file, metadataProbe);
188
+ const expectedDigest = p.entry.afterDigest; p.entry.afterDigest = observed.digest;
189
+ if (observed.securityContext !== candidate.securityContext || observed.digest !== expectedDigest || !(p.entry.harness === 'claude' ? claudeTrusts(result.root, { env }) : codexTrustsRoot(result.root, { env }))) throw new Error('verification failed');
190
+ p.entry.status = 'applied'; reason = 'audit'; append(p.entry, 'outcome', 'applied'); current = null;
191
+ }
192
+ result.audit.status = 'recorded';
193
+ } catch {
194
+ if (current) {
195
+ current.entry.status = currentMayHaveChanged ? 'incomplete' : 'failed';
196
+ // The intent retains the proposed digest. A failed outcome reports only
197
+ // bytes actually observed, never the proposal as proof of a replacement.
198
+ try { checkParent(current.entry.file); current.entry.afterDigest = snapshot(current.entry.file, metadataProbe).digest; }
199
+ catch { current.entry.afterDigest = null; result.warnings.push(`Final digest unconfirmed for ${current.entry.file}.`); }
200
+ if (reason !== 'audit') { try { append(current.entry, 'outcome', current.entry.status); result.audit.status = 'recorded'; } catch { result.audit.status = 'incomplete'; } }
201
+ }
202
+ for (const p of plans) if (p.entry.status === 'change') p.entry.status = 'not-attempted';
203
+ failure = error('E_HARNESS_TRUST_INCOMPLETE', `Harness trust ${reason} failed${reason === 'locked' && acquiringLock ? `; could not acquire lock ${acquiringLock}` : ''}; inspect native configuration and ${auditPath} before retrying. No rollback was attempted.`, { ...result, reason, mayHaveChanged });
204
+ } finally {
205
+ // Cleanup is part of the outcome. Do not silently succeed with a lock left
206
+ // behind, and never delete a path another writer replaced.
207
+ for (const [path, owned] of [...temps, ...locks.reverse().map(l => [l.path, l.identity])]) {
208
+ try {
209
+ const observed = stat(path);
210
+ if (!observed) continue;
211
+ if (identity(observed) !== owned) throw new Error('replaced cleanup path');
212
+ fs.unlinkSync(path);
213
+ } catch {
214
+ result.warnings.push(`Cleanup unconfirmed for ${path}; inspect it before retrying.`);
215
+ failure ??= error('E_HARNESS_TRUST_INCOMPLETE', 'Harness trust cleanup failed; native changes and audit are retained. Inspect the reported paths before retrying.', { ...result, reason: 'write', mayHaveChanged });
216
+ }
217
+ }
218
+ }
219
+ if (failure) throw failure;
220
+ return result;
221
+ }
@@ -2,15 +2,15 @@
2
2
  * covered by the operator's one-time trust of the deployment root, so the launched session
3
3
  * does not stop at the harness's folder-trust prompt.
4
4
  *
5
- * The operator's harness configuration is only read, never written: trusting the deployment
6
- * root is the operator's act. A configuration that is missing, unreadable or in a form this
5
+ * This module only reads native configuration. The explicit operator command
6
+ * in harness-trust-write.mjs is the separate deployment-root write boundary. A configuration that is missing, unreadable or in a form this
7
7
  * reader does not know counts as not trusted, so a launch is warned about rather than
8
8
  * silently stalled.
9
9
  *
10
10
  * - Claude walks up from its working directory, stopping at a git root, and honours
11
11
  * `projects["<dir>"].hasTrustDialogAccepted` in ~/.claude.json
12
- * ($CLAUDE_CONFIG_DIR/.claude.json when that is set). Instance homes are not inside a git
13
- * repository, so one entry for the deployment root covers every home under it.
12
+ * ($CLAUDE_CONFIG_DIR/.claude.json when that is set). A deployment-root entry covers
13
+ * descendants only when no intervening Git boundary prevents inheritance.
14
14
  * - Codex honours only an exact `[projects."<dir>"] trust_level = "trusted"` entry in
15
15
  * ~/.codex/config.toml ($CODEX_HOME/config.toml), never a parent's. A per-invocation
16
16
  * override does trust a home, so the kernel's codex launch adds one for the home when the
@@ -19,7 +19,7 @@ import { existsSync, readFileSync, realpathSync } from "node:fs";
19
19
  import { dirname, join, resolve } from "node:path";
20
20
  import { homedir } from "node:os";
21
21
 
22
- const real = (p) => { try { return realpathSync(p); } catch { return resolve(p); } };
22
+ const real = (p) => { try { return realpathSync.native(p); } catch { return resolve(p); } };
23
23
  const userHome = (env) => env.HOME || homedir();
24
24
 
25
25
  /** `dir` and its ancestors, nearest first. */
@@ -92,7 +92,7 @@ function assignment(line) {
92
92
  /** The directories config.toml marks `trust_level = "trusted"`, in the forms Codex writes and
93
93
  * their plain TOML equivalents: `[projects."<dir>"]` tables, `"<dir>" = { trust_level = … }`
94
94
  * under `[projects]`, and dotted `projects."<dir>".trust_level` keys. */
95
- function codexTrustedDirs(text) {
95
+ export function codexTrustedDirs(text) {
96
96
  const trusted = new Set();
97
97
  let table = [];
98
98
  for (const raw of text.split(/\r?\n/)) {
@@ -125,11 +125,12 @@ export function codexTrustsRoot(root, { env = process.env } = {}) {
125
125
  return false;
126
126
  }
127
127
 
128
- /** The step that trusts the deployment root, per harness. */
129
- const TRUST_STEP = {
130
- claude: (root) => `run \`claude\` in ${root} and accept its folder-trust prompt; one entry covers every instance home under it`,
131
- codex: (root) => `run \`codex\` in ${root} and choose "Trust and continue"; OATS then trusts each new home under it at launch`,
132
- };
128
+ /** Shell-quoted operator remedy; never invoked by readiness or a launch. */
129
+ const quote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'";
130
+ const TRUST_STEP = Object.fromEntries(["claude", "codex"].map(harness => [harness, root => {
131
+ const command = `oats harness trust --dir ${quote(root)} --harness ${harness}`;
132
+ return `preview with \`${command} --plan\`, then apply with \`${command}\`; a nested Git boundary may still require operator inspection`;
133
+ }]));
133
134
 
134
135
  /** The spawn and readiness warning for a home its harness will not trust without asking;
135
136
  * null when `covered`, or for a harness without a folder-trust prompt. */
@@ -24,6 +24,7 @@ import { loadLocal } from "./workspace.mjs";
24
24
  import { ensureModuleTree } from "./operator-dispatch.mjs";
25
25
  import { operatorCoverage, operatorProblems } from "./operator-coverage.mjs";
26
26
  import { readLockIfPresent } from "./packages.mjs";
27
+ import { composeSoulInstructions } from "./soul-composition.mjs";
27
28
  /** Bounds of a provider check's answer (bytes, nesting, entries), as the released binding wire set them. */
28
29
  const BINDING_LIMITS = Object.freeze({ maxBytes: 1024 * 1024, maxDepth: 32, maxEntries: 16384 });
29
30
  import { parseStrictJson } from "./canonical-json.mjs";
@@ -248,7 +249,25 @@ function soulRow(t) {
248
249
  return { soulsApi: SOULS_API, name: s.name, repoKey: s.repoKey, commit: s.commit, kind: s.external === true ? "external" : s.external === false ? "member" : null, path: s.path,
249
250
  description: def.description ?? null, work: def.work ?? null, harness: def.harness ?? null, model: def.model ?? null,
250
251
  declarations: declarationsOf(s.definition), declarationProblems: s.problems,
251
- instructions: s.soulDir ? readTextCapped(join(s.soulDir, "AGENTS.md")) : null };
252
+ instructions: s.soulDir ? readTextCapped(join(s.soulDir, "AGENTS.md")) : null,
253
+ // Feature soul-composed-instructions: only on a soul target that asked (inspect --instructions).
254
+ ...(t.kind === "soul" && t.composedInstructions !== undefined ? { composedInstructions: t.composedInstructions } : {}) };
255
+ }
256
+
257
+ /** The soul target with `composedInstructions` (feature soul-composed-instructions): the AGENTS.md a
258
+ * spawn of it here with no flags would write (lib/soul-composition.mjs), or null when the soul
259
+ * resolves but cannot be composed here — with the kernel's refusal as a problem naming
260
+ * composedInstructions, unless the soul copy's own problem (copyError) already says why. */
261
+ export async function withComposedInstructions(t, { compose = composeSoulInstructions } = {}) {
262
+ if (t.kind !== "soul") return t;
263
+ if (t.soul.copyError || !t.soul.soulDir || !t.prepared) return { ...t, composedInstructions: null };
264
+ try {
265
+ const { composedInstructions } = await compose({ deployment: t.deployment, prepared: t.prepared, soulDir: t.soul.soulDir });
266
+ return { ...t, composedInstructions };
267
+ } catch (e) {
268
+ if (typeof e?.code !== "string" || !e.code.startsWith("E_")) throw e;
269
+ return { ...t, composedInstructions: null, composedInstructionsProblem: { code: e.code, message: `composedInstructions: ${e.message}` } };
270
+ }
252
271
  }
253
272
 
254
273
  /** `oats inspect --json` on the workspace model. */
@@ -280,7 +299,7 @@ export function inspectDocument(t, { kernel }) {
280
299
  launchConfig: m.launch?.launchConfig ?? null, launchConfigDefault: m.launch?.launchConfigDefault === true, launched: !!m.launched, createdAt: m.createdAt || null,
281
300
  resolution: m.workspace?.resolution ?? null, soulDir: t.soul.soulDir, instructions: { ...readTextCapped(join(t.home, "AGENTS.md")), sources: m.instructions || [] } } : null,
282
301
  ...(m ? { identity: servedIdentityOf(m) } : {}),
283
- problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.discoveryError ? [t.discoveryError] : []),
302
+ problems: [...t.soul.problems, ...(t.soul.copyError ? [t.soul.copyError] : []), ...(t.composedInstructionsProblem ? [t.composedInstructionsProblem] : []), ...(t.discoveryError ? [t.discoveryError] : []),
284
303
  ...t.modules.filter((x) => !x.manifest).map((x) => ({ code: "module-missing", message: `${x.name} is recorded but its module copy has no readable oats.json`, capability: x.name })),
285
304
  ...capabilities.filter((c) => !c.compatibility.ok).map((c) => ({ code: "capability-incompatible", message: `${c.id} requires oats ${c.compatibility.range}; this kernel is ${c.compatibility.kernel} (re-spawn from the deployment with a release whose range admits it)`, capability: c.id, range: c.compatibility.range, kernel: c.compatibility.kernel }))],
286
305
  };
@@ -1,11 +1,24 @@
1
1
  /** Formatting shared by current preparation and retained instruction projection.
2
2
  * Selection/order is supplied by the caller; this module never discovers config. */
3
3
 
4
- export function renderInstructionText(body, blocks) {
4
+ /** The composed document and where each part of it is: `body` and every `blocks[i]` as
5
+ * `[start, end)` in JS string units. The parts tile the text: the body starts at 0, each
6
+ * part ends where the next starts (after the blank separator line before the next opening
7
+ * marker), and the last part ends at `text.length`. A block starts at the `<` of its opening
8
+ * marker. The one renderer: renderInstructionText is its `.text`. */
9
+ export function renderInstructionParts(body, blocks) {
5
10
  let text = body.replace(/\n*$/, "\n");
11
+ const spans = [];
6
12
  for (const { source, file, content } of blocks) {
7
- text += `\n<!-- oats:${source} src=${file} -->\n${content.trim()}\n<!-- /oats:${source} -->\n`;
13
+ text += "\n";
14
+ const start = text.length;
15
+ text += `<!-- oats:${source} src=${file} -->\n${content.trim()}\n<!-- /oats:${source} -->\n`;
16
+ spans.push({ start });
8
17
  }
9
- return text;
18
+ const bodyEnd = spans.length ? spans[0].start : text.length;
19
+ return { text, body: { start: 0, end: bodyEnd }, blocks: spans.map(({ start }, i) => ({ start, end: i + 1 < spans.length ? spans[i + 1].start : text.length })) };
10
20
  }
11
21
 
22
+ export function renderInstructionText(body, blocks) {
23
+ return renderInstructionParts(body, blocks).text;
24
+ }
@@ -0,0 +1,67 @@
1
+ /** Completion reporting only, never input authority. Source-qualified Claude
2
+ * 2.1.289 non-Jt footer layout; the caller must enforce qualification and one
3
+ * submitted answer. Unknown dialogs retaining this region can evade the finite
4
+ * markers. That reporting risk is accepted; no subsequent key may be sent.
5
+ * See launch-prompt-fixtures/structural-completion.json and README.md. */
6
+ export const CLAUDE_QUESTION_MARKERS = Object.freeze([
7
+ 'Accessing workspace:',
8
+ 'Quick safety check:',
9
+ 'Yes, I trust this folder',
10
+ 'No, continue without these permissions',
11
+ 'No, exit',
12
+ 'WARNING: Loading development channels',
13
+ 'I am using this for local development',
14
+ 'Managed settings require approval',
15
+ 'Yes, I trust these settings',
16
+ 'No, exit Claude Code',
17
+ 'Do you want to use this API key?',
18
+ 'Detected a custom API key in your environment',
19
+ 'Select login method:',
20
+ 'Do you want to proceed?',
21
+ 'Do you want to allow this connection?',
22
+ 'Waiting for permission…',
23
+ 'Enter to confirm',
24
+ 'Esc to cancel',
25
+ 'esc to cancel',
26
+ 'Enter to select',
27
+ 'Esc to exit',
28
+ ]);
29
+
30
+ const modes = [
31
+ ['default', '⏸ manual mode on'], ['plan', '⏸ plan mode on'],
32
+ ['acceptEdits', '⏵⏵ accept edits on'], ['bypassPermissions', '⏵⏵ bypass permissions on'],
33
+ ['dontAsk', "⏵⏵ don't ask on"], ['auto', '⏵⏵ auto mode on'],
34
+ ];
35
+ const efforts = ['○ low · /effort', '◐ medium · /effort', '● high · /effort', '◉ xhigh · /effort', '◈ max · /effort'];
36
+ const hints = ['', ' · ← for agents', ' · esc to interrupt', ' · esc to interrupt · ← for agents'];
37
+ const shortcuts = [' · ? for shortcuts', ' · ? for shortcuts · ← for agents'];
38
+ const footers = new Set();
39
+ for (const [mode, label] of modes) {
40
+ for (const cycle of mode === 'default' ? [''] : ['', ' (shift+tab to cycle)']) {
41
+ for (const hint of mode === 'default' ? [...hints, ...shortcuts] : hints) {
42
+ for (const right of efforts) {
43
+ const left = label + cycle + hint;
44
+ // Every enumerated character is single-column in the qualified layout.
45
+ const gap = 108 - 2 - left.length - right.length;
46
+ if (gap >= 1) footers.add(' ' + left + ' '.repeat(gap) + right);
47
+ }
48
+ }
49
+ }
50
+ }
51
+ const border = '─'.repeat(110);
52
+
53
+ export function classifyClaudeLaunchCompletion(screen) {
54
+ if (screen?.width !== 110 || screen?.height !== 35 || typeof screen.text !== 'string'
55
+ || Buffer.byteLength(screen.text, 'utf8') > 64 * 1024) return null;
56
+ // No exemptions for unknown questions. Ordinary shortcut/interrupt hints are
57
+ // simply not markers; do not broaden this into a generic '?' or Esc rule.
58
+ if (CLAUDE_QUESTION_MARKERS.some(marker => screen.text.includes(marker))) return 'blocked';
59
+ if (/[\x00-\x09\x0b-\x1f]/.test(screen.text)) return null;
60
+ const rows = screen.text.split('\n');
61
+ if (rows.length !== 36 || rows.pop() !== '') return null;
62
+ let footer = rows.length - 1;
63
+ while (footer >= 0 && rows[footer] === '') footer--;
64
+ if (footer < 3 || !footers.has(rows[footer]) || rows[footer - 1] !== border
65
+ || rows[footer - 2] !== '❯\u00a0' || rows[footer - 3] !== border) return null;
66
+ return 'completed';
67
+ }