@defrex/autobuild 1.3.0 → 1.4.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 (142) hide show
  1. package/README.md +1 -1
  2. package/SPEC.md +302 -26
  3. package/docs/accounts.md +38 -0
  4. package/docs/architecture.md +187 -19
  5. package/docs/build-store.md +18 -0
  6. package/docs/builds.md +5 -1
  7. package/docs/cli.md +1 -1
  8. package/docs/configuration.md +38 -19
  9. package/docs/dispatcher-hosting.md +42 -0
  10. package/docs/dispatcher.md +41 -0
  11. package/docs/forges.md +5 -0
  12. package/docs/integration-tree.md +8 -0
  13. package/docs/operating.md +11 -3
  14. package/docs/operator-api.md +37 -4
  15. package/docs/plugin-authoring.md +45 -1
  16. package/docs/remote-store-protocol.md +258 -42
  17. package/docs/remote-ticket-protocol.md +12 -10
  18. package/docs/restacking.md +60 -3
  19. package/docs/setup.md +37 -8
  20. package/docs/skills.md +1 -1
  21. package/docs/spec-standard.md +37 -3
  22. package/docs/troubleshooting.md +9 -0
  23. package/docs/workspaces.md +1 -1
  24. package/package.json +4 -3
  25. package/packages/core/src/accounts/availability.ts +96 -0
  26. package/packages/core/src/accounts/local-owner.ts +49 -2
  27. package/packages/core/src/cli/attention.ts +2 -0
  28. package/packages/core/src/cli/binary.ts +17 -1
  29. package/packages/core/src/cli/context.ts +62 -0
  30. package/packages/core/src/cli/dashboard/model.ts +12 -3
  31. package/packages/core/src/cli/dashboard/poll.ts +65 -8
  32. package/packages/core/src/cli/dashboard/refresh.ts +2 -0
  33. package/packages/core/src/cli/dashboard/render.ts +46 -5
  34. package/packages/core/src/cli/dispatch-args.ts +27 -3
  35. package/packages/core/src/cli/dispatch-frontend.ts +178 -52
  36. package/packages/core/src/cli/dispatch-mode.ts +94 -0
  37. package/packages/core/src/cli/dispatch-preflight.ts +43 -0
  38. package/packages/core/src/cli/dispatch-repository-feed.ts +45 -9
  39. package/packages/core/src/cli/dispatch.ts +145 -11
  40. package/packages/core/src/cli/harvest.ts +2 -1
  41. package/packages/core/src/cli/help.ts +16 -3
  42. package/packages/core/src/cli/historical-build-state.ts +6 -0
  43. package/packages/core/src/cli/main.ts +15 -2
  44. package/packages/core/src/cli/publication-settlement.ts +17 -0
  45. package/packages/core/src/cli/remote-poll.ts +11 -1
  46. package/packages/core/src/cli/repository-status.ts +11 -0
  47. package/packages/core/src/cli/status.ts +7 -1
  48. package/packages/core/src/cli/wait.ts +9 -2
  49. package/packages/core/src/cli/watch.ts +38 -3
  50. package/packages/core/src/config/roles.ts +16 -1
  51. package/packages/core/src/events/catalog.ts +7 -0
  52. package/packages/core/src/events/payloads.ts +85 -2
  53. package/packages/core/src/events/policy.ts +10 -0
  54. package/packages/core/src/events/repository.ts +35 -0
  55. package/packages/core/src/kernel/__snapshots__/reducer-accumulator-shapes.json +189 -0
  56. package/packages/core/src/kernel/dispatch-placement.ts +30 -0
  57. package/packages/core/src/kernel/engine.ts +19 -12
  58. package/packages/core/src/kernel/generators/leaf-restack-log.ts +17 -1
  59. package/packages/core/src/kernel/leaf-restack-state.ts +24 -2
  60. package/packages/core/src/kernel/log-index.ts +1 -1
  61. package/packages/core/src/kernel/node-landing.ts +27 -10
  62. package/packages/core/src/kernel/node-restack-demand.ts +1 -0
  63. package/packages/core/src/kernel/node-restack-state.ts +16 -1
  64. package/packages/core/src/kernel/node-restack-transaction.ts +14 -0
  65. package/packages/core/src/kernel/read-facts.ts +114 -9
  66. package/packages/core/src/kernel/reconcile-head.ts +34 -11
  67. package/packages/core/src/kernel/reconcile-restack.ts +106 -72
  68. package/packages/core/src/kernel/reducer-registry.ts +3 -0
  69. package/packages/core/src/kernel/reducer.ts +20 -2
  70. package/packages/core/src/kernel/replay-retention.ts +176 -0
  71. package/packages/core/src/kernel/target-lineage.ts +65 -0
  72. package/packages/core/src/kernel/target-observation.ts +117 -0
  73. package/packages/core/src/operator/registry.ts +5 -13
  74. package/packages/core/src/operator/tickets.ts +8 -2
  75. package/packages/core/src/plugin-sdk/index.ts +1 -0
  76. package/packages/core/src/ports/forge/fake.ts +22 -0
  77. package/packages/core/src/ports/forge/git-rewrite.ts +49 -12
  78. package/packages/core/src/ports/forge/github.ts +42 -10
  79. package/packages/core/src/ports/forge/local-git.ts +16 -1
  80. package/packages/core/src/ports/types.ts +58 -4
  81. package/packages/core/src/ports/workspace/account-policy.ts +2 -1
  82. package/packages/core/src/ports/workspace/commit-preservation.ts +175 -0
  83. package/packages/core/src/ports/workspace/create.ts +2 -0
  84. package/packages/core/src/ports/workspace/fake.ts +4 -0
  85. package/packages/core/src/ports/workspace/git-worktree.ts +22 -1
  86. package/packages/core/src/ports/workspace/vercel-sandbox.ts +304 -56
  87. package/packages/core/src/processes/build-runner.ts +240 -111
  88. package/packages/core/src/processes/dispatcher-selectors.ts +3 -2
  89. package/packages/core/src/processes/dispatcher.ts +262 -80
  90. package/packages/core/src/processes/execution-no-progress.ts +7 -0
  91. package/packages/core/src/processes/harvest-runner.ts +6 -7
  92. package/packages/core/src/processes/publication-state.ts +2 -1
  93. package/packages/core/src/processes/repo-view.ts +22 -0
  94. package/packages/core/src/processes/workspace-preservation.ts +164 -0
  95. package/packages/core/src/scenarios/harness.ts +7 -0
  96. package/packages/core/src/store/adapter.ts +9 -0
  97. package/packages/core/src/store/build-scope.ts +28 -0
  98. package/packages/core/src/store/contract.ts +125 -0
  99. package/packages/core/src/store/event-reads.ts +156 -0
  100. package/packages/core/src/store/local/schema.ts +11 -0
  101. package/packages/core/src/store/local/store.ts +117 -2
  102. package/packages/core/src/store/memory.ts +237 -0
  103. package/packages/core/src/store/phase-session.ts +47 -0
  104. package/packages/core/src/store/reduced-reads.ts +8 -0
  105. package/packages/core/src/store/reducer-value-shapes.json +6262 -5227
  106. package/packages/core/src/store/reducer-value-validation.ts +3 -0
  107. package/packages/core/src/store/reducer-values.ts +62 -2
  108. package/packages/core/src/store/remote/client.ts +161 -16
  109. package/packages/core/src/store/remote/compatibility.ts +177 -46
  110. package/packages/core/src/store/remote/errors.ts +16 -0
  111. package/packages/core/src/store/remote/index.ts +11 -0
  112. package/packages/core/src/store/remote/protocol.ts +22 -0
  113. package/packages/core/src/store/remote/released-clients.json +37 -0
  114. package/packages/core/src/store/remote/released-clients.ts +88 -0
  115. package/packages/core/src/store/remote/released-reducer-values/1.3.0.json +25093 -0
  116. package/packages/core/src/store/remote/released-reducer-values/1.4.0.json +26128 -0
  117. package/packages/core/src/store/remote/released-reducer-values/index.ts +13 -0
  118. package/packages/core/src/store/remote/version.ts +5 -2
  119. package/packages/core/src/store/repo-state-events.ts +4 -3
  120. package/packages/core/src/store/scan-cadence.ts +15 -0
  121. package/packages/core/src/store/session-handle.ts +18 -0
  122. package/packages/core/src/store/types.ts +27 -6
  123. package/packages/core/src/testing/dispatch-read-budget.ts +313 -2
  124. package/packages/core/src/testing/index.ts +5 -0
  125. package/packages/core/src/testing/reduced-read-budget.ts +728 -5
  126. package/skills/guide/SKILL.md +177 -16
  127. package/skills/guide/references/accounts.md +38 -0
  128. package/skills/guide/references/integration-tree.md +8 -0
  129. package/skills/guide/references/operator-api.md +37 -4
  130. package/skills/guide/references/plugin-authoring.md +45 -1
  131. package/skills/guide/references/remote-store-protocol.md +258 -42
  132. package/skills/guide/references/remote-ticket-protocol.md +12 -10
  133. package/skills/guide/references/restacking.md +60 -3
  134. package/skills/guide/references/setup.md +37 -8
  135. package/skills/guide/references/spec-standard.md +37 -3
  136. package/skills/implement/SKILL.md +12 -3
  137. package/skills/operate/SKILL.md +64 -7
  138. package/skills/plan/SKILL.md +27 -4
  139. package/skills/plan-review/SKILL.md +22 -2
  140. package/skills/reconcile/SKILL.md +10 -1
  141. package/skills/spec/SKILL.md +7 -4
  142. package/templates/hosted-service/package.json +2 -2
package/docs/setup.md CHANGED
@@ -9,6 +9,15 @@ build or phase. Work directly in the repository and involve the maintainer in
9
9
  choices that cannot be derived from source. Secrets belong in the environment
10
10
  or an ignored `.env`, never in `autobuild.toml`, commits, or validation reports.
11
11
 
12
+ Local dispatch checks selected primary and alternate account credentials before
13
+ taking the repository lease. Supply the configured environment slot or a local
14
+ ChatGPT login (`bun ab accounts login NAME --local`). Hosted account absence
15
+ appears once in repository attention: set `bun ab secrets set VARIABLE`, or
16
+ renew with `bun ab accounts login NAME --project`. The next tick resumes without
17
+ per-build retries or infrastructure-attempt consumption. Unused accounts do not
18
+ block startup; present rejected credentials keep their rejection attention.
19
+ See [account admission and remedies](accounts.md#dispatcher-admission).
20
+
12
21
  ## Choose the execution environment
13
22
 
14
23
  Keep the default `git-worktree` provider unless the maintainer explicitly opts
@@ -250,12 +259,13 @@ sources agree with the running system by construction:
250
259
  **running dispatcher's version** (read from the installed distribution's
251
260
  `package.json`), so the guest runs the dispatcher's own release.
252
261
 
253
- A service accepts stable and prerelease clients from its own `major.minor`
254
- release line and the two preceding minor lines in the same major. A major starts a new family:
255
- X.0 accepts only X.0, X.1 accepts X.0/X.1, and X.2 onward accepts three lines.
256
- Patch versions are interchangeable in both directions and must never change
257
- the protocol. Keep project clients within the instance’s published window. Supported release lines retain their wire handlers and known
258
- protocol identities; an unknown protocol is refused independently of version.
262
+ A published release line stays supported by a service until both at least two newer minor lines have been published and 90 days have passed since the first release of the line that superseded it. The rule spans majors: a new major keeps supporting earlier lines on the same terms. The policy floor is 1.2: lines before 1.2 are refused regardless of publication dates because their clients rebuild server state from the journal. Lines newer than the service stay unsupported (service first). Supported means the published clients of that line can use the service’s retained protocol handlers and read its reduced answers in the shapes their released clients accept.
263
+
264
+ Stable patches never reset a line’s first-publication date. Only actually published
265
+ lines at or below the service line count; prereleases do not start retirement clocks.
266
+ Publication facts survive removal of retired identities, contracts, and handlers.
267
+ Patch releases must retain their line’s protocol identity. Unknown historical
268
+ protocol identities are refused independently of the numeric window.
259
269
  Stable and prerelease service and client identities share their numeric major/minor
260
270
  line. Malformed or missing identities, build metadata (`+…`), prefixes and
261
271
  whitespace are refused with HTTP 409.
@@ -266,8 +276,9 @@ and supported range.
266
276
  Unauthenticated `GET /health` publishes `ok`, `autobuildVersion`,
267
277
  `protocolVersion`, and `supportedClientRange: { minVersion, maxVersionExclusive }`.
268
278
  Range endpoints remain stable versions. The range is inclusive at the minimum
269
- and exclusive at the maximum; a 0.11.x
270
- service publishes `>=0.9.0 <0.12.0`. Health needs no credentials, version
279
+ and exclusive at the maximum; a 1.3.x
280
+ service publishes `>=1.2.0 <1.4.0` until later publication facts permit retirement.
281
+ The service reads the clock for each decision, so retirement needs no redeploy. Health needs no credentials, version
271
282
  headers, or available backend.
272
283
 
273
284
  `ab upgrade` probes this public range before installation or project changes.
@@ -507,3 +518,21 @@ change local files or configuration. Failed cleanup is retryable with access
507
518
  already refused. Reconnecting requires fresh browser approval and starts empty,
508
519
  with hosted ticket numbering reset to 1. See
509
520
  [permanent project deletion](operator-api.md#permanent-project-deletion).
521
+
522
+ ## Hosted dispatch and local viewing
523
+
524
+ A plain `ab dispatch` reads dispatch placement once before starting local execution.
525
+ For a hosted project it opens the Store-only viewer automatically, displaying
526
+ `viewer · dispatched by <host>` from the placement origin (including a nondefault
527
+ port). `--once`, `--plain`, and `--interval` retain their viewer meanings.
528
+ `--takeover` explicitly dispatches locally, with a warning that it can displace
529
+ the hosted dispatcher; it cannot be combined with `--viewer`. Startup intake
530
+ flags require `--takeover` when placement selects viewer.
531
+
532
+ An unreadable placement fails closed with a typed error naming the cause:
533
+ use `--viewer` to watch or `--takeover` to dispatch locally. Both explicit modes
534
+ skip placement discovery. Older services without the capability and projects
535
+ with unknown or nonhosted placement retain local dispatch behavior. Local stores
536
+ need no placement request. Origin mode (`--repository` or `AB_REPOSITORY`) and
537
+ hosted cron dispatch bypass this check. Placement is a startup snapshot, not a
538
+ liveness probe or a polling input.
package/docs/skills.md CHANGED
@@ -12,7 +12,7 @@ Skills guide the agents that plan, implement, review and operate Autobuild, one
12
12
 
13
13
  ## Strong defaults, yours to edit
14
14
 
15
- `ab init` installs the shipped skills as repository files under `.agents/skills/ab-<name>/`: a `SKILL.md` plus optional references or scripts. For example, tell `.agents/skills/ab-implement/SKILL.md` to use the shared database adapter, follow the existing error vocabulary and run the project's integration checks.
15
+ `ab init` installs the shipped skills as repository files under `.agents/skills/ab-<name>/`: a `SKILL.md` plus optional references or scripts. For example, tell `.agents/skills/ab-implement/SKILL.md` to use the shared database adapter, follow the existing error vocabulary and run the project's codegen before committing.
16
16
 
17
17
  - Change how agents work, not the lifecycle's gates. Keep each skill's typed CLI contract: context, notes deposit and completion command.
18
18
  - Commit edits so every agent shares them.
@@ -61,15 +61,16 @@ plan review, code review, the repository's full verify suite, finalize,
61
61
  merge, and a restack for everything queued behind it. Ten small tickets pay
62
62
  that cost ten times, and a blocker chain pays it in series. Prefer fewer,
63
63
  larger tickets: one ticket per coherent change, as large as one plan and one
64
- review pass can hold without the quality bar slipping.
64
+ review pass can hold without the quality bar slipping, and no larger than one
65
+ implement session can finish.
65
66
 
66
67
  A ticket is the right size when its acceptance criteria describe one feature
67
68
  or fix a reviewer can judge in a single pass, one plan can cover it without
68
69
  deferring a design decision to a later build, and its out-of-scope list is
69
70
  short and obvious. It is too big when its criteria fall into groups that share
70
- no behavior, when part of it waits on a decision nobody has made, or when its
71
+ no behavior, when part of it waits on a decision nobody has made, when its
71
72
  parts need different merge — one can ship now while another needs consent
72
- or must wait.
73
+ or must wait — or when implementing it would outgrow one session.
73
74
 
74
75
  Do not split:
75
76
 
@@ -80,6 +81,39 @@ Do not split:
80
81
  - to make progress visible, or because the spec got long. A long spec with
81
82
  clear criteria is fine.
82
83
 
84
+ ### Fit one implement session
85
+
86
+ Larger stops paying off where the work outgrows one agent session. The first
87
+ implement round is a single session, and everything it does stays in that
88
+ session's context: the spec and plan, every file it reads, every edit, every
89
+ test and check run and its output, and every debugging detour. A ticket that
90
+ fills the implementer's context window — commonly a million tokens or less —
91
+ degrades mid-build: the harness compacts away the reasoning that held the
92
+ change together, or an operator has to clear context and restart by hand.
93
+ Size each ticket to finish well inside one window, with headroom for
94
+ debugging.
95
+
96
+ Nothing measures this at grooming time, so estimate from what the
97
+ implementer must do, not from how long the spec is:
98
+
99
+ - **Reading.** Count the code it must understand before it can edit safely.
100
+ Several unfamiliar subsystems, each read end to end, cost more than the
101
+ diff itself.
102
+ - **Edit sites.** Count files touched, not lines changed. A rename or
103
+ signature change threaded through dozens of callers spends context on
104
+ every one, however mechanical.
105
+ - **Iteration.** Count the separate behaviors that each need their own
106
+ tests, failures, and fixes, and the slow or verbose loops — full suites,
107
+ UI captures, migrations — the session will repeat.
108
+ - **Your own reading.** If writing the spec meant reading most of several
109
+ subsystems, the implementer reads them again, then writes the code and
110
+ tests on top.
111
+
112
+ Most tickets sit far below this ceiling; it is a limit, not a target. A
113
+ ticket that touches one subsystem and a handful of files needs no estimate.
114
+ When the signals put a ticket near the ceiling, split it at a seam (below)
115
+ rather than gamble on the build fitting.
116
+
83
117
  ### Cut along seams
84
118
 
85
119
  A seam decides where to cut once a split is justified; it is not a reason to
@@ -9,6 +9,15 @@ description: "Diagnose configuration, idle dispatch, authentication, stalled bui
9
9
 
10
10
  Start from the symptom and recorded state. Your operator agent inspects the CLI and suggests fixes; you manage dispatcher processes and credentials.
11
11
 
12
+ Local dispatch checks selected primary and alternate account credentials before
13
+ taking the repository lease. Supply the configured environment slot or a local
14
+ ChatGPT login (`bun ab accounts login NAME --local`). Hosted account absence
15
+ appears once in repository attention: set `bun ab secrets set VARIABLE`, or
16
+ renew with `bun ab accounts login NAME --project`. The next tick resumes without
17
+ per-build retries or infrastructure-attempt consumption. Unused accounts do not
18
+ block startup; present rejected credentials keep their rejection attention.
19
+ See [account admission and remedies](accounts.md#dispatcher-admission).
20
+
12
21
  ## Invalid configuration
13
22
 
14
23
  **Symptom.** Startup reports a TOML syntax error, invalid config with field paths, or a runtime-routing error naming a role.
@@ -113,7 +113,7 @@ Sandbox preparation order:
113
113
  - **Runtimes.** Every primary and alternate runtime needs a pinned install and exact-version preflight, and gets only the credentials named in `environmentVariables`, except declared [accounts](configuration-overview.md#accounts), whose credentials remain on the host and are brokered by egress policy using guest placeholders.
114
114
  - **Repetition.** New sandboxes repeat provisioning and preflights rerun before each build-runner; keep setup idempotent.
115
115
  - **Validation.** `bun ab init --validate` runs named provisioning, setup, runtime and Store checks in a disposable environment, deletes it even on failure, and starts no build. For every declared account, including unused accounts, it runs a tool-free model probe through the account's runtime (Claude Code for Claude/Kimi, Codex for ChatGPT); these probes create no ordinary build phase or persistent agent session. Hosted ChatGPT project secrets report readiness from write-only status metadata instead; the first hosted build is the live check.
116
- - **Lifetime.** `timeoutSeconds` bounds a sandbox; provider operations have their own timeouts. An intact sandbox resumes; an expired or lost one is rebuilt from durable workspace and publication evidence, losing unpublished work that lived only on it.
116
+ - **Lifetime.** `timeoutSeconds` bounds a sandbox; provider operations have their own timeouts. An intact sandbox resumes. Before replacement, the dispatcher fences it, preserves reachable unpublished commits to build-private refs, and records a receipt; the next workspace restores those commits. Loss is limited to already absent or unrecoverable work and uncommitted files; known loss appears in the next session's recovery context. See the [workspace recovery contract](architecture.md#key-boundaries).
117
117
 
118
118
  ### Private repositories
119
119
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defrex/autobuild",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Agent-driven software delivery from groomed ticket to merged PR",
5
5
  "repository": {
6
6
  "type": "git",
@@ -156,8 +156,8 @@
156
156
  },
157
157
  "devDependencies": {
158
158
  "@biomejs/biome": "2.5.5",
159
- "@defrex/autobuild-postgres-store": "1.3.0",
160
- "@defrex/autobuild-vercel-sandbox": "1.3.0",
159
+ "@defrex/autobuild-postgres-store": "1.4.0",
160
+ "@defrex/autobuild-vercel-sandbox": "1.4.0",
161
161
  "@resvg/resvg-js": "2.6.2",
162
162
  "@types/bun": "^1.3.14",
163
163
  "@types/node": "^24.0.0",
@@ -165,6 +165,7 @@
165
165
  "dejavu-fonts-ttf": "2.37.0",
166
166
  "drizzle-kit": "^0.31.10",
167
167
  "git-format-staged": "4.0.1",
168
+ "happy-dom": "^21.0.4",
168
169
  "husky": "9.1.7",
169
170
  "typescript": "5.9.3"
170
171
  }
@@ -0,0 +1,96 @@
1
+ import { accountRemedy, type Accounts, type SelectedAccount } from '../config/accounts'
2
+ import type { RepositoryReadFacts } from '../store/reduced-reads'
3
+ import type { RepositoryEventWrite } from '../events/repository'
4
+ import { DISPATCHER } from '../events/envelope'
5
+
6
+ export interface MissingAccountCredential extends SelectedAccount {
7
+ source: 'environment' | 'project-secrets'
8
+ remedy: string
9
+ }
10
+
11
+ /** Presence only: no provider calls, token validation, or secret values in diagnostics. */
12
+ export function missingAccountCredentials(
13
+ accounts: Accounts,
14
+ env: Readonly<Record<string, string | undefined>>,
15
+ source: MissingAccountCredential['source'] = 'environment',
16
+ workspaceProvider = 'vercel-sandbox',
17
+ ): MissingAccountCredential[] {
18
+ return Object.entries(accounts)
19
+ .sort(([a], [b]) => a.localeCompare(b))
20
+ .filter(
21
+ ([, descriptor]) =>
22
+ !env[descriptor.credentialEnv] &&
23
+ !(
24
+ source === 'environment' &&
25
+ workspaceProvider !== 'vercel-sandbox' &&
26
+ descriptor.kind === 'claude-subscription'
27
+ ),
28
+ )
29
+ .map(([name, descriptor]) => ({
30
+ name,
31
+ descriptor,
32
+ source,
33
+ remedy:
34
+ source === 'environment'
35
+ ? accountRemedy({ name, descriptor })
36
+ : `account ${JSON.stringify(name)} (${descriptor.credentialEnv}): set the project secret with ab secrets set ${descriptor.credentialEnv}` +
37
+ (descriptor.kind === 'chatgpt-subscription'
38
+ ? ` or renew with ab accounts login ${JSON.stringify(name)} --project`
39
+ : ''),
40
+ }))
41
+ }
42
+ export function formatMissingAccountCredentials(
43
+ missing: readonly MissingAccountCredential[],
44
+ ): string {
45
+ return `Missing credentials: ${missing.map((account) => `${account.remedy} [${account.source}]`).join('; ')}`
46
+ }
47
+ export class MissingAccountCredentialsError extends Error {
48
+ constructor(readonly missing: MissingAccountCredential[]) {
49
+ super(formatMissingAccountCredentials(missing))
50
+ this.name = 'MissingAccountCredentialsError'
51
+ }
52
+ }
53
+
54
+ /** Reconcile against the canonical reduced value, shared by all launches in a tick. */
55
+ export async function reconcileMissingAccounts(
56
+ missing: readonly MissingAccountCredential[],
57
+ current: RepositoryReadFacts['missingAccounts'],
58
+ append: (event: RepositoryEventWrite) => Promise<unknown>,
59
+ ): Promise<void> {
60
+ const next = new Map(missing.map((account) => [account.name, account]))
61
+ for (const [name] of Object.entries(current))
62
+ if (!next.has(name))
63
+ await append({ actor: DISPATCHER, type: 'account.credentials-recovered', payload: { name } })
64
+ for (const account of missing)
65
+ if (!sameMissingAccount(current[account.name], account))
66
+ await append({ actor: DISPATCHER, type: 'account.credentials-unavailable', payload: account })
67
+ }
68
+
69
+ function sameMissingAccount(
70
+ left: MissingAccountCredential | undefined,
71
+ right: MissingAccountCredential,
72
+ ): boolean {
73
+ return (
74
+ !!left &&
75
+ left.name === right.name &&
76
+ left.source === right.source &&
77
+ left.remedy === right.remedy &&
78
+ left.descriptor.kind === right.descriptor.kind &&
79
+ left.descriptor.credentialEnv === right.descriptor.credentialEnv &&
80
+ (left.descriptor.kind !== 'kimi-code' ||
81
+ (right.descriptor.kind === 'kimi-code' && left.descriptor.region === right.descriptor.region))
82
+ )
83
+ }
84
+
85
+ /** The project snapshot is authoritative even when empty. Do not borrow service credentials. */
86
+ export function applyProjectAccountSnapshot(
87
+ accounts: Accounts,
88
+ env: Record<string, string | undefined>,
89
+ snapshot: Readonly<Record<string, string>>,
90
+ ) {
91
+ for (const descriptor of Object.values(accounts)) {
92
+ delete env[descriptor.credentialEnv]
93
+ if (snapshot[descriptor.credentialEnv])
94
+ env[descriptor.credentialEnv] = snapshot[descriptor.credentialEnv]
95
+ }
96
+ }
@@ -8,6 +8,7 @@ import type { ChatGPTState } from './chatgpt-state'
8
8
  * written before HTTP, and uncertain completion is terminal for that generation. */
9
9
  export class LocalAccountOwner {
10
10
  readonly id = randomUUID()
11
+ readonly injected = new Map<string, string>()
11
12
  constructor(
12
13
  readonly credentials: LocalCredentials,
13
14
  private readonly refresh = refreshChatGPT,
@@ -106,18 +107,64 @@ export async function renewLocalAccounts(
106
107
  if (descriptor.kind !== 'chatgpt-subscription') continue
107
108
  try {
108
109
  const record = owner.credentials.load(name)
109
- if (!record || record.status === 'failed') {
110
- delete env[descriptor.credentialEnv]
110
+ if (!record) {
111
+ if (owner.injected.get(descriptor.credentialEnv) === env[descriptor.credentialEnv])
112
+ delete env[descriptor.credentialEnv]
113
+ owner.injected.delete(descriptor.credentialEnv)
111
114
  continue
112
115
  }
116
+ if (
117
+ record.status === 'failed' ||
118
+ JSON.stringify(record.descriptor) !== JSON.stringify(descriptor)
119
+ )
120
+ throw new Error('ChatGPT account failed or descriptor changed; sign in again')
113
121
  owner.claim(name)
114
122
  claimed.add(name)
115
123
  // Only expose a still-valid access value during the rotating HTTP call.
116
124
  if (record.state.expiresAt > now) env[descriptor.credentialEnv] = record.state.accessToken
117
125
  else delete env[descriptor.credentialEnv]
118
126
  Object.assign(env, await owner.tick({ [name]: descriptor }, now))
127
+ owner.injected.set(descriptor.credentialEnv, env[descriptor.credentialEnv]!)
119
128
  } catch {
120
129
  delete env[descriptor.credentialEnv]
121
130
  }
122
131
  }
123
132
  }
133
+
134
+ /** Inspect transferability without claiming ownership or consuming refresh state.
135
+ * Startup may allow a live peer solely for the pre-lease presence check; actual
136
+ * resolution must still claim after acquiring the repository lease.
137
+ */
138
+ export function inspectLocalAccountEnvironment(
139
+ credentials: LocalCredentials,
140
+ accounts: Accounts,
141
+ env: Readonly<Record<string, string | undefined>>,
142
+ predecessorPid?: number,
143
+ allowLivePeer = false,
144
+ ): Record<string, string | undefined> {
145
+ const available = { ...env }
146
+ for (const [name, descriptor] of Object.entries(accounts)) {
147
+ if (descriptor.kind !== 'chatgpt-subscription') continue
148
+ try {
149
+ const record = credentials.load(name)
150
+ if (!record) continue
151
+ const ownerAvailable =
152
+ allowLivePeer ||
153
+ !record.owner ||
154
+ ownerProcessEnded(record.ownerPid) ||
155
+ (predecessorPid !== undefined && record.ownerPid === predecessorPid)
156
+ if (
157
+ record.status === 'ready' &&
158
+ (record.state.expiresAt > Date.now() ||
159
+ Date.now() >= (record.state.earliestRefreshAt ?? 0)) &&
160
+ ownerAvailable &&
161
+ JSON.stringify(record.descriptor) === JSON.stringify(descriptor)
162
+ )
163
+ available[descriptor.credentialEnv] = 'local-refreshing-source'
164
+ else delete available[descriptor.credentialEnv]
165
+ } catch {
166
+ delete available[descriptor.credentialEnv]
167
+ }
168
+ }
169
+ return available
170
+ }
@@ -41,6 +41,7 @@ export function mergeDecisionFromFacts(
41
41
  export function buildNeedsAttention(events: AbEvent[], state: BuildState): boolean {
42
42
  return (
43
43
  state.janitor?.attention === true ||
44
+ !!state.targetRewrite ||
44
45
  (state.compatibility?.decisiveFacts ?? 0) > 0 ||
45
46
  (state.openEscalations?.length ?? 0) > 0 ||
46
47
  mergeDecision(events, new Date(0), state) !== null
@@ -53,6 +54,7 @@ export function mergeIdentity(slug: string, pr: number): string {
53
54
 
54
55
  export function repositoryNeedsAttention(event: RepositoryEvent): boolean {
55
56
  switch (event.type) {
57
+ case 'account.credentials-unavailable':
56
58
  case 'harvest.escalated':
57
59
  case 'harvest.recovery-exhausted':
58
60
  case 'dispatcher.forge-readiness-failed':
@@ -1,3 +1,5 @@
1
+ import { selectDispatchMode } from './dispatch-mode'
2
+ import { spawnExec } from '../ports/workspace/git-worktree'
1
3
  import { join } from 'node:path'
2
4
  import type { DashboardRendererResolver } from './dashboard/render'
3
5
  import { loadDotEnv } from './dotenv'
@@ -27,7 +29,21 @@ export async function runBinary(
27
29
  ) {
28
30
  try {
29
31
  const args = parseDispatchArgs(argv.slice(1), process.env)
30
- if (!args.once && !args.repository) return await launchDispatcher(argv)
32
+ if (!args.viewer && !args.once && !args.repository) {
33
+ const mode = await selectDispatchMode({
34
+ ...args,
35
+ targetRepo: process.cwd(),
36
+ env: process.env,
37
+ exec: spawnExec,
38
+ stderr: console.error,
39
+ })
40
+ if (!mode.viewer) return await launchDispatcher(argv)
41
+ const { runDirectBinary } = await import('./binary-direct')
42
+ return runDirectBinary(
43
+ [...argv, '--viewer', '--dispatched-by', mode.dispatchedBy!],
44
+ resolver,
45
+ )
46
+ }
31
47
  } catch (error) {
32
48
  console.error(error instanceof Error ? error.message : String(error))
33
49
  return 1
@@ -71,6 +71,7 @@ export type MaterializedEntry = ArtifactRef | 'derived'
71
71
  * commands validate with, so skills are self-checking.
72
72
  */
73
73
  export interface ContextManifest {
74
+ workspaceRecovery?: string
74
75
  compatibility?: import('../events/compatibility').CompatibilityState
75
76
  compatibilityDiagnostic?: string
76
77
  build: string
@@ -295,6 +296,67 @@ export async function buildContext(deps: ContextDeps): Promise<ContextManifest>
295
296
  materialized,
296
297
  }
297
298
 
299
+ // A receipt belongs to the next session, including repeated hydration. The
300
+ // preceding session start bounds that window without consuming notes on read.
301
+ const [earlier, latest] =
302
+ events.sessionStarts.length === 2 ? events.sessionStarts : [undefined, events.sessionStarts[0]]
303
+ const previousSession = (latest?.session === env.session ? earlier?.seq : latest?.seq) ?? 0
304
+ const loss =
305
+ events.workspaceLoss && events.workspaceLoss.seq > previousSession
306
+ ? events.workspaceLoss.payload
307
+ : undefined
308
+ const checkpoint = events.workspacePreservation
309
+ const preserved =
310
+ checkpoint && checkpoint.seq > previousSession && checkpoint.payload.heads.length
311
+ ? checkpoint.payload
312
+ : undefined
313
+ const recoveries = Object.values(events.candidateRecoveries).filter(
314
+ (recovery) =>
315
+ recovery && (events.candidateRecoverySeqs[recovery.operation] ?? 0) > previousSession,
316
+ )
317
+ const legacyRequest = events.publication.latestUncompletedRequest()
318
+ if (
319
+ loss ||
320
+ preserved ||
321
+ recoveries.length ||
322
+ (legacyRequest && events.publication.lostRecorded(legacyRequest))
323
+ ) {
324
+ const lines = ['# Workspace commit recovery', '']
325
+ if (preserved) {
326
+ lines.push(`Preserved from ${preserved.ref}, ${preserved.phase}@${preserved.round}:`)
327
+ for (const head of preserved.heads)
328
+ lines.push(
329
+ `- ${head.role}: ${head.sha} (${head.remoteRef}); commits: ${head.commits.join(', ')}`,
330
+ )
331
+ lines.push(
332
+ 'Replacement provisioning restores these exact refs before starting a session.',
333
+ '',
334
+ )
335
+ }
336
+ if (loss)
337
+ lines.push(
338
+ `Source workspace ${loss.ref}, ${loss.phase}@${loss.round}: ${loss.reason}`,
339
+ `Known lost candidates: ${loss.shas.join(', ') || '(no SHA inventory was observable)'}. Additional unpublished SHAs are unavailable.`,
340
+ '',
341
+ )
342
+ for (const recovery of recoveries) {
343
+ if (!recovery) continue
344
+ lines.push(
345
+ `${recovery.operation} candidate ${recovery.sha} was confirmed unavailable. Reconstruct its producer result under retained intent ${recovery.replacementId}; do not search for the retired candidate.`,
346
+ '',
347
+ )
348
+ }
349
+ const legacy = events.publication.latestUncompletedRequest()
350
+ if (!loss && legacy && events.publication.lostRecorded(legacy))
351
+ lines.push(
352
+ `Historical publication loss names ${legacy.payload.sha} (${legacy.payload.operation}). Availability must be checked before treating it as irrecoverable.`,
353
+ )
354
+ manifest.workspaceRecovery = await writeDerived(
355
+ 'workspace-recovery.md',
356
+ `${lines.join('\n')}\n`,
357
+ )
358
+ }
359
+
298
360
  if (inputs.ticket === true) {
299
361
  const created = events.created
300
362
  if (created !== undefined && created.type === 'build.created') {
@@ -1,3 +1,4 @@
1
+ import { repositoryReadFactsReducer } from '../../kernel/read-facts'
1
2
  import { workTargetDistance } from './target-distance'
2
3
  import { migrationIdentity, ticketMigrationsReducer } from '../../kernel/ticket-migrations'
3
4
  import { projectRollback, type DashboardRollback } from './rollback'
@@ -313,6 +314,7 @@ export interface DashboardCounter {
313
314
  }
314
315
 
315
316
  export interface DashboardModel {
317
+ viewer?: { dispatchedBy?: string }
316
318
  rollback?: DashboardRollback
317
319
  handoffs?: DashboardHandoff[]
318
320
  repo: string
@@ -1350,6 +1352,15 @@ export function buildDashboardFromProjected(
1350
1352
  const builds = enrichIntegrationRows(
1351
1353
  projectedBuilds.map((row) => enrichDrainingRow(row, upgrade.draining)),
1352
1354
  ).sort((a, b) => a.slug.localeCompare(b.slug))
1355
+ const missingAccounts = Array.isArray(repositoryEvents)
1356
+ ? repositoryReadFactsReducer.reduce(repositoryEvents).missingAccounts
1357
+ : repositoryEvents.missingAccounts
1358
+ const warningLines = [
1359
+ ...(header.warningLines ?? []),
1360
+ ...Object.values(missingAccounts).map(
1361
+ (account) => `Missing credentials: ${account.remedy} [${account.source}]`,
1362
+ ),
1363
+ ]
1353
1364
  const harvestProjection = projectRepositoryHarvest(repositoryEvents)
1354
1365
  const settings = Array.isArray(repositoryEvents)
1355
1366
  ? reduceDispatchSettings(repositoryEvents)
@@ -1372,9 +1383,7 @@ export function buildDashboardFromProjected(
1372
1383
  ...(header.selection !== undefined ? { selection: header.selection } : {}),
1373
1384
  ...(header.standby !== undefined ? { standby: header.standby } : {}),
1374
1385
  ...(header.availableUpgrade !== undefined ? { availableUpgrade: header.availableUpgrade } : {}),
1375
- ...(header.warningLines !== undefined && header.warningLines.length > 0
1376
- ? { warningLines: header.warningLines }
1377
- : {}),
1386
+ ...(warningLines.length > 0 ? { warningLines } : {}),
1378
1387
  ...(header.resumeInput !== undefined ? { resumeInput: header.resumeInput } : {}),
1379
1388
  builds,
1380
1389
  ...(harvestProjection.harvest !== undefined ? { harvest: harvestProjection.harvest } : {}),
@@ -14,8 +14,20 @@ import {
14
14
  parseBuildConfigMetadata,
15
15
  parseEffectiveBuildConfig,
16
16
  } from '../../processes/build-execution-state'
17
- import type { Artifact, BuildRecord, StreamRecord, StreamScope } from '../../store/types'
18
- import { projectBuild, type DashboardBuild } from './model'
17
+ import type {
18
+ Artifact,
19
+ BuildRecord,
20
+ BuildStore,
21
+ StreamRecord,
22
+ StreamScope,
23
+ } from '../../store/types'
24
+ import { readBuildFacts } from '../../store/reduced-reads'
25
+ import {
26
+ projectBuild,
27
+ projectBuildFromFacts,
28
+ type DashboardBuild,
29
+ type DashboardRowFacts,
30
+ } from './model'
19
31
 
20
32
  /** The read-only BuildStore surface needed to construct dashboard build rows.
21
33
  * `listStreams` is optional: when present, build-scope records enrich each
@@ -24,6 +36,7 @@ import { projectBuild, type DashboardBuild } from './model'
24
36
  * metadata decorates each row with its pinned pipeline source and revision
25
37
  * (SPEC §16.1). */
26
38
  export interface DashboardBuildReader {
39
+ getReducerValue?: BuildStore['getReducerValue']
27
40
  listBuildsForRepo(repo: string): Promise<BuildRecord[]>
28
41
  getEvents(slug: string, sinceSeq?: number): Promise<AbEvent[]>
29
42
  listStreams?(scope: StreamScope): Promise<StreamRecord[]>
@@ -61,7 +74,17 @@ interface TerminalEntry {
61
74
  record: BuildRecord
62
75
  }
63
76
 
64
- type PollEntry = LiveEntry | TerminalEntry
77
+ interface ReducedEntry {
78
+ kind: 'reduced'
79
+ cursor: number
80
+ record: BuildRecord
81
+ state: BuildState
82
+ workspace: boolean
83
+ provisioning: boolean
84
+ build: DashboardBuild | null
85
+ }
86
+
87
+ type PollEntry = LiveEntry | TerminalEntry | ReducedEntry
65
88
 
66
89
  function isTerminal(state: BuildState): boolean {
67
90
  // `build.aborted` acknowledges cancellation but begins the checkpointed
@@ -93,8 +116,9 @@ function validateDelta(slug: string, sinceSeq: number, events: AbEvent[]): void
93
116
  * Process-local, display-only acceleration for the interactive dispatch frame.
94
117
  *
95
118
  * Every refresh still discovers records with `listBuildsForRepo(repo)`. A first-seen
96
- * stream is hydrated from seq 0; a cached dashboard-visible stream is read only
97
- * after its reduced `lastSeq`. Empty deltas preserve the exact reduction and
119
+ * stream uses persisted build facts when available, with no event reads; local
120
+ * readers without reduced values hydrate from seq 0, then read only after their
121
+ * reduced `lastSeq`. Empty deltas preserve the exact reduction and
98
122
  * projected row, so phase timing is not recomputed. Only fully completed
99
123
  * streams compact to tombstones; acknowledged aborts remain live through their
100
124
  * cleanup checkpoints and final completion.
@@ -179,6 +203,7 @@ export class DashboardBuildPollCache {
179
203
  state: BuildState,
180
204
  events: AbEvent[],
181
205
  config: Config,
206
+ facts?: DashboardRowFacts,
182
207
  ): Promise<DashboardBuild | null> {
183
208
  const [streams, artifact] = await Promise.all([
184
209
  this.readStreams(record.slug),
@@ -186,7 +211,9 @@ export class DashboardBuildPollCache {
186
211
  ])
187
212
  const pinnedConfig =
188
213
  artifact?.config !== undefined ? composeBuildConfig(artifact.config, config) : undefined
189
- const build = projectBuild(record, state, config, events, streams, pinnedConfig)
214
+ const build = facts
215
+ ? projectBuildFromFacts(record, state, facts, config, streams, pinnedConfig)
216
+ : projectBuild(record, state, config, events, streams, pinnedConfig)
190
217
  if (build !== null && artifact !== undefined) {
191
218
  if (artifact.revision !== undefined) build.effectiveConfigRev = artifact.revision
192
219
  if (artifact.pipelineSource !== undefined) build.pipelineSource = artifact.pipelineSource
@@ -225,6 +252,35 @@ export class DashboardBuildPollCache {
225
252
  continue
226
253
  }
227
254
 
255
+ if (this.reader.getReducerValue !== undefined) {
256
+ const { cursor, value } = await readBuildFacts(
257
+ { getReducerValue: this.reader.getReducerValue.bind(this.reader) },
258
+ record.slug,
259
+ )
260
+ if (isTerminal(value.state)) {
261
+ next.set(record.slug, { kind: 'terminal', record })
262
+ } else {
263
+ next.set(record.slug, {
264
+ kind: 'reduced',
265
+ cursor,
266
+ record,
267
+ state: value.state,
268
+ workspace: value.workspace !== null,
269
+ provisioning: value.provisionMarker !== undefined,
270
+ build:
271
+ current?.kind === 'reduced' &&
272
+ current.cursor === cursor &&
273
+ !fullEnrichment &&
274
+ !configChanged &&
275
+ current.build?.ticketId === record.ticket?.id
276
+ ? current.build
277
+ : await this.projectRow(record, value.state, [], config, value),
278
+ })
279
+ }
280
+ continue
281
+ }
282
+ if (current?.kind === 'reduced') throw new Error('dashboard reader lost reduced values')
283
+
228
284
  const sinceSeq = current?.state.lastSeq ?? 0
229
285
  const delta = await this.reader.getEvents(record.slug, sinceSeq)
230
286
  validateDelta(record.slug, sinceSeq, delta)
@@ -288,8 +344,9 @@ export class DashboardBuildPollCache {
288
344
  capacityBuilds.push({
289
345
  record: entry.record,
290
346
  state: entry.state,
291
- workspace: entry.workspace.open !== null,
292
- provisioning: entry.provisionMarker.marker !== null,
347
+ workspace: entry.kind === 'reduced' ? entry.workspace : entry.workspace.open !== null,
348
+ provisioning:
349
+ entry.kind === 'reduced' ? entry.provisioning : entry.provisionMarker.marker !== null,
293
350
  })
294
351
  states.set(slug, entry.state)
295
352
  if (entry.build !== null) builds.push(entry.build)