agent-dealer 1.4.4 → 1.4.6

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 (70) hide show
  1. package/bundle/server/dist/adapters/github.js +233 -3
  2. package/bundle/server/dist/adapters/github.test.js +177 -1
  3. package/bundle/server/dist/adapters/muse-capability.js +81 -8
  4. package/bundle/server/dist/adapters/muse-capability.test.js +89 -1
  5. package/bundle/server/dist/coordinator/commands.js +2 -1
  6. package/bundle/server/dist/coordinator/developer-effect.js +11 -1
  7. package/bundle/server/dist/coordinator/developer-effect.test.js +26 -1
  8. package/bundle/server/dist/coordinator/failure-reason.js +3 -0
  9. package/bundle/server/dist/coordinator/merge-conflict-sync.js +5 -1
  10. package/bundle/server/dist/coordinator/routing.js +5 -0
  11. package/bundle/server/dist/coordinator/routing.test.js +32 -0
  12. package/bundle/server/package.json +2 -2
  13. package/bundle/server/static-ui/assets/index-2IuALSbV.js +64 -0
  14. package/bundle/server/static-ui/assets/index-MgimDoh2.css +1 -0
  15. package/bundle/server/static-ui/index.html +2 -2
  16. package/bundle/shared/package.json +1 -1
  17. package/dist/bin.js +0 -0
  18. package/package.json +2 -3
  19. package/bundle/server/dist/adapters/authority-lifecycle.js +0 -289
  20. package/bundle/server/dist/adapters/execution-authority.js +0 -103
  21. package/bundle/server/dist/adapters/execution-authority.test.js +0 -166
  22. package/bundle/server/dist/adapters/external.js +0 -20
  23. package/bundle/server/dist/coordinator/authority-recovery.integration.test.js +0 -661
  24. package/bundle/server/dist/coordinator/dispatcher.js +0 -58
  25. package/bundle/server/dist/coordinator/dispatcher.test.js +0 -81
  26. package/bundle/server/dist/coordinator/intent-forecast.js +0 -13
  27. package/bundle/server/dist/coordinator/intent-forecast.test.js +0 -34
  28. package/bundle/server/dist/coordinator/session-lifecycle.integration.test.js +0 -127
  29. package/bundle/server/dist/coordinator/session-lifecycle.js +0 -280
  30. package/bundle/server/dist/coordinator/session-lifecycle.test.js +0 -121
  31. package/bundle/server/dist/db/authority-attempts-stale-at-migration.test.js +0 -65
  32. package/bundle/server/dist/intake/agent-routing.js +0 -32
  33. package/bundle/server/dist/queue/answers.test.js +0 -117
  34. package/bundle/server/dist/queue/dispatcher-recovery.test.js +0 -37
  35. package/bundle/server/dist/queue/dispatcher.js +0 -597
  36. package/bundle/server/dist/queue/plan-delegation.js +0 -27
  37. package/bundle/server/dist/queue/plan-delegation.test.js +0 -61
  38. package/bundle/server/dist/queue/plan-gate.test.js +0 -55
  39. package/bundle/server/dist/queue/result-qa.js +0 -66
  40. package/bundle/server/dist/queue/result-qa.test.js +0 -146
  41. package/bundle/server/dist/repository/authority-attempts.js +0 -189
  42. package/bundle/server/dist/repository/result-qa.js +0 -37
  43. package/bundle/server/dist/runners/codex-args.js +0 -59
  44. package/bundle/server/dist/runners/codex-args.test.js +0 -72
  45. package/bundle/server/dist/runners/codex-resume.test.js +0 -19
  46. package/bundle/server/dist/runners/codex.js +0 -46
  47. package/bundle/server/dist/runners/muse-code-settings.js +0 -23
  48. package/bundle/server/dist/runners/muse-code-settings.test.js +0 -18
  49. package/bundle/server/dist/runners/persist.js +0 -142
  50. package/bundle/server/dist/runners/qa.js +0 -54
  51. package/bundle/server/dist/runners/run-context.js +0 -183
  52. package/bundle/server/dist/runners/stream-json.test.js +0 -95
  53. package/bundle/server/dist/trace-summary.js +0 -93
  54. package/bundle/server/dist/usage-summary.js +0 -61
  55. package/bundle/server/dist/usage-summary.test.js +0 -33
  56. package/bundle/server/static-ui/assets/index-CHCiztRI.css +0 -1
  57. package/bundle/server/static-ui/assets/index-CrLQFFpw.js +0 -64
  58. package/bundle/server/static-ui/fonts/Monaco.ttf +0 -0
  59. package/bundle/shared/dist/cursor-auth-health.d.ts +0 -12
  60. package/bundle/shared/dist/cursor-auth-health.js +0 -36
  61. package/bundle/shared/dist/cursor-auth-health.test.d.ts +0 -1
  62. package/bundle/shared/dist/cursor-auth-health.test.js +0 -40
  63. package/bundle/shared/dist/plan-triage.d.ts +0 -317
  64. package/bundle/shared/dist/plan-triage.js +0 -65
  65. package/bundle/shared/dist/plan-triage.test.d.ts +0 -1
  66. package/bundle/shared/dist/plan-triage.test.js +0 -66
  67. package/bundle/shared/dist/result-qa.d.ts +0 -45
  68. package/bundle/shared/dist/result-qa.js +0 -25
  69. package/bundle/shared/dist/result-qa.test.d.ts +0 -1
  70. package/bundle/shared/dist/result-qa.test.js +0 -60
@@ -1,661 +0,0 @@
1
- // packages/server/src/coordinator/authority-recovery.integration.test.ts
2
- //
3
- // NOT-91's recovery/idempotency matrix: named acceptance scenarios for the durable
4
- // execution-authority ledger (repository/authority-attempts.ts) and the shared acquire/
5
- // release lifecycle (adapters/authority-lifecycle.ts) it backs. Each test proves one named
6
- // scenario from the ticket and, together, they prove the suite's cross-cutting properties:
7
- // no duplicate human actions, no duplicate provider effects, no leaked authority secrets,
8
- // and no permanently occupied workers.
9
- import { test, before, beforeEach } from "node:test";
10
- import assert from "node:assert/strict";
11
- import fs from "node:fs";
12
- import os from "node:os";
13
- import path from "node:path";
14
- process.env.AGENT_DEALER_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "dealer-authrecovery-"));
15
- process.env.COORDINATOR_FAIL_BACKOFF_MS = "0";
16
- const { migrate, getDb } = await import("../db/index.js");
17
- const { BUILTIN_AGENT_CLAUDE_ID, BUILTIN_AGENT_CURSOR_ID } = await import("@agent-dealer/shared");
18
- const { createIssue, getIssue } = await import("../repository/issues.js");
19
- const { listWorkItemsForIssue, getWorkItem, claimWorkItem } = await import("../repository/work-items.js");
20
- const { createHumanAction, listHumanActionsForIssue } = await import("../repository/human-actions.js");
21
- const { createAuthorityAttempt, activateAuthorityAttempt, getAuthorityAttempt, listOpenAuthorityAttemptsForOwner, markAuthorityAttemptStale, } = await import("../repository/authority-attempts.js");
22
- const { acquireAuthorityForAttempt, reconcileAuthoritiesAtStartup, retryStaleAuthorityAttempts, resolveAcquiringAttempts, } = await import("../adapters/authority-lifecycle.js");
23
- const { startWorkflow, abortIssue, resolveHumanActionAndAdvance } = await import("./commands.js");
24
- const { recoverCoordinator } = await import("./recovery.js");
25
- const { updateAgent } = await import("../repository/agents.js");
26
- const { createRun, addArtifact, transitionRun, updateRunFields, getRun } = await import("../repository/runs.js");
27
- const { approveRunWithDeliver } = await import("../queue/approve-deliver.js");
28
- before(() => {
29
- migrate();
30
- updateAgent(BUILTIN_AGENT_CLAUDE_ID, { workspaceRoot: process.env.AGENT_DEALER_HOME });
31
- });
32
- beforeEach(() => {
33
- getDb().exec("DELETE FROM work_items");
34
- // The periodic-retry tests query listStaleAcquiringAuthorityAttempts() globally (unscoped
35
- // by owner) — a stale_at row left behind by an earlier test in this shared DB would leak
36
- // into that scan and inflate its result.
37
- getDb().exec("DELETE FROM authority_attempts");
38
- });
39
- const DECK = "6e825b59-13de-4ddd-ab7e-55ab5a1c279a";
40
- function newIssue() {
41
- return createIssue({
42
- title: "NOT-91 recovery matrix",
43
- acceptanceCriteria: "It works",
44
- repo: "/repo",
45
- developerAgentId: BUILTIN_AGENT_CLAUDE_ID,
46
- reviewerAgentId: BUILTIN_AGENT_CURSOR_ID,
47
- baseBranch: "main",
48
- maxReviewRounds: 3,
49
- maxInfraAttempts: 3,
50
- source: "manual",
51
- }).id;
52
- }
53
- function mintOk(authoritySecret = "authzs_secret") {
54
- return async (input) => ({
55
- ok: true,
56
- authority: {
57
- authorityId: `authz_${input.idempotencyKey}`,
58
- authoritySecret,
59
- deckId: input.deckId,
60
- audience: "dealer-worker",
61
- allowedServices: [],
62
- allowedTools: [],
63
- expiresAt: "2026-01-01T00:30:00Z",
64
- },
65
- });
66
- }
67
- test("scenario: cancellation revokes an in-flight attempt's execution authority", () => {
68
- const issueId = newIssue();
69
- startWorkflow(issueId);
70
- const item = listWorkItemsForIssue(issueId)[0];
71
- const row = createAuthorityAttempt({
72
- ownerKind: item.kind,
73
- ownerId: `${issueId}:${item.kind}`,
74
- idempotencyKey: `${item.id}:1`,
75
- deckId: DECK,
76
- runId: item.id,
77
- attemptId: `${item.id}:1`,
78
- ttlMs: 60_000,
79
- });
80
- activateAuthorityAttempt(row.id, { authorityId: "authz_cancel", expiresAt: "2099-01-01T00:00:00Z" });
81
- const result = abortIssue(issueId, "tester");
82
- assert.equal(result.ok, true);
83
- // The ledger row is flipped synchronously inside abortIssue's own transaction — no
84
- // permanently-occupied slot, and nothing left live until TTL for a cancelled attempt.
85
- assert.equal(getAuthorityAttempt(row.id).status, "revoked");
86
- });
87
- test("scenario: cancelling an item whose authority attempt is still acquiring never terminalizes it inside the transaction on a guess", () => {
88
- const issueId = newIssue();
89
- startWorkflow(issueId);
90
- const item = listWorkItemsForIssue(issueId)[0];
91
- // No authorityId yet — models a crash between "asked Deck for authority" and "this row
92
- // got activated." abortIssue's own transaction must not assume this is safe to revoke
93
- // directly (there is no authorityId to revoke, and no proof nothing was ever minted) — it
94
- // has to be resolved via its stored idempotencyKey afterward, not bulk-terminalized here
95
- // (NOT-91 review, round 3).
96
- const row = createAuthorityAttempt({
97
- ownerKind: item.kind,
98
- ownerId: `${issueId}:${item.kind}`,
99
- idempotencyKey: `${item.id}:1`,
100
- deckId: DECK,
101
- runId: item.id,
102
- attemptId: `${item.id}:1`,
103
- ttlMs: 60_000,
104
- });
105
- const result = abortIssue(issueId, "tester");
106
- assert.equal(result.ok, true);
107
- // Still `acquiring` immediately after abortIssue returns — the transaction only revoked
108
- // `active` rows synchronously; this one is left for the async, out-of-transaction resolve
109
- // step (fire-and-forget), never flipped to `revoked` on a guess.
110
- assert.equal(getAuthorityAttempt(row.id).status, "acquiring");
111
- });
112
- test("scenario: late approval after cancellation is recorded but cannot restart work", () => {
113
- const issueId = newIssue();
114
- startWorkflow(issueId);
115
- const instance = listWorkItemsForIssue(issueId)[0];
116
- void instance;
117
- // A control-plane park exactly like acquireWorkerAuthority raises on INTERACTION_REQUIRED.
118
- const parked = createHumanAction({
119
- issueId,
120
- actionType: "deck_interaction_required",
121
- reason: "Approve the coordinator enrollment.",
122
- question: "Resume or close?",
123
- responseOptions: [{ choice: "resume" }, { choice: "close" }],
124
- });
125
- // The operator cancels the whole issue before ever looking at the queue...
126
- const aborted = abortIssue(issueId, "tester");
127
- assert.equal(aborted.ok, true);
128
- // ...and the parked action was auto-resolved by the abort itself (commands.ts's
129
- // abortIssue resolves every still-open human action as part of the same transaction).
130
- assert.equal(listHumanActionsForIssue(issueId).find((a) => a.id === parked.id).status, "resolved");
131
- // A late "resume" arriving after that (an operator who had the tab open) must be
132
- // rejected, never silently reopen the now-closed issue or enqueue new work.
133
- const late = resolveHumanActionAndAdvance(parked.id, "operator", "resume");
134
- assert.equal(late.ok, false);
135
- assert.equal(getIssue(issueId).status, "closed");
136
- const items = listWorkItemsForIssue(issueId);
137
- assert.equal(items.length, 1, "the late approval enqueued no additional work item");
138
- assert.equal(items[0].status, "cancelled");
139
- });
140
- test("scenario: duplicate callback/error for the same request id dedupes to one open human action under a race", () => {
141
- const issueId = newIssue();
142
- // Two "concurrent" duplicate INTERACTION_REQUIRED deliveries both call createHumanAction
143
- // directly (skipping the read-then-create check callers normally do first) — proving the
144
- // DB-level ON CONFLICT, not just the read-check, is what prevents the duplicate.
145
- const first = createHumanAction({
146
- issueId,
147
- actionType: "deck_interaction_required",
148
- reason: "Approve the coordinator enrollment.",
149
- question: "Resume or close?",
150
- responseOptions: [{ choice: "resume" }, { choice: "close" }],
151
- requestId: "req_dup_race",
152
- });
153
- const second = createHumanAction({
154
- issueId,
155
- actionType: "deck_interaction_required",
156
- reason: "Approve the coordinator enrollment (repeat delivery).",
157
- question: "Resume or close?",
158
- responseOptions: [{ choice: "resume" }, { choice: "close" }],
159
- requestId: "req_dup_race",
160
- });
161
- assert.equal(second.id, first.id, "the second insert must dedupe onto the first, not create a sibling row");
162
- assert.equal(listHumanActionsForIssue(issueId).filter((a) => a.actionType === "deck_interaction_required" && a.status === "open").length, 1);
163
- });
164
- test("scenario: coordinator restart revokes every attempt a crashed process left open, and only those", async () => {
165
- // A DIFFERENT item IS still leased — a live claim outstanding when the process boots. Its
166
- // authority must be left alone here; recovery.ts's own lease-expiry reclaim is what
167
- // eventually revokes it, not the startup sweep (revoking a live attempt out from under a
168
- // genuinely still-running worker would be the leak this suite exists to prevent). Claimed
169
- // first (while it's the only pending item) so `claimWorkItem`'s oldest-pending pick can't
170
- // grab the "stale" item created below instead.
171
- const liveIssueId = newIssue();
172
- startWorkflow(liveIssueId);
173
- const liveItem = listWorkItemsForIssue(liveIssueId)[0];
174
- claimWorkItem("leaseholder", { leaseMs: 600_000 });
175
- assert.equal(getWorkItem(liveItem.id).status, "leased");
176
- const liveActive = createAuthorityAttempt({
177
- ownerKind: liveItem.kind,
178
- ownerId: `${liveIssueId}:${liveItem.kind}`,
179
- idempotencyKey: `${liveItem.id}:1`,
180
- deckId: DECK,
181
- runId: liveItem.id,
182
- attemptId: `${liveItem.id}:1`,
183
- ttlMs: 60_000,
184
- });
185
- activateAuthorityAttempt(liveActive.id, { authorityId: "authz_live", expiresAt: "2099-01-01T00:00:00Z" });
186
- // Item is `pending`, not `leased` — simulates "the coordinator crashed before this
187
- // attempt's worker was ever claimed/spawned."
188
- const staleIssueId = newIssue();
189
- startWorkflow(staleIssueId);
190
- const staleItem = listWorkItemsForIssue(staleIssueId)[0];
191
- assert.equal(getWorkItem(staleItem.id).status, "pending");
192
- const staleActive = createAuthorityAttempt({
193
- ownerKind: staleItem.kind,
194
- ownerId: `${staleIssueId}:${staleItem.kind}`,
195
- idempotencyKey: `${staleItem.id}:1`,
196
- deckId: DECK,
197
- runId: staleItem.id,
198
- attemptId: `${staleItem.id}:1`,
199
- ttlMs: 60_000,
200
- });
201
- activateAuthorityAttempt(staleActive.id, { authorityId: "authz_stale", expiresAt: "2099-01-01T00:00:00Z" });
202
- // Still `acquiring` with no ledger authorityId — models a crash between "Deck committed
203
- // the mint" and "this row got activated." Reconciliation must not assume there's nothing
204
- // to revoke just because the ledger never recorded an id; it must resolve by replaying the
205
- // stored idempotencyKey, discover the live authority the mint stub hands back, and revoke
206
- // that instead of silently dropping it (NOT-91 review).
207
- const stillAcquiring = createAuthorityAttempt({
208
- ownerKind: "reflect",
209
- ownerId: staleIssueId,
210
- idempotencyKey: "reflect-1",
211
- deckId: DECK,
212
- runId: staleIssueId,
213
- attemptId: "reflect-1",
214
- ttlMs: 60_000,
215
- });
216
- const revokedIds = [];
217
- const result = await reconcileAuthoritiesAtStartup({
218
- revoke: async (id) => void revokedIds.push(id),
219
- mint: async () => ({
220
- ok: true,
221
- authority: {
222
- authorityId: "authz_resolved_reflect",
223
- authoritySecret: null,
224
- deckId: DECK,
225
- audience: "dealer-worker",
226
- allowedServices: [],
227
- allowedTools: [],
228
- expiresAt: "2099-01-01T00:00:00Z",
229
- },
230
- }),
231
- });
232
- assert.ok(result.revoked.includes(staleActive.id));
233
- assert.ok(result.revoked.includes(stillAcquiring.id));
234
- assert.ok(!result.revoked.includes(liveActive.id), "a still-leased owner's authority must not be revoked by the startup sweep");
235
- assert.deepEqual(new Set(revokedIds), new Set(["authz_stale", "authz_resolved_reflect"]), "an acquiring row with no ledger authorityId is resolved via its idempotency key before being terminalized, not skipped");
236
- assert.equal(getAuthorityAttempt(staleActive.id).status, "revoked");
237
- assert.equal(getAuthorityAttempt(stillAcquiring.id).status, "revoked");
238
- assert.equal(getAuthorityAttempt(liveActive.id).status, "active");
239
- });
240
- test("scenario: coordinator restart leaves an unresolved acquiring attempt open when Deck is unreachable, rather than guessing it's safe to drop", async () => {
241
- const issueId = newIssue();
242
- const row = createAuthorityAttempt({
243
- ownerKind: "reflect",
244
- ownerId: issueId,
245
- idempotencyKey: "reflect-unreachable",
246
- deckId: DECK,
247
- runId: issueId,
248
- attemptId: "reflect-unreachable",
249
- ttlMs: 60_000,
250
- });
251
- const result = await reconcileAuthoritiesAtStartup({
252
- revoke: async () => { },
253
- mint: async () => ({ ok: false, code: "DECK_UNAVAILABLE", message: "ECONNREFUSED" }),
254
- });
255
- assert.ok(result.unresolved.includes(row.id));
256
- assert.ok(!result.revoked.includes(row.id));
257
- assert.equal(getAuthorityAttempt(row.id).status, "acquiring", "left open for a later sweep instead of being guessed-terminalized while Deck is unreachable");
258
- });
259
- test("scenario: coordinator restart leaves an acquiring attempt open on a local enrollment error too, not just DECK_UNAVAILABLE", async () => {
260
- // COORDINATOR_NOT_ENROLLED/RESOURCE_OUT_OF_SCOPE can both be produced without the resolve
261
- // replay ever proving whether Deck committed the original mint — only AUTHORITY_EXPIRED/
262
- // AUTHORITY_REVOKED positively prove nothing is left to revoke (NOT-91 review, round 3).
263
- const issueId = newIssue();
264
- const row = createAuthorityAttempt({
265
- ownerKind: "reflect",
266
- ownerId: issueId,
267
- idempotencyKey: "reflect-not-enrolled",
268
- deckId: DECK,
269
- runId: issueId,
270
- attemptId: "reflect-not-enrolled",
271
- ttlMs: 60_000,
272
- });
273
- const result = await reconcileAuthoritiesAtStartup({
274
- revoke: async () => { },
275
- mint: async () => ({ ok: false, code: "COORDINATOR_NOT_ENROLLED", message: "no bearer configured" }),
276
- });
277
- assert.ok(result.unresolved.includes(row.id));
278
- assert.ok(!result.revoked.includes(row.id));
279
- assert.equal(getAuthorityAttempt(row.id).status, "acquiring");
280
- });
281
- test("scenario: worker death (lease expiry) revokes the attempt's authority and returns the item to pending, never permanently occupied", () => {
282
- const issueId = newIssue();
283
- startWorkflow(issueId);
284
- const item = listWorkItemsForIssue(issueId)[0];
285
- claimWorkItem("crashed-worker", { leaseMs: 1 });
286
- const row = createAuthorityAttempt({
287
- ownerKind: item.kind,
288
- ownerId: `${issueId}:${item.kind}`,
289
- idempotencyKey: `${item.id}:1`,
290
- deckId: DECK,
291
- runId: item.id,
292
- attemptId: `${item.id}:1`,
293
- ttlMs: 60_000,
294
- });
295
- activateAuthorityAttempt(row.id, { authorityId: "authz_deadworker", expiresAt: "2099-01-01T00:00:00Z" });
296
- const res = recoverCoordinator({ now: Date.now() + 3_600_000 });
297
- assert.deepEqual(res.reclaimed, [item.id]);
298
- assert.equal(getWorkItem(item.id).status, "pending", "the worker slot is freed, never left occupied by the dead attempt");
299
- assert.equal(getAuthorityAttempt(row.id).status, "revoked");
300
- });
301
- test("scenario: worker death never terminalizes a still-acquiring attempt inside the reclaim itself, only via async resolve", () => {
302
- const issueId = newIssue();
303
- startWorkflow(issueId);
304
- const item = listWorkItemsForIssue(issueId)[0];
305
- claimWorkItem("crashed-worker-2", { leaseMs: 1 });
306
- // No authorityId yet — same ambiguous case as the cancellation regression above, but via
307
- // the lease-expiry reclaim path (recovery.ts's revokeStaleAuthoritiesForItem).
308
- const row = createAuthorityAttempt({
309
- ownerKind: item.kind,
310
- ownerId: `${issueId}:${item.kind}`,
311
- idempotencyKey: `${item.id}:1`,
312
- deckId: DECK,
313
- runId: item.id,
314
- attemptId: `${item.id}:1`,
315
- ttlMs: 60_000,
316
- });
317
- const res = recoverCoordinator({ now: Date.now() + 3_600_000 });
318
- assert.deepEqual(res.reclaimed, [item.id]);
319
- assert.equal(getAuthorityAttempt(row.id).status, "acquiring", "left for the async, out-of-loop resolve step — recovery's own synchronous CAS never guesses this is safe to revoke");
320
- });
321
- test("scenario: Agent Deck outage is a bounded, typed failure — no infinite retry, no ledger row stuck open", async () => {
322
- let mintCalls = 0;
323
- const result = await acquireAuthorityForAttempt({
324
- ownerKind: "developer",
325
- ownerId: "wi-outage",
326
- runId: "run-outage",
327
- attemptId: "wi-outage",
328
- deckId: DECK,
329
- ttlMs: 60_000,
330
- idempotencyKey: "wi-outage:1",
331
- mint: async () => {
332
- mintCalls += 1;
333
- return { ok: false, code: "DECK_UNAVAILABLE", message: "ECONNREFUSED" };
334
- },
335
- revoke: async () => { },
336
- });
337
- assert.equal(result.ok, false);
338
- if (!result.ok)
339
- assert.equal(result.kind, "infra_failure");
340
- assert.equal(mintCalls, 1, "an outright connection failure is not the bounded auto-retry's job — it surfaces immediately to the caller's own infra-retry policy");
341
- assert.equal(listOpenAuthorityAttemptsForOwner("developer", "wi-outage").length, 0, "the failed ledger row is closed out, not left acquiring forever");
342
- });
343
- test("scenario: authority expiry mid-attempt auto-recovers under a fresh key, distinct from an explicit revoke", async () => {
344
- let call = 0;
345
- const seenKeys = [];
346
- const result = await acquireAuthorityForAttempt({
347
- ownerKind: "developer",
348
- ownerId: "wi-expiry",
349
- runId: "run-expiry",
350
- attemptId: "wi-expiry",
351
- deckId: DECK,
352
- ttlMs: 60_000,
353
- idempotencyKey: "wi-expiry:1",
354
- mint: async (input) => {
355
- call += 1;
356
- seenKeys.push(input.idempotencyKey);
357
- if (call === 1)
358
- return { ok: false, code: "AUTHORITY_EXPIRED", message: "expired" };
359
- return mintOk()(input);
360
- },
361
- revoke: async () => { },
362
- });
363
- assert.equal(result.ok, true);
364
- assert.equal(call, 2, "expiry is recovered from transparently — never surfaced as a caller-visible failure");
365
- assert.notEqual(seenKeys[0], seenKeys[1], "the retry after expiry must use a fresh idempotency key, not repeat the dead one");
366
- // An explicit AUTHORITY_REVOKED, by contrast, is never auto-retried — it parks.
367
- const revokedResult = await acquireAuthorityForAttempt({
368
- ownerKind: "developer",
369
- ownerId: "wi-revoked",
370
- runId: "run-revoked",
371
- attemptId: "wi-revoked",
372
- deckId: DECK,
373
- ttlMs: 60_000,
374
- idempotencyKey: "wi-revoked:1",
375
- mint: async () => ({ ok: false, code: "AUTHORITY_REVOKED", message: "revoked by operator", requestId: "req_revoked" }),
376
- revoke: async () => { },
377
- });
378
- assert.equal(revokedResult.ok, false);
379
- if (!revokedResult.ok) {
380
- assert.equal(revokedResult.kind, "interaction_required", "a revoke is an operator/policy decision — it must wait for a human, not silently remint");
381
- assert.equal(revokedResult.requestId, "req_revoked");
382
- }
383
- });
384
- test("scenario: an ambiguous downstream result (timeout) is parked for a human decision, never silently auto-retried", async () => {
385
- const { deliverOutboundDraft } = await import("../adapters/outbound-delivery.js");
386
- const result = await deliverOutboundDraft(DECK, { serviceName: "slack", toolName: "chat_postMessage", arguments: {} }, {
387
- callTool: async () => {
388
- throw new Error("Outbound deliver timed out after 60000ms");
389
- },
390
- });
391
- assert.equal(result.ok, false);
392
- if (!result.ok)
393
- assert.equal(result.kind, "ambiguous");
394
- const run = createRun({ title: "Ambiguous delivery", taskCategory: "communication", status: "plan_pending", agentId: BUILTIN_AGENT_CLAUDE_ID });
395
- updateRunFields(run.id, { deck_id: DECK });
396
- transitionRun(run.id, "plan_approved");
397
- transitionRun(run.id, "running");
398
- transitionRun(run.id, "review");
399
- addArtifact(run.id, "slack_draft", {
400
- draft: { actionType: "slack_message", summary: { target: "#test", body: "hi" }, toolCall: { serviceName: "slack", toolName: "chat_postMessage", arguments: {} } },
401
- status: "pending",
402
- }, "agent");
403
- const approveRes = await approveRunWithDeliver(run.id, {
404
- deliver: async () => ({ ok: false, kind: "ambiguous", reason: "timed out — unknown" }),
405
- });
406
- assert.equal(approveRes.ok, false);
407
- if (!approveRes.ok)
408
- assert.equal(approveRes.errorCode, "AMBIGUOUS_RESULT");
409
- const { listHumanActionsForRun } = await import("../repository/human-actions.js");
410
- const parked = listHumanActionsForRun(run.id).find((a) => a.actionType === "outbound_delivery_interaction_required" && a.status === "open");
411
- assert.ok(parked, "an ambiguous result must raise an explicit retry/reject decision, not disappear as an ordinary failure");
412
- assert.equal(getRun(run.id).status, "review", "still blocked on the human decision, never silently advanced");
413
- });
414
- test("scenario: same-attempt idempotent remint recovers instead of failing the whole attempt, and revokes the orphaned secret-less authority", async () => {
415
- const revoked = [];
416
- const result = await acquireAuthorityForAttempt({
417
- ownerKind: "outbound_delivery",
418
- ownerId: "run-remint",
419
- runId: "run-remint",
420
- attemptId: "draft-1",
421
- deckId: DECK,
422
- ttlMs: 60_000,
423
- idempotencyKey: "draft-1:1",
424
- mint: mintOk(null), // every mint in this test "succeeds" but never issues a secret
425
- revoke: async (id) => void revoked.push(id),
426
- });
427
- // Both the genuine attempt and its one bounded retry hit the same secret-less remint —
428
- // the second failure is the one that finally surfaces, but neither ever leaked a
429
- // usable secret to the caller.
430
- assert.equal(result.ok, false);
431
- if (!result.ok)
432
- assert.equal(result.kind, "infra_failure");
433
- assert.equal(revoked.length, 2, "every secret-less authority Deck ever handed back was revoked, not left live");
434
- // The success path: the first mint is a secret-less remint, the second (fresh key) is real.
435
- let call = 0;
436
- const recovered = await acquireAuthorityForAttempt({
437
- ownerKind: "outbound_delivery",
438
- ownerId: "run-remint-2",
439
- runId: "run-remint-2",
440
- attemptId: "draft-2",
441
- deckId: DECK,
442
- ttlMs: 60_000,
443
- idempotencyKey: "draft-2:1",
444
- mint: async (input) => {
445
- call += 1;
446
- return mintOk(call === 1 ? null : "authzs_real")(input);
447
- },
448
- revoke: async (id) => void revoked.push(id),
449
- });
450
- assert.equal(recovered.ok, true);
451
- if (recovered.ok)
452
- assert.equal(recovered.authority.authoritySecret, "authzs_real");
453
- });
454
- test("scenario: revoke-before-new-attempt — a fresh attempt for the same owner revokes its predecessor's still-open authority first", async () => {
455
- const ownerId = "wi-supersede";
456
- const revoked = [];
457
- const first = await acquireAuthorityForAttempt({
458
- ownerKind: "developer",
459
- ownerId,
460
- runId: "run-supersede",
461
- attemptId: ownerId,
462
- deckId: DECK,
463
- ttlMs: 60_000,
464
- idempotencyKey: `${ownerId}:1`,
465
- mint: mintOk(),
466
- revoke: async (id) => void revoked.push(id),
467
- });
468
- assert.equal(first.ok, true);
469
- // A retry of the SAME owner under a NEW idempotencyKey (e.g. a reclaimed lease bumped
470
- // attempt_count) — the first attempt's authority was never explicitly released (the
471
- // crash this scenario models), so it is still `active` in the ledger.
472
- assert.equal(listOpenAuthorityAttemptsForOwner("developer", ownerId).length, 1);
473
- const second = await acquireAuthorityForAttempt({
474
- ownerKind: "developer",
475
- ownerId,
476
- runId: "run-supersede",
477
- attemptId: ownerId,
478
- deckId: DECK,
479
- ttlMs: 60_000,
480
- idempotencyKey: `${ownerId}:2`,
481
- mint: mintOk(),
482
- revoke: async (id) => void revoked.push(id),
483
- });
484
- assert.equal(second.ok, true);
485
- if (first.ok)
486
- assert.ok(revoked.includes(first.authority.authorityId), "the superseded attempt's authority must be revoked, not left live until TTL");
487
- assert.equal(listOpenAuthorityAttemptsForOwner("developer", ownerId).length, 1, "exactly the new attempt is open — no leaked duplicate authority for one owner");
488
- });
489
- test("scenario: revoke-before-new-attempt resolves an acquiring (no authorityId yet) predecessor via replay, not a guess", async () => {
490
- const ownerId = "wi-supersede-acquiring";
491
- const revoked = [];
492
- // The predecessor never got past `acquiring` — models a crash between "asked Deck for
493
- // authority" and "this row got activated." This used to be bulk-terminalized by a fresh
494
- // attempt without ever attempting to resolve it (NOT-91 review, round 3's exact repro).
495
- const stalePredecessor = createAuthorityAttempt({
496
- ownerKind: "developer",
497
- ownerId,
498
- idempotencyKey: `${ownerId}:1`,
499
- deckId: DECK,
500
- runId: "run-supersede-acquiring",
501
- attemptId: ownerId,
502
- ttlMs: 60_000,
503
- });
504
- let mintCalls = 0;
505
- const second = await acquireAuthorityForAttempt({
506
- ownerKind: "developer",
507
- ownerId,
508
- runId: "run-supersede-acquiring",
509
- attemptId: ownerId,
510
- deckId: DECK,
511
- ttlMs: 60_000,
512
- idempotencyKey: `${ownerId}:2`,
513
- mint: async (input) => {
514
- mintCalls += 1;
515
- // Replaying the predecessor's own key hands back the live authority Deck actually
516
- // committed before the crash (an idempotent remint — no new secret); the real
517
- // second-attempt mint, under its own key, succeeds normally.
518
- if (input.idempotencyKey === `${ownerId}:1`)
519
- return mintOk(null)(input);
520
- return mintOk()(input);
521
- },
522
- revoke: async (id) => void revoked.push(id),
523
- });
524
- assert.equal(second.ok, true);
525
- assert.ok(mintCalls >= 2, "the predecessor's key was replayed to resolve it, not skipped");
526
- assert.ok(revoked.includes(`authz_${ownerId}:1`), "the live authority discovered behind the acquiring predecessor was revoked, not left until TTL");
527
- assert.equal(getAuthorityAttempt(stalePredecessor.id).status, "revoked");
528
- });
529
- test("scenario: a fresh attempt fails closed rather than minting beside an unresolved predecessor", async () => {
530
- const ownerId = "wi-supersede-unresolved";
531
- const revoked = [];
532
- let newKeyMintCalls = 0;
533
- const stalePredecessor = createAuthorityAttempt({
534
- ownerKind: "developer",
535
- ownerId,
536
- idempotencyKey: `${ownerId}:1`,
537
- deckId: DECK,
538
- runId: "run-supersede-unresolved",
539
- attemptId: ownerId,
540
- ttlMs: 60_000,
541
- });
542
- const second = await acquireAuthorityForAttempt({
543
- ownerKind: "developer",
544
- ownerId,
545
- runId: "run-supersede-unresolved",
546
- attemptId: ownerId,
547
- deckId: DECK,
548
- ttlMs: 60_000,
549
- idempotencyKey: `${ownerId}:2`,
550
- mint: async (input) => {
551
- // COORDINATOR_NOT_ENROLLED can be produced locally (missing bearer) before any
552
- // request reaches Deck — it proves nothing about whether the original mint
553
- // committed, unlike AUTHORITY_EXPIRED/AUTHORITY_REVOKED (NOT-91 review, round 3).
554
- if (input.idempotencyKey === `${ownerId}:1`) {
555
- return { ok: false, code: "COORDINATOR_NOT_ENROLLED", message: "no bearer" };
556
- }
557
- newKeyMintCalls += 1;
558
- return mintOk()(input);
559
- },
560
- revoke: async (id) => void revoked.push(id),
561
- });
562
- // An unresolved predecessor's live/dead state is unknown — minting a new authority beside
563
- // it would risk two live authorities for the same owner if it turns out to have been live
564
- // all along. Must fail closed instead of proceeding (NOT-91 review, round 4).
565
- assert.equal(second.ok, false, "must not mint a new authority while a predecessor's state is unknown");
566
- if (!second.ok)
567
- assert.equal(second.kind, "infra_failure");
568
- assert.equal(newKeyMintCalls, 0, "no new authority was minted beside the unresolved predecessor");
569
- assert.equal(getAuthorityAttempt(stalePredecessor.id).status, "acquiring", "an enrollment error proves nothing about whether Deck actually committed the original mint — must not be terminalized on a guess");
570
- assert.equal(revoked.length, 0, "nothing was revoked for a row that was never positively resolved");
571
- });
572
- test("scenario: the periodic retry only ever finds rows durably flagged stale — a live active row is never even a candidate", async () => {
573
- const revoked = [];
574
- const liveRow = createAuthorityAttempt({
575
- ownerKind: "reflect",
576
- ownerId: "issue-live-reflect",
577
- idempotencyKey: "reflect-live",
578
- deckId: DECK,
579
- runId: "issue-live-reflect",
580
- attemptId: "reflect-live",
581
- ttlMs: 60_000,
582
- });
583
- activateAuthorityAttempt(liveRow.id, { authorityId: "authz_live_reflect", expiresAt: "2099-01-01T00:00:00Z" });
584
- // Nothing ever flagged this row `stale_at` (unlike an unresolved row from
585
- // reconcileAuthoritiesAtStartup/abort/reclaim/revoke-before-new-attempt, all of which go
586
- // through resolveAcquiringAttempt's stamp) — retryStaleAuthorityAttempts's DB query for
587
- // `status='acquiring' AND stale_at IS NOT NULL` structurally excludes it, whether or not it
588
- // is `active` (NOT-91 review, round 5).
589
- const result = await retryStaleAuthorityAttempts({ revoke: async (id) => void revoked.push(id) });
590
- assert.deepEqual(result.revoked, []);
591
- assert.deepEqual(result.unresolved, []);
592
- assert.equal(revoked.length, 0);
593
- assert.equal(getAuthorityAttempt(liveRow.id).status, "active", "a live active row must never be revoked by the periodic retry");
594
- });
595
- test("scenario: the periodic retry's defensive lease check still applies even if a row were somehow flagged stale while genuinely live", async () => {
596
- const issueId = newIssue();
597
- startWorkflow(issueId);
598
- const item = listWorkItemsForIssue(issueId)[0];
599
- claimWorkItem("live-leaseholder", { leaseMs: 600_000 });
600
- assert.equal(getWorkItem(item.id).status, "leased");
601
- const ownerId = `${issueId}:${item.kind}`;
602
- const liveAcquiring = createAuthorityAttempt({
603
- ownerKind: item.kind,
604
- ownerId,
605
- idempotencyKey: `${item.id}:1`,
606
- deckId: DECK,
607
- runId: item.id,
608
- attemptId: `${item.id}:1`,
609
- ttlMs: 60_000,
610
- });
611
- // Simulates a row wrongly flagged stale (in reality, nothing flags a developer/reviewer row
612
- // stale while its item is still leased — reconcileAuthoritiesAtStartup's own `isOwnerLeased`
613
- // check filters it out first) — the retry's own lease check is defense in depth for exactly
614
- // this case (NOT-91 review, round 5).
615
- markAuthorityAttemptStale(liveAcquiring.id);
616
- let mintCalls = 0;
617
- const result = await retryStaleAuthorityAttempts({
618
- mint: async () => {
619
- mintCalls += 1;
620
- return { ok: false, code: "DECK_UNAVAILABLE", message: "should never be called" };
621
- },
622
- revoke: async () => { },
623
- });
624
- assert.deepEqual(result.revoked, []);
625
- assert.deepEqual(result.unresolved, []);
626
- assert.equal(mintCalls, 0, "a still-leased owner's row must never be resolved, even once flagged stale");
627
- assert.equal(getAuthorityAttempt(liveAcquiring.id).status, "acquiring");
628
- });
629
- test("scenario: the periodic retry finds a row that only became unresolved outside the startup sweep, e.g. via a cancellation while Deck was unreachable", async () => {
630
- const row = createAuthorityAttempt({
631
- ownerKind: "reflect",
632
- ownerId: "issue-post-startup-cancel",
633
- idempotencyKey: "reflect-post-startup-cancel",
634
- deckId: DECK,
635
- runId: "issue-post-startup-cancel",
636
- attemptId: "reflect-post-startup-cancel",
637
- ttlMs: 60_000,
638
- });
639
- // Models what abortIssue's fire-and-forget resolve does when Deck happens to be
640
- // unreachable at cancel time: resolveAcquiringAttempts durably flags the row `stale_at`
641
- // (via resolveAcquiringAttempt) even though it can't resolve it this call. No startup
642
- // sweep ever ran on this row — it only exists because of a cancellation that happened
643
- // during normal runtime, well after boot (NOT-91 review, round 5).
644
- const firstAttempt = await resolveAcquiringAttempts([row], {
645
- mint: async () => ({ ok: false, code: "DECK_UNAVAILABLE", message: "ECONNREFUSED" }),
646
- revoke: async () => { },
647
- });
648
- assert.deepEqual(firstAttempt.unresolved, [row.id]);
649
- assert.equal(getAuthorityAttempt(row.id).status, "acquiring");
650
- let mintCalls = 0;
651
- const result = await retryStaleAuthorityAttempts({
652
- mint: async (input) => {
653
- mintCalls += 1;
654
- return mintOk()(input);
655
- },
656
- revoke: async () => { },
657
- });
658
- assert.equal(mintCalls, 1, "the periodic sweep found the row via its durable stale_at flag, with no in-memory list carrying it forward");
659
- assert.deepEqual(result.revoked, [row.id]);
660
- assert.equal(getAuthorityAttempt(row.id).status, "revoked");
661
- });