@awebai/oats 0.50.0 → 0.52.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.
Files changed (132) hide show
  1. package/README.md +1 -0
  2. package/bin/oats.mjs +153 -51
  3. package/docs/capabilities.md +11 -3
  4. package/docs/configuration.md +134 -88
  5. package/docs/desktop-cli-api.md +994 -71
  6. package/docs/desktop-instance-start.md +56 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +230 -59
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +73 -8
  12. package/docs/integrations.md +9 -8
  13. package/docs/knowledge-reference/acceptance.md +1 -0
  14. package/docs/knowledge-reference/harvester.md +5 -3
  15. package/docs/knowledge-reference/model.md +5 -3
  16. package/docs/knowledge-theory.md +1 -1
  17. package/docs/knowledge.md +43 -7
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/oats-local.schema.json +4 -3
  20. package/docs/official-catalog.md +4 -4
  21. package/docs/packages.md +14 -14
  22. package/docs/release-lane.md +15 -5
  23. package/docs/release-notes/v0.44.0.md +1 -1
  24. package/docs/release-notes/v0.51.0.md +156 -0
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/schedules.md +91 -4
  27. package/docs/servers.md +21 -2
  28. package/docs/souls-and-instances.md +113 -21
  29. package/docs/tui.md +152 -0
  30. package/docs/workspaces.md +2 -2
  31. package/lib/claim.mjs +266 -0
  32. package/lib/core.mjs +845 -166
  33. package/lib/errors.mjs +170 -0
  34. package/lib/harness-trust-write.mjs +68 -27
  35. package/lib/harness-trust.mjs +34 -16
  36. package/lib/instance-inspect.mjs +40 -11
  37. package/lib/instance-lifecycle.mjs +169 -47
  38. package/lib/launch-preference.mjs +16 -0
  39. package/lib/launch-prompt-completion.mjs +7 -43
  40. package/lib/launch-prompt-evidence.mjs +14 -7
  41. package/lib/launch-prompt-fixtures/README.md +86 -152
  42. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  43. package/lib/launch-prompt-fixtures.mjs +122 -109
  44. package/lib/launch-prompt-transport.mjs +2 -56
  45. package/lib/launch-prompts.mjs +102 -100
  46. package/lib/schedule-host.mjs +154 -22
  47. package/lib/schedule.mjs +73 -24
  48. package/lib/servers.mjs +20 -4
  49. package/lib/session-viewer.mjs +87 -10
  50. package/lib/system-tools.mjs +39 -0
  51. package/lib/tmux-server-scope.mjs +62 -0
  52. package/lib/triggers.mjs +4 -4
  53. package/lib/workspace.mjs +5 -11
  54. package/lib/worktree-hooks.mjs +116 -23
  55. package/lib/worktree.mjs +89 -102
  56. package/package-catalog.json +3 -3
  57. package/package.json +7 -2
  58. package/packages/client/capability-show-contract.mjs +230 -0
  59. package/packages/client/capability-warnings-contract.mjs +57 -0
  60. package/packages/client/cli-adapter.mjs +548 -0
  61. package/packages/client/cli-environment.mjs +53 -0
  62. package/packages/client/cli-locator.mjs +253 -0
  63. package/packages/client/cli-probe-contract.mjs +47 -0
  64. package/packages/client/client-terms.mjs +60 -0
  65. package/packages/client/deployment-contract.mjs +68 -0
  66. package/packages/client/deployment-data.mjs +483 -0
  67. package/packages/client/deployment-facts.mjs +34 -0
  68. package/packages/client/deployment-label.mjs +76 -0
  69. package/packages/client/deployment-observer.mjs +89 -0
  70. package/packages/client/deployment-panel.mjs +142 -0
  71. package/packages/client/deployment-read-cli.mjs +53 -0
  72. package/packages/client/display-text.mjs +44 -0
  73. package/packages/client/harness-names.mjs +30 -0
  74. package/packages/client/inspect-contract.mjs +62 -0
  75. package/packages/client/instance-acts.mjs +54 -0
  76. package/packages/client/instance-admission.mjs +45 -0
  77. package/packages/client/instance-events-contract.mjs +74 -0
  78. package/packages/client/instance-git-contract.mjs +80 -0
  79. package/packages/client/instance-presentation.mjs +22 -0
  80. package/packages/client/instance-tree.mjs +453 -0
  81. package/packages/client/kernel-environment.mjs +11 -0
  82. package/packages/client/launch-contract.mjs +51 -0
  83. package/packages/client/launch-prompt-outcome.mjs +165 -0
  84. package/packages/client/lifecycle-cli.mjs +61 -0
  85. package/packages/client/lifecycle-contract.mjs +372 -0
  86. package/packages/client/liveness-main.mjs +10 -0
  87. package/packages/client/liveness.mjs +35 -0
  88. package/packages/client/machine-contract.mjs +123 -0
  89. package/packages/client/own-environment.mjs +22 -0
  90. package/packages/client/panel-views.mjs +286 -0
  91. package/packages/client/readiness-contract.mjs +172 -0
  92. package/packages/client/refresh-loop.mjs +52 -0
  93. package/packages/client/remote-address.mjs +126 -0
  94. package/packages/client/remote-roster.mjs +67 -0
  95. package/packages/client/roster-sections.mjs +80 -0
  96. package/packages/client/spawn-apply-cli.mjs +104 -0
  97. package/packages/client/spawn-apply-contract.mjs +183 -0
  98. package/packages/client/spawn-decision.mjs +46 -0
  99. package/packages/client/spawn-messages.mjs +119 -0
  100. package/packages/client/spawn-preview-cli.mjs +32 -0
  101. package/packages/client/spawn-preview-contract.mjs +314 -0
  102. package/packages/client/team-members.mjs +41 -0
  103. package/packages/client/team-rows.mjs +45 -0
  104. package/packages/client/terminal-contract.mjs +57 -0
  105. package/packages/client/tmux-status.mjs +66 -0
  106. package/packages/client/waiting-on-you.mjs +88 -0
  107. package/packages/client/workspace-admission.mjs +45 -0
  108. package/packages/client/workspace-cli.mjs +142 -0
  109. package/packages/client/workspace-views.mjs +147 -0
  110. package/packages/tui/README.md +46 -0
  111. package/packages/tui/bin/tui.mjs +7 -0
  112. package/packages/tui/lib/actions.mjs +29 -0
  113. package/packages/tui/lib/client.mjs +4 -0
  114. package/packages/tui/lib/main.mjs +105 -0
  115. package/packages/tui/lib/term/keys.mjs +323 -0
  116. package/packages/tui/lib/term/screen.mjs +122 -0
  117. package/packages/tui/lib/term/style.mjs +43 -0
  118. package/packages/tui/lib/term/text.mjs +49 -0
  119. package/packages/tui/lib/term/tty.mjs +168 -0
  120. package/packages/tui/lib/term/width.mjs +124 -0
  121. package/packages/tui/lib/views/frame.mjs +62 -0
  122. package/packages/tui/lib/views/help.mjs +28 -0
  123. package/packages/tui/package.json +8 -0
  124. package/skills/oats-getting-started/SKILL.md +29 -22
  125. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  126. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  127. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  128. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  129. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  130. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  131. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  132. package/lib/launch-prompt-policy.mjs +0 -87
@@ -8,17 +8,27 @@
8
8
  * make a retried apply return the first receipt rather than act twice.
9
9
  * Unknown is reported as unknown — never as "clean" or "no children". */
10
10
  import { createHash } from "node:crypto";
11
- import { existsSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
+ import { existsSync, lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
12
12
  import { basename, join } from "node:path";
13
- import { attachedWorkLink, extraWorktreePlan, findInstanceHomes, inspectInstanceSession, listAgents, listInstances, observeSessionWithoutReceipt, retirePendingMarkerPath, retirementRecoveryFacts, stopInstanceSession } from "./core.mjs";
13
+ import { attachedWorkLink, claimHomeFor, extraWorktreePlan, findInstanceHomes, homeClaimHolder, identifiedHomeRecord, inspectInstanceSession, listAgents, listInstances, observeSessionWithoutReceipt, readHomeRecord, releaseHomeClaim, requireStopGrace, retireClaimPath, retirePendingMarkerPath, retirementRecoveryFacts, stillRunningOf, stopInstanceSession, STOP_UNDER_CLAIM } from "./core.mjs";
14
14
  import { groupedByOwner } from "./retire-output.mjs";
15
15
  import { observeInstanceGit } from "./instance-git.mjs";
16
16
  import { appendEvent } from "./instance-events.mjs";
17
- import { oatsError } from "./errors.mjs";
17
+ import { afterFirstEffect, isAnswerCode, kernelCode, lifecycleBusy, oatsError, reportDefect } from "./errors.mjs";
18
18
 
19
19
  export const LIFECYCLE_API = 1;
20
20
  const KEY = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
21
- const stopPendingPath = (home) => join(home, ".oats-stop-pending.json");
21
+ /** A reserved name: a kernel before feature `lifecycle-claim-stop` wrote this file into each target
22
+ * of a stop apply and left it there when it was killed. This kernel neither writes nor reads it;
23
+ * a stop apply removes one it finds, once it holds that home's claim. */
24
+ const leftoverStopMarkerPath = (home) => join(home, ".oats-stop-pending.json");
25
+ /** An option of planStop: the nonces of the lifecycle claims the caller holds (a stop apply reads
26
+ * its plan again under its own claims), which the plan does not report as a stop in progress. A
27
+ * symbol, so no caller can set it from parsed arguments or JSON. */
28
+ const OWN_HOLDINGS = Symbol("oats.stopPlanOwnHoldings");
29
+ /** The warnings of a stop apply (a leftover marker that could not be removed), on its receipt
30
+ * under a symbol: the receipt's JSON, printed or stored, does not carry them. */
31
+ export const STOP_WARNINGS = Symbol("oats.stopWarnings");
22
32
  const stopReceiptPath = (home, key) => join(home, `.oats-stop-receipt.${key}.json`);
23
33
 
24
34
  function readJson(path) { try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; } }
@@ -38,6 +48,24 @@ export function resolveInstance(ctx, root, name, { home } = {}) {
38
48
  if (candidates.length > 1) throw Object.assign(oatsError("E_AMBIGUOUS_INSTANCE", `instance ${JSON.stringify(name)} has ${candidates.length} homes; pass --home <abs>`), { candidates });
39
49
  return candidates[0];
40
50
  }
51
+ /** The home a stop or a retire is about: resolved (resolveInstance), and refused when its record is
52
+ * there and cannot be read (core identifiedHomeRecord), before a plan reads anything of it. */
53
+ function resolveTarget(ctx, root, name, opts) {
54
+ const me = resolveInstance(ctx, root, name, opts);
55
+ identifiedHomeRecord(me.home);
56
+ return me;
57
+ }
58
+ /** The record of the home a plan is about, read for the plan's facts: the same reader and the same
59
+ * refusal as the resolution, so that a record which became unreadable since then (the listing
60
+ * reads it in between) refuses the plan instead of giving it empty facts. → the record's object,
61
+ * or undefined for a home without one. */
62
+ const targetRecord = (home) => identifiedHomeRecord(home).meta;
63
+ /** The record of ANOTHER home (a child's, any home's lineage) → its object, or undefined when it is
64
+ * absent or cannot be read: such a home decides only for itself, and is nobody's parent or child. */
65
+ function otherRecord(home) {
66
+ const record = readHomeRecord(home);
67
+ return record.state === "record" ? record.meta : undefined;
68
+ }
41
69
 
42
70
  /** Every instance under the roots whose recorded parent chain reaches `name`,
43
71
  * deepest first (children are acted on before their parent). Recorded
@@ -46,7 +74,7 @@ export function descendantsOf(root, name) {
46
74
  const rows = [];
47
75
  for (const a of listAgents(root)) for (const i of listInstances(root).filter((x) => x.name === a.name)) for (const inst of i.instances || []) {
48
76
  const home = join(a._dir, "instances", inst.instance);
49
- const meta = readJson(join(home, "instance.json"));
77
+ const meta = otherRecord(home);
50
78
  if (meta) rows.push({ instance: inst.instance, agent: a.name, home, parent: meta.parentInstance ?? null });
51
79
  }
52
80
  // Recorded parentage is a BARE name, and names are unique only per agent
@@ -70,46 +98,58 @@ export function descendantsOf(root, name) {
70
98
  /** `state` is the session backend's word: "shell"/"stopped"/"not-launched" are
71
99
  * idle; "unknown" means a NON-shell process is running whose identity tmux
72
100
  * cannot name (the ordinary case for a launched harness). "Could not be
73
- * established" is a different thing and is `present: null` with a reason. */
101
+ * established" is a different thing and is `present: null` with a reason:
102
+ * the kernel code of what failed, never a system error's (E_SESSION_UNAVAILABLE
103
+ * for one that has none; workFacts: E_GIT_FAILED). */
74
104
  function sessionFacts(home) {
75
105
  try { const s = inspectInstanceSession(home); return { state: s.state, present: s.present, backend: s.backend ?? null, established: true }; }
76
- catch (e) { return { state: "unestablished", present: null, backend: null, established: false, reason: e.code || "E_SESSION_UNAVAILABLE" }; }
106
+ catch (e) { return { state: "unestablished", present: null, backend: null, established: false, reason: kernelCode(e, "E_SESSION_UNAVAILABLE") }; }
77
107
  }
78
108
  /** Retire's view of a home without its session receipt (before 0.25.9): the
79
109
  * retirement needs only absence, which it can observe — `{state: "absent",
80
110
  * present: false, established: true, note}`; live or ambiguous stays
81
111
  * unestablished, with the note saying why (retire refuses it). */
82
- function retireSessionFacts(home, session) {
112
+ function retireSessionFacts(home, session, meta) {
83
113
  if (session.established || session.reason !== "E_RUNTIME_ENDPOINT_UNKNOWN") return session;
84
- const meta = readJson(join(home, "instance.json"));
85
114
  if (!meta) return session;
86
115
  const seen = observeSessionWithoutReceipt(home, meta);
87
116
  return seen.absent ? { state: "absent", present: false, backend: seen.backend, established: true, note: seen.note } : { ...session, note: seen.note };
88
117
  }
89
118
  const running = (s) => s.established && s.present === true && !["shell", "stopped", "not-launched"].includes(s.state);
90
119
  function workFacts(home) {
91
- if (!existsSync(join(home, "work"))) return { observed: false, reason: "no-worktree" };
120
+ if (!existsSync(join(home, "work"))) {
121
+ // Not there, unless the home cannot be looked into: then nothing is known of its work.
122
+ try { lstatSync(join(home, "work")); } catch (e) { if (e?.code !== "ENOENT") return { observed: false, reason: "E_WORK_INSPECTION_FAILED" }; }
123
+ return { observed: false, reason: "no-worktree" };
124
+ }
92
125
  try {
93
126
  const g = observeInstanceGit(home);
94
127
  return { observed: true, revision: g.observation.revision, branch: g.observation.branch, detached: g.observation.detached, drift: g.recorded.drift,
95
128
  changed: g.summary.changed + g.summary.renamed + g.summary.copied + g.summary.unmerged, untracked: g.summary.untracked,
96
129
  upstream: g.upstream, base: { ref: g.base.ref, ahead: g.base.ahead, behind: g.base.behind }, remote: g.remote ? { host: g.remote.host, path: g.remote.path } : null };
97
- } catch (e) { return { observed: false, reason: e.code || "E_GIT_FAILED" }; }
130
+ } catch (e) { return { observed: false, reason: kernelCode(e, "E_GIT_FAILED") }; }
98
131
  }
99
- function targetFacts(row) {
100
- const meta = readJson(join(row.home, "instance.json")) || {};
132
+ /** The facts of one target of a plan. `meta` is its record's object: the plan's own home's
133
+ * (targetRecord) or a child's (otherRecord). `retiring` and `stopPending` are read from the
134
+ * home's lifecycle claim (core homeClaimHolder), by the holder's verb: a holder that is not gone
135
+ * (alive, or of a liveness that cannot be read) counts, and `retiring` is also true while a
136
+ * self-retire is scheduled (its pending marker). A claim in `own` is the caller's and is not
137
+ * reported. */
138
+ function targetFacts(row, meta = {}, own) {
139
+ const held = homeClaimHolder(row.home);
140
+ const holds = (action) => !!held && held.action === action && held.state !== "gone" && !own?.has(held.holder.nonce);
101
141
  return { instance: row.instance, agent: row.agent, home: row.home, depth: row.depth ?? 0, workMode: meta.work ?? null, launched: meta.launched === true,
102
142
  session: sessionFacts(row.home), work: workFacts(row.home),
103
- retiring: existsSync(retirePendingMarkerPath(row.home)), stopPending: existsSync(stopPendingPath(row.home)) };
143
+ retiring: existsSync(retirePendingMarkerPath(row.home)) || holds("retire"), stopPending: holds("stop") };
104
144
  }
105
145
 
106
146
  /** Facts for Stop: the instance, its recorded descendants (deepest first),
107
147
  * each with session state and dirty-work counts. `midTask` is REPORTED
108
148
  * activity: dirty work or a running session; unknown says unknown. */
109
- export function planStop(ctx, root, name, { home, recursive = true } = {}) {
110
- const me = resolveInstance(ctx, root, name, { home });
149
+ export function planStop(ctx, root, name, { home, recursive = true, [OWN_HOLDINGS]: own } = {}) {
150
+ const me = resolveTarget(ctx, root, name, { home });
111
151
  const kids = recursive ? descendantsOf(me.root, name) : [];
112
- const targets = [...kids.map(targetFacts), targetFacts({ ...me, instance: name, depth: 0 })];
152
+ const targets = [...kids.map((kid) => targetFacts(kid, otherRecord(kid.home), own)), targetFacts({ ...me, instance: name, depth: 0 }, targetRecord(me.home), own)];
113
153
  // Reported activity: a running session or dirty work is mid-task; when the
114
154
  // session could not be established and work is not observed, say unknown.
115
155
  for (const t of targets) t.midTask = running(t.session) || (t.work.observed && t.work.changed + t.work.untracked > 0) ? true : (!t.session.established || !t.work.observed) ? "unknown" : false;
@@ -120,44 +160,124 @@ export function planStop(ctx, root, name, { home, recursive = true } = {}) {
120
160
  ambiguous: ambiguousEdges,
121
161
  planRevision: planRevision(safety),
122
162
  notes: [...(ambiguousEdges.length ? [`${ambiguousEdges.length} instance(s) record this name as parent but the name is not unique under this root; they are listed under ambiguous and NOT acted on`] : []),
123
- ...(targets.some((t) => t.retiring) ? ["a target is being retired; apply will refuse it"] : []), ...(targets.some((t) => !t.session.established) ? ["a session state could not be established; it is reported unestablished, not idle"] : [])] };
163
+ ...(targets.some((t) => t.retiring) ? ["a target is being retired; apply will refuse it"] : []),
164
+ ...(targets.some((t) => t.stopPending) ? ["a stop holds a target's claim; apply will refuse it until that stop has ended"] : []), ...(targets.some((t) => !t.session.established) ? ["a session state could not be established; it is reported unestablished, not idle"] : [])] };
124
165
  return plan;
125
166
  }
126
167
 
127
- /** Apply a Stop plan: revalidate the revision, take the stop-pending marker
128
- * per target (refusing retiring targets), stop deepest-first, record a
129
- * receipt keyed by idempotency key. A retried apply with the same key
130
- * returns the recorded receipt without acting again. */
168
+ /** The field of a stop receipt FILE, never of an answer, that says its rows were written under the
169
+ * rules of feature `lifecycle-kernel-codes`: a kernel code in every failed row, and `stillRunning:
170
+ * []` only for a harness that exited (core.mjs stillRunningOf). A replay strips it. */
171
+ const STORED_UNDER_KERNEL_CODES = "lifecycleKernelCodes";
172
+ /** The results of a receipt stored WITHOUT that field, by a kernel from before the feature, as this
173
+ * kernel answers them: a replay is an answer of this kernel. Such a failed row can hold the
174
+ * system's own code, which becomes E_SESSION_STOP_FAILED (the row's message keeps the system's
175
+ * text), and `stillRunning: []`, which that kernel wrote only for a stop whose signalled processes
176
+ * were gone while the session did not read as idle: null, nothing established. The stored file is
177
+ * evidence and is never rewritten. */
178
+ function replayedResults(results) {
179
+ if (!Array.isArray(results)) return results;
180
+ return results.map((r) => {
181
+ if (!r || typeof r !== "object" || r.ok !== false) return r;
182
+ const code = "code" in r && !isAnswerCode(r.code) ? { code: "E_SESSION_STOP_FAILED" } : {};
183
+ const none = Array.isArray(r.stillRunning) && !r.stillRunning.length ? { stillRunning: null } : {};
184
+ return { ...r, ...code, ...none };
185
+ });
186
+ }
187
+
188
+ /** How many times a stop apply takes its targets' claims before it gives up on a set of targets
189
+ * that is another one under each read (applyStop, step 4). One pass is every stop there is but
190
+ * the one that meets a child appearing between its two reads. */
191
+ const STOP_CLAIM_PASSES = 3;
192
+
193
+ /** Apply a Stop plan. A stop holds the lifecycle claim of EVERY target (core claimHomeFor, the
194
+ * retire's file) before it stops the first one, and until it has written its receipt
195
+ * (awebai/oats#866, #890). In this order:
196
+ * 1. the plan, read for its targets and for the home of the receipt;
197
+ * 2. a receipt recorded under the same key is replayed (STORED_UNDER_KERNEL_CODES,
198
+ * replayedResults): read-only, before any claim;
199
+ * 3. the claim of every target, in one fixed order (by claim path), so that two overlapping
200
+ * stops cannot each hold half: one wins the first file both want, the other is refused at
201
+ * once and releases what it took. A holder is answered here, before a stale plan:
202
+ * E_INSTANCE_RETIRING beside a retire, E_LIFECYCLE_BUSY beside a stop, with the plan read
203
+ * before the claims;
204
+ * 4. the plan again, under the claims: the plan that is acted on. Every target IT names is held
205
+ * by this apply before anything is done: one it does not hold (a child recorded, or readable
206
+ * again, since the read of 1) sends the apply back to 3 with this plan's targets, every claim
207
+ * released first, so that the order of 3 holds (STOP_CLAIM_PASSES bounds it). Then the one
208
+ * comparison with the revision the caller sent: a child retired or re-made, a session started
209
+ * or ended, a self-retire scheduled since the plan was shown is E_PLAN_STALE with the fresh
210
+ * plan (the guarded retire's pattern, core RETIRE_UNDER_CLAIM). The plan's own refusals come
211
+ * from this read too: the instance itself retired since (E_SESSION_UNKNOWN), its record no
212
+ * longer readable (E_UNIDENTIFIED_INSTANCE_HOME);
213
+ * 5. a scheduled self-retire the caller was shown: E_INSTANCE_RETIRING;
214
+ * 6. a marker an older kernel left in a target is removed (leftoverStopMarkerPath);
215
+ * 7. each target is stopped, deepest first; 8. the receipt is written; 9. the claims are released.
216
+ * Everything through 6 is before any effect. From 7 on no answer says that nothing happened: a
217
+ * target's failure is a row of the receipt, and an error that would leave with a code this verb
218
+ * answers only before any effect is a kernel defect (lib/errors.mjs afterFirstEffect). */
131
219
  export function applyStop(ctx, root, name, { home, recursive = true, planRevision: expected, idempotencyKey, graceMs } = {}) {
132
220
  if (typeof expected !== "string" || !expected) throw oatsError("E_BAD_ARGS", "apply needs --plan-revision from a prior `--plan`");
133
221
  if (typeof idempotencyKey !== "string" || !KEY.test(idempotencyKey)) throw oatsError("E_BAD_ARGS", "apply needs --idempotency-key (1-128 chars of [A-Za-z0-9._:-])");
134
- const plan = planStop(ctx, root, name, { home, recursive });
135
- const prior = readJson(stopReceiptPath(plan.home, idempotencyKey));
136
- if (prior && prior.idempotencyKey === idempotencyKey) return { ...prior, replayed: true };
137
- if (plan.planRevision !== expected) throw Object.assign(oatsError("E_PLAN_STALE", `the stop plan changed since it was shown (${expected} → ${plan.planRevision}); review the fresh plan`), { plan });
138
- const retiring = plan.targets.filter((t) => t.retiring);
139
- if (retiring.length) throw Object.assign(oatsError("E_INSTANCE_RETIRING", `${retiring.map((t) => t.instance).join(", ")} ${retiring.length === 1 ? "is" : "are"} being retired; nothing was stopped`), { plan });
140
- const pending = plan.targets.filter((t) => t.stopPending);
141
- if (pending.length) throw Object.assign(oatsError("E_LIFECYCLE_BUSY", `${pending.map((t) => t.instance).join(", ")} already ${pending.length === 1 ? "has" : "have"} a stop in progress`), { plan });
142
- const results = [];
143
- const marker = { action: "stop", idempotencyKey, planRevision: expected, at: new Date().toISOString() };
144
- for (const t of plan.targets) { try { writeFileSyncAtomic(stopPendingPath(t.home), marker); } catch { /* best effort marker; the lock is advisory across our own apply paths */ } }
222
+ // Here, for the whole apply: refused per target it would be one row each, after the key was used.
223
+ requireStopGrace(graceMs);
224
+ const shown = planStop(ctx, root, name, { home, recursive });
225
+ const prior = readJson(stopReceiptPath(shown.home, idempotencyKey));
226
+ if (prior && prior.idempotencyKey === idempotencyKey) {
227
+ // A receipt this kernel stored is replayed as stored, without the file's own field.
228
+ const { [STORED_UNDER_KERNEL_CODES]: current, ...stored } = prior;
229
+ return { ...stored, results: current === true ? stored.results : replayedResults(stored.results), replayed: true };
230
+ }
231
+ const held = [];
232
+ const release = () => { for (const h of held.splice(0)) releaseHomeClaim(h); };
233
+ // Whether the first target's stop began: the one fact that says an effect may have happened.
234
+ let began = false;
145
235
  try {
236
+ let plan;
237
+ for (let before = shown, pass = 1; ; pass++) {
238
+ const order = before.targets.map((t) => ({ t, lock: retireClaimPath(t.home) })).sort((a, b) => (a.lock < b.lock ? -1 : a.lock > b.lock ? 1 : 0));
239
+ for (const { t } of order) {
240
+ // The refusal's details are of the target whose claim refused, which may be a child.
241
+ try { held.push(claimHomeFor("stop", t.instance, t.home)); } catch (e) { throw Object.assign(e, { plan: before }); }
242
+ }
243
+ const fresh = planStop(ctx, root, name, { home, recursive, [OWN_HOLDINGS]: new Set(held.map((h) => h.me.nonce)) });
244
+ const mine = new Set(held.map((h) => h.lock));
245
+ // A claim it holds for a home the fresh plan no longer names is released with the rest.
246
+ if (fresh.targets.every((t) => mine.has(retireClaimPath(t.home)))) { plan = fresh; break; }
247
+ release();
248
+ if (pass === STOP_CLAIM_PASSES) throw Object.assign(lifecycleBusy("none", `the instances a stop of ${name} would stop changed each of the ${pass} times their claims were taken; nothing was stopped`, "run the command again", { instance: name, home: fresh.home }), { plan: fresh });
249
+ before = fresh;
250
+ }
251
+ if (plan.planRevision !== expected) throw Object.assign(oatsError("E_PLAN_STALE", `the stop plan changed since it was shown (${expected} → ${plan.planRevision}); review the fresh plan`), { plan });
252
+ const retiring = plan.targets.filter((t) => t.retiring);
253
+ if (retiring.length) throw Object.assign(oatsError("E_INSTANCE_RETIRING", `${retiring.map((t) => t.instance).join(", ")} ${retiring.length === 1 ? "is" : "are"} being retired; nothing was stopped`), { plan });
254
+ const warnings = [];
146
255
  for (const t of plan.targets) {
256
+ const left = leftoverStopMarkerPath(t.home);
257
+ try { rmSync(left, { force: true }); } catch (e) { warnings.push(`${left}, a stop marker an older OATS left, could not be removed (${e?.message ?? e}); it refuses nothing, and the stop went on`); }
258
+ }
259
+ const results = [];
260
+ for (const t of plan.targets) {
261
+ began = true;
147
262
  try {
148
- const r = stopInstanceSession(t.home, { graceMs });
263
+ const r = stopInstanceSession(t.home, { graceMs, [STOP_UNDER_CLAIM]: true });
149
264
  results.push({ instance: t.instance, home: t.home, ok: true, stopped: r.stopped, alreadyIdle: r.alreadyIdle, state: r.state });
150
265
  } catch (e) {
151
- results.push({ instance: t.instance, home: t.home, ok: false, code: e.code || "E_SESSION_STOP_FAILED", message: e.message, stillRunning: e.receipt?.stillRunning ?? null });
266
+ reportDefect(e); // the error becomes a row here: its stack would otherwise be lost
267
+ results.push({ instance: t.instance, home: t.home, ok: false, code: kernelCode(e, "E_SESSION_STOP_FAILED"), message: e.message, stillRunning: stillRunningOf(e) });
152
268
  }
153
269
  }
154
- } finally { for (const t of plan.targets) rmSync(stopPendingPath(t.home), { force: true }); }
155
- const receipt = { lifecycleApi: LIFECYCLE_API, action: "stop", instance: name, home: plan.home, idempotencyKey, planRevision: expected, at: new Date().toISOString(),
156
- ok: results.every((r) => r.ok), results, retained: ["home", "work", "transcript", "launch"], replayed: false };
157
- // One receipt file per key: a retry of ANY earlier key replays its own
158
- // receipt for as long as the home exists (the replay horizon).
159
- try { writeFileSyncAtomic(stopReceiptPath(plan.home, idempotencyKey), receipt); } catch { /* receipt is evidence, not authority */ }
160
- return receipt;
270
+ const receipt = { lifecycleApi: LIFECYCLE_API, action: "stop", instance: name, home: plan.home, idempotencyKey, planRevision: expected, at: new Date().toISOString(),
271
+ ok: results.every((r) => r.ok), results, retained: ["home", "work", "transcript", "launch"], replayed: false };
272
+ // One receipt file per key: a retry of ANY earlier key replays its own
273
+ // receipt for as long as the home exists (the replay horizon).
274
+ try { writeFileSyncAtomic(stopReceiptPath(plan.home, idempotencyKey), { ...receipt, [STORED_UNDER_KERNEL_CODES]: true }); } catch { /* receipt is evidence, not authority */ }
275
+ return warnings.length ? Object.defineProperty(receipt, STOP_WARNINGS, { value: warnings }) : receipt;
276
+ } catch (e) {
277
+ throw began ? afterFirstEffect(e, "instance stop", "a target's stop had begun") : e;
278
+ } finally {
279
+ release();
280
+ }
161
281
  }
162
282
 
163
283
  function writeFileSyncAtomic(path, value) {
@@ -165,7 +285,7 @@ function writeFileSyncAtomic(path, value) {
165
285
  writeFileSync(tmp, JSON.stringify(value, null, 2)); renameSync(tmp, path);
166
286
  }
167
287
 
168
- /** What the Desktop reads of a plan's notes (packages/desktop/renderer/lifecycle-contract.mjs): at
288
+ /** What the Desktop reads of a plan's notes (packages/client/lifecycle-contract.mjs): at
169
289
  * most 64, each at most 4096 characters; it refuses a plan with more, so every note is built to fit
170
290
  * (#658). A path is never cut: what does not fit is left to the plan JSON or the receipt. */
171
291
  const PLAN_NOTES_MAX = 64;
@@ -257,11 +377,13 @@ const PLAN_NOT_COPIED_CAP = 16;
257
377
  * is the dialog's opt-in. No retire deletes a branch: `deleteBranch` is
258
378
  * always false. */
259
379
  export function planRetire(ctx, root, name, { home } = {}) {
260
- const me = resolveInstance(ctx, root, name, { home });
380
+ const me = resolveTarget(ctx, root, name, { home });
261
381
  const kids = descendantsOf(me.root, name);
262
- const target = targetFacts({ ...me, instance: name, depth: 0 });
263
- target.session = retireSessionFacts(me.home, target.session);
264
- const meta = readJson(join(me.home, "instance.json")) || {};
382
+ // Read once, after the lineage: every fact of the plan that the record gives is of this read.
383
+ const recorded = targetRecord(me.home);
384
+ const meta = recorded || {};
385
+ const target = targetFacts({ ...me, instance: name, depth: 0 }, recorded);
386
+ target.session = retireSessionFacts(me.home, target.session, recorded);
265
387
  // The home's extra trees and what retire does with each: listed, and bound
266
388
  // into the revision (below), so that an apply refuses as stale when a tree
267
389
  // was created, removed, dirtied or cleaned, or its target was taken.
@@ -65,6 +65,22 @@ export function launchConfigUnknown({ name, from, at }) {
65
65
  return fail("E_LAUNCH_CONFIG_UNKNOWN", `${at ?? "the launch preference"} names launch configuration ${JSON.stringify(name)}, which ${LOCAL_FILE} does not declare (launch-configs:); oats launch-config list shows what is`, { name, from, at });
66
66
  }
67
67
 
68
+ const NAMED = 10;
69
+ /** E_LAUNCH_CONFIG_AMBIGUOUS, or null: a new launch on `harness` that chose no configuration (`config`
70
+ * null after the harness default was looked up) although this host declares several for it and marks
71
+ * none `default: true`. A choice that asked for the bare harness (`--launch-config none`, or a
72
+ * souls.launch "none") is a choice; an inline or soul preference and `--harness` alone are not. */
73
+ export function launchConfigAmbiguous({ launchConfigs = {}, harness, config, choice }) {
74
+ if (config || (choice.selection.launchConfig === "none" && !choice.preference)) return null;
75
+ const configurations = Object.keys(launchConfigs).filter((name) => launchConfigs[name]?.harness === harness).sort();
76
+ if (configurations.length < 2) return null;
77
+ const fix = `name one with --launch-config <name> (or souls.launch in ${LOCAL_FILE}), or mark one default: true (oats launch-config set)`;
78
+ // The message names at most NAMED configurations, so it stays within a reader's bound (the
79
+ // Desktop refuses a problem message over 1024 characters); details keep the full list.
80
+ const named = configurations.length > NAMED ? [...configurations.slice(0, NAMED), `and ${configurations.length - NAMED} more`] : configurations;
81
+ return fail("E_LAUNCH_CONFIG_AMBIGUOUS", `${LOCAL_FILE} declares ${configurations.length} ${harness} launch configurations (${named.join(", ")}) and none is default: true, and this launch names none; ${fix}`, { harness, configurations, fix });
82
+ }
83
+
68
84
  /** The fix for a missing harness, by the layer that chose it. */
69
85
  export function harnessFix(harness, from) {
70
86
  if (from === "flag") return `install ${harness}, or choose another --harness / --launch-config`;
@@ -1,8 +1,7 @@
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. */
1
+ /** Completion reporting only, never input authority. After the sole Enter, a
2
+ * capture containing any of these strings is a question Claude is asking, and
3
+ * the launch blocks: no subsequent key may be sent. One list, the only one.
4
+ * See docs/launch-prompt-completion.md. */
6
5
  export const CLAUDE_QUESTION_MARKERS = Object.freeze([
7
6
  'Accessing workspace:',
8
7
  'Quick safety check:',
@@ -27,41 +26,6 @@ export const CLAUDE_QUESTION_MARKERS = Object.freeze([
27
26
  'Esc to exit',
28
27
  ]);
29
28
 
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
- }
29
+ // Ordinary shortcut/interrupt hints are simply not markers; do not broaden
30
+ // this into a generic '?' or Esc rule.
31
+ export const hasClaudeQuestionMarker = text => CLAUDE_QUESTION_MARKERS.some(marker => text.includes(marker));
@@ -12,6 +12,14 @@ const fail = () => { throw new Error('private launch evidence unavailable'); };
12
12
  const uid = () => process.getuid?.();
13
13
  const identity = s => ({ dev: s.dev, ino: s.ino });
14
14
 
15
+ // The pairs this kernel writes: a miss, a stable post-answer screen, and the
16
+ // screen whose notice block says Claude ignored the development-channel flag.
17
+ const WRITTEN = [['blocked', 'unmatched'], ['completed', 'stable-screen'], ['flag-ignored', 'notice-block']];
18
+ // Readable too: receipts whose completion was recognized by Claude's footer
19
+ // structure; they stay on disk unchanged.
20
+ const READABLE = [...WRITTEN, ['completed', 'structural']];
21
+ const pairIn = (pairs, outcome, recognition) => pairs.some(([o, r]) => o === outcome && r === recognition);
22
+
15
23
  /** Decode only the private receipt's recognition tag. This is not evidence
16
24
  * verification: collection must still bind bytes/identities and checked public
17
25
  * outcome. Historical receipts remain unchanged on disk. */
@@ -20,9 +28,7 @@ export function launchPromptEvidenceRecognition(receipt) {
20
28
  && !Object.hasOwn(receipt, 'outcome') && !Object.hasOwn(receipt, 'recognition')) {
21
29
  return { outcome: 'blocked', recognition: 'unmatched' };
22
30
  }
23
- if (receipt?.version === 2 && receipt.kind === 'launch-prompt-frame'
24
- && ((receipt.outcome === 'blocked' && receipt.recognition === 'unmatched')
25
- || (receipt.outcome === 'completed' && receipt.recognition === 'structural'))) {
31
+ if (receipt?.version === 2 && receipt.kind === 'launch-prompt-frame' && pairIn(READABLE, receipt.outcome, receipt.recognition)) {
26
32
  return { outcome: receipt.outcome, recognition: receipt.recognition };
27
33
  }
28
34
  return null;
@@ -123,12 +129,13 @@ export function retainLaunchPromptFrame({ home, homeIdentity, startId, target, s
123
129
  try {
124
130
  // This private receipt records the recognition being saved, not the final
125
131
  // public launch result: a subsequent audit/cleanup failure can be incomplete.
126
- if (!launchPromptEvidenceRecognition({ version: 2, kind: 'launch-prompt-frame', outcome, recognition })) fail();
132
+ if (!pairIn(WRITTEN, outcome, recognition)) fail();
127
133
  if (typeof home !== 'string' || !isAbsolute(home) || !homeIdentity
128
134
  || typeof startId !== 'string' || !startId.length || startId.length > 256 || startId.includes('\0')
129
135
  || !target || !isAbsolute(target.socket || '') || !/^@\d+$/.test(target.windowId) || !/^%\d+$/.test(target.paneId) || !/^[1-9]\d*$/.test(String(target.pid))
130
- || screen?.width !== 110 || screen?.height !== 35 || typeof screen.text !== 'string'
131
- || !screen.text.endsWith('\n') || screen.text.split('\n').length !== 36) fail();
136
+ || !Number.isSafeInteger(screen?.width) || screen.width < 1 || screen.width > 1000
137
+ || !Number.isSafeInteger(screen.height) || screen.height < 1 || screen.height > 1000 || typeof screen.text !== 'string'
138
+ || !screen.text.endsWith('\n') || screen.text.split('\n').length !== screen.height + 1) fail();
132
139
  const bytes = Buffer.from(screen.text, 'utf8');
133
140
  if (bytes.length > 64 * 1024) fail();
134
141
  check();
@@ -143,7 +150,7 @@ export function retainLaunchPromptFrame({ home, homeIdentity, startId, target, s
143
150
  const frameIdentity = publish(dir, 'frame.txt', bytes);
144
151
  const receipt = Buffer.from(JSON.stringify({ version: 2, kind: 'launch-prompt-frame', outcome, recognition, home, homeIdentity: identity(homeIdentity), startId,
145
152
  target: { socket: target.socket, windowId: target.windowId, paneId: target.paneId, pid: String(target.pid) },
146
- width: 110, height: 35, bytes: bytes.length, signatureDigest: sha256(bytes), frame: 'frame.txt', frameIdentity,
153
+ width: screen.width, height: screen.height, bytes: bytes.length, signatureDigest: sha256(bytes), frame: 'frame.txt', frameIdentity,
147
154
  source: 'controller-compared-frame', captureTime: null, retainedAt: new Date().toISOString() }) + '\n');
148
155
  publish(dir, 'receipt.json', receipt);
149
156
  verify(join(dir, 'frame.txt'), frameIdentity, bytes);