@ngockhoale/ckit 0.0.0-stage → 0.1.1

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 (246) hide show
  1. package/.env.example +21 -0
  2. package/README.md +70 -2
  3. package/dist/src/adapters/agent/claude/errors.d.ts +13 -0
  4. package/dist/src/adapters/agent/claude/errors.js +16 -0
  5. package/dist/src/adapters/agent/claude/normalize.d.ts +11 -0
  6. package/dist/src/adapters/agent/claude/normalize.js +83 -0
  7. package/dist/src/adapters/agent/errors.d.ts +13 -0
  8. package/dist/src/adapters/agent/errors.js +19 -0
  9. package/dist/src/adapters/agent/fixtures/claude-transcript.d.ts +70 -0
  10. package/dist/src/adapters/agent/fixtures/claude-transcript.js +15 -0
  11. package/dist/src/adapters/agent/fixtures/omp-transcript.d.ts +60 -0
  12. package/dist/src/adapters/agent/fixtures/omp-transcript.js +14 -0
  13. package/dist/src/adapters/agent/normalize.d.ts +18 -0
  14. package/dist/src/adapters/agent/normalize.js +77 -0
  15. package/dist/src/adapters/agent/transport.d.ts +35 -0
  16. package/dist/src/adapters/agent/transport.js +39 -0
  17. package/dist/src/adapters/agent/worker-service.d.ts +49 -0
  18. package/dist/src/adapters/agent/worker-service.js +77 -0
  19. package/dist/src/adapters/fake/fake-advisor.d.ts +15 -0
  20. package/dist/src/adapters/fake/fake-advisor.js +29 -0
  21. package/dist/src/adapters/fake/fake-agent.d.ts +12 -0
  22. package/dist/src/adapters/fake/fake-agent.js +21 -0
  23. package/dist/src/adapters/fake/fake-store.d.ts +13 -0
  24. package/dist/src/adapters/fake/fake-store.js +23 -0
  25. package/dist/src/adapters/fake/fake-web.d.ts +12 -0
  26. package/dist/src/adapters/fake/fake-web.js +21 -0
  27. package/dist/src/adapters/fake/fault-injector.d.ts +18 -0
  28. package/dist/src/adapters/fake/fault-injector.js +64 -0
  29. package/dist/src/adapters/fake/virtual-clock.d.ts +12 -0
  30. package/dist/src/adapters/fake/virtual-clock.js +35 -0
  31. package/dist/src/adapters/launch/discover.d.ts +18 -0
  32. package/dist/src/adapters/launch/discover.js +55 -0
  33. package/dist/src/adapters/launch/executor.d.ts +117 -0
  34. package/dist/src/adapters/launch/executor.js +383 -0
  35. package/dist/src/adapters/launch/profile.d.ts +35 -0
  36. package/dist/src/adapters/launch/profile.js +73 -0
  37. package/dist/src/adapters/launch/spawn.d.ts +29 -0
  38. package/dist/src/adapters/launch/spawn.js +18 -0
  39. package/dist/src/adapters/openai/openai-advisor.d.ts +56 -0
  40. package/dist/src/adapters/openai/openai-advisor.js +146 -0
  41. package/dist/src/cli/ckit.d.ts +5 -0
  42. package/dist/src/cli/ckit.js +384 -0
  43. package/dist/src/cli/demo.d.ts +1 -0
  44. package/dist/src/cli/demo.js +30 -0
  45. package/dist/src/cli/lifecycle.d.ts +19 -0
  46. package/dist/src/cli/lifecycle.js +90 -0
  47. package/dist/src/cli/sessions.d.ts +10 -0
  48. package/dist/src/cli/sessions.js +381 -0
  49. package/dist/src/cli/setup.d.ts +11 -0
  50. package/dist/src/cli/setup.js +115 -0
  51. package/dist/src/committee/decision.d.ts +84 -0
  52. package/dist/src/committee/decision.js +167 -0
  53. package/dist/src/committee/handover.d.ts +115 -0
  54. package/dist/src/committee/handover.js +191 -0
  55. package/dist/src/committee/no-progress.d.ts +44 -0
  56. package/dist/src/committee/no-progress.js +64 -0
  57. package/dist/src/committee/primary-registry.d.ts +15 -0
  58. package/dist/src/committee/primary-registry.js +60 -0
  59. package/dist/src/committee/reply-parser.d.ts +28 -0
  60. package/dist/src/committee/reply-parser.js +53 -0
  61. package/dist/src/committee/reviewer-scheduler.d.ts +101 -0
  62. package/dist/src/committee/reviewer-scheduler.js +163 -0
  63. package/dist/src/committee/role-epoch.d.ts +91 -0
  64. package/dist/src/committee/role-epoch.js +154 -0
  65. package/dist/src/core/control.d.ts +18 -0
  66. package/dist/src/core/control.js +29 -0
  67. package/dist/src/core/entities.d.ts +166 -0
  68. package/dist/src/core/entities.js +119 -0
  69. package/dist/src/core/errors.d.ts +9 -0
  70. package/dist/src/core/errors.js +17 -0
  71. package/dist/src/core/events.d.ts +72 -0
  72. package/dist/src/core/events.js +125 -0
  73. package/dist/src/core/ids.d.ts +47 -0
  74. package/dist/src/core/ids.js +32 -0
  75. package/dist/src/core/machine.d.ts +55 -0
  76. package/dist/src/core/machine.js +110 -0
  77. package/dist/src/core/policy.d.ts +34 -0
  78. package/dist/src/core/policy.js +59 -0
  79. package/dist/src/core/provenance.d.ts +20 -0
  80. package/dist/src/core/provenance.js +21 -0
  81. package/dist/src/core/record.d.ts +35 -0
  82. package/dist/src/core/record.js +67 -0
  83. package/dist/src/core/replay.d.ts +10 -0
  84. package/dist/src/core/replay.js +36 -0
  85. package/dist/src/core/run-task.d.ts +20 -0
  86. package/dist/src/core/run-task.js +48 -0
  87. package/dist/src/diagnostics/doctor.d.ts +78 -0
  88. package/dist/src/diagnostics/doctor.js +365 -0
  89. package/dist/src/diagnostics/journal-lock.d.ts +38 -0
  90. package/dist/src/diagnostics/journal-lock.js +181 -0
  91. package/dist/src/evidence/linker.d.ts +44 -0
  92. package/dist/src/evidence/linker.js +75 -0
  93. package/dist/src/evidence/report-parser.d.ts +27 -0
  94. package/dist/src/evidence/report-parser.js +17 -0
  95. package/dist/src/evidence/store.d.ts +36 -0
  96. package/dist/src/evidence/store.js +57 -0
  97. package/dist/src/gui/server.d.ts +27 -0
  98. package/dist/src/gui/server.js +497 -0
  99. package/dist/src/host/checkpoint.d.ts +22 -0
  100. package/dist/src/host/checkpoint.js +74 -0
  101. package/dist/src/host/export.d.ts +52 -0
  102. package/dist/src/host/export.js +45 -0
  103. package/dist/src/host/ipc.d.ts +57 -0
  104. package/dist/src/host/ipc.js +124 -0
  105. package/dist/src/host/leases.d.ts +27 -0
  106. package/dist/src/host/leases.js +40 -0
  107. package/dist/src/host/retention.d.ts +47 -0
  108. package/dist/src/host/retention.js +130 -0
  109. package/dist/src/host/supervisor.d.ts +59 -0
  110. package/dist/src/host/supervisor.js +64 -0
  111. package/dist/src/intake/owner-intake.d.ts +31 -0
  112. package/dist/src/intake/owner-intake.js +97 -0
  113. package/dist/src/intake/types.d.ts +46 -0
  114. package/dist/src/intake/types.js +2 -0
  115. package/dist/src/intent/context-packet.d.ts +68 -0
  116. package/dist/src/intent/context-packet.js +76 -0
  117. package/dist/src/intent/idea-ledger.d.ts +50 -0
  118. package/dist/src/intent/idea-ledger.js +136 -0
  119. package/dist/src/intent/ledger.d.ts +35 -0
  120. package/dist/src/intent/ledger.js +40 -0
  121. package/dist/src/intent/registry.d.ts +51 -0
  122. package/dist/src/intent/registry.js +44 -0
  123. package/dist/src/intent/revision.d.ts +37 -0
  124. package/dist/src/intent/revision.js +48 -0
  125. package/dist/src/orchestration/dispatcher.d.ts +32 -0
  126. package/dist/src/orchestration/dispatcher.js +136 -0
  127. package/dist/src/orchestration/milestone-loop.d.ts +149 -0
  128. package/dist/src/orchestration/milestone-loop.js +132 -0
  129. package/dist/src/orchestration/recovery-coordinator.d.ts +74 -0
  130. package/dist/src/orchestration/recovery-coordinator.js +180 -0
  131. package/dist/src/orchestration/work-order-contract.d.ts +44 -0
  132. package/dist/src/orchestration/work-order-contract.js +85 -0
  133. package/dist/src/orchestration/work-queue.d.ts +56 -0
  134. package/dist/src/orchestration/work-queue.js +95 -0
  135. package/dist/src/ports/advisor.d.ts +33 -0
  136. package/dist/src/ports/advisor.js +2 -0
  137. package/dist/src/ports/agent.d.ts +31 -0
  138. package/dist/src/ports/agent.js +2 -0
  139. package/dist/src/ports/capabilities.d.ts +3 -0
  140. package/dist/src/ports/capabilities.js +5 -0
  141. package/dist/src/ports/clock.d.ts +5 -0
  142. package/dist/src/ports/clock.js +5 -0
  143. package/dist/src/ports/store.d.ts +13 -0
  144. package/dist/src/ports/store.js +2 -0
  145. package/dist/src/ports/web.d.ts +29 -0
  146. package/dist/src/ports/web.js +2 -0
  147. package/dist/src/run/api-run.d.ts +49 -0
  148. package/dist/src/run/api-run.js +173 -0
  149. package/dist/src/run/plan-run.d.ts +22 -0
  150. package/dist/src/run/plan-run.js +233 -0
  151. package/dist/src/run/plan.d.ts +36 -0
  152. package/dist/src/run/plan.js +119 -0
  153. package/dist/src/run/verify.d.ts +25 -0
  154. package/dist/src/run/verify.js +81 -0
  155. package/dist/src/security/redact.d.ts +7 -0
  156. package/dist/src/security/redact.js +21 -0
  157. package/dist/src/settings/env-config.d.ts +64 -0
  158. package/dist/src/settings/env-config.js +232 -0
  159. package/dist/src/storage/artifacts.d.ts +30 -0
  160. package/dist/src/storage/artifacts.js +105 -0
  161. package/dist/src/storage/audit.d.ts +6 -0
  162. package/dist/src/storage/audit.js +6 -0
  163. package/dist/src/storage/db.d.ts +9 -0
  164. package/dist/src/storage/db.js +43 -0
  165. package/dist/src/storage/events.d.ts +20 -0
  166. package/dist/src/storage/events.js +69 -0
  167. package/dist/src/storage/migrations.d.ts +8 -0
  168. package/dist/src/storage/migrations.js +48 -0
  169. package/dist/src/storage/outbox.d.ts +25 -0
  170. package/dist/src/storage/outbox.js +40 -0
  171. package/dist/src/storage/projections.d.ts +18 -0
  172. package/dist/src/storage/projections.js +40 -0
  173. package/dist/src/storage/reconcile.d.ts +14 -0
  174. package/dist/src/storage/reconcile.js +93 -0
  175. package/dist/src/storage/reservations.d.ts +12 -0
  176. package/dist/src/storage/reservations.js +80 -0
  177. package/dist/src/storage/store.d.ts +34 -0
  178. package/dist/src/storage/store.js +105 -0
  179. package/dist/src/team/attachments.d.ts +22 -0
  180. package/dist/src/team/attachments.js +211 -0
  181. package/dist/src/team/cli-models.d.ts +24 -0
  182. package/dist/src/team/cli-models.js +72 -0
  183. package/dist/src/team/config.d.ts +20 -0
  184. package/dist/src/team/config.js +113 -0
  185. package/dist/src/team/engine.d.ts +28 -0
  186. package/dist/src/team/engine.js +443 -0
  187. package/dist/src/team/journal.d.ts +30 -0
  188. package/dist/src/team/journal.js +70 -0
  189. package/dist/src/team/runners.d.ts +79 -0
  190. package/dist/src/team/runners.js +436 -0
  191. package/dist/src/team/secrets.d.ts +10 -0
  192. package/dist/src/team/secrets.js +68 -0
  193. package/dist/src/team/types.d.ts +157 -0
  194. package/dist/src/team/types.js +5 -0
  195. package/dist/src/tui/app.d.ts +29 -0
  196. package/dist/src/tui/app.js +96 -0
  197. package/dist/src/tui/control-model.d.ts +101 -0
  198. package/dist/src/tui/control-model.js +109 -0
  199. package/dist/src/tui/control-screens.d.ts +27 -0
  200. package/dist/src/tui/control-screens.js +85 -0
  201. package/dist/src/tui/graph-model.d.ts +34 -0
  202. package/dist/src/tui/graph-model.js +29 -0
  203. package/dist/src/tui/graph-screens.d.ts +13 -0
  204. package/dist/src/tui/graph-screens.js +4 -0
  205. package/dist/src/tui/inspector-model.d.ts +150 -0
  206. package/dist/src/tui/inspector-model.js +15 -0
  207. package/dist/src/tui/inspector-screens.d.ts +14 -0
  208. package/dist/src/tui/inspector-screens.js +61 -0
  209. package/dist/src/tui/live.d.ts +16 -0
  210. package/dist/src/tui/live.js +39 -0
  211. package/dist/src/tui/mission-action-screens.d.ts +15 -0
  212. package/dist/src/tui/mission-action-screens.js +105 -0
  213. package/dist/src/tui/mission-actions.d.ts +46 -0
  214. package/dist/src/tui/mission-actions.js +53 -0
  215. package/dist/src/tui/mission-model.d.ts +120 -0
  216. package/dist/src/tui/mission-model.js +164 -0
  217. package/dist/src/tui/mission-nav.d.ts +82 -0
  218. package/dist/src/tui/mission-nav.js +131 -0
  219. package/dist/src/tui/mission-plan-screens.d.ts +11 -0
  220. package/dist/src/tui/mission-plan-screens.js +40 -0
  221. package/dist/src/tui/mission-plan.d.ts +45 -0
  222. package/dist/src/tui/mission-plan.js +166 -0
  223. package/dist/src/tui/mission-screens.d.ts +7 -0
  224. package/dist/src/tui/mission-screens.js +263 -0
  225. package/dist/src/tui/provenance-label.d.ts +11 -0
  226. package/dist/src/tui/provenance-label.js +16 -0
  227. package/dist/src/tui/screens.d.ts +10 -0
  228. package/dist/src/tui/screens.js +34 -0
  229. package/dist/src/tui/session-outcome.d.ts +14 -0
  230. package/dist/src/tui/session-outcome.js +57 -0
  231. package/dist/src/tui/setup-model.d.ts +159 -0
  232. package/dist/src/tui/setup-model.js +234 -0
  233. package/dist/src/tui/setup-screens.d.ts +66 -0
  234. package/dist/src/tui/setup-screens.js +72 -0
  235. package/dist/src/tui/team/app.d.ts +24 -0
  236. package/dist/src/tui/team/app.js +228 -0
  237. package/dist/src/tui/team/demo-handle.d.ts +22 -0
  238. package/dist/src/tui/team/demo-handle.js +42 -0
  239. package/dist/src/tui/team/model.d.ts +81 -0
  240. package/dist/src/tui/team/model.js +133 -0
  241. package/gui/app.css +177 -0
  242. package/gui/app.js +677 -0
  243. package/gui/index.html +51 -0
  244. package/gui/network.js +413 -0
  245. package/package.json +44 -4
  246. package/src/storage/schema.sql +42 -0
@@ -0,0 +1,84 @@
1
+ import { PrimaryRegistry } from './primary-registry.js';
2
+ export type PrimaryPurpose = 'bootstrap' | 'repair' | 'continue';
3
+ export type PrimaryStatus = 'prepared' | 'sent' | 'unknown' | 'released';
4
+ export interface PrimaryCall {
5
+ readonly requestId: string;
6
+ readonly advisorId: string;
7
+ readonly purpose: PrimaryPurpose;
8
+ readonly status: PrimaryStatus;
9
+ readonly response?: unknown;
10
+ }
11
+ export interface ReviewerCall {
12
+ readonly requestId: string;
13
+ readonly reviewerId: string;
14
+ readonly evidenceRevision: number;
15
+ readonly status: 'pending' | 'submitted' | 'timed_out';
16
+ readonly opinion?: unknown;
17
+ }
18
+ export interface DecisionAudit {
19
+ readonly kind: string;
20
+ readonly requestId?: string;
21
+ readonly reason?: string;
22
+ readonly [key: string]: unknown;
23
+ }
24
+ export interface DecisionSnapshot {
25
+ readonly decisionId: string;
26
+ readonly primaryId: string;
27
+ readonly primary: readonly PrimaryCall[];
28
+ readonly reviewers: readonly ReviewerCall[];
29
+ readonly audit: readonly DecisionAudit[];
30
+ readonly outcome: 'open' | 'final' | 'needs_owner';
31
+ readonly fingerprints: readonly string[];
32
+ readonly fingerprintCounts: Readonly<Record<string, number>>;
33
+ readonly loopLimit: number;
34
+ readonly snapshotRevision: number;
35
+ readonly synthesis: readonly unknown[] | null;
36
+ readonly orders: readonly {
37
+ readonly workOrderId: string;
38
+ readonly payload: unknown;
39
+ readonly dispatchCount: number;
40
+ readonly state: 'accepted' | 'unknown' | 'reconciled';
41
+ }[];
42
+ }
43
+ export interface DecisionEngineOptions {
44
+ readonly decisionId: string;
45
+ readonly primaryId: string;
46
+ readonly registry?: PrimaryRegistry;
47
+ readonly loopLimit?: number;
48
+ }
49
+ /** In-memory decision journal. Exported snapshots are detached, immutable restart records. */
50
+ export declare class DecisionEngine {
51
+ private state;
52
+ private roles;
53
+ constructor(options: DecisionEngineOptions);
54
+ static restore(snapshot: DecisionSnapshot, registry?: PrimaryRegistry): DecisionEngine;
55
+ snapshot(): DecisionSnapshot;
56
+ reservePrimary(requestId: string, purpose: PrimaryPurpose): PrimaryCall;
57
+ settlePrimary(requestId: string, result: 'sent' | 'unknown' | 'not_sent'): PrimaryStatus;
58
+ reconcilePrimary(requestId: string, result: 'sent' | 'unknown' | 'not_sent'): 'consumed' | 'needs_reconciliation' | 'released';
59
+ finishPrimary(requestId: string, reply: {
60
+ readonly kind: 'final';
61
+ readonly outcome: string;
62
+ readonly rationale: string;
63
+ } | {
64
+ readonly kind: 'review-request';
65
+ readonly reason: string;
66
+ readonly reviewers: readonly string[];
67
+ }): {
68
+ readonly outcome: 'final' | 'needs_owner' | 'review_requested';
69
+ };
70
+ reserveReviewers(reviewerIds: readonly string[], evidenceRevision: number): readonly ReviewerCall[];
71
+ submitReviewerOpinion(requestId: string, opinion: unknown): 'accepted' | 'late_ignored';
72
+ timeoutReviewer(requestId: string): void;
73
+ synthesizeReviewers(): readonly unknown[];
74
+ settleUnavailableFallback(): void;
75
+ recordProblem(raw: string): 'continue' | 'needs_owner';
76
+ recordAcceptedOrder(workOrderId: string, payload: unknown): void;
77
+ reconcileAcceptedOrder(workOrderId: string, result: 'accepted' | 'unknown' | 'not_received'): 'accepted' | 'needs_owner' | 'not_received';
78
+ replayOrder(workOrderId: string): never;
79
+ private primaryIndex;
80
+ private assertOpen;
81
+ private log;
82
+ private touch;
83
+ }
84
+ export declare function normalizeProblemFingerprint(raw: string): string;
@@ -0,0 +1,167 @@
1
+ import { PrimaryRegistry } from './primary-registry.js';
2
+ import { RoleEpoch } from './role-epoch.js';
3
+ const copyRoleOptions = (decisionId, registry) => registry === undefined ? { decisionId } : { decisionId, registry };
4
+ const copyEngineOptions = (decisionId, primaryId, loopLimit, registry) => registry === undefined ? { decisionId, primaryId, loopLimit } : { decisionId, primaryId, loopLimit, registry };
5
+ /** In-memory decision journal. Exported snapshots are detached, immutable restart records. */
6
+ export class DecisionEngine {
7
+ state;
8
+ roles;
9
+ constructor(options) {
10
+ if (!options || typeof options.decisionId !== 'string' || !options.decisionId.trim() || typeof options.primaryId !== 'string' || !options.primaryId.trim())
11
+ throw new TypeError('decisionId and primaryId required');
12
+ const loopLimit = options.loopLimit ?? 2;
13
+ if (!Number.isSafeInteger(loopLimit) || loopLimit < 1)
14
+ throw new TypeError('loopLimit must be positive');
15
+ this.roles = new RoleEpoch(options.primaryId, copyRoleOptions(options.decisionId, options.registry));
16
+ this.state = { decisionId: options.decisionId, primaryId: options.primaryId, primary: [], reviewers: [], audit: [], outcome: 'open', fingerprints: [], fingerprintCounts: {}, loopLimit, snapshotRevision: 0, synthesis: null, orders: [] };
17
+ }
18
+ static restore(snapshot, registry) {
19
+ validateSnapshot(snapshot);
20
+ const engine = new DecisionEngine(copyEngineOptions(snapshot.decisionId, snapshot.primaryId, snapshot.loopLimit, registry));
21
+ engine.state = cloneSnapshot(snapshot);
22
+ return engine;
23
+ }
24
+ snapshot() { return freezeSnapshot(this.state); }
25
+ reservePrimary(requestId, purpose) {
26
+ validateId(requestId);
27
+ if (!['bootstrap', 'repair', 'continue'].includes(purpose))
28
+ throw new TypeError('invalid primary purpose');
29
+ const existing = this.state.primary.find((slot) => slot.requestId === requestId);
30
+ if (existing)
31
+ return cloneValue(existing);
32
+ if (this.state.outcome !== 'open')
33
+ throw new Error('decision is terminal');
34
+ if (this.state.primary.filter((slot) => slot.status !== 'released').length >= 2) {
35
+ this.state.outcome = 'needs_owner';
36
+ this.log({ kind: 'needs-owner', reason: 'primary budget exhausted' });
37
+ this.touch();
38
+ throw new Error('primary slot budget exhausted; needs-owner is terminal');
39
+ }
40
+ const call = Object.freeze({ requestId, advisorId: this.roles.activeEpoch.primaryId, purpose, status: 'prepared' });
41
+ this.roles.consumePrimarySlot(requestId); // T07-01 enforces the shared two-slot invariant.
42
+ this.state.primary.push(call);
43
+ this.log({ kind: 'primary-reserved', requestId, purpose });
44
+ this.touch();
45
+ return cloneValue(call);
46
+ }
47
+ settlePrimary(requestId, result) {
48
+ const index = this.primaryIndex(requestId), slot = this.state.primary[index];
49
+ if (slot.status !== 'prepared' && slot.status !== 'unknown')
50
+ throw new TypeError('primary request is not prepared or reconcilable');
51
+ const status = result === 'sent' ? 'sent' : result === 'unknown' ? 'unknown' : 'released';
52
+ this.state.primary[index] = Object.freeze({ ...slot, status });
53
+ this.log({ kind: 'primary-settled', requestId, reason: status });
54
+ this.touch();
55
+ return status;
56
+ }
57
+ reconcilePrimary(requestId, result) {
58
+ const status = this.settlePrimary(requestId, result);
59
+ return status === 'sent' ? 'consumed' : status === 'unknown' ? 'needs_reconciliation' : 'released';
60
+ }
61
+ finishPrimary(requestId, reply) {
62
+ const index = this.primaryIndex(requestId), slot = this.state.primary[index];
63
+ if (slot.status !== 'sent')
64
+ throw new TypeError('primary response requires a sent request');
65
+ if (!reply || typeof reply !== 'object')
66
+ throw new TypeError('structured primary reply required');
67
+ if (reply.kind === 'review-request') {
68
+ if (typeof reply.reason !== 'string' || !reply.reason.trim() || !Array.isArray(reply.reviewers) || !reply.reviewers.length || reply.reviewers.some((id) => typeof id !== 'string' || !id.trim()))
69
+ throw new TypeError('invalid reviewer request');
70
+ this.log({ kind: 'review-requested', requestId, reason: reply.reason });
71
+ this.touch();
72
+ if (this.state.primary.filter((call) => call.status !== 'released').length >= 2) {
73
+ this.state.outcome = 'needs_owner';
74
+ this.log({ kind: 'needs-owner', reason: 'primary exhausted while requesting more review' });
75
+ this.touch();
76
+ return Object.freeze({ outcome: 'needs_owner' });
77
+ }
78
+ return Object.freeze({ outcome: 'review_requested' }); // one bounded reviewer request.
79
+ }
80
+ if (reply.kind !== 'final' || !['execute', 'investigate', 'needs_owner', 'done', 'reject'].includes(reply.outcome) || typeof reply.rationale !== 'string' || !reply.rationale.trim())
81
+ throw new TypeError('invalid final decision');
82
+ this.state.outcome = reply.outcome === 'needs_owner' ? 'needs_owner' : 'final';
83
+ this.log({ kind: 'decision-final', requestId, reason: reply.rationale });
84
+ this.touch();
85
+ return Object.freeze({ outcome: this.state.outcome });
86
+ }
87
+ reserveReviewers(reviewerIds, evidenceRevision) {
88
+ this.assertOpen();
89
+ if (!Array.isArray(reviewerIds) || !reviewerIds.length || !Number.isSafeInteger(evidenceRevision) || evidenceRevision < 1)
90
+ throw new TypeError('reviewers and positive evidence revision required');
91
+ if (new Set(reviewerIds).size !== reviewerIds.length || reviewerIds.some((id) => typeof id !== 'string' || !id.trim()))
92
+ throw new TypeError('unique reviewer IDs required');
93
+ const calls = reviewerIds.map((reviewerId, index) => Object.freeze({ requestId: `review-${this.state.decisionId}-${this.state.reviewers.length + index + 1}`, reviewerId, evidenceRevision, status: 'pending' }));
94
+ this.state.reviewers.push(...calls);
95
+ for (const call of calls)
96
+ this.log({ kind: 'reviewer-dispatched', requestId: call.requestId });
97
+ this.touch();
98
+ return Object.freeze(calls.map((call) => cloneValue(call)));
99
+ }
100
+ submitReviewerOpinion(requestId, opinion) {
101
+ const index = this.state.reviewers.findIndex((call) => call.requestId === requestId);
102
+ if (index < 0)
103
+ throw new TypeError('unknown reviewer request');
104
+ const call = this.state.reviewers[index];
105
+ if (call.status === 'timed_out' || this.state.synthesis !== null) {
106
+ this.log({ kind: 'late-review-ignored', requestId });
107
+ this.touch();
108
+ return 'late_ignored';
109
+ }
110
+ this.state.reviewers[index] = Object.freeze({ ...call, status: 'submitted', opinion: cloneValue(opinion) });
111
+ this.touch();
112
+ return 'accepted';
113
+ }
114
+ timeoutReviewer(requestId) { const i = this.state.reviewers.findIndex((x) => x.requestId === requestId); if (i < 0 || this.state.reviewers[i].status !== 'pending')
115
+ throw new TypeError('reviewer is not pending'); this.state.reviewers[i] = Object.freeze({ ...this.state.reviewers[i], status: 'timed_out' }); this.log({ kind: 'reviewer-timeout', requestId }); this.touch(); }
116
+ synthesizeReviewers() { if (this.state.reviewers.some((x) => x.status === 'pending'))
117
+ throw new Error('all reviewer calls must settle before synthesis'); const opinions = this.state.reviewers.filter((x) => x.status === 'submitted').map((x) => cloneValue(x.opinion && typeof x.opinion === 'object' && 'opinion' in x.opinion ? x.opinion.opinion : x.opinion)); this.state.synthesis = opinions; this.touch(); return Object.freeze(opinions); }
118
+ settleUnavailableFallback() { if (this.state.outcome !== 'open')
119
+ return; this.state.outcome = this.state.reviewers.some((x) => x.status === 'pending') ? 'needs_owner' : 'final'; this.log({ kind: this.state.outcome === 'final' ? 'final-with-coverage' : 'needs-owner', reason: 'fallback unavailable' }); this.touch(); }
120
+ recordProblem(raw) { if (typeof raw !== 'string' || !raw.trim())
121
+ throw new TypeError('problem description required'); const fp = normalizeProblemFingerprint(raw); const count = (this.state.fingerprintCounts[fp] ?? 0) + 1; this.state.fingerprintCounts[fp] = count; if (!this.state.fingerprints.includes(fp))
122
+ this.state.fingerprints.push(fp); this.log({ kind: 'problem-observed', reason: fp }); if (count >= this.state.loopLimit) {
123
+ this.state.outcome = 'needs_owner';
124
+ this.log({ kind: 'needs-owner', reason: 'same problem reached loop ceiling' });
125
+ this.touch();
126
+ return 'needs_owner';
127
+ } this.touch(); return 'continue'; }
128
+ recordAcceptedOrder(workOrderId, payload) { validateId(workOrderId); if (this.state.orders.some((x) => x.workOrderId === workOrderId))
129
+ throw new TypeError('accepted order is immutable and unique'); this.state.orders.push(Object.freeze({ workOrderId, payload: cloneValue(payload), dispatchCount: 1, state: 'accepted' })); this.log({ kind: 'order-accepted', requestId: workOrderId }); this.touch(); }
130
+ reconcileAcceptedOrder(workOrderId, result) { const i = this.state.orders.findIndex((x) => x.workOrderId === workOrderId); if (i < 0)
131
+ throw new TypeError('unknown accepted order'); if (result === 'accepted')
132
+ return 'accepted'; if (result === 'unknown') {
133
+ this.state.orders[i] = Object.freeze({ ...this.state.orders[i], state: 'unknown' });
134
+ this.state.outcome = 'needs_owner';
135
+ this.log({ kind: 'order-reconciliation-unknown', requestId: workOrderId });
136
+ this.touch();
137
+ return 'needs_owner';
138
+ } this.state.orders[i] = Object.freeze({ ...this.state.orders[i], state: 'reconciled' }); this.touch(); return 'not_received'; }
139
+ replayOrder(workOrderId) { if (this.state.orders.some((x) => x.workOrderId === workOrderId))
140
+ throw new Error('accepted order mutation cannot be replayed'); throw new TypeError('unknown order'); }
141
+ primaryIndex(id) { const i = this.state.primary.findIndex((x) => x.requestId === id); if (i < 0)
142
+ throw new TypeError('unknown primary request'); return i; }
143
+ assertOpen() { if (this.state.outcome !== 'open')
144
+ throw new Error('decision is terminal'); }
145
+ log(entry) { this.state.audit.push(Object.freeze(entry)); }
146
+ touch() { this.state.snapshotRevision++; }
147
+ }
148
+ function validateId(id) { if (typeof id !== 'string' || !/^[a-z][a-z0-9_-]{5,63}$/.test(id))
149
+ throw new TypeError('valid request/order ID required'); }
150
+ export function normalizeProblemFingerprint(raw) { if (typeof raw !== 'string' || !raw.trim())
151
+ throw new TypeError('problem description required'); const normalized = raw.toLowerCase().replace(/\b\d{4}-\d\d-\d\d(?:t\d\d:\d\d(?::\d\d(?:\.\d+)?)?z)?\b/gi, ' ').replace(/\b\d{1,2}:\d{2}(?::\d{2})?\b/g, ' ').replace(/\b(at|on|the|a|an|while|when|occurred|happened|response|reading|read|got|was|is|during)\b/g, ' ').replace(/\b(time\s*out|timed\s*out|timeout)\b/g, ' timeout ').replace(/[^a-z0-9]+/g, ' ').trim().split(/\s+/).filter(Boolean).sort(); return normalized.join(' '); }
152
+ function cloneValue(value) { return structuredClone(value); }
153
+ function cloneSnapshot(s) { return structuredClone(s); }
154
+ function freezeSnapshot(s) { return deepFreeze(cloneSnapshot(s)); }
155
+ function deepFreeze(value) { if (value && typeof value === 'object' && !Object.isFrozen(value)) {
156
+ Object.values(value).forEach((v) => deepFreeze(v));
157
+ Object.freeze(value);
158
+ } return value; }
159
+ function validateSnapshot(s) { if (!s || typeof s !== 'object' || typeof s.decisionId !== 'string' || typeof s.primaryId !== 'string' || !Array.isArray(s.primary) || !Array.isArray(s.reviewers) || !Array.isArray(s.audit) || s.primary.length > 2 || !Number.isSafeInteger(s.snapshotRevision) || s.snapshotRevision < 0)
160
+ throw new TypeError('invalid decision snapshot'); const ids = new Set(); for (const slot of s.primary) {
161
+ validateId(slot.requestId);
162
+ if (ids.has(slot.requestId) || !['prepared', 'sent', 'unknown', 'released'].includes(slot.status))
163
+ throw new TypeError('invalid or duplicate primary slot');
164
+ ids.add(slot.requestId);
165
+ } if (s.outcome !== 'open' && s.outcome !== 'final' && s.outcome !== 'needs_owner')
166
+ throw new TypeError('invalid outcome'); }
167
+ //# sourceMappingURL=decision.js.map
@@ -0,0 +1,115 @@
1
+ type FailureKind = 'quota' | 'login' | 'network' | 'unknown';
2
+ export interface ProviderFailure {
3
+ readonly kind: FailureKind;
4
+ readonly message?: string;
5
+ }
6
+ export interface FailurePolicy {
7
+ readonly kind: FailureKind;
8
+ readonly automaticFailover: boolean;
9
+ readonly retryLimit: number;
10
+ readonly cooldown: boolean;
11
+ readonly requiresOwner: boolean;
12
+ }
13
+ export interface HandoverOptions {
14
+ readonly decisionId: string;
15
+ readonly primaryId: string;
16
+ readonly cooldownMs?: number;
17
+ readonly now?: () => number;
18
+ readonly instanceId?: string;
19
+ readonly networkRetryLimit?: number;
20
+ }
21
+ export interface HandoverContext {
22
+ readonly decision: unknown;
23
+ readonly consumedSlots: readonly string[];
24
+ readonly currentWork: Readonly<{
25
+ id: string;
26
+ state: string;
27
+ checkpoint: unknown;
28
+ dispatchCount: number;
29
+ }> | null;
30
+ }
31
+ export interface HandoverFence {
32
+ readonly epoch: number;
33
+ readonly primaryId: string;
34
+ readonly instanceId: string;
35
+ }
36
+ /**
37
+ * `not_sent` is a contract that no external side effect occurred. A thrown exception or
38
+ * ambiguous outcome is treated as unknown and remains charged; return `not_sent` only
39
+ * when the callback can guarantee the operation was not externally applied.
40
+ */
41
+ export type PrimarySlotSend = () => Promise<'sent' | 'unknown' | 'not_sent'> | 'sent' | 'unknown' | 'not_sent';
42
+ /** SIMULATED provider-state seam: in-memory policies/fencing only; live provider observation is not performed here. */
43
+ export declare class HandoverService {
44
+ private primary;
45
+ private epoch;
46
+ private readonly roles;
47
+ private readonly instanceId;
48
+ private readonly networkRetryLimit;
49
+ private readonly networkRetries;
50
+ private cooldowns;
51
+ private readonly events;
52
+ private history;
53
+ private transferred;
54
+ private dispatched;
55
+ private terminal;
56
+ private exhaustedResult;
57
+ private readonly clock;
58
+ private readonly cooldownMs;
59
+ readonly decisionId: string;
60
+ readonly persistence: 'in-memory';
61
+ constructor(options: HandoverOptions);
62
+ get currentPrimary(): string;
63
+ get currentFence(): HandoverFence;
64
+ get primarySlotsRemaining(): number;
65
+ get responseHistory(): readonly {
66
+ readonly fence: HandoverFence;
67
+ readonly value: any;
68
+ }[];
69
+ get audit(): readonly {
70
+ readonly kind: string;
71
+ readonly reason: string;
72
+ readonly provider?: string;
73
+ }[];
74
+ classifyFailure(failure: ProviderFailure): ProviderFailure;
75
+ failurePolicy(kind: FailureKind): FailurePolicy;
76
+ recordFailure(failure: ProviderFailure): FailurePolicy;
77
+ recordNetworkRetry(requestId: string): boolean;
78
+ consumePrimarySlot(requestId: string): number;
79
+ primarySlotState(requestId: string): 'reserved' | 'sent' | 'unknown' | 'accepted' | 'released' | undefined;
80
+ acceptPrimarySlot(requestId: string): void;
81
+ releasePrimarySlot(requestId: string): number;
82
+ /**
83
+ * Runs the only valid settlement path for a consumed primary slot. The callback's `not_sent`
84
+ * return is a guarantee that no external side effect occurred; exceptions/ambiguous values
85
+ * are charged as unknown.
86
+ */
87
+ dispatchPrimarySlot(requestId: string, send: PrimarySlotSend): Promise<'sent' | 'unknown' | 'not_sent'>;
88
+ failover(input: {
89
+ readonly failure: ProviderFailure;
90
+ readonly candidates: readonly string[];
91
+ readonly now?: number;
92
+ }): {
93
+ readonly decisionId: string;
94
+ readonly primaryId: string;
95
+ readonly primarySlotsRemaining: number;
96
+ readonly reason: string;
97
+ };
98
+ manualSwitch(primaryId: string, reason?: string): HandoverFence;
99
+ availableProviders(providers: readonly string[], now?: number): readonly string[];
100
+ transfer(context: HandoverContext): HandoverContext;
101
+ dispatchWorkOrder(workOrderId: string): boolean;
102
+ dispatchCount(workOrderId: string): number;
103
+ recordPrimaryResponse(fence: HandoverFence, value: unknown): 'current' | 'stale';
104
+ authorizeSideEffect(fence: HandoverFence): boolean;
105
+ exhaustFallbacks(input: {
106
+ readonly reviewerTimedOut: boolean;
107
+ readonly unavailable: readonly string[];
108
+ readonly coverage: readonly string[];
109
+ }): {
110
+ readonly terminal: true;
111
+ readonly outcome: 'final' | 'needs-owner';
112
+ readonly coverage: readonly string[];
113
+ };
114
+ }
115
+ export {};
@@ -0,0 +1,191 @@
1
+ import { advisorId } from '../core/ids.js';
2
+ import { RoleEpoch } from './role-epoch.js';
3
+ /** SIMULATED provider-state seam: in-memory policies/fencing only; live provider observation is not performed here. */
4
+ export class HandoverService {
5
+ primary;
6
+ epoch = 1;
7
+ roles;
8
+ instanceId;
9
+ networkRetryLimit;
10
+ networkRetries = new Map();
11
+ cooldowns = new Map();
12
+ events = [];
13
+ history = [];
14
+ transferred = null;
15
+ dispatched = new Set();
16
+ terminal = false;
17
+ exhaustedResult = null;
18
+ clock;
19
+ cooldownMs;
20
+ decisionId;
21
+ persistence = 'in-memory';
22
+ constructor(options) {
23
+ if (!options || typeof options.decisionId !== 'string' || !options.decisionId.trim())
24
+ throw new TypeError('decision ID required');
25
+ this.decisionId = options.decisionId;
26
+ this.primary = advisorId(options.primaryId);
27
+ this.roles = new RoleEpoch(this.primary, { decisionId: this.decisionId });
28
+ this.clock = options.now ?? Date.now;
29
+ this.cooldownMs = options.cooldownMs ?? 60_000;
30
+ this.instanceId = options.instanceId ?? `handover-${Math.random().toString(36).slice(2)}`;
31
+ this.networkRetryLimit = options.networkRetryLimit ?? 2;
32
+ if (!Number.isSafeInteger(this.cooldownMs) || this.cooldownMs < 0)
33
+ throw new TypeError('non-negative cooldown required');
34
+ if (!Number.isSafeInteger(this.networkRetryLimit) || this.networkRetryLimit < 0)
35
+ throw new TypeError('non-negative network retry limit required');
36
+ if (typeof this.instanceId !== 'string' || !this.instanceId.trim())
37
+ throw new TypeError('instance ID required');
38
+ }
39
+ get currentPrimary() { return this.primary; }
40
+ get currentFence() { return Object.freeze({ epoch: this.epoch, primaryId: this.primary, instanceId: this.instanceId }); }
41
+ get primarySlotsRemaining() { return this.roles.primarySlotsRemaining; }
42
+ get responseHistory() { return Object.freeze(this.history.map((entry) => Object.freeze({ fence: entry.fence, value: structuredClone(entry.value) }))); }
43
+ get audit() { return Object.freeze(this.events.map((event) => Object.freeze({ ...event }))); }
44
+ classifyFailure(failure) {
45
+ if (!failure || !['quota', 'login', 'network', 'unknown'].includes(failure.kind))
46
+ throw new TypeError('provider failure kind required');
47
+ return Object.freeze({ ...failure });
48
+ }
49
+ failurePolicy(kind) {
50
+ if (!['quota', 'login', 'network', 'unknown'].includes(kind))
51
+ throw new TypeError('provider failure kind required');
52
+ if (kind === 'quota')
53
+ return Object.freeze({ kind, automaticFailover: true, retryLimit: 0, cooldown: true, requiresOwner: false });
54
+ if (kind === 'login')
55
+ return Object.freeze({ kind, automaticFailover: false, retryLimit: 0, cooldown: false, requiresOwner: true });
56
+ if (kind === 'network')
57
+ return Object.freeze({ kind, automaticFailover: false, retryLimit: this.networkRetryLimit, cooldown: false, requiresOwner: false });
58
+ return Object.freeze({ kind, automaticFailover: false, retryLimit: 0, cooldown: false, requiresOwner: true });
59
+ }
60
+ recordFailure(failure) {
61
+ const classified = this.classifyFailure(failure), policy = this.failurePolicy(classified.kind);
62
+ if (classified.kind === 'quota')
63
+ this.cooldowns.set(this.primary, this.clock() + this.cooldownMs);
64
+ if (classified.kind === 'login')
65
+ this.events.push(Object.freeze({ kind: 'login-owner-required', reason: 'login failure requires owner re-authentication; not counted as quota', provider: this.primary }));
66
+ else if (classified.kind === 'network')
67
+ this.events.push(Object.freeze({ kind: 'network-retry-bounded', reason: `network retry limit ${policy.retryLimit}`, provider: this.primary }));
68
+ else if (classified.kind === 'quota')
69
+ this.events.push(Object.freeze({ kind: 'quota-cooldown', reason: 'quota failure recorded; cooldown before failover', provider: this.primary }));
70
+ else
71
+ this.events.push(Object.freeze({ kind: 'unknown-owner-required', reason: 'unknown failure requires owner review', provider: this.primary }));
72
+ return policy;
73
+ }
74
+ recordNetworkRetry(requestId) {
75
+ if (typeof requestId !== 'string' || !requestId.trim())
76
+ throw new TypeError('request ID required');
77
+ const attempts = this.networkRetries.get(requestId) ?? 0;
78
+ if (attempts >= this.networkRetryLimit)
79
+ return false;
80
+ this.networkRetries.set(requestId, attempts + 1);
81
+ return true;
82
+ }
83
+ consumePrimarySlot(requestId) { return this.roles.consumePrimarySlot(requestId); }
84
+ primarySlotState(requestId) { return this.roles.primarySlotState(requestId); }
85
+ acceptPrimarySlot(requestId) { this.roles.acceptPrimarySlot(requestId); }
86
+ releasePrimarySlot(requestId) { return this.roles.releasePrimarySlot(requestId); }
87
+ /**
88
+ * Runs the only valid settlement path for a consumed primary slot. The callback's `not_sent`
89
+ * return is a guarantee that no external side effect occurred; exceptions/ambiguous values
90
+ * are charged as unknown.
91
+ */
92
+ async dispatchPrimarySlot(requestId, send) {
93
+ if (typeof send !== 'function')
94
+ throw new TypeError('send operation required');
95
+ return this.roles.dispatchPrimarySlot(requestId, send);
96
+ }
97
+ failover(input) {
98
+ if (this.terminal)
99
+ throw new Error('decision is terminal');
100
+ const failure = this.classifyFailure(input?.failure);
101
+ if (failure.kind !== 'quota')
102
+ throw new Error('quota failure required for automatic failover');
103
+ if (this.primarySlotsRemaining === 0)
104
+ throw new Error('primary slot budget exhausted');
105
+ const now = input.now ?? this.clock();
106
+ if (!Number.isFinite(now))
107
+ throw new TypeError('valid failover timestamp required');
108
+ const candidates = (input.candidates ?? []).map((id) => advisorId(id));
109
+ // The exhausted primary cooldown is intentionally recorded before checking terminal fallback availability.
110
+ this.cooldowns.set(this.primary, now + this.cooldownMs);
111
+ const next = candidates.find((id) => id !== this.primary && (this.cooldowns.get(id) ?? -Infinity) <= now);
112
+ if (!next) {
113
+ this.terminal = true;
114
+ throw new Error('no available fallback; decision is terminal');
115
+ }
116
+ const prior = this.primary;
117
+ this.primary = next;
118
+ this.epoch++;
119
+ const reason = `quota failure on ${prior}; selected fallback ${next}`;
120
+ this.events.push(Object.freeze({ kind: 'failover', reason, provider: next }));
121
+ return Object.freeze({ decisionId: this.decisionId, primaryId: next, primarySlotsRemaining: this.primarySlotsRemaining, reason });
122
+ }
123
+ manualSwitch(primaryId, reason = 'manual owner switch') {
124
+ if (this.terminal)
125
+ throw new Error('decision is terminal');
126
+ if (typeof reason !== 'string' || !reason.trim())
127
+ throw new TypeError('switch reason required');
128
+ const next = advisorId(primaryId);
129
+ this.primary = next;
130
+ this.epoch++;
131
+ this.events.push(Object.freeze({ kind: 'manual-switch', reason, provider: next }));
132
+ return this.currentFence;
133
+ }
134
+ availableProviders(providers, now = this.clock()) {
135
+ if (!Number.isFinite(now))
136
+ throw new TypeError('valid provider observation timestamp required');
137
+ return Object.freeze(providers.map((id) => advisorId(id)).filter((id) => (this.cooldowns.get(id) ?? -Infinity) <= now));
138
+ }
139
+ transfer(context) {
140
+ if (!context || !Array.isArray(context.consumedSlots) || !(context.currentWork === null || context.currentWork && typeof context.currentWork.id === 'string'))
141
+ throw new TypeError('decision, slots and current work state required');
142
+ if (context.currentWork && (!Number.isSafeInteger(context.currentWork.dispatchCount) || context.currentWork.dispatchCount !== 1))
143
+ throw new TypeError('accepted work must retain exactly one dispatch');
144
+ const cloned = structuredClone(context);
145
+ if (this.transferred === null)
146
+ this.transferred = deepFreeze(cloned);
147
+ else if (JSON.stringify(this.transferred) !== JSON.stringify(cloned))
148
+ throw new Error('handover context is immutable once transferred');
149
+ if (cloned.currentWork)
150
+ this.dispatched.add(cloned.currentWork.id);
151
+ return deepFreeze(structuredClone(this.transferred));
152
+ }
153
+ dispatchWorkOrder(workOrderId) {
154
+ if (typeof workOrderId !== 'string' || !workOrderId.trim())
155
+ throw new TypeError('work order ID required');
156
+ if (this.dispatched.has(workOrderId))
157
+ throw new Error('work order already received; redispatch refused');
158
+ this.dispatched.add(workOrderId);
159
+ return true;
160
+ }
161
+ dispatchCount(workOrderId) { return this.dispatched.has(workOrderId) ? 1 : 0; }
162
+ recordPrimaryResponse(fence, value) {
163
+ if (!fence || !Number.isSafeInteger(fence.epoch) || typeof fence.primaryId !== 'string' || typeof fence.instanceId !== 'string')
164
+ throw new TypeError('valid fencing token required');
165
+ const classification = fence.epoch === this.epoch && fence.primaryId === this.primary && fence.instanceId === this.instanceId ? 'current' : 'stale';
166
+ this.history.push(Object.freeze({ fence: Object.freeze({ ...fence }), value: structuredClone(value) }));
167
+ this.events.push(Object.freeze({ kind: 'primary-response', reason: `${classification} response retained in history` }));
168
+ return classification;
169
+ }
170
+ authorizeSideEffect(fence) {
171
+ return !!fence && Number.isSafeInteger(fence.epoch) && fence.epoch === this.epoch && fence.primaryId === this.primary && fence.instanceId === this.instanceId;
172
+ }
173
+ exhaustFallbacks(input) {
174
+ if (!input || !Array.isArray(input.unavailable) || !Array.isArray(input.coverage))
175
+ throw new TypeError('fallback results and coverage required');
176
+ if (this.exhaustedResult)
177
+ return this.exhaustedResult;
178
+ this.terminal = true;
179
+ const coverage = Object.freeze([...input.coverage]);
180
+ const outcome = coverage.length > 0 ? 'final' : 'needs-owner';
181
+ const reason = `reviewer timed out=${input.reviewerTimedOut}; unavailable fallbacks=${input.unavailable.length}; outcome=${outcome}`;
182
+ this.events.push(Object.freeze({ kind: 'fallbacks-exhausted', reason }));
183
+ this.exhaustedResult = Object.freeze({ terminal: true, outcome, coverage });
184
+ return this.exhaustedResult;
185
+ }
186
+ }
187
+ function deepFreeze(value) { if (value && typeof value === 'object' && !Object.isFrozen(value)) {
188
+ Object.values(value).forEach((child) => deepFreeze(child));
189
+ Object.freeze(value);
190
+ } return value; }
191
+ //# sourceMappingURL=handover.js.map
@@ -0,0 +1,44 @@
1
+ export interface NoProgressState {
2
+ readonly attemptCount: number;
3
+ readonly terminal: boolean;
4
+ readonly outcome: 'open' | 'final_with_coverage' | 'needs_owner';
5
+ readonly failureCounts: Readonly<Record<string, number>>;
6
+ readonly lastEvidenceFingerprint: string | null;
7
+ readonly rejectedIdeas: readonly string[];
8
+ readonly rejectedIdeaEvidence: Readonly<Record<string, string>>;
9
+ }
10
+ export type NoProgressEvent = {
11
+ readonly kind: 'primary';
12
+ readonly turn: number;
13
+ readonly asksForMore: boolean;
14
+ } | {
15
+ readonly kind: 'attempt';
16
+ readonly failure: string;
17
+ readonly evidenceFingerprint: string;
18
+ } | {
19
+ readonly kind: 'reviewer-timeout' | 'late-review' | 'fallback-unavailable';
20
+ readonly evidenceFingerprint: string;
21
+ } | {
22
+ readonly kind: 'rejected-idea';
23
+ readonly ideaFingerprint: string;
24
+ readonly evidenceFingerprint: string;
25
+ } | {
26
+ readonly kind: 'read-only-report';
27
+ readonly adequate: boolean;
28
+ readonly evidenceFingerprint: string;
29
+ } | {
30
+ readonly kind: 'disagreement';
31
+ readonly evidenceFingerprint: string;
32
+ };
33
+ export interface NoProgressOptions {
34
+ readonly loopLimit: number;
35
+ readonly taskAttemptBudget: number;
36
+ }
37
+ export interface NoProgressResult {
38
+ readonly state: NoProgressState;
39
+ readonly outcome: 'continue' | 'investigate' | 'not_requeued' | 'final_with_coverage' | 'needs_owner';
40
+ readonly progress: boolean;
41
+ }
42
+ export declare function initialNoProgressState(): NoProgressState;
43
+ /** Pure task-level attempt policy. It does not invoke providers or mutate shared decision history. */
44
+ export declare function evaluateNoProgress(state: NoProgressState, event: NoProgressEvent, options?: NoProgressOptions): NoProgressResult;