@awebai/oats 0.51.0 → 0.53.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 (166) hide show
  1. package/README.md +3 -1
  2. package/bin/oats.mjs +407 -123
  3. package/docs/capabilities.md +75 -6
  4. package/docs/configuration.md +200 -91
  5. package/docs/desktop-cli-api.md +1563 -113
  6. package/docs/desktop-instance-start.md +69 -0
  7. package/docs/desktop.md +10 -7
  8. package/docs/execution-targets.md +145 -58
  9. package/docs/first-team.md +3 -1
  10. package/docs/harness-trust.md +50 -2
  11. package/docs/implementation.md +238 -17
  12. package/docs/integrations.md +13 -9
  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 +25 -2
  18. package/docs/launch-prompt-completion.md +50 -48
  19. package/docs/macos-test-runs.md +246 -0
  20. package/docs/oats-local.schema.json +4 -3
  21. package/docs/official-catalog.md +5 -5
  22. package/docs/packages.md +14 -14
  23. package/docs/release-lane.md +225 -11
  24. package/docs/release-notes/v0.44.0.md +1 -1
  25. package/docs/release-notes/v0.52.0.md +933 -0
  26. package/docs/release-notes/v0.53.0.md +1274 -0
  27. package/docs/schedules.md +97 -4
  28. package/docs/souls-and-instances.md +332 -40
  29. package/docs/tui.md +584 -0
  30. package/docs/upgrading.md +298 -0
  31. package/docs/workspaces.md +3 -3
  32. package/lib/automations.mjs +22 -22
  33. package/lib/claim.mjs +278 -49
  34. package/lib/config-data.mjs +4 -1
  35. package/lib/core.mjs +1282 -289
  36. package/lib/errors.mjs +170 -0
  37. package/lib/harness-trust-write.mjs +68 -27
  38. package/lib/harness-trust.mjs +34 -16
  39. package/lib/instance-events.mjs +19 -1
  40. package/lib/instance-git.mjs +39 -3
  41. package/lib/instance-inspect.mjs +45 -17
  42. package/lib/instance-lifecycle.mjs +306 -57
  43. package/lib/instance-resolution.mjs +59 -6
  44. package/lib/launch-preference.mjs +236 -9
  45. package/lib/launch-prompt-completion.mjs +7 -43
  46. package/lib/launch-prompt-evidence.mjs +14 -7
  47. package/lib/launch-prompt-fixtures/README.md +86 -152
  48. package/lib/launch-prompt-fixtures/dev-channel-confirmation.json +50 -0
  49. package/lib/launch-prompt-fixtures.mjs +122 -109
  50. package/lib/launch-prompt-transport.mjs +2 -56
  51. package/lib/launch-prompts.mjs +102 -100
  52. package/lib/local-edit.mjs +118 -0
  53. package/lib/packages.mjs +13 -4
  54. package/lib/pi-bridge.mjs +308 -0
  55. package/lib/refused-text.mjs +11 -0
  56. package/lib/remote.mjs +190 -25
  57. package/lib/resolve.mjs +2 -1
  58. package/lib/retained-after-retire.mjs +2 -2
  59. package/lib/retire-output.mjs +12 -1
  60. package/lib/schedule-host.mjs +125 -22
  61. package/lib/schedule.mjs +73 -24
  62. package/lib/shell-word.mjs +13 -0
  63. package/lib/soul-launch-verbs.mjs +153 -0
  64. package/lib/stable-node.mjs +62 -0
  65. package/lib/system-tools.mjs +39 -0
  66. package/lib/teams-verbs.mjs +18 -46
  67. package/lib/tmux-server-scope.mjs +62 -0
  68. package/lib/triggers.mjs +4 -4
  69. package/lib/workspace.mjs +54 -30
  70. package/lib/worktree-hooks.mjs +98 -20
  71. package/lib/worktree.mjs +83 -24
  72. package/package-catalog.json +4 -4
  73. package/package.json +8 -2
  74. package/packages/client/attach-exit.mjs +25 -0
  75. package/packages/client/capability-show-contract.mjs +230 -0
  76. package/packages/client/capability-warnings-contract.mjs +57 -0
  77. package/packages/client/cli-adapter.mjs +561 -0
  78. package/packages/client/cli-environment.mjs +53 -0
  79. package/packages/client/cli-locator.mjs +253 -0
  80. package/packages/client/cli-probe-contract.mjs +47 -0
  81. package/packages/client/client-terms.mjs +60 -0
  82. package/packages/client/deployment-contract.mjs +72 -0
  83. package/packages/client/deployment-data.mjs +483 -0
  84. package/packages/client/deployment-facts.mjs +95 -0
  85. package/packages/client/deployment-label.mjs +76 -0
  86. package/packages/client/deployment-observer.mjs +89 -0
  87. package/packages/client/deployment-panel.mjs +180 -0
  88. package/packages/client/deployment-read-cli.mjs +57 -0
  89. package/packages/client/display-text.mjs +50 -0
  90. package/packages/client/harness-names.mjs +30 -0
  91. package/packages/client/inspect-contract.mjs +62 -0
  92. package/packages/client/instance-acts.mjs +90 -0
  93. package/packages/client/instance-admission.mjs +45 -0
  94. package/packages/client/instance-events-contract.mjs +76 -0
  95. package/packages/client/instance-git-contract.mjs +80 -0
  96. package/packages/client/instance-presentation.mjs +86 -0
  97. package/packages/client/instance-tree.mjs +462 -0
  98. package/packages/client/kernel-environment.mjs +11 -0
  99. package/packages/client/kernel-lines.mjs +31 -0
  100. package/packages/client/kernel-made.mjs +23 -0
  101. package/packages/client/launch-contract.mjs +51 -0
  102. package/packages/client/launch-prompt-outcome.mjs +200 -0
  103. package/packages/client/lifecycle-cli.mjs +61 -0
  104. package/packages/client/lifecycle-contract.mjs +413 -0
  105. package/packages/client/liveness-main.mjs +10 -0
  106. package/packages/client/liveness.mjs +48 -0
  107. package/packages/client/machine-contract.mjs +123 -0
  108. package/packages/client/own-codes.mjs +31 -0
  109. package/packages/client/own-environment.mjs +22 -0
  110. package/packages/client/panel-views.mjs +293 -0
  111. package/packages/client/readiness-contract.mjs +174 -0
  112. package/packages/client/refresh-loop.mjs +52 -0
  113. package/packages/client/remote-address.mjs +151 -0
  114. package/packages/client/remote-identity-memory.mjs +94 -0
  115. package/packages/client/remote-roster.mjs +153 -0
  116. package/packages/client/roster-sections.mjs +80 -0
  117. package/packages/client/session-attach.mjs +175 -0
  118. package/packages/client/spawn-apply-cli.mjs +104 -0
  119. package/packages/client/spawn-apply-contract.mjs +195 -0
  120. package/packages/client/spawn-decision.mjs +46 -0
  121. package/packages/client/spawn-messages.mjs +142 -0
  122. package/packages/client/spawn-preview-cli.mjs +38 -0
  123. package/packages/client/spawn-preview-contract.mjs +318 -0
  124. package/packages/client/team-members.mjs +41 -0
  125. package/packages/client/team-rows.mjs +45 -0
  126. package/packages/client/terminal-contract.mjs +57 -0
  127. package/packages/client/terminal-exec.mjs +21 -0
  128. package/packages/client/tmux-status.mjs +66 -0
  129. package/packages/client/waiting-on-you.mjs +88 -0
  130. package/packages/client/workspace-admission.mjs +45 -0
  131. package/packages/client/workspace-choices.mjs +95 -0
  132. package/packages/client/workspace-cli.mjs +142 -0
  133. package/packages/client/workspace-views.mjs +183 -0
  134. package/packages/record/README.md +21 -0
  135. package/packages/record/bin/setup.mjs +108 -15
  136. package/packages/tui/README.md +64 -0
  137. package/packages/tui/bin/tui.mjs +7 -0
  138. package/packages/tui/lib/actions.mjs +44 -0
  139. package/packages/tui/lib/client.mjs +35 -0
  140. package/packages/tui/lib/config.mjs +151 -0
  141. package/packages/tui/lib/main.mjs +176 -0
  142. package/packages/tui/lib/model.mjs +392 -0
  143. package/packages/tui/lib/read.mjs +473 -0
  144. package/packages/tui/lib/store.mjs +364 -0
  145. package/packages/tui/lib/term/keys.mjs +367 -0
  146. package/packages/tui/lib/term/screen.mjs +134 -0
  147. package/packages/tui/lib/term/style.mjs +43 -0
  148. package/packages/tui/lib/term/text.mjs +109 -0
  149. package/packages/tui/lib/term/tty.mjs +178 -0
  150. package/packages/tui/lib/term/width.mjs +124 -0
  151. package/packages/tui/lib/views/detail.mjs +46 -0
  152. package/packages/tui/lib/views/frame.mjs +256 -0
  153. package/packages/tui/lib/views/help.mjs +140 -0
  154. package/packages/tui/lib/views/instances.mjs +137 -0
  155. package/packages/tui/lib/views/scroll.mjs +19 -0
  156. package/packages/tui/lib/views/switcher.mjs +97 -0
  157. package/packages/tui/package.json +8 -0
  158. package/skills/oats-getting-started/SKILL.md +30 -23
  159. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-05-channel-seeded.txt +0 -35
  160. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-06-first-after-channel.txt +0 -35
  161. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-07-after-channel-200ms.txt +0 -35
  162. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/frame-08-installed-after-channel-200ms.txt +0 -35
  163. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/manifest.json +0 -77
  164. package/lib/launch-prompt-fixtures/claude-2.1.289-darwin-arm64/max-bypass-source.json +0 -88
  165. package/lib/launch-prompt-fixtures/structural-completion.json +0 -205
  166. package/lib/launch-prompt-policy.mjs +0 -87
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The error codes the shared home writes itself: names of the kernel's shape (`E_` and capitals) that the
3
+ * kernel's code does not write. A client reads them in the same places as the kernel's codes, and several
4
+ * carry behaviour, so a kernel code that took one of these names would be read as the client's own.
5
+ *
6
+ * test/client-own-codes.test.mjs holds the list both ways: no name here is written in the kernel's code,
7
+ * and every name of that shape written in this directory is here or is the kernel's. So a code of the
8
+ * client's own that a table or a reader gains is added here in the same change. Nothing reads the list
9
+ * when the client runs.
10
+ */
11
+ export const CLIENT_OWN_CODES = Object.freeze([
12
+ // The CLI, and the call that carries its answer.
13
+ 'E_CLI_FAILED', 'E_CLI_OUTPUT_LIMIT', 'E_CLI_PROTOCOL', 'E_CLI_TIMEOUT', 'E_CLI_UNAVAILABLE',
14
+ // Reading a deployment, a workspace and another machine's roster.
15
+ 'E_CAPABILITY_SHOW_FEATURE', 'E_DEPLOYMENT_BUSY', 'E_DEPLOYMENT_FEATURE', 'E_DEPLOYMENT_SCOPE', 'E_DEPLOYMENT_STALE',
16
+ 'E_REMOTE_ROSTER', 'E_WORKSPACE_FEATURE', 'E_WORKSPACE_UNKNOWN',
17
+ // A spawn: its preview, its apply and the wake saved with it.
18
+ 'E_APPLY_UNAVAILABLE', 'E_BACKEND_UNAVAILABLE', 'E_BUSY', 'E_FORBIDDEN_FRAME', 'E_INPUT_PREPARATION', 'E_INSTANCE_GONE',
19
+ 'E_INTENT_EXPIRED', 'E_OUTCOME_UNKNOWN', 'E_PREFLIGHT_INCOMPLETE', 'E_PREVIEW_UNAVAILABLE', 'E_TARGET_CHANGED',
20
+ 'E_UNSUPPORTED_OPTION', 'E_WAKE_OUTCOME_UNKNOWN', 'E_WAKE_SAVE_FAILED',
21
+ // Stop, start, restart and remove, and the plan a person confirms (a spawn's plan too).
22
+ 'E_LIFECYCLE_UNAVAILABLE', 'E_OPTION_UNAVAILABLE', 'E_PLAN_CHANGED', 'E_PLAN_EXPIRED', 'E_PLAN_LIMIT', 'E_PLAN_REQUIRED',
23
+ // An instance's Activity.
24
+ 'E_EVENTS_UNAVAILABLE', 'E_NOT_IN_SCOPE',
25
+ // A terminal.
26
+ 'E_TERM_ATTACHMENT_FAILED', 'E_TERM_ATTACHMENT_INTERRUPTED', 'E_TERM_BAD_ARGS', 'E_TERM_BUSY', 'E_TERM_CAP',
27
+ 'E_TERM_CLOSE_PENDING', 'E_TERM_CLOSING', 'E_TERM_CONTEXT_CHANGED', 'E_TERM_FORBIDDEN_FRAME', 'E_TERM_INPUT_LIMIT',
28
+ 'E_TERM_LEASE', 'E_TERM_NOT_READY', 'E_TERM_OPEN_FAILED', 'E_TERM_OUTPUT_LIMIT', 'E_TERM_PREPARE_TIMEOUT',
29
+ 'E_TERM_READY_TIMEOUT', 'E_TERM_REMOTE_GONE', 'E_TERM_REMOTE_NO_ANSWER', 'E_TERM_REMOTE_NO_SSH',
30
+ 'E_TERM_REMOTE_UNREACHABLE', 'E_TERM_REUSED', 'E_TERM_TRANSPORT',
31
+ ].sort());
@@ -0,0 +1,22 @@
1
+ // A Desktop process that runs as Node (the backend, the liveness collector) is started with the
2
+ // environment its parent was started with, so the packaged executable starts exactly as before,
3
+ // and then drops what the Desktop and its packaging added: everything it starts inherits the
4
+ // user's environment, with no change at the places that start a program.
5
+ //
6
+ // This must happen before anything else is loaded, because modules take their environment when
7
+ // they are loaded. So it is not a statement in a body: it is the FIRST import of the program's
8
+ // entry module (packages/desktop/server/oats-web.mjs, liveness-main.mjs). A module's imports are evaluated
9
+ // in source order, each one completely before the next. This module and the leaf it imports must
10
+ // have no other imports, so that nothing can load ahead of the step. A library must never import
11
+ // this: it changes the environment of whoever does.
12
+ import { cliEnvironment } from "./cli-environment.mjs";
13
+
14
+ /** The environment this process was started with. Its one use: the backend starts the collector with it. */
15
+ export const launchEnvironment = Object.freeze({ ...process.env });
16
+
17
+ // In place: process.env is never reassigned.
18
+ const user = cliEnvironment(launchEnvironment);
19
+ for (const name of Object.keys(launchEnvironment)) {
20
+ if (!Object.hasOwn(user, name)) delete process.env[name];
21
+ else if (user[name] !== launchEnvironment[name]) process.env[name] = user[name];
22
+ }
@@ -0,0 +1,293 @@
1
+ /** The deployments a client serves and the workspace views over them (#482, workspace-views.mjs; #855, 1d):
2
+ * what the switcher lists, what a panel holds, and which deployment a request is addressed to.
3
+ * A view is one per matched workspace identity, plus one per unattached deployment under that
4
+ * deployment's own id. Everything is built per call from what the client holds; never a CLI read.
5
+ *
6
+ * No state. Every function that reads what a client holds takes it as its first argument, `held`,
7
+ * reads it and never changes it. The client builds one per call from its own store:
8
+ *
9
+ * held = {
10
+ * ctxs, // string[]: this machine's deployments, in served order
11
+ * snapshot, // { byWs: Map<deployment id, entry | remote panel> } (deployment-panel.mjs entries)
12
+ * remoteGroups, // the last readable remote roster's groups (remote-roster.mjs)
13
+ * remembered, // the remembered remote identities: an object with get(id), note(id), all()
14
+ * rosterAnswered, // boolean: a roster answer arrived under the current CLI
15
+ * rosterFailure, // string | null: the roster read's failure while no answer has arrived
16
+ * cli, // the kernel record (cli-locator.mjs)
17
+ * observing, // Set<deployment id>: a read in flight
18
+ * remoteCollecting, // boolean: the remote roster is being read
19
+ * home, // string: the user's home directory, for the short label
20
+ * at, // string: the ISO time of this call
21
+ * }
22
+ *
23
+ * These functions read no clock: the one time they stamp is `held.at`, and the same `held` gives the
24
+ * same answer. A remote deployment's panel is remote-roster.mjs `remotePanel`, made at `held.at`; what
25
+ * a remote roster's answer becomes is that module's `remoteRosterState`, whose answer is the three
26
+ * roster values of `held`.
27
+ *
28
+ * `remembered` is the client's own store, passed in: this module calls its three reading methods and
29
+ * keeps nothing. `note(id)` answers the sentence left for a machine that moved to another workspace,
30
+ * or null. The store's writing method is never called from here.
31
+ *
32
+ * A function that reaches a sentence or a label takes the client's terms (client-terms.mjs) after its
33
+ * required arguments and before its optional ones, and throws without them.
34
+ *
35
+ * Not for a page: this module imports `node:path`, and so does deployment-panel.mjs. */
36
+ import { basename } from 'node:path';
37
+ import { remoteWorkspace, remotePanel } from './remote-roster.mjs';
38
+ import { readIdentity, attachment, buildViews, deploymentReason, deploymentReasonParts } from './workspace-views.mjs';
39
+ import { shortPath, deploymentLabel } from './deployment-label.mjs';
40
+ import { deploymentUnavailableText, keptFailure } from './deployment-facts.mjs';
41
+ import { publicDeployment } from './deployment-panel.mjs';
42
+ import { teamMembers } from './team-members.mjs';
43
+ import { requireTerms } from './client-terms.mjs';
44
+
45
+ /** Roots come ONLY from the kernel's observed `status.root`; before (or
46
+ * without) an observation there is nothing to act on. No layout guess. */
47
+ export function workspaceEntry(held, ctx) {
48
+ const deployment = held.snapshot.byWs.get(ctx)?.deployment;
49
+ const observed = deployment?.status === "observed";
50
+ return { id: ctx, name: (observed && deployment.workspace?.name) || basename(ctx) || ctx, scope: ctx, team: null,
51
+ roots: observed ? [deployment.root] : [] };
52
+ }
53
+ /** Every served deployment, in served order: the local deployments, then the
54
+ * remote roster groups, then (only while there is no roster answer at all) the remembered remote
55
+ * groups, which have no rows. An id here is a deployment id: every instance-addressed route
56
+ * resolves only these. */
57
+ export function deployments(held) {
58
+ return [...held.ctxs.map((ctx) => workspaceEntry(held, ctx)), ...held.remoteGroups.map(remoteWorkspace), ...rememberedGroups(held).map(remoteWorkspace)];
59
+ }
60
+
61
+ /** Remembered remote groups shown only while no roster answer exists: not reached, no rows (Q3). */
62
+ export function rememberedGroups(held) {
63
+ if (held.rosterAnswered) return [];
64
+ const listed = new Set(held.remoteGroups.map((g) => g.id));
65
+ return held.remembered.all().filter((e) => !listed.has(e.id)).map((e) => ({
66
+ id: e.id, server: e.server, label: e.label, registrationPresent: true, remembered: true,
67
+ target: { workspace: e.path }, probe: { ok: false, error: { code: "E_REMOTE_ROSTER", message: held.rosterFailure || "no roster answer" } },
68
+ agentsRoot: undefined, workspace: null, souls: [], instances: [], retireFailures: [],
69
+ }));
70
+ }
71
+ /** Whether a kernel record (cli-locator.mjs) reads other machines: an accepted CLI whose `remote` lists
72
+ * `roster`. Without it a client makes no roster read (remote-roster.mjs `remoteRosterState`: "gated"). */
73
+ export const cliReadsRemotes = (cli) => !!cli.ok && !!cli.remote?.includes("roster");
74
+ const identityFeature = (held) => !!held.cli.features?.includes("workspace-identity");
75
+ /** One deployment's identity, attachment, machine label and reason. */
76
+ export function deploymentInfo(held, d, terms) {
77
+ requireTerms(terms, 'deploymentInfo');
78
+ if (!d.remote) {
79
+ const entry = held.snapshot.byWs.get(d.id), observed = entry?.deployment;
80
+ const live = observed?.status === "observed";
81
+ // A failed re-read kept the last observation (deployment-panel.mjs `failedEntry`): its identity still places
82
+ // it in its view, but it is stale, not live, and says why. Still reachable: this computer's own deployment.
83
+ // Whether one is kept is deployment-facts.mjs `keptFailure`'s to say, never a test of the message.
84
+ const kept = live ? keptFailure(entry) : null;
85
+ const read = !live ? { status: "none" } : !identityFeature(held) ? { status: "feature" }
86
+ : observed.reachable?.identityInvalid ? { status: "invalid" } : readIdentity(observed.reachable);
87
+ const identity = read.status === "identity" ? read.identity : null;
88
+ const attach = attachment(identity);
89
+ // Not observed (yet): the reading or unavailable sentence, never a silent empty.
90
+ const unavailable = live ? null : deploymentUnavailableText(observed || { status: "pending" }, terms);
91
+ return { id: d.id, local: true, machine: terms.thisMachine, path: d.id, label: shortPath(d.id, { home: held.home }), name: d.name,
92
+ live: live && !kept, reachable: live, ...(kept ? { stale: true } : {}), identityFrom: identity ? "reported" : null, identity, attach,
93
+ teamLabel: identity?.defaultTeam?.label ?? null,
94
+ ...reasonFields(deploymentReasonParts({ local: true, identityStatus: read.status, attach, ref: identity?.ref, unavailable,
95
+ ...(kept ? { readError: kept.message, readErrorOrigin: kept.origin } : {}) }, terms)),
96
+ note: attach.note === "standalone" ? deploymentReason({ local: true, attach: { unattached: "standalone" } }, terms) : null };
97
+ }
98
+ const g = d.group, machine = g.label || g.server;
99
+ const reached = g.probe?.ok === true;
100
+ let read = reached ? (identityFeature(held) ? readIdentity(g.workspace) : { status: "feature" }) : { status: "none" };
101
+ let identityFrom = read.status === "identity" ? "reported" : null;
102
+ if (!reached && (g.remembered || held.remembered.get(g.id))) {
103
+ const memory = held.remembered.get(g.id);
104
+ if (memory) { read = { status: "identity", identity: memory.workspace }; identityFrom = "remembered"; }
105
+ }
106
+ const identity = read.status === "identity" ? read.identity : null;
107
+ const attach = attachment(identity);
108
+ const reason = reasonFields(deploymentReasonParts({ local: false, machine, sshHost: g.target?.sshHost, probe: g.probe, identityStatus: read.status, attach,
109
+ ref: identity?.ref, cliReadsRemotes: cliReadsRemotes(held.cli), rosterError: g.remembered ? held.rosterFailure : null }, terms));
110
+ const moved = held.remembered.note(g.id);
111
+ const standalone = attach.note === "standalone" ? deploymentReason({ local: false, attach: { unattached: "standalone" } }, terms) : null;
112
+ return { id: d.id, local: false, machine, path: g.target?.workspace || "", label: shortPath(g.target?.workspace || ""), name: d.name,
113
+ live: reached, reachable: reached, identityFrom, identity, attach, teamLabel: identity?.defaultTeam?.label ?? null,
114
+ ...reason, note: [moved, standalone].filter(Boolean).join(" ") || null };
115
+ }
116
+ /** A reason's parts as a deployment's fields: `reason` (the full sentence), `short` and `fix` (UI spec, #482). */
117
+ export function reasonFields(parts) {
118
+ return parts ? { reason: parts.detail, short: parts.short, fix: parts.fix } : { reason: null, short: null, fix: [] };
119
+ }
120
+ /** The views and the per-deployment facts they rest on: `{ views, infos: Map<deploymentId, info> }`. */
121
+ export function viewModel(held, terms) {
122
+ requireTerms(terms, 'viewModel');
123
+ const infos = new Map(deployments(held).map((d) => [d.id, deploymentInfo(held, d, terms)]));
124
+ const views = buildViews([...infos.values()]).map((v) => {
125
+ const unattachedReason = v.unattached ? infos.get(v.primary)?.reason ?? null : null;
126
+ const unattachedShort = v.unattached ? infos.get(v.primary)?.short ?? null : null;
127
+ const ref = v.unattached ? infos.get(v.primary)?.identity?.ref ?? null : null;
128
+ return { ...v, ...(unattachedReason ? { reason: unattachedReason } : {}), ...(unattachedShort ? { short: unattachedShort } : {}), ...(ref ? { ref } : {}) };
129
+ });
130
+ return { views, infos };
131
+ }
132
+ /** The view a selector names: a view id, or a deployment id (answered with the view that holds it, so
133
+ * a selection saved before views opens its view). No selector means the first view. `model` is a
134
+ * view model already built for this call (`viewModel`); without one, it is built here. */
135
+ export function viewFor(held, wsId, terms, model) {
136
+ requireTerms(terms, 'viewFor');
137
+ if (model === undefined) model = viewModel(held, terms);
138
+ if (!wsId) return model.views[0] || null;
139
+ return model.views.find((v) => v.id === wsId) || model.views.find((v) => v.deployments.includes(wsId)) || null;
140
+ }
141
+ /** A deployment-level surface (header, capabilities, sync, automations, schedules, teams configuration,
142
+ * brain, launch configurations, spawn catalog): a deployment id as itself, a view id as that view's
143
+ * PRIMARY deployment (its first local one, else its first). Never used for an instance-addressed route,
144
+ * which resolves deployment ids only (`deployments(held).find`), so a view id there is refused. */
145
+ export function deploymentFor(held, wsId, terms) {
146
+ requireTerms(terms, 'deploymentFor');
147
+ const exact = wsId ? deployments(held).find((w) => w.id === wsId) : null;
148
+ if (exact) return exact;
149
+ const view = viewFor(held, wsId, terms);
150
+ return view ? deployments(held).find((w) => w.id === view.primary) || null : null;
151
+ }
152
+ /** A body that names an instance home (capabilities, launch configurations, schedules) addresses that
153
+ * instance: only an exact deployment id resolves it, never a view id. Anything else is deployment-level. */
154
+ const namesInstance = (request) => request?.selector?.home !== undefined || request?.spec?.home !== undefined;
155
+ export function surfaceDeployment(held, wsId, request, terms) {
156
+ requireTerms(terms, 'surfaceDeployment');
157
+ if (!wsId) return undefined; // these routes name their workspace: no selector is no workspace, never the first
158
+ return namesInstance(request) ? deployments(held).find((w) => w.id === wsId) : deploymentFor(held, wsId, terms);
159
+ }
160
+ /** The forge roster's context for a view (or a deployment id, read as its view): the union of its
161
+ * local deployments' rows and clones, under the view's id. */
162
+ export function viewForgeContext(held, wsId, terms) {
163
+ requireTerms(terms, 'viewForgeContext');
164
+ const view = viewFor(held, wsId, terms);
165
+ if (!view) return { workspace: undefined, cli: held.cli, instances: [], clones: [] };
166
+ const local = view.deployments.filter((id) => held.ctxs.includes(id));
167
+ const observed = local.map((id) => held.snapshot.byWs.get(id)).filter(Boolean);
168
+ return { workspace: { id: view.id, name: view.name, remote: local.length === 0 }, cli: held.cli,
169
+ instances: observed.flatMap((o) => o.instances || []), clones: observed.flatMap((o) => o.deployment?.workspaceStatus?.clones || []) };
170
+ }
171
+ /** One deployment's own rows (never its view's union): what an instance-addressed request may admit. */
172
+ export function deploymentRows(held, ws) {
173
+ return deploymentPanel(held, ws).instances || [];
174
+ }
175
+ /** The ids a client may let a caller select: every view id and every deployment id. */
176
+ export function isServed(held, id, terms) {
177
+ requireTerms(terms, 'isServed');
178
+ const model = viewModel(held, terms);
179
+ return model.views.some((v) => v.id === id) || model.infos.has(id);
180
+ }
181
+ /** The members of a view's deployments only, each tagged with its deployment (Q5; team-members.mjs);
182
+ * null for a selector that names no view. */
183
+ export function teamMembersFor(held, wsId, terms) {
184
+ requireTerms(terms, 'teamMembersFor');
185
+ const model = viewModel(held, terms);
186
+ const view = viewFor(held, wsId, terms, model);
187
+ if (!view) return null;
188
+ const members = view.deployments.map((id) => deployments(held).find((w) => w.id === id)).filter(Boolean);
189
+ return teamMembers({
190
+ deployments: members.filter((d) => !d.remote).map((d) => ({ deployment: deploymentTag(model.infos.get(d.id)), instances: held.snapshot.byWs.get(d.id)?.instances || [] })),
191
+ groups: members.filter((d) => d.remote).map((d) => ({ group: d.group, deployment: deploymentTag(model.infos.get(d.id)),
192
+ panel: held.snapshot.byWs.get(d.id) || remotePanel(d.group, held.at) })) });
193
+ }
194
+
195
+ /** A workspace's own machines (#517): the view's key, the deployment every
196
+ * machine call runs in and its messaging slot. The key is the one the view's primary local deployment
197
+ * reports (keyFrom "workspace" only; a matched view's deployments all share it); without one, or with no
198
+ * local deployment, `key` is null and `reason` says which. null for a selector that names no view. */
199
+ export function machineScope(held, wsId, terms) {
200
+ requireTerms(terms, 'machineScope');
201
+ const model = viewModel(held, terms);
202
+ const view = viewFor(held, wsId, terms, model);
203
+ if (!view) return null;
204
+ const local = view.deployments.map((id) => model.infos.get(id)).find((info) => info?.local);
205
+ if (!local) return { key: null, deployment: null, messaging: null, reason: "no-local" };
206
+ const identity = local.identity;
207
+ const messaging = held.snapshot.byWs.get(local.id)?.deployment?.workspaceStatus?.defaults?.slots?.messaging?.name ?? null;
208
+ if (identity?.keyFrom !== "workspace" || typeof identity.key !== "string" || !identity.key) return { key: null, deployment: local.id, messaging, reason: "no-key" };
209
+ return { key: identity.key, deployment: local.id, messaging };
210
+ }
211
+
212
+ /** A deployment as the panel and the rows name it. */
213
+ export const deploymentTag = (info) => ({ id: info.id, machine: info.machine, path: info.path });
214
+ /** A deployment's entry in the panel's `deployments` list (roster-sections.mjs `deploymentState` reads one). */
215
+ export function deploymentEntry(info, primary) {
216
+ return { ...deploymentTag(info), label: info.label, local: info.local, reachable: info.reachable,
217
+ identityFrom: info.identityFrom, primary: info.id === primary, ...(info.stale ? { stale: true } : {}),
218
+ ...(info.reason ? { reason: info.reason } : {}), ...(info.short ? { short: info.short } : {}),
219
+ ...(info.reason && info.fix?.length ? { fix: [...info.fix] } : {}), ...(info.note ? { note: info.note } : {}) };
220
+ }
221
+
222
+ /** One deployment's own panel, as served before views. */
223
+ export function deploymentPanel(held, ws) {
224
+ // Another machine's panel never says who made its `error`: the key is removed here whatever the panel carried.
225
+ if (ws?.remote) { const { errorOrigin: _sent, ...panel } = remotePanel(ws.group, held.at); return { ...panel, observedAt: null, refreshing: held.remoteCollecting }; }
226
+ const observed = ws ? held.snapshot.byWs.get(ws.id) : null;
227
+ const instances = observed?.instances || [], kept = keptFailure(observed);
228
+ return {
229
+ workspace: ws ? { id: ws.id, name: ws.name, team: null } : null,
230
+ team: null,
231
+ deployment: publicDeployment(observed?.deployment),
232
+ generatedAt: observed?.generatedAt || held.at,
233
+ // When the kernel observed the remotes this roster rests on, and whether a newer
234
+ // observation of this deployment is running right now (a client labels stale data).
235
+ observedAt: observed?.observedAt ?? null,
236
+ refreshing: !!ws && held.observing.has(ws.id),
237
+ running: instances.filter((i) => i.running).length,
238
+ instances,
239
+ // A failed re-read kept the last observation (deployment-panel.mjs `failedEntry`): its message, who made it
240
+ // (`errorOrigin`, "kernel" or absent) and its bounded cause. `error` is a string exactly when one is kept.
241
+ ...(kept ? { error: kept.message, ...(kept.origin ? { errorOrigin: kept.origin } : {}) } : {}),
242
+ ...(observed?.errorCause ? { errorCause: observed.errorCause } : {}),
243
+ };
244
+ }
245
+
246
+ /** Panel data is served from the latest observation and never blocks on a
247
+ * CLI read: a client's views and its readiness probes stay responsive. A view's panel is its
248
+ * primary deployment's panel (header, error, stamps) with the union of every deployment's rows,
249
+ * each row tagged with its deployment, and the view's deployments listed. */
250
+ export function panelData(held, wsId, terms) {
251
+ requireTerms(terms, 'panelData');
252
+ const model = viewModel(held, terms);
253
+ const view = viewFor(held, wsId, terms, model);
254
+ const choices = workspaceChoices(held, terms, model);
255
+ if (!view) return { ...deploymentPanel(held, null), workspaces: choices, deployments: [] };
256
+ const members = view.deployments.map((id) => deployments(held).find((w) => w.id === id)).filter(Boolean);
257
+ const panels = members.map((d) => [d, deploymentPanel(held, d)]);
258
+ const [, primary] = panels.find(([d]) => d.id === view.primary) || panels[0];
259
+ const instances = panels.flatMap(([d, p]) => (p.instances || []).map((row) => ({ ...row, deployment: deploymentTag(model.infos.get(d.id)) })));
260
+ return {
261
+ ...primary,
262
+ // `primary`: the deployment a deployment-level request is addressed to (it echoes that deployment back).
263
+ workspace: { ...primary.workspace, id: view.id, name: view.name, primary: view.primary, ...(view.key ? { key: view.key, teamId: view.team } : {}) },
264
+ workspaces: choices,
265
+ deployments: view.deployments.map((id) => deploymentEntry(model.infos.get(id), view.primary)),
266
+ refreshing: panels.some(([, p]) => p.refreshing),
267
+ running: instances.filter((i) => i.running).length,
268
+ instances,
269
+ };
270
+ }
271
+
272
+ /** The switcher's list: views, not deployments. Each names its deployments (a client lets a caller
273
+ * select any of these ids); an unattached view keeps today's remote fields and says why. `model` is a
274
+ * view model already built for this call (`viewModel`); without one, it is built here. */
275
+ export function workspaceChoices(held, terms, model) {
276
+ requireTerms(terms, 'workspaceChoices');
277
+ if (model === undefined) model = viewModel(held, terms);
278
+ return model.views.map((v) => {
279
+ const primary = deployments(held).find((w) => w.id === v.primary);
280
+ const remoteOnly = v.deployments.every((id) => !model.infos.get(id)?.local);
281
+ // Without the CLI's workspace-identity feature nothing can match: every deployment keeps its own entry, listed as
282
+ // before views, not as "not matched" (each deployment's own reason still says why).
283
+ const unmatched = v.unattached && identityFeature(held);
284
+ return { id: v.id, name: v.name, team: null, deployments: [...v.deployments],
285
+ // The deployments' labels, in the same order, for a view that is not on screen ("This Mac · ~/Agents/oats").
286
+ deploymentLabels: v.deployments.map((id) => deploymentLabel(model.infos.get(id), terms)),
287
+ // The switcher's one-liner (UI spec, #482): the machines, in order and once each, and how many deployments aren't live.
288
+ machines: [...new Set(v.deployments.map((id) => model.infos.get(id)?.machine).filter(Boolean))],
289
+ notLive: v.deployments.filter((id) => !model.infos.get(id)?.live).length,
290
+ ...(v.key ? { key: v.key } : {}), ...(unmatched ? { unattached: true } : {}), ...(unmatched && v.reason ? { reason: v.reason } : {}), ...(unmatched && v.short ? { short: v.short } : {}), ...(unmatched && v.ref ? { ref: v.ref } : {}),
291
+ ...(remoteOnly && primary?.remote ? { server: primary.server, remote: true } : {}) };
292
+ });
293
+ }
@@ -0,0 +1,174 @@
1
+ /** Readiness on the workspace model (`readinessApi: 2`), shared by the
2
+ * zero-dependency server and renderer. The subject is a soul or an instance,
3
+ * never a scope. The four checks are the kernel's; a provider's binding check
4
+ * is relayed verbatim. An admitted read is not a lease or spawn authority. */
5
+ import { effectiveOf, REPORT_FROM } from './launch-contract.mjs';
6
+ import { defaultTeamOf } from './team-rows.mjs';
7
+ import { remoteReason } from './remote-address.mjs';
8
+ import { warningsOf } from './capability-warnings-contract.mjs';
9
+ import { displayLine } from './display-text.mjs';
10
+ export const READINESS_API = 2;
11
+ export const CHECKS = ['installed', 'configured', 'member', 'providers'];
12
+ export const record = v => !!v && typeof v === 'object' && !Array.isArray(v);
13
+ export const absolute = v => typeof v === 'string' && v.startsWith('/') && v.length <= 4096 && !/[\x00-\x1f\x7f]/.test(v);
14
+ const name = v => typeof v === 'string' && /^[A-Za-z0-9][A-Za-z0-9._-]{0,255}$/.test(v);
15
+ const exact = (v, keys) => record(v) && Object.keys(v).every(k => keys.includes(k));
16
+ const states = ['pass', 'fail', 'unknown', 'not-applicable'];
17
+ // The URL alternative finds `://` first and looks behind it for the scheme, as display-text.mjs `UNSAFE`
18
+ // does and for its reason: time that grows with the length of the text, not with the square of a run.
19
+ const unsafe = /[\x00-\x08\x0b-\x1f\x7f]|:\/\/(?<=[a-z][a-z0-9+.-]*:\/\/)[^\s/]*@|(?:token|authorization|password|secret|api[_ -]?key)\s*[:=]\s*\S+/i;
20
+ function text(v, max = 1024) { if (typeof v !== 'string' || v.length > max) throw Error(); return unsafe.test(v) ? '[Detail withheld]' : v; }
21
+ const nullable = v => v == null ? null : text(v);
22
+ export function readinessSelector(v) {
23
+ if (!record(v)) return null;
24
+ if (v.kind === 'soul' && exact(v, ['kind', 'soul', 'agentsRoot']) && name(v.soul) && absolute(v.agentsRoot)) return { kind: v.kind, soul: v.soul, agentsRoot: v.agentsRoot };
25
+ if (v.kind === 'instance' && exact(v, ['kind', 'instance', 'agent', 'agentsRoot', 'server']) && name(v.instance) && name(v.agent) && absolute(v.agentsRoot)
26
+ && (v.server == null || typeof v.server === 'string' && /^[a-z0-9][a-z0-9-]{0,63}$/.test(v.server))) return { kind: v.kind, instance: v.instance, agent: v.agent, agentsRoot: v.agentsRoot, server: v.server ?? null };
27
+ return null;
28
+ }
29
+ /** The probe integer is the gate (no feature string). */
30
+ export function readinessSupported(cli) { return cli?.ok === true && absolute(cli.bin) && cli.readinessApi === READINESS_API; }
31
+ export function readinessTarget(v) {
32
+ const selector = readinessSelector(v?.selector);
33
+ if (!selector || !record(v) || typeof v.workspace !== 'string' || !v.workspace || v.workspace.length > 4096 || !absolute(v.context)
34
+ || v.observedAs !== selector.kind || selector.kind === 'instance' && !absolute(v.home)) return null;
35
+ return { workspace: v.workspace, context: v.context, observedAs: selector.kind, selector, ...(selector.kind === 'instance' ? { home: v.home } : {}) };
36
+ }
37
+ const ERRORS = {
38
+ E_BAD_ARGS: 'Readiness requires one workspace and a bounded, qualified read selector.',
39
+ E_WORKSPACE_UNKNOWN: 'Select a known local workspace.', E_TARGET_CHANGED: 'The selected workspace, target or CLI changed. Refresh readiness.',
40
+ E_SESSION_UNKNOWN: 'The selected instance is no longer reported.', E_AMBIGUOUS_INSTANCE: 'The selected instance is ambiguous.',
41
+ E_SOUL_UNKNOWN: 'Select one local soul and its exact agents root.', E_HOME_MISMATCH: 'The instance home no longer matches its admitted identity.',
42
+ 'cli-unavailable': 'Select a compatible installed OATS CLI.', 'cli-no-readiness': 'The installed OATS CLI is older than this Desktop (no readiness API 2). Update OATS and retry.',
43
+ 'unsupported-remote-operation': "This computer's OATS can't route this to the server. Update OATS here.",
44
+ E_UNSUPPORTED_MODE: 'Captured incarnation: readiness comes from its resolution, not current configuration.',
45
+ 'unsupported-action': 'Readiness is unavailable for this captured target; no classic fallback.', E_BUSY: 'The readiness read limit is reached. Retry when another read finishes.',
46
+ E_FORBIDDEN_FRAME: 'This frame cannot request readiness.', E_CLI_FAILED: 'The installed CLI could not complete the readiness read.',
47
+ E_CLI_TIMEOUT: 'The readiness read timed out.', E_CLI_OUTPUT_LIMIT: 'The readiness read exceeded its output limit.',
48
+ E_CLI_PROTOCOL: 'The installed CLI returned invalid or contradictory readiness data.',
49
+ 'classic-workspace': 'This workspace still uses the classic layout, which answers an older readiness shape. Readiness shows here once it is on the workspace model.', E_USAGE: 'The installed CLI does not support this read.',
50
+ };
51
+ /** A provider binding check's own answer → the item status the kernel reports for it. */
52
+ export const PROVIDER_ITEM_STATUS = Object.freeze({ ready: 'pass', 'needs-configuration': 'fail', 'authorization-required': 'fail', unavailable: 'unknown' });
53
+ /** `reason`: a remote read's reason (remote-address.mjs), kept only when it validates. */
54
+ export function readinessFailure(code, target = null, reason = null) {
55
+ if (!Object.hasOwn(ERRORS, code)) code = 'E_CLI_FAILED';
56
+ return { readinessViewApi: 1, status: 'unavailable', target: readinessTarget(target), data: null, reason: remoteReason(reason) || { code, message: ERRORS[code] } };
57
+ }
58
+ /** The fixed sentence for a readiness code: the headline of a host refusal outside the remote table. */
59
+ export const readinessMessage = code => readinessFailure(code).reason.message;
60
+ const problems = v => {
61
+ if (!Array.isArray(v) || v.length > 64) throw Error();
62
+ return v.map(p => { if (!record(p)) throw Error(); return { code: text(p.code, 128), message: text(p.message) }; });
63
+ };
64
+ /** A module's origin as the kernel records it: member commit, or package version + commit + integrity. */
65
+ function origin(v) {
66
+ if (!record(v) || !['member', 'package', 'external'].includes(v.kind)) throw Error();
67
+ const out = { kind: v.kind };
68
+ for (const k of ['package', 'version', 'commit', 'integrity', 'repoKey']) if (Object.hasOwn(v, k)) out[k] = nullable(v[k]);
69
+ return out;
70
+ }
71
+ const EVIDENCE = ['repoKey', 'workspace', 'commit', 'command', 'version', 'integrity', 'file'];
72
+ function item(v) {
73
+ if (!record(v) || !states.includes(v.status) || typeof v.required !== 'boolean') throw Error();
74
+ const evidence = {};
75
+ if (v.evidence != null) {
76
+ if (!record(v.evidence)) throw Error();
77
+ for (const k of EVIDENCE) if (Object.hasOwn(v.evidence, k)) evidence[k] = v.evidence[k] === null ? null : text(v.evidence[k], 4096);
78
+ if (Object.hasOwn(v.evidence, 'from')) evidence.from = origin(v.evidence.from);
79
+ }
80
+ const out = { subject: text(v.subject), status: v.status, required: v.required, reason: nullable(v.reason), producer: text(v.producer),
81
+ evidence, remedy: nullable(v.remedy) };
82
+ if (v.capability != null) { if (!record(v.capability)) throw Error(); out.capability = { id: text(v.capability.id, 256) }; }
83
+ if (typeof v.code === 'string') out.code = text(v.code, 128);
84
+ // launch-prompt (0.52.0): the home's last start stopped at a screen the kernel does not confirm, and its
85
+ // reason quotes what that terminal showed. One display line, for this code only; the kernel's sentence
86
+ // already says whose text it is ("found …"). The item's own `differed` is not read: the reason says it once.
87
+ if (v.code === 'launch-prompt') out.reason = displayLine(out.reason);
88
+ // harness-trust (0.52.0): the configuration file whose folder trust the item is about, top-level beside
89
+ // `evidence`, also on a passing item. Read tolerantly: anything but an absolute path with nothing unsafe
90
+ // in it drops this fact, never the read (dropped, not withheld: the answer must read the same when it is
91
+ // projected again). The item's other top-level keys (`harness`, `deployment`) are not read.
92
+ if (v.code === 'harness-trust' && absolute(v.file) && !unsafe.test(v.file)) out.file = v.file;
93
+ // Team model v2 (0.30, K1 amendment g): team items live in checks.configured (no fifth check),
94
+ // subject 'team <label>' or 'teams', and carry the team's label, whether it is the default, and
95
+ // where it is declared (at).
96
+ if (Object.hasOwn(v, 'label')) { if (typeof v.label !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(v.label)) throw Error(); out.label = v.label; }
97
+ if (Object.hasOwn(v, 'default')) { if (typeof v.default !== 'boolean') throw Error(); out.default = v.default; }
98
+ // Where the value is declared (a team; launch-changed's current layer), or null: launch-changed's `at`
99
+ // is null when the current launch comes from a flag or the host default.
100
+ if (Object.hasOwn(v, 'at')) { if (v.at !== null && (typeof v.at !== 'string' || !v.at || v.at.length > 512 || /[\x00-\x1f\x7f]/.test(v.at))) throw Error(); out.at = v.at; }
101
+ // `recorded`/`current` mean what the item's code says (--home only), so they are decoded per code:
102
+ // - launch-changed (launch preferences): each an effective launch {harness, model, launchConfig}, plus
103
+ // the current layer's `from` (its `at` is above: null when that layer is the host default);
104
+ // - default-team-changed (team model v2): each the kernel's DefaultTeam {label, team, from}, or null.
105
+ // Another code's recorded/current/from are not read (they may be anything; the item still shows).
106
+ if (v.code === 'launch-changed') {
107
+ for (const key of ['recorded', 'current']) { const l = effectiveOf(v[key]); if (!l) throw Error(); out[key] = l; }
108
+ if (!REPORT_FROM.includes(v.from)) throw Error(); out.from = v.from;
109
+ if (!Object.hasOwn(v, 'at')) throw Error();
110
+ } else if (v.code === 'default-team-changed') {
111
+ for (const key of ['recorded', 'current']) { const d = Object.hasOwn(v, key) ? defaultTeamOf(v[key]) : undefined; if (d === undefined) throw Error(); out[key] = d; }
112
+ }
113
+ // The provider's own binding-check answer, relayed verbatim (`providers`):
114
+ // {status, problems, warnings}. Warnings (always emitted, maybe []) never change status.
115
+ if (Object.hasOwn(v, 'result')) {
116
+ if (v.result === null) out.result = null;
117
+ // A known answer fixes the item status (a contradiction fails closed). The four
118
+ // statuses are additive: an unrecognised one is relayed as sent, and the kernel's
119
+ // item status stands (docs/desktop-cli-api.md, providers).
120
+ else if (record(v.result) && typeof v.result.status === 'string' && v.result.status && v.result.status.length <= 64
121
+ && (!Object.hasOwn(PROVIDER_ITEM_STATUS, v.result.status) || PROVIDER_ITEM_STATUS[v.result.status] === v.status)) {
122
+ out.result = { status: v.result.status, problems: problems(v.result.problems), warnings: problems(v.result.warnings) };
123
+ } else throw Error();
124
+ }
125
+ if (Object.hasOwn(v, 'problems')) out.problems = problems(v.problems);
126
+ return out;
127
+ }
128
+ function subjectOf(v, t) {
129
+ if (!record(v)) return null;
130
+ if (t.observedAs === 'soul') {
131
+ if (v.kind !== 'soul' || v.soul !== t.selector.soul) return null;
132
+ return { kind: 'soul', soul: v.soul, repoKey: nullable(v.repoKey), commit: nullable(v.commit), team: nullable(v.team) };
133
+ }
134
+ if (v.kind !== 'instance' || v.instance !== t.selector.instance || v.home !== t.home || v.soul !== t.selector.agent) return null;
135
+ return { kind: 'instance', instance: v.instance, home: v.home, soul: v.soul };
136
+ }
137
+ function policy(v) {
138
+ if (!record(v)) throw Error();
139
+ const result = {};
140
+ for (const key of ['childSpawns', 'worktrees']) {
141
+ const p = v[key];
142
+ if (!record(p) || ![true, false, null].includes(p.allowed) || typeof p.enforced !== 'boolean' || !record(p.origin)) throw Error();
143
+ result[key] = { allowed: p.allowed, enforced: p.enforced, origin: { kind: text(p.origin.kind), detail: nullable(p.origin.detail) },
144
+ ...(key === 'worktrees' ? { mode: nullable(p.mode) } : {}) };
145
+ }
146
+ return result;
147
+ }
148
+ export function readinessData(v, target) {
149
+ try {
150
+ const t = readinessTarget(target);
151
+ if (!t || !record(v) || v.readinessApi !== READINESS_API || !record(v.checks) || !record(v.summary)) return null;
152
+ const subject = subjectOf(v.subject, t);
153
+ if (!subject) return null;
154
+ if (typeof v.at !== 'string' || v.at.length > 40 || !Number.isFinite(Date.parse(v.at))) return null;
155
+ const checks = {};
156
+ for (const key of CHECKS) {
157
+ const c = v.checks[key];
158
+ if (!record(c) || !states.includes(c.status) || !Array.isArray(c.items) || c.items.length > 1000) return null;
159
+ checks[key] = { status: c.status, items: c.items.map(item) };
160
+ }
161
+ const required = Object.values(checks).flatMap(c => c.items).filter(i => i.required);
162
+ const s = v.summary;
163
+ if (typeof s.ready !== 'boolean' || !['required', 'pass', 'fail', 'unknown'].every(k => Number.isInteger(s[k]) && s[k] >= 0)
164
+ || s.required !== required.length || ['pass', 'fail', 'unknown'].some(k => s[k] !== required.filter(i => i.status === k).length)
165
+ || s.ready !== (required.length > 0 && required.every(i => ['pass', 'not-applicable'].includes(i.status)))) return null;
166
+ if (!Array.isArray(v.notes) || v.notes.length > 64) return null;
167
+ return { readinessApi: READINESS_API, subject, at: v.at, checks,
168
+ summary: { ready: s.ready, required: s.required, pass: s.pass, fail: s.fail, unknown: s.unknown },
169
+ policy: policy(v.policy), notes: v.notes.map(n => text(n)),
170
+ // Capability warnings (0.49.0): tolerant (a malformed list reads as none, never refuses the document), idempotent
171
+ // (the server projects, the renderer projects again), and outside the summary: they never change ready or a count.
172
+ warnings: warningsOf(v.warnings) };
173
+ } catch { return null; }
174
+ }
@@ -0,0 +1,52 @@
1
+ /** The deployment refresh loop: one observation cycle at a time, the next one
2
+ * scheduled an interval AFTER the previous completed (never back to back, so
3
+ * a slow kernel is never asked twice at once), backing off while the window
4
+ * is blurred. A request during a run schedules exactly one follow-up, never
5
+ * a queue: a mutation's result must be observed, and one requester asking
6
+ * `live` is enough to make that follow-up live. */
7
+ export const REFRESH_FOCUSED_MS = 5000, REFRESH_BLURRED_MS = 30000;
8
+
9
+ export function createRefreshLoop({ run, focusedMs = REFRESH_FOCUSED_MS, blurredMs = REFRESH_BLURRED_MS, timers = { setTimeout, clearTimeout }, now = () => Date.now() } = {}) {
10
+ let focused = true, active = false, timer = null, inflight = null, followUp = null, completedAt = null;
11
+ function clear() { if (timer !== null) { timers.clearTimeout(timer); timer = null; } }
12
+ function arm(ms) {
13
+ clear();
14
+ timer = timers.setTimeout(() => { timer = null; void execute(false); }, Math.max(0, ms));
15
+ if (typeof timer?.unref === 'function') timer.unref(); // the loop never keeps the process alive on its own
16
+ }
17
+ function execute(live) {
18
+ clear();
19
+ inflight = Promise.resolve().then(() => run({ live })).catch(() => {}).then(() => {
20
+ inflight = null; completedAt = now();
21
+ if (followUp) {
22
+ // The follow-up runs regardless of stop(): its requesters await an observation.
23
+ const { live: again, waiters } = followUp; followUp = null;
24
+ const promise = execute(again); for (const resolve of waiters) resolve(promise);
25
+ } else if (active) arm(focused ? focusedMs : blurredMs);
26
+ });
27
+ return inflight;
28
+ }
29
+ return {
30
+ start() { active = true; return execute(false); },
31
+ /** Observe now (or right after the current run) and resolve once that observation completed. */
32
+ request({ live = false } = {}) {
33
+ if (!inflight) return execute(live);
34
+ followUp ||= { live: false, waiters: [] };
35
+ followUp.live ||= live; // never downgrade a live request
36
+ return new Promise(resolve => followUp.waiters.push(resolve));
37
+ },
38
+ setFocused(value) {
39
+ const next = Boolean(value);
40
+ if (next === focused) return;
41
+ focused = next;
42
+ if (!active) return;
43
+ // Focus return: one prompt refresh when idle; a run in flight already is that refresh.
44
+ if (focused) { if (!inflight) void execute(false); }
45
+ // Blur with a timer pending: the next run moves out to blurredMs after the last completion, never earlier.
46
+ else if (timer !== null) arm(completedAt + blurredMs - now());
47
+ },
48
+ running() { return inflight !== null; },
49
+ focused() { return focused; },
50
+ stop() { active = false; clear(); },
51
+ };
52
+ }