@awebai/oats 0.45.0 → 0.46.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,71 @@
1
+ # OATS 0.46.0
2
+
3
+ ## Added
4
+
5
+ - **`oats inspect --soul <soul> --instructions` shows the instructions a new
6
+ instance would get.** `souls[0].composedInstructions` is the AGENTS.md a
7
+ spawn of that soul here would write: the soul's own text, then the
8
+ instance-boundary and work-mode blocks and each capability's inject,
9
+ produced by spawn's own composition, with nothing written to the
10
+ deployment. The soul's text and each block are given as ranges into the
11
+ text, named like an instance's `instructions.sources`, so the Desktop can
12
+ show which part comes from where. Without `--instructions` nothing extra is
13
+ composed; with `--home` it is refused. Feature `soul-composed-instructions`.
14
+ `oats doctor --soul` uses the same composition, and its capability markers
15
+ now name the inject home-relative instead of a deleted temporary path.
16
+ Routed with `--server <id>`, a host whose probe does not advertise
17
+ `soul-composed-instructions` is refused with `E_REMOTE_INCOMPATIBLE`, and
18
+ nothing is sent.
19
+
20
+ ## Fixed
21
+
22
+ - **Interim subscription completion extension:** the qualified Claude 2.1.289
23
+ darwin-arm64 110x35 empty Opus 5.5 / auto / medium frames additionally accept
24
+ exactly Claude Max, Pro, Team and Enterprise billing labels. These variants
25
+ are source-derived synthetic frames, not captured subscription sessions.
26
+ The exact Enter-authorizing prompt, explicit home consent and all launch
27
+ guards are unchanged. Completion closes input authority and proves no
28
+ account/channel readiness. This is **not the #754 onboarding fix**: #754
29
+ remains open for task-filled and bypass-permissions completion recognition.
30
+ Other unqualified frames still retain a blocked result after a submitted
31
+ answer; there is no automatic retry.
32
+
33
+ - **`oats doctor --soul` lists every inject block of a capability that
34
+ declares several.** Its `instructionBlocks` kept only the first block of
35
+ such a capability, though its composed text had them all; it now lists
36
+ each one, as a spawn records them.
37
+
38
+ ## Changed
39
+
40
+ - **The Desktop accepts OATS CLIs `>=0.25.8 <0.47.0`.** Its kernel band
41
+ admits 0.46; the soul composed-instructions feature is not read by the
42
+ Desktop yet, so no new gate is needed.
43
+
44
+ - **oats.framework 1.7.0: oats.setup 2.4.0 and oats.core 2.4.2.** Instruction
45
+ text only; no kernel, schema or provider contract changes.
46
+ - **oats.setup 2.4.0: team setup instructions are executable from one
47
+ authorized intake.** The onboarding and teams skills carry one
48
+ authorized intake through team configuration, operator composition
49
+ checks and first-task verification; they link the provider-owned
50
+ identity and delivery procedures, distinguish unsupported paths, and keep
51
+ project operator advice independent of central knowledge identities. An
52
+ instruction change, not a new team or provider primitive
53
+ ([#709](https://github.com/awebai/oats/issues/709), #721). The setup
54
+ inject and `oats-automations` keep configuration repairs proportional to
55
+ the requested outcome (#689, #692) and describe schedule and trigger
56
+ descriptions, retained-attempt reconciliation and supervisor cleanup as
57
+ the kernel now does them (#684, #591, #592, #593).
58
+ - **oats.core 2.4.2:** `oats-operate` covers the extra work trees a
59
+ work-mode briefing allows and their retirement (#678), and what
60
+ `oats session input` does and does not prove (#595).
61
+
62
+ - Add explicit host-local `oats harness trust --plan` and bare apply for one
63
+ canonical deployment-root Claude/Codex trust entry. Edits preserve unrelated
64
+ native bytes and record a durable `.agents/harness-trust.jsonl` audit. Partial
65
+ failures are retained with `E_HARNESS_TRUST_INCOMPLETE`; no rollback is claimed.
66
+ Spawn/start/retire do not write native trust. Claude ancestor qualification is
67
+ bounded to2.1.289 darwin-arm64/no-Git paths; Codex format qualification is separate.
68
+ Nested Git boundaries and unsupported native formats still refuse or warn.
69
+ Native canonicalization preserves on-disk root casing on APFS; result keys,
70
+ audit and reader verification agree. Lock refusals name the exact blocking
71
+ lock in human/JSON errors without stealing or deleting it.
package/docs/servers.md CHANGED
@@ -216,7 +216,7 @@ sent as text or on stdin, never as paths.
216
216
  | `okf harvest --instance <name>` | the saved home | `harvest` |
217
217
  | `schedule ...` | registered workspace | `schedule` |
218
218
  | `launch-config list\|set\|remove\|preview` | `--dir`, the instance's home, or the registered workspace | `launch-config` |
219
- | `inspect`, `operation run` | `--dir`, the instance's home, or the registered workspace | `operations` |
219
+ | `inspect`, `operation run` | `--dir`, the instance's home, or the registered workspace | `operations`; `inspect --instructions` also `soul-composed-instructions` |
220
220
  | `readiness` | the instance's home, `--dir`, or the registered workspace | `readiness` (`readinessApi: 2`) |
221
221
  | `instance events` | the instance's home | `instance-events-2` (`eventsApi: 2`) |
222
222
  | `instance git`, `instance diff` | the instance's home; the Git runs there | `instance-git` (`instanceGitApi: 1`) |
@@ -105,7 +105,10 @@ souls) is ordinary capability content: **`oats.core`** (package
105
105
  knowledge an onboarding expert needs. Neither is kernel magic; the kernel still
106
106
  composes its own instance-boundary and work-mode briefings, and the "You run
107
107
  on OATS" briefing is `oats.core`'s inject: a soul without `oats.core` gets no
108
- OATS operating instructions, and `oats doctor --soul` says so.
108
+ OATS operating instructions, and `oats doctor --soul` says so. Its capability
109
+ markers' `src=` is home-relative (`.oats/modules/<cap>/<inject>`), composed by
110
+ the same path as `oats inspect --soul --instructions`; kernel markers keep the
111
+ installed package's path.
109
112
 
110
113
  ## Instance anatomy
111
114
 
@@ -210,18 +213,18 @@ instructions and pins model/provider settings; it excludes nothing.
210
213
  Claude Code and Codex ask before they work in a folder they have not seen, and
211
214
  every instance home is new. A launch stopped at that prompt waits for a human,
212
215
  so the operator trusts the **deployment directory** (where `oats-local.yaml`
213
- is) once per harness. OATS only reads the harnesses' configuration; it never
214
- writes it.
216
+ is) once per harness. Launches only read native configuration. The explicit
217
+ `oats harness trust --dir D --harness all --plan` previews the entry; the same
218
+ command without `--plan` applies it with a deployment audit. See
219
+ [native trust](harness-trust.md) for safe operation and partial-failure recovery.
215
220
 
216
221
  - **Claude Code** looks for an accepted entry for its folder or an ancestor, up
217
- to a git root. Instance homes are not inside a git repository, so one entry
218
- for the deployment covers every home under it. To add it, run `claude` in the
219
- deployment once and accept the prompt. That records
222
+ to a Git root. An intervening repository can prevent deployment-root inheritance;
223
+ the command does not automatically trust another root. The native field is
220
224
  `projects["<deployment>"].hasTrustDialogAccepted` in `~/.claude.json`
221
225
  (`$CLAUDE_CONFIG_DIR/.claude.json` when that is set).
222
226
  - **Codex** applies only an exact entry: a trusted parent does not cover the
223
- folders below it. To give the operator's consent, run `codex` in the
224
- deployment once and choose "Trust and continue". That records
227
+ folders below it. The explicit deployment-root command records
225
228
  `[projects."<deployment>"] trust_level = "trusted"` in
226
229
  `~/.codex/config.toml` (`$CODEX_HOME/config.toml`). With that entry, or one
227
230
  for an ancestor of the deployment, each codex launch trusts its own new home
@@ -0,0 +1,81 @@
1
+ /** Lossless JSON span edits for the one native Claude trust leaf. The parser
2
+ * rejects duplicate keys and never converts unrelated numeric tokens to Number. */
3
+ const bad = () => { throw new Error('unsupported or invalid native JSON configuration'); };
4
+ export function jsonDocument(text) {
5
+ let i = 0;
6
+ const space = () => { while (/\s/.test(text[i] ?? '') && i < text.length) { if (!' \r\n\t'.includes(text[i])) bad(); i++; } };
7
+ const string = () => {
8
+ const start = i++;
9
+ while (i < text.length) {
10
+ if (text[i] === '\\') { i += 2; continue; }
11
+ if (text[i++] === '"') { try { return { start, end: i, value: JSON.parse(text.slice(start, i)) }; } catch { bad(); } }
12
+ }
13
+ bad();
14
+ };
15
+ const value = (depth = 0) => {
16
+ if (depth > 128) bad();
17
+ space(); const start = i;
18
+ if (text[i] === '{') {
19
+ i++; space(); const fields = new Map();
20
+ if (text[i] !== '}') for (;;) {
21
+ if (text[i] !== '"') bad();
22
+ const key = string(); if (fields.has(key.value)) bad();
23
+ space(); if (text[i++] !== ':') bad();
24
+ fields.set(key.value, value(depth + 1)); space();
25
+ if (text[i] !== ',') break;
26
+ i++; space();
27
+ }
28
+ if (text[i++] !== '}') bad();
29
+ return { kind: 'object', start, end: i, fields };
30
+ }
31
+ if (text[i] === '[') {
32
+ i++; space(); const items = [];
33
+ if (text[i] !== ']') for (;;) {
34
+ items.push(value(depth + 1)); space();
35
+ if (text[i] !== ',') break;
36
+ i++; space();
37
+ }
38
+ if (text[i++] !== ']') bad();
39
+ return { kind: 'array', start, end: i, items };
40
+ }
41
+ if (text[i] === '"') return { kind: 'string', ...string() };
42
+ const match = /^(?:true|false|null|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?)/.exec(text.slice(i));
43
+ if (!match) bad();
44
+ i += match[0].length;
45
+ return { kind: 'scalar', start, end: i, token: match[0] };
46
+ };
47
+ const node = value(); space(); if (i !== text.length) bad(); return node;
48
+ }
49
+ const fingerprint = (n) => n.kind === 'object' ? ['object', [...n.fields].map(([k, v]) => [k, fingerprint(v)])]
50
+ : n.kind === 'array' ? ['array', n.items.map(fingerprint)] : [n.kind, n.value ?? n.token];
51
+ /** Return the exact candidate bytes; no configuration I/O or host defaults. */
52
+ export function editClaudeTrust(text, root) {
53
+ const document = jsonDocument(text);
54
+ const path = ['projects', root, 'hasTrustDialogAccepted'];
55
+ let parent = document;
56
+ for (let at = 0; at < path.length; at++) {
57
+ if (parent.kind !== 'object') bad();
58
+ const key = path[at], child = parent.fields.get(key);
59
+ if (!child) {
60
+ let inserted = true;
61
+ for (let n = path.length - 1; n > at; n--) inserted = { [path[n]]: inserted };
62
+ const insertion = `${parent.fields.size ? ',' : ''}${JSON.stringify(key)}:${JSON.stringify(inserted)}`;
63
+ const candidate = text.slice(0, parent.end - 1) + insertion + text.slice(parent.end - 1);
64
+ const after = jsonDocument(candidate);
65
+ // Independently derive the expected tree: only the missing suffix may appear.
66
+ parent.fields.set(key, jsonDocument(JSON.stringify(inserted)));
67
+ if (JSON.stringify(fingerprint(document)) !== JSON.stringify(fingerprint(after))) bad();
68
+ return { text: candidate, current: null };
69
+ }
70
+ if (at === path.length - 1) {
71
+ if (child.kind !== 'scalar' || !['true', 'false'].includes(child.token)) bad();
72
+ if (child.token === 'true') return { text, current: true };
73
+ const candidate = text.slice(0, child.start) + 'true' + text.slice(child.end);
74
+ child.token = 'true';
75
+ if (JSON.stringify(fingerprint(document)) !== JSON.stringify(fingerprint(jsonDocument(candidate)))) bad();
76
+ return { text: candidate, current: false };
77
+ }
78
+ parent = child;
79
+ }
80
+ bad();
81
+ }
@@ -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. */