@awebai/oats 0.69.19 → 0.69.20

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 (38) hide show
  1. package/bin/oats.mjs +2 -2
  2. package/docs/capabilities.md +26 -13
  3. package/docs/container.md +218 -18
  4. package/docs/desktop-cli-api.md +25 -11
  5. package/docs/desktop.md +16 -0
  6. package/docs/implementation.md +2 -1
  7. package/docs/integrations.md +1 -1
  8. package/docs/knowledge.md +5 -5
  9. package/docs/official-catalog.md +4 -4
  10. package/docs/packages.md +11 -11
  11. package/docs/release-notes/v0.69.20.md +325 -0
  12. package/docs/servers.md +4 -2
  13. package/docs/souls-and-instances.md +4 -2
  14. package/docs/upgrading.md +11 -5
  15. package/docs/workspaces.md +13 -7
  16. package/lib/core.mjs +31 -195
  17. package/lib/hook-outcome.mjs +6 -0
  18. package/lib/instance-lifecycle.mjs +3 -1
  19. package/lib/instance-listing.mjs +3 -2
  20. package/lib/launch-prompt-fixtures/README.md +6 -0
  21. package/lib/retire-admission.mjs +215 -0
  22. package/lib/servers.mjs +3 -0
  23. package/package-catalog.json +2 -2
  24. package/package.json +1 -1
  25. package/packages/client/attributed-human.mjs +13 -0
  26. package/packages/client/deployment-data.mjs +4 -0
  27. package/packages/client/deployment-panel.mjs +2 -0
  28. package/packages/client/instance-lifecycle.mjs +6 -4
  29. package/packages/client/lifecycle-confirmation.mjs +4 -2
  30. package/packages/client/lifecycle-contract.mjs +11 -6
  31. package/packages/client/remote-roster.mjs +4 -0
  32. package/packages/record/README.md +15 -2
  33. package/packages/record/docs/capture-service.md +14 -0
  34. package/packages/record/lib/canonical.mjs +2 -70
  35. package/packages/record/lib/capture-aw-unit.mjs +14 -3
  36. package/packages/record/lib/capture-aw.mjs +11 -5
  37. package/packages/record/lib/capture-health.mjs +16 -5
  38. package/skills/oats-getting-started/SKILL.md +2 -2
@@ -0,0 +1,215 @@
1
+ // Internal lifecycle admission shared by Remove plans and retire apply.
2
+ // The record and cleanup readers live here; core re-exports only its existing API.
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { directoryRollbackPath, isCapturedHome, readHomeRecord, unreadableRecordSaid } from "./instance-listing.mjs";
6
+ import { isPlainObject } from "./session-inspect.mjs";
7
+ import { processLiveness } from "./worktree-hooks.mjs";
8
+ import { lifecycleBusy, oatsError } from "./errors.mjs";
9
+
10
+ /** The work modes spawn accepts — also the enum a quarantine cleanup descriptor
11
+ * must satisfy, so the retry cannot skip Git cleanup on an unrecognised value. */
12
+ export const WORK_MODES = ["worktree", "checkout", "attached", "workspace", "directory"];
13
+ /** The quarantine cleanup-descriptor contract version. Bump when the shape the
14
+ * retry consumes changes, so an older/newer marker fails closed instead of
15
+ * driving a retry that cannot do what it claims.
16
+ *
17
+ * The rule applies from the first RELEASE of this shape onward. Markers are only
18
+ * ever written when a `required` spawn hook fails, and required hooks do not
19
+ * exist in any released kernel — so no deployment can hold a marker of an earlier
20
+ * v1 shape, and there is nothing to migrate from. A migration path for a file
21
+ * that has never existed would be dead code claiming to protect real data. */
22
+ export const QUARANTINE_CLEANUP_VERSION = 1;
23
+ /** The rollback-owned Git steps a quarantine can still owe. */
24
+ export const QUARANTINE_GIT_DEBT = ["worktree", "branch"];
25
+
26
+
27
+ /** The refusal of a lifecycle verb (retire, stop, session start) for a home whose record is there
28
+ * and cannot be read: E_UNIDENTIFIED_INSTANCE_HOME, with the file, the reason, `nothing` (what the
29
+ * verb had done by then: nothing; a spawn that names the home says "nothing was spawned") and the
30
+ * one remedy that exists. Every caller raises it before any effect: a client reads this code from
31
+ * a stop or a retire as "refused, nothing happened". `--force` does not apply to it: it removes a
32
+ * home that has NO record, never, blind, one whose record cannot be read. */
33
+ function unreadableRecordRefusal(record, nothing = "nothing was done") {
34
+ return oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${unreadableRecordSaid(record)}; ${nothing}. Restoring the file from a copy makes the home usable again; removing such a home through OATS is not possible yet.`);
35
+ }
36
+ /** The one check a lifecycle verb makes when it has resolved its home, before it takes a claim or
37
+ * reads anything of the home: a record that cannot be read refuses the verb (unreadableRecordRefusal).
38
+ * → the record as read (readHomeRecord), a record or an absent one. */
39
+ export function identifiedHomeRecord(home, nothing) {
40
+ const record = readHomeRecord(home);
41
+ if (record.state === "unreadable") throw unreadableRecordRefusal(record, nothing);
42
+ return record;
43
+ }
44
+ export function nonEmptyString(v) { return typeof v === "string" && !!v.trim(); }
45
+ export function usableCleanupDescriptor(marker) {
46
+ const c = marker?.cleanup;
47
+ if (!isPlainObject(c)) return false;
48
+ if (c.version !== QUARANTINE_CLEANUP_VERSION) return false;
49
+ if (!nonEmptyString(c.repo)) return false;
50
+ if (!WORK_MODES.includes(c.work)) return false;
51
+ if (c.work === "worktree" && !nonEmptyString(c.branch)) return false;
52
+ if (c.branch !== undefined && !nonEmptyString(c.branch)) return false;
53
+ if (c.capabilityMeta !== undefined && !isPlainObject(c.capabilityMeta)) return false;
54
+ const directoryDebt = c.outstanding?.directory === true && c.work === "directory";
55
+ if (c.outstanding?.directory !== undefined && !directoryDebt) return false;
56
+ // A worktree directory whose git admin entry is gone (awebai/oats#444) is debt too: the retry proves it
57
+ // cleared when the directory is no longer there or has its admin entry back.
58
+ const orphanDebt = c.outstanding?.orphanedWork === true && c.work === "worktree";
59
+ if (c.outstanding?.orphanedWork !== undefined && !orphanDebt) return false;
60
+ if (!Array.isArray(c.capabilityRuntime) || (!c.capabilityRuntime.length && !directoryDebt && !orphanDebt)) return false;
61
+ if (!c.capabilityRuntime.every((cap) => isPlainObject(cap) && nonEmptyString(cap.id))) return false;
62
+ if (!isPlainObject(c.outstanding) || !Array.isArray(c.outstanding.hooks) || !Array.isArray(c.outstanding.git)) return false;
63
+ if (!c.outstanding.hooks.every(nonEmptyString)) return false;
64
+ if (!c.outstanding.git.every((g) => QUARANTINE_GIT_DEBT.includes(g))) return false;
65
+ // Git debt only exists where the rollback owns Git steps, so claiming it in any
66
+ // other work mode describes a quarantine that could not have happened.
67
+ if (c.outstanding.git.length && c.work !== "worktree") return false;
68
+ // The decisive invariant: a quarantine with NOTHING outstanding is a proof
69
+ // obligation of zero. Directory preservation is also real debt: the retry's
70
+ // independent-authority inspection and verified snapshots must succeed even
71
+ // when no capability has a retire hook. It is never a Git/shared-work escape.
72
+ if (!c.outstanding.hooks.length && !c.outstanding.git.length && !directoryDebt && !orphanDebt) return false;
73
+ // The retry must be ABLE to rerun what it must prove: an outstanding hook whose
74
+ // capability is not in the set could never run, so the quarantine would never
75
+ // clear — and the home would be unremovable without --force.
76
+ const known = new Set(c.capabilityRuntime.map((cap) => cap.id));
77
+ if (!c.outstanding.hooks.every((id) => known.has(id))) return false;
78
+ return true;
79
+ }
80
+
81
+ /** The capabilities whose spawn hooks ran in a captured home (its identities, memberships):
82
+ * retire cannot run their captured retire hooks, so it names them. */
83
+ export function capturedHomeCapabilities(meta) {
84
+ const order = Array.isArray(meta?.captured?.hookOrder) ? meta.captured.hookOrder.filter((id) => typeof id === "string") : [];
85
+ const withMeta = meta?.capabilityMeta && typeof meta.capabilityMeta === "object" ? Object.keys(meta.capabilityMeta) : [];
86
+ const intents = isPlainObject(meta?.captured?.hookIntents) ? Object.keys(meta.captured.hookIntents) : [];
87
+ const failures = Array.isArray(meta?.captured?.hookFailures) ? meta.captured.hookFailures.map(failure => failure?.capability).filter(nonEmptyString) : [];
88
+ return [...new Set([...order, ...withMeta, ...intents, ...failures])].sort();
89
+ }
90
+ /** Read and admit the recorded cleanup before any lifecycle effect. Shared by
91
+ * Remove plans and every retire apply, including deferred self retirement.
92
+ * No current deployment configuration can prove an old home created no state.
93
+ * `readWork` is core's actual instanceWork reader, passed by both callers to
94
+ * keep the leaf independent of core while preserving its Git repo resolution. */
95
+ export function retireCleanupAdmission(home, name, { force = false } = {}, readWork) {
96
+ if (typeof readWork !== "function") throw new TypeError("retireCleanupAdmission requires the instanceWork reader");
97
+ const metaPath = join(home, "instance.json");
98
+ const directoryFallbackPath = directoryRollbackPath(home);
99
+ const quarantinePath = existsSync(directoryFallbackPath) ? directoryFallbackPath : join(home, ".oats-rollback-incomplete.json");
100
+ let quarantine;
101
+ let markerUnusable = false;
102
+ let rawMarker;
103
+ // A marker means the home is quarantined, WHETHER OR NOT instance.json exists:
104
+ // the post-launch rollback retains a home that already has one, and gating on
105
+ // its absence meant that quarantine was silently ignored — retire took the
106
+ // ordinary path, where hook failures do not retain, and deleted the credential
107
+ // while the external state survived (reviewer-final0130bc8).
108
+ if (existsSync(quarantinePath)) {
109
+ // A marker without a USABLE cleanup descriptor is NOT a quarantine we can
110
+ // retry — it is an unidentified home. Treating an unusable one as retryable
111
+ // made --force unable to ever clear it: the retry could not run, so the home
112
+ // was retained again, forever (reviewer-adff009). "Parses as JSON" is not
113
+ // the bar; "can actually drive the retry" is, so the shape is checked
114
+ // against what the retry below consumes (reviewer-45ff039r2).
115
+ try {
116
+ const parsed = JSON.parse(readFileSync(quarantinePath, "utf8"));
117
+ rawMarker = parsed;
118
+ if (isPlainObject(parsed) && usableCleanupDescriptor(parsed)) quarantine = parsed;
119
+ else markerUnusable = true;
120
+ } catch { markerUnusable = true; }
121
+ }
122
+ // #796: a marker a spawn wrote before its spawn or worktree hooks (`inProgress`). While that spawn's
123
+ // process is verifiably alive it is a spawn in progress, never a quarantine to retry, --force
124
+ // included. Once it is gone, the hook group it left is ended when its leader is alive at the
125
+ // recorded start time; a group whose leader is gone is never signalled, only reported (its id may
126
+ // be another group's by now). The retry below completes the rollback from the marker like any other.
127
+ // Whether that process still runs may also be unreadable (no procfs and `ps` failing): that is never
128
+ // taken for gone. Retire refuses it, naming the recorded pid and start for a check by hand, and the
129
+ // existing forced path (`--force`) is the way out; a forced retry then keeps the spawn's branch.
130
+ // The same holds for a hook group with members whose leader's start cannot be read.
131
+ const spawnGroupWarnings = [];
132
+ let inProgressUnverified = false;
133
+ if (isPlainObject(rawMarker?.inProgress)) {
134
+ const p = rawMarker.inProgress;
135
+ const live = processLiveness(p);
136
+ if (live.state === "alive") throw lifecycleBusy("running", `${name} is still being spawned (pid ${p.pid}, running its hooks since ${p.startedAt ?? "?"}); nothing was retired`, "wait for the spawn to end, or stop that process, then retire");
137
+ if (live.state === "unknown") {
138
+ if (!force) throw lifecycleBusy("unknown", `${name}: whether its spawn (pid ${p.pid}, recorded start ${p.processStart ?? "none"}, running its hooks since ${p.startedAt ?? "?"}) still runs cannot be read (${live.reason}); nothing was retired`,
139
+ `check that pid by hand, and if it is not that spawn, run \`oats retire ${name} --force\``, { pid: p.pid, processStart: p.processStart ?? null, unknown: live.reason, remedy: `oats retire ${name} --force` });
140
+ inProgressUnverified = true;
141
+ spawnGroupWarnings.push(`retired with --force although whether its spawn (pid ${p.pid}) still runs could not be read (${live.reason}); its branch is kept`);
142
+ }
143
+ }
144
+ // The retire's own read of the record, with the same reader as the resolution: one that became
145
+ // unreadable since then refuses as there. It comes before retireSteps' first signal,
146
+ // so E_UNIDENTIFIED_INSTANCE_HOME for an unreadable record is only ever answered
147
+ // while nothing was done: `reached` is untouched ("before-effects").
148
+ const liveMeta = identifiedHomeRecord(home).meta;
149
+ // A quarantined home may carry an instance.json that is NOT the spawn record:
150
+ // module materialization writes a pre-hook stub ({ modules, providers,
151
+ // resolutionRevision }) before the spawn hooks run, and a required-hook
152
+ // failure retains the home with that stub in place. Trusting it over the
153
+ // cleanup descriptor left meta.repo undefined, so the retry never re-ran the
154
+ // owed retire hook and reported "cleanup descriptor lost its context repo"
155
+ // on every attempt — only --force could clear the home (found by an operator
156
+ // rehearsal on 0.25.3). The descriptor is written FOR this retry; a live
157
+ // record only wins when it is a complete spawn record (repo + work present).
158
+ const liveIsSpawnRecord = !!liveMeta && nonEmptyString(liveMeta.repo) && WORK_MODES.includes(liveMeta.work);
159
+ const meta = liveIsSpawnRecord || !quarantine ? (liveMeta || quarantine?.cleanup || {}) : { ...liveMeta, ...quarantine.cleanup };
160
+ // Compensation metadata is the SPAWN's, from whichever record survived — never
161
+ // a failed retry's report, which says nothing about what still needs undoing.
162
+ if (!liveMeta?.capabilityMeta && quarantine?.cleanup?.capabilityMeta) meta.capabilityMeta = quarantine.cleanup.capabilityMeta;
163
+ if (quarantine && typeof quarantine.cleanup.launched === "boolean") {
164
+ meta.launched = quarantine.cleanup.launched;
165
+ meta.tmux = quarantine.cleanup.tmux;
166
+ meta.sessionTarget = quarantine.cleanup.sessionTarget;
167
+ }
168
+ // A home with NEITHER instance.json NOR a usable cleanup descriptor cannot be
169
+ // retired safely: hooks would be skipped and the directory removed, which is
170
+ // the credential deletion the quarantine exists to prevent — and the spawn
171
+ // path tolerates a failed marker write, so this state is reachable. Fail
172
+ // closed; `force` is the deliberate manual-cleanup escape.
173
+ // A marker that cannot drive a retry is not "ignore me" — it is evidence that
174
+ // cleanup was interrupted and OATS cannot tell what remains. Fail closed even
175
+ // when instance.json is present; `--force` is the deliberate manual escape.
176
+ if (markerUnusable && !force) {
177
+ throw oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${home} carries a rollback marker that cannot drive a retry (unreadable, or missing the cleanup descriptor fields the retry consumes), so OATS cannot tell what external state still depends on this home. Inspect it, then re-run with \`--force\` to remove it anyway.`);
178
+ }
179
+ if (!existsSync(metaPath) && !quarantine && !force) {
180
+ throw oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${home} has no instance.json and no cleanup descriptor, so OATS cannot tell whether external state (identities, worktrees) still depends on it. Retiring it would delete whatever it holds without running any cleanup. Inspect it, then re-run with \`--force\` to remove it anyway.`);
181
+ }
182
+ // #962: a missing recorded repo does not mean the own worktree has none.
183
+ // Resolve it with exactly the reader the retire uses; keep the raw record
184
+ // untouched so the plan still shows (and binds) its missing-repo fact.
185
+ const workIs = readWork(home, meta);
186
+ const repoFromGit = workIs.is === "own-tree" && !meta.repo ? workIs.tree?.repo : undefined;
187
+ const hookRepo = meta.repo || repoFromGit;
188
+ // Only positive evidence from this record can authorize skipping cleanup.
189
+ const bindings = meta.capabilityRuntime;
190
+ const knownBindings = Array.isArray(bindings) && bindings.every(cap =>
191
+ isPlainObject(cap) && nonEmptyString(cap.id) &&
192
+ (cap.hooks === undefined || isPlainObject(cap.hooks) &&
193
+ (!Object.hasOwn(cap.hooks, "retire") || nonEmptyString(cap.hooks.retire))));
194
+ const noRetireHooks = knownBindings && !bindings.some(cap => cap.hooks?.retire);
195
+ const captured = isCapturedHome(meta);
196
+ const noCapturedSpawn = Array.isArray(meta.captured?.hookOrder) && meta.captured.hookOrder.length === 0 &&
197
+ (meta.capabilityMeta === undefined || isPlainObject(meta.capabilityMeta) && Object.keys(meta.capabilityMeta).length === 0) &&
198
+ (meta.captured.hookIntents === undefined || isPlainObject(meta.captured.hookIntents) && Object.keys(meta.captured.hookIntents).length === 0) &&
199
+ (meta.captured.hookFailures === undefined || Array.isArray(meta.captured.hookFailures) && meta.captured.hookFailures.length === 0) &&
200
+ (meta.captured.lifecycle === undefined || typeof meta.captured.lifecycle === "string" && !meta.captured.lifecycle.endsWith("-cleanup-required"));
201
+ const cause = captured && !noCapturedSpawn
202
+ ? "is a captured home from before 0.26 whose retire hooks cannot run, and its record does not prove that no capability's spawn hook ran"
203
+ : !captured && !knownBindings
204
+ ? "does not record capabilityRuntime, or its recorded capability hooks cannot be identified (homes spawned before capabilityRuntime need manual cleanup)"
205
+ : !captured && !nonEmptyString(hookRepo) && !noRetireHooks
206
+ ? "names no repository in which its recorded retire hooks can run"
207
+ : null;
208
+ if (!force && cause) {
209
+ const named = [...new Set([...capturedHomeCapabilities(meta),
210
+ ...(Array.isArray(bindings) ? bindings.map(cap => cap?.id).filter(nonEmptyString) : [])])];
211
+ const capabilities = named.length ? `Capabilities that may have left state: ${named.join(", ")}. ` : "";
212
+ throw oatsError("E_UNIDENTIFIED_INSTANCE_HOME", `${metaPath} ${cause}. ${capabilities}External identities or memberships may still depend on this home. Nothing was stopped, run or removed, including children. Inspect the home and clean up that state with the provider's tooling, then remove it with \`oats retire ${name} --force\`; --force removes the home without revoking state whose retire hooks cannot run.`);
213
+ }
214
+ return { meta, liveMeta, workIs, repoFromGit, hookRepo, directoryFallbackPath, quarantinePath, quarantine, hooksKnown: knownBindings, spawnGroupWarnings, inProgressUnverified };
215
+ }
package/lib/servers.mjs CHANGED
@@ -1791,6 +1791,9 @@ export function redactArgv(argv) {
1791
1791
  * relay the host's envelope verbatim) and inherited otherwise; stderr is always inherited.
1792
1792
  * → { status, stdout } (stdout only under json). */
1793
1793
  export function routeCapability(serverId, argv, { server, spawnSync: spawn = spawnSync, stdinIsTTY = process.stdin.isTTY, json = false } = {}) {
1794
+ if (argv.some(arg => arg === "--invite" || arg.startsWith("--invite="))) {
1795
+ throw serverError("E_BAD_ARGS", "routed capability commands cannot carry --invite in argv: use --invite-stdin and pipe the invite on stdin so it is not exposed in the ssh process arguments");
1796
+ }
1794
1797
  const target = targetOf(server);
1795
1798
  const [bin, ...rest] = sshArgv(target, argv, { cwd: target.workspace, control: controlUsable(target, { serverId }) });
1796
1799
  const r = spawn(bin, rest, { stdio: [stdinIsTTY ? "ignore" : "inherit", json ? "pipe" : "inherit", "inherit"], maxBuffer: 64 * 1024 * 1024 });
@@ -3,7 +3,7 @@
3
3
  "packages": {
4
4
  "oats.okf": {
5
5
  "url": "https://github.com/awebai/oats-okf.git",
6
- "ref": "v6.0.3",
6
+ "ref": "v6.2.0",
7
7
  "path": "oats-package"
8
8
  },
9
9
  "oats.aweb": {
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "oats.framework": {
50
50
  "url": "https://github.com/awebai/oats.git",
51
- "ref": "oats-framework/v1.25.2",
51
+ "ref": "oats-framework/v1.26.0",
52
52
  "path": "oats-package"
53
53
  }
54
54
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@awebai/oats",
3
- "version": "0.69.19",
3
+ "version": "0.69.20",
4
4
  "description": "OATS (Open Agent Team Specification) — durable souls, disposable instances, targetable capability packages, and the runtime-neutral oats CLI/kernel.",
5
5
  "keywords": [
6
6
  "agents",
@@ -0,0 +1,13 @@
1
+ /** The owning human (feature spawn-attribution): a status row's `attributedHuman`, the label of the human
2
+ * the instance's messaging identity is attributed to, or null (docs/desktop-cli-api.md, "Attributed human").
3
+ * Read as the kernel gives it, under the contract's own rule for the label (a waiting claim's message rule,
4
+ * waiting-on-you.mjs `waitingMessage`), on a local row and again on a remote row its host relayed. Anything
5
+ * else (not a string, blank, a refused character, over 200 code points, or text withheld as unsafe) is null:
6
+ * no human, never a fault, so a malformed value can't fail the row. Pure, never throws. */
7
+ import { waitingMessage } from './waiting-on-you.mjs';
8
+ import { EVENTS_WITHHELD } from './instance-events-contract.mjs';
9
+
10
+ export function attributedHumanData(v) {
11
+ const label = waitingMessage(v);
12
+ return label === EVENTS_WITHHELD || !label?.trim() ? null : label;
13
+ }
@@ -8,6 +8,7 @@ import { teamRow, teamRowsOf, defaultTeamOf, TEAM_ID } from './team-rows.mjs';
8
8
  import { launchOf, REPORT_FROM } from './launch-contract.mjs';
9
9
  import { readIdentity } from './workspace-views.mjs';
10
10
  import { waitingOnYouData } from './waiting-on-you.mjs';
11
+ import { attributedHumanData } from './attributed-human.mjs';
11
12
  import { retireData } from './retire-state.mjs';
12
13
  import { instanceColor } from './instance-presentation.mjs';
13
14
  const text = value => typeof value === 'string' && value.length <= 8192 && !value.includes('\0');
@@ -244,6 +245,9 @@ export function deploymentStatusData(document, deployment) {
244
245
  // Needs input (PR K): validated, never check()ed — an invalid claim is null (unknown), never an E_* that
245
246
  // fails the roster. Absent stays absent.
246
247
  if (own(instance, 'waitingOnYou')) row.waitingOnYou = waitingOnYouData(instance.waitingOnYou);
248
+ // Feature spawn-attribution: the owning human's label, or null. Validated, never check()ed: a malformed
249
+ // value is null (no human), never an E_* that fails the roster. Absent stays absent.
250
+ if (own(instance, 'attributedHuman')) row.attributedHuman = attributedHumanData(instance.attributedHuman);
247
251
  return [row];
248
252
  });
249
253
  return out;
@@ -133,6 +133,8 @@ export function panelInstance(i) {
133
133
  // Needs input (PR K): the validated claim (or null, unknown) as status reported it; absent stays absent.
134
134
  // The client's liveness is merged before projection, so running/runtimeState beside it are the probe's.
135
135
  ...(i.waitingOnYou !== undefined ? { waitingOnYou: i.waitingOnYou } : {}),
136
+ // The owning human (feature spawn-attribution): the label deployment-data.mjs validated, or null; absent stays absent.
137
+ ...(i.attributedHuman !== undefined ? { attributedHuman: i.attributedHuman } : {}),
136
138
  // Feature instance-color: the row's colour as instanceColor reads it, present only when it is one.
137
139
  ...(instanceColor(i) !== null ? { color: instanceColor(i) } : {}),
138
140
  // Feature instance-background (#1579): exactly true, else absent (instance-tree.mjs backgroundPlacement).
@@ -53,9 +53,9 @@ const kernelAnswered = envelope => envelope?.origin === 'kernel' && envelope.sch
53
53
  * A kernel's E_LIFECYCLE_BUSY whose kernel (`features`: the answering kernel's) says who holds the claim
54
54
  * reads by that (`holder`, busyHolder), local or remote, and names the target of `plan` the refusal is
55
55
  * about when that is not the instance acted on (`about`). */
56
- function failureReason(envelope, remote, terms, { code = envelope?.error?.code, features = null, plan = null } = {}) {
56
+ function failureReason(envelope, remote, terms, { code = envelope?.error?.code, features = null, plan = null, operation } = {}) {
57
57
  const kernel = kernelAnswered(envelope), undescribed = kernel ? undescribedAnswer(code, terms) : null;
58
- const reason = undescribed || lifecycleReason(code, terms), details = envelope?.error?.details;
58
+ const reason = undescribed || lifecycleReason(code, terms, { operation }), details = envelope?.error?.details;
59
59
  const holder = kernel ? busyHolder(code, details, features) : null, about = holder ? busyAbout(plan, details?.home) : null;
60
60
  const busy = holder ? { holder, ...(about ? { about } : {}) } : {};
61
61
  const message = holder ? busyHeadline(holder) : reason.message;
@@ -140,7 +140,8 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
140
140
  if (!same(selected, current)) return denied('E_PLAN_CHANGED', selected.target);
141
141
  if (envelope?.schemaVersion !== 1 || envelope.ok !== true) {
142
142
  const code = envelope?.error?.code || 'E_CLI_PROTOCOL';
143
- return denied(code, selected.target, { reason: failureReason(envelope, selected.remote, terms, { code, features: selected.features }) });
143
+ return denied(code, selected.target, { reason: failureReason(envelope, selected.remote, terms, { code, features: selected.features,
144
+ operation: request.operation }) });
144
145
  }
145
146
  // The plan is read by the features of the kernel that made it: for a relayed plan its host's, never this computer's.
146
147
  const data = lifecyclePlan(envelope.result, selected.target, request.operation, choices, { features: selected.features });
@@ -180,7 +181,8 @@ export function createLifecycleBoundary({ invoke = cliLifecycle, now = () => per
180
181
  // children have already stopped. The user must explicitly read a new plan.
181
182
  return failure(code, 'refused', { plan: fresh, childrenStopped });
182
183
  }
183
- if (beforeEffect.has(code)) return failure(code, 'refused', { reason: failureReason(envelope, entry.remote, terms, { features, plan: entry.plan }) });
184
+ if (beforeEffect.has(code)) return failure(code, 'refused', { reason: failureReason(envelope, entry.remote, terms,
185
+ { features, plan: entry.plan, operation: entry.plan.action }) });
184
186
  return failure('E_OUTCOME_UNKNOWN', 'unknown', { cause: failureReason(envelope, entry.remote, terms, { features }) });
185
187
  }
186
188
  /** The apply of this client that is running, as a reply names it. */
@@ -213,8 +213,10 @@ function refusal(reason, plan, { operation, leftover }, terms) {
213
213
  return { status: { headline: LEFTOVER_HELD, more: [], next: 'retire-with-force', code: reason.code }, blocks: [{ type: 'quote', text: shown.detail }] };
214
214
  // A reason with no code reads as the table's fallback, and says that fallback's code; a code only the client
215
215
  // raises (one the table does not know) keeps its own, so the client can word it.
216
- const table = lifecycleReason(reason?.code, terms), own = typeof reason?.code === 'string' && reason.code ? reason.code : table.code;
217
- const status = remote ? { headline: remote.message, code: remote.code } : undescribed ? { headline: undescribed.message, code: reason.code }
216
+ const table = lifecycleReason(reason?.code, terms, { operation });
217
+ const own = typeof reason?.code === 'string' && reason.code ? reason.code : table.code;
218
+ // This code's headline must hold for every cause, even when a relayed sentence still offers force.
219
+ const status = remote ? { headline: remote.code === 'E_UNIDENTIFIED_INSTANCE_HOME' ? table.message : remote.message, code: remote.code } : undescribed ? { headline: undescribed.message, code: reason.code }
218
220
  : { headline: table.message, code: own };
219
221
  return { status: { more: [], next: null, ...status }, blocks: shown ? [{ type: 'details', reason: shown, bare: !!undescribed }] : [] };
220
222
  }
@@ -22,9 +22,13 @@ const messages = {
22
22
  E_USAGE: 'Invalid lifecycle request.', E_WORKSPACE_UNKNOWN: 'Choose an advertised workspace.',
23
23
  E_SESSION_UNKNOWN: 'This instance is no longer in the current roster.', E_AMBIGUOUS_INSTANCE: 'Select an exact instance home.',
24
24
  E_HOME_MISMATCH: 'The instance home no longer matches this selection.',
25
- // The kernel's, for a home it cannot work from: a record that is there and cannot be read, a rollback
26
- // marker that cannot drive a retry, or neither a record nor a cleanup descriptor. Answered only before any effect.
27
- E_UNIDENTIFIED_INSTANCE_HOME: "OATS couldn't find or read what it needs in this instance's home folder, so nothing was done.",
25
+ // The kernel's, for a home whose record or cleanup cannot be used. Answered only before any effect.
26
+ // The envelope has no structured cause discriminator. Details gives the remedy; never parse its words
27
+ // or promise force, which cannot bypass a record that is there and cannot be read.
28
+ E_UNIDENTIFIED_INSTANCE_HOME: (_terms, context) => {
29
+ if (context?.operation !== 'retire') return "OATS couldn't find or read what it needs in this instance's home folder, so nothing was done.";
30
+ return "OATS can't tell what this home's capabilities created, or can't run their cleanup, so nothing was removed. Details says what may be left and how to finish.";
31
+ },
28
32
  'cli-unavailable': 'Choose a compatible installed OATS CLI.',
29
33
  E_LIFECYCLE_UNAVAILABLE: terms => `This OATS can't stop or retire instances from ${terms.name}. Update OATS.`,
30
34
  'unsupported-remote-operation': "This computer's OATS can't route this to the server. Update OATS here.",
@@ -53,11 +57,12 @@ export const LIFECYCLE_CODES = Object.freeze(Object.keys(messages));
53
57
  /** The code as the table knows it: itself, or `E_CLI_FAILED` for one it has no sentence for. Needs no terms. */
54
58
  export const lifecycleCode = code => (Object.hasOwn(messages, code) ? code : 'E_CLI_FAILED');
55
59
  /** The code and its sentence, in the client's terms (client-terms.mjs): a sentence that names the client is
56
- * built from them. */
57
- export function lifecycleReason(code, terms) {
60
+ * built from them. `context` supplies the explicit operation for a Remove's cleanup refusal;
61
+ * without it the unidentified-home sentence stays neutral, as it is for Stop. */
62
+ export function lifecycleReason(code, terms, context = {}) {
58
63
  requireTerms(terms, 'lifecycleReason');
59
64
  const known = lifecycleCode(code), message = messages[known];
60
- return { code: known, message: typeof message === 'function' ? message(terms) : message };
65
+ return { code: known, message: typeof message === 'function' ? message(terms, context) : message };
61
66
  }
62
67
  /** A kernel's error answer whose code has no sentence here. It says "OATS answered", so it is chosen only
63
68
  * for a code read out of the kernel's own error envelope: by where the code came from, which only the caller
@@ -2,6 +2,7 @@ import { harnessOf } from "./harness-names.mjs";
2
2
  import { unsupportedSession, unsupportedSessionOrigin, hasRuntimeError } from "./instance-presentation.mjs";
3
3
  import { madeByKernel } from "./kernel-made.mjs";
4
4
  import { waitingOnYouData } from "./waiting-on-you.mjs";
5
+ import { attributedHumanData } from "./attributed-human.mjs";
5
6
  import { retireData } from "./retire-state.mjs";
6
7
  import { readIdentity } from "./workspace-views.mjs";
7
8
  import { sameRepo } from "./repo-moves.mjs";
@@ -61,6 +62,9 @@ export function remotePanel(group, at) {
61
62
  tmux: i.tmux || null, git: i.git || null, task: i.task || "", next: i.next || "",
62
63
  // Needs input: only a remote kernel with the feature reports it — validated, never synthesized when absent.
63
64
  ...(Object.hasOwn(i, "waitingOnYou") ? { waitingOnYou: waitingOnYouData(i.waitingOnYou) } : {}),
65
+ // The owning human (feature spawn-attribution): the host's label validated again here (attributed-human.mjs),
66
+ // a malformed one null; a host that does not report it leaves it absent.
67
+ ...(Object.hasOwn(i, "attributedHuman") ? { attributedHuman: attributedHumanData(i.attributedHuman) } : {}),
64
68
  // #1247: the host's retire state, relayed unchanged when it is in the contract (retire-state.mjs), else absent.
65
69
  ...(retireData(sentRetire) ? { retire: retireData(sentRetire) } : {}),
66
70
  // #1577: the host's same-work flag, true only (anything else reads unflagged). `sameWorkKnown` is this
@@ -19,8 +19,9 @@ the oats repo and run as `oats experimental <cmd>`. They are deliberately not
19
19
  part of this package.
20
20
 
21
21
  - **`lib/canonical.mjs`** — canonical JSON (integers only in the core),
22
- `t1:` content ids, did:key Ed25519 verification. Byte-compatible with awid
23
- message signing.
22
+ `t1:` content ids, and consistency checks for duplicated signed fields.
23
+ Byte-compatible with awid message signing; capture preserves source signatures
24
+ verbatim and does not verify them.
24
25
  - **`lib/store.mjs`** — the store: `streams/<owner>~<source>/journal.jsonl`
25
26
  (owner-only append, torn-tail tolerant), `objects/sha256/` (immutable
26
27
  blobs), `index/` (derived, never replicated). Merge is prefix extension
@@ -497,3 +498,15 @@ Anything that binds nothing is an error,
497
498
  See [capture algorithms and recovery](docs/capture-service.md) for the shared
498
499
  append-only input assumption, reset/retry commands, bounded status inventory,
499
500
  resource accounting and v0.53.0 downgrade/re-upgrade contract.
501
+
502
+ ### Sealed aw logs
503
+
504
+ A sealed client-log envelope (`v`, `key_id`, `enc`, `ct`, with optional `tag`) contains
505
+ ciphertext this recorder cannot read. Capture stops before that line and
506
+ reports a separate `sealed` count, without counting it as a projection failure
507
+ or advancing its cursor. Later lines wait too. Command capture sets the input
508
+ aside with reason “sealed, not readable by this recorder”; status reports it
509
+ under the set-aside count. Supply a readable source and explicitly retry the
510
+ set-aside input, or ignore that source. Resetting a cursor cannot decrypt it.
511
+ Readable lines that fail projection retain their existing consume-and-count
512
+ behaviour.
@@ -81,6 +81,20 @@ For a conflicting native prefix, either:
81
81
  input from active set-aside entries. Removing the ignore rule later does not
82
82
  authorize the conflict.
83
83
 
84
+ **Sealed aw logs.** Capture stops before a sealed client-log envelope (`v`,
85
+ `key_id`, `enc`, `ct`, optional `tag`) and leaves its cursor at the line's
86
+ start. It reports a distinct `sealed` count, and command capture sets the input
87
+ aside with reason `sealed, not readable by this recorder`. Later lines wait.
88
+ The owner can export readable JSONL with `aw log read <file>... --json`,
89
+ using the keychain and passphrase where the sealing key was created. The
90
+ recorder has no unattended decryption authority or passphrase transport. The
91
+ native reader may emit a readable prefix before failing, so partial stdout
92
+ does not prove the whole source was read.
93
+
94
+ Supply a readable source and run `capture --retry-set-aside`, or ignore the
95
+ source; retry and cursor reset cannot decrypt ciphertext. Readable projection
96
+ errors retain their existing consume-and-count behaviour.
97
+
84
98
  **Oversized records.** The 8 MiB raw-record limit applies to capture beyond
85
99
  the captured prefix. The supervised worker never allocates, captures or
86
100
  modifies a new raw source record larger than 8 MiB. It appends and checkpoints
@@ -1,9 +1,9 @@
1
- // Canonical JSON, turn ids, and signature verification for turn.jsonl v1.
1
+ // Canonical JSON, turn ids, and signed-field consistency for turn.jsonl v1.
2
2
  // Contract: docs/turn-record-sot.md in this package. The byte rules intentionally
3
3
  // match awid message signing (sorted keys, minimal separators, no HTML
4
4
  // escaping, ensure_ascii=false) so the same canonical form serves both.
5
5
 
6
- import { createHash, createPublicKey, verify as edVerify } from "node:crypto";
6
+ import { createHash } from "node:crypto";
7
7
 
8
8
  export class CanonicalError extends Error {}
9
9
 
@@ -57,74 +57,6 @@ export function verifyTurnId(turn) {
57
57
  return typeof turn.id === "string" && turnId(turn) === turn.id;
58
58
  }
59
59
 
60
- // --------------------------------------------------------------- did:key
61
-
62
- const B58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
63
-
64
- export function base58Decode(s) {
65
- let n = 0n;
66
- for (const c of s) {
67
- const i = B58_ALPHABET.indexOf(c);
68
- if (i < 0) throw new CanonicalError(`invalid base58 character ${JSON.stringify(c)}`);
69
- n = n * 58n + BigInt(i);
70
- }
71
- const bytes = [];
72
- while (n > 0n) {
73
- bytes.push(Number(n & 0xffn));
74
- n >>= 8n;
75
- }
76
- bytes.reverse();
77
- for (const c of s) {
78
- if (c === "1") bytes.unshift(0);
79
- else break;
80
- }
81
- return Uint8Array.from(bytes);
82
- }
83
-
84
- const ED25519_SPKI_PREFIX = Buffer.from("302a300506032b6570032100", "hex");
85
-
86
- export function publicKeyFromDidKey(did) {
87
- if (!did.startsWith("did:key:z")) throw new CanonicalError(`unsupported did ${did}`);
88
- const decoded = base58Decode(did.slice("did:key:z".length));
89
- if (decoded.length !== 34 || decoded[0] !== 0xed || decoded[1] !== 0x01) {
90
- throw new CanonicalError(`not an ed25519 did:key: ${did}`);
91
- }
92
- return createPublicKey({
93
- key: Buffer.concat([ED25519_SPKI_PREFIX, Buffer.from(decoded.subarray(2))]),
94
- format: "der",
95
- type: "spki",
96
- });
97
- }
98
-
99
- // Base64 signatures arrive unpadded, in either the standard or URL-safe
100
- // alphabet (awid accepts both; so do we).
101
- export function base64DecodeLoose(s) {
102
- const normalized = s.replaceAll("-", "+").replaceAll("_", "/");
103
- const padded = normalized + "=".repeat((4 - (normalized.length % 4)) % 4);
104
- return Buffer.from(padded, "base64");
105
- }
106
-
107
- // Verify an Ed25519 signature by a did:key over utf-8 payload text.
108
- // Returns boolean; malformed inputs are a failed verification, not a throw.
109
- export function verifyDidKeySignature(did, payloadText, signatureB64) {
110
- try {
111
- return edVerify(
112
- null,
113
- Buffer.from(payloadText, "utf8"),
114
- publicKeyFromDidKey(did),
115
- base64DecodeLoose(signatureB64),
116
- );
117
- } catch {
118
- return false;
119
- }
120
- }
121
-
122
- // Verify a turn's envelope signature (`sig` over the canonical core).
123
- export function verifyTurnSig(turn) {
124
- if (!turn.sig) return false;
125
- return verifyDidKeySignature(turn.sig.by, coreString(turn), turn.sig.sig);
126
- }
127
-
128
60
  // Value equality via canonical bytes — `to` may legally be an array, so a
129
61
  // reference compare would flag every multi-recipient turn read from disk.
130
62
  function sameValue(a, b) {
@@ -2,7 +2,7 @@
2
2
  // Explicit per-file public APIs keep their full-reprojection defaults.
3
3
  import { closeSync, constants, fstatSync, openSync } from "node:fs";
4
4
  import { basename } from "node:path";
5
- import { awBoundaryWitness, awLogLines, awStream } from "./capture-aw.mjs";
5
+ import { awBoundaryWitness, awLogLines, awStream, SEALED_AW_LOG_REASON } from "./capture-aw.mjs";
6
6
  import { captureContext } from "./capture-context.mjs";
7
7
  import { CAPTURE_POLICY } from "./capture-budget.mjs";
8
8
  import { fileVersion, statVersion, sameVersion } from "./derived-state.mjs";
@@ -27,7 +27,8 @@ export function captureAwUnit(store, { owner, path, kind = "comm", selfName, wor
27
27
  return { ...result, ignored: true, complete: true };
28
28
  }
29
29
  const blocked = state.get("set-aside", key);
30
- if (blocked && !blocked.retry) return { ...result, setAside: blocked };
30
+ if (blocked && !blocked.retry) return { ...result, setAside: blocked,
31
+ ...(blocked.reason === SEALED_AW_LOG_REASON ? { sealed: 1 } : {}) };
31
32
  const fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
32
33
  try {
33
34
  const observe = () => {
@@ -85,7 +86,7 @@ export function captureAwUnit(store, { owner, path, kind = "comm", selfName, wor
85
86
  };
86
87
  const project = kind === "comm" ? entry => projectCommLogEntry(entry, { selfName: account }) :
87
88
  entry => projectInteractionLogEntry(entry, { selfName, workspace });
88
- let bytes = 0, records = 0, scanned = false, oversized = null;
89
+ let bytes = 0, records = 0, scanned = false, oversized = null, sealed = null;
89
90
  const turns = [], iterator = awLogLines(chunks(), { start: unitStart, maxBytes: maxRecordBytes, frontier: job.frontier ?? 0 });
90
91
  try {
91
92
  while (records < maxRecords && bytes < maxBytes && !stopped()) {
@@ -93,6 +94,11 @@ export function captureAwUnit(store, { owner, path, kind = "comm", selfName, wor
93
94
  if (next.done) { scanned = true; break; }
94
95
  const record = next.value;
95
96
  if (records && bytes + record.bytes > maxBytes) break;
97
+ if (record.sealed) {
98
+ result.entries++; result.sealed = 1; sealed = record.start;
99
+ if (work) work.sourceRecords = (work.sourceRecords ?? 0) + 1;
100
+ break;
101
+ }
96
102
  records++; bytes += record.bytes; job.bytes = record.end;
97
103
  if (work) work.sourceRecords = (work.sourceRecords ?? 0) + 1;
98
104
  if (record.skipped) result.skipped++;
@@ -125,6 +131,11 @@ export function captureAwUnit(store, { owner, path, kind = "comm", selfName, wor
125
131
  if (blocked && (job.bytes > blocked.offset || atEnd)) state.delete("set-aside", key);
126
132
  if (scanned || atEnd) state.delete("aw-unit", key);
127
133
  else state.set("aw-unit", key, job);
134
+ if (sealed !== null) {
135
+ const row = { owner, source: "aw", path, offset: sealed, reason: SEALED_AW_LOG_REASON, retry: false };
136
+ state.set("set-aside", key, row);
137
+ return { ...result, setAside: row };
138
+ }
128
139
  if (oversized !== null) {
129
140
  // Not captured past its exact start. Later records wait for an edited
130
141
  // source or an ignore of the whole input.