sentinelayer-cli 0.6.2 → 0.8.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 (280) hide show
  1. package/README.md +1009 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. package/src/ui/markdown.js +220 -220
@@ -1,770 +1,1083 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
-
4
- import { WORK_ITEM_STATUSES, resolveErrorDaemonStorage } from "./error-worker.js";
5
-
6
- const LEDGER_SCHEMA_VERSION = "1.0.0";
7
- const QUEUE_SCHEMA_VERSION = "1.0.0";
8
-
9
- export const ASSIGNMENT_STATUSES = Object.freeze([
10
- "QUEUED",
11
- "CLAIMED",
12
- "IN_PROGRESS",
13
- "RELEASED",
14
- "DONE",
15
- "BLOCKED",
16
- "SQUASHED",
17
- ]);
18
-
19
- const ASSIGNMENT_STATUS_SET = new Set(ASSIGNMENT_STATUSES);
20
- const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
21
- const ACTIVE_ASSIGNMENT_STATUSES = new Set(["CLAIMED", "IN_PROGRESS"]);
22
- const RELEASE_TARGET_STATUSES = new Set(["QUEUED", "DONE", "BLOCKED", "SQUASHED"]);
23
-
24
- function normalizeString(value) {
25
- return String(value || "").trim();
26
- }
27
-
28
- function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
29
- const normalized = normalizeString(value);
30
- if (!normalized) {
31
- return fallbackIso;
32
- }
33
- const epoch = Date.parse(normalized);
34
- if (!Number.isFinite(epoch)) {
35
- return fallbackIso;
36
- }
37
- return new Date(epoch).toISOString();
38
- }
39
-
40
- function normalizePositiveInteger(value, fallbackValue = 1) {
41
- if (value === undefined || value === null || normalizeString(value) === "") {
42
- return fallbackValue;
43
- }
44
- const normalized = Number(value);
45
- if (!Number.isFinite(normalized) || normalized <= 0) {
46
- throw new Error("Value must be a positive integer.");
47
- }
48
- return Math.floor(normalized);
49
- }
50
-
51
- function normalizeMetadata(value) {
52
- if (!value || typeof value !== "object" || Array.isArray(value)) {
53
- return {};
54
- }
55
- return { ...value };
56
- }
57
-
58
- function normalizeAssignmentStatus(value, fallbackValue = "QUEUED") {
59
- const normalized = normalizeString(value).toUpperCase();
60
- if (ASSIGNMENT_STATUS_SET.has(normalized)) {
61
- return normalized;
62
- }
63
- return fallbackValue;
64
- }
65
-
66
- function normalizeWorkItemStatus(value, fallbackValue = "QUEUED") {
67
- const normalized = normalizeString(value).toUpperCase();
68
- if (WORK_ITEM_STATUS_SET.has(normalized)) {
69
- return normalized;
70
- }
71
- return fallbackValue;
72
- }
73
-
74
- function toIsoAfterSeconds(nowIso, seconds) {
75
- const baseEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString())) || Date.now();
76
- return new Date(baseEpoch + seconds * 1000).toISOString();
77
- }
78
-
79
- function parseStatusList(statuses = []) {
80
- if (!Array.isArray(statuses)) {
81
- return null;
82
- }
83
- const normalized = statuses
84
- .map((item) => normalizeString(item).toUpperCase())
85
- .filter(Boolean)
86
- .filter((item) => ASSIGNMENT_STATUS_SET.has(item));
87
- if (normalized.length === 0) {
88
- return null;
89
- }
90
- return new Set(normalized);
91
- }
92
-
93
- function createInitialLedger(nowIso = new Date().toISOString()) {
94
- return {
95
- schemaVersion: LEDGER_SCHEMA_VERSION,
96
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
97
- assignments: [],
98
- };
99
- }
100
-
101
- function createInitialQueue(nowIso = new Date().toISOString()) {
102
- return {
103
- schemaVersion: QUEUE_SCHEMA_VERSION,
104
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
105
- items: [],
106
- };
107
- }
108
-
109
- function normalizeAssignmentRecord(record = {}, nowIso = new Date().toISOString()) {
110
- const updatedAt = normalizeIsoTimestamp(record.updatedAt, nowIso);
111
- return {
112
- workItemId: normalizeString(record.workItemId),
113
- assignedAgentIdentity: normalizeString(record.assignedAgentIdentity) || null,
114
- leasedAt: record.leasedAt ? normalizeIsoTimestamp(record.leasedAt, updatedAt) : null,
115
- leaseTtlSeconds: Math.max(1, normalizePositiveInteger(record.leaseTtlSeconds, 1800)),
116
- leaseExpiresAt: record.leaseExpiresAt ? normalizeIsoTimestamp(record.leaseExpiresAt, updatedAt) : null,
117
- status: normalizeAssignmentStatus(record.status),
118
- stage: normalizeString(record.stage) || "triage",
119
- runId: normalizeString(record.runId) || null,
120
- jiraIssueKey: normalizeString(record.jiraIssueKey) || null,
121
- budgetSnapshot: normalizeMetadata(record.budgetSnapshot),
122
- heartbeatAt: record.heartbeatAt ? normalizeIsoTimestamp(record.heartbeatAt, updatedAt) : null,
123
- releasedAt: record.releasedAt ? normalizeIsoTimestamp(record.releasedAt, updatedAt) : null,
124
- releaseReason: normalizeString(record.releaseReason) || null,
125
- updatedAt,
126
- };
127
- }
128
-
129
- function isAssignmentExpired(record = {}, nowIso = new Date().toISOString()) {
130
- if (!record || !ACTIVE_ASSIGNMENT_STATUSES.has(normalizeAssignmentStatus(record.status))) {
131
- return false;
132
- }
133
- const expiry = Date.parse(String(record.leaseExpiresAt || ""));
134
- const now = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
135
- if (!Number.isFinite(expiry) || !Number.isFinite(now)) {
136
- return false;
137
- }
138
- return expiry <= now;
139
- }
140
-
141
- function normalizeQueueItem(item = {}, nowIso = new Date().toISOString()) {
142
- return {
143
- ...item,
144
- workItemId: normalizeString(item.workItemId),
145
- status: normalizeWorkItemStatus(item.status),
146
- updatedAt: normalizeIsoTimestamp(item.updatedAt, nowIso),
147
- metadata: normalizeMetadata(item.metadata),
148
- };
149
- }
150
-
151
- async function loadJsonFile(filePath, defaultFactory) {
152
- try {
153
- const raw = await fsp.readFile(filePath, "utf-8");
154
- return JSON.parse(raw);
155
- } catch (error) {
156
- if (error && typeof error === "object" && error.code === "ENOENT") {
157
- return defaultFactory();
158
- }
159
- throw error;
160
- }
161
- }
162
-
163
- async function writeJsonFile(filePath, payload = {}) {
164
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
165
- await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
166
- }
167
-
168
- async function appendEvent(filePath, payload = {}) {
169
- await fsp.mkdir(path.dirname(filePath), { recursive: true });
170
- await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
171
- }
172
-
173
- async function loadLedger(ledgerPath, nowIso = new Date().toISOString()) {
174
- const parsed = await loadJsonFile(ledgerPath, () => createInitialLedger(nowIso));
175
- return {
176
- schemaVersion: normalizeString(parsed.schemaVersion) || LEDGER_SCHEMA_VERSION,
177
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
178
- assignments: Array.isArray(parsed.assignments)
179
- ? parsed.assignments
180
- .map((record) => normalizeAssignmentRecord(record, nowIso))
181
- .filter((record) => normalizeString(record.workItemId))
182
- : [],
183
- };
184
- }
185
-
186
- async function writeLedger(ledgerPath, ledger = {}, nowIso = new Date().toISOString()) {
187
- const normalized = {
188
- schemaVersion: LEDGER_SCHEMA_VERSION,
189
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
190
- assignments: Array.isArray(ledger.assignments)
191
- ? ledger.assignments
192
- .map((record) => normalizeAssignmentRecord(record, nowIso))
193
- .filter((record) => normalizeString(record.workItemId))
194
- : [],
195
- };
196
- await writeJsonFile(ledgerPath, normalized);
197
- return normalized;
198
- }
199
-
200
- async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
201
- const parsed = await loadJsonFile(queuePath, () => createInitialQueue(nowIso));
202
- return {
203
- schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
204
- generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
205
- items: Array.isArray(parsed.items)
206
- ? parsed.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
207
- : [],
208
- };
209
- }
210
-
211
- async function writeQueue(queuePath, queue = {}, nowIso = new Date().toISOString()) {
212
- const normalized = {
213
- schemaVersion: QUEUE_SCHEMA_VERSION,
214
- generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
215
- items: Array.isArray(queue.items)
216
- ? queue.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
217
- : [],
218
- };
219
- await writeJsonFile(queuePath, normalized);
220
- return normalized;
221
- }
222
-
223
- function getAssignmentStoragePaths(baseStorage = {}) {
224
- return {
225
- ...baseStorage,
226
- ledgerPath: path.join(baseStorage.baseDir, "assignment-ledger.json"),
227
- eventsPath: path.join(baseStorage.baseDir, "assignment-events.ndjson"),
228
- };
229
- }
230
-
231
- async function loadLedgerAndQueue(storage, nowIso) {
232
- const [ledger, queue] = await Promise.all([
233
- loadLedger(storage.ledgerPath, nowIso),
234
- loadQueue(storage.queuePath, nowIso),
235
- ]);
236
- return { ledger, queue };
237
- }
238
-
239
- function findQueueItem(queue = {}, workItemId = "") {
240
- return queue.items.find((item) => item.workItemId === workItemId) || null;
241
- }
242
-
243
- function updateQueueItem({
244
- queue,
245
- workItemId,
246
- status,
247
- assignedAgentIdentity = null,
248
- stage = "",
249
- runId = null,
250
- jiraIssueKey = null,
251
- nowIso,
252
- } = {}) {
253
- const index = queue.items.findIndex((item) => item.workItemId === workItemId);
254
- if (index < 0) {
255
- throw new Error(`Work item '${workItemId}' was not found in daemon queue.`);
256
- }
257
- const existing = queue.items[index];
258
- queue.items[index] = normalizeQueueItem(
259
- {
260
- ...existing,
261
- status: normalizeWorkItemStatus(status, existing.status),
262
- updatedAt: nowIso,
263
- metadata: {
264
- ...normalizeMetadata(existing.metadata),
265
- assignedAgentIdentity: assignedAgentIdentity || null,
266
- stage: normalizeString(stage) || null,
267
- runId: normalizeString(runId) || null,
268
- jiraIssueKey: normalizeString(jiraIssueKey) || null,
269
- },
270
- },
271
- nowIso
272
- );
273
- return queue.items[index];
274
- }
275
-
276
- function findAssignmentIndex(ledger = {}, workItemId = "") {
277
- return ledger.assignments.findIndex((record) => record.workItemId === workItemId);
278
- }
279
-
280
- function requireAgentIdentity(value, fieldName = "agentIdentity") {
281
- const normalized = normalizeString(value);
282
- if (!normalized) {
283
- throw new Error(`${fieldName} is required.`);
284
- }
285
- return normalized;
286
- }
287
-
288
- function normalizeReleaseTargetStatus(value) {
289
- const normalized = normalizeString(value).toUpperCase();
290
- if (!RELEASE_TARGET_STATUSES.has(normalized)) {
291
- throw new Error(
292
- `status must be one of: ${[...RELEASE_TARGET_STATUSES].join(", ")}.`
293
- );
294
- }
295
- return normalized;
296
- }
297
-
298
- export async function resolveAssignmentLedgerStorage({
299
- targetPath = ".",
300
- outputDir = "",
301
- env,
302
- homeDir,
303
- } = {}) {
304
- const daemonStorage = await resolveErrorDaemonStorage({
305
- targetPath,
306
- outputDir,
307
- env,
308
- homeDir,
309
- });
310
- return getAssignmentStoragePaths(daemonStorage);
311
- }
312
-
313
- export async function claimAssignment({
314
- targetPath = ".",
315
- outputDir = "",
316
- workItemId,
317
- agentIdentity,
318
- leaseTtlSeconds = 1800,
319
- stage = "triage",
320
- runId = "",
321
- jiraIssueKey = "",
322
- budgetSnapshot = {},
323
- env,
324
- homeDir,
325
- nowIso = new Date().toISOString(),
326
- } = {}) {
327
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
328
- const normalizedWorkItemId = normalizeString(workItemId);
329
- if (!normalizedWorkItemId) {
330
- throw new Error("workItemId is required.");
331
- }
332
- const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
333
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
334
- const storage = await resolveAssignmentLedgerStorage({
335
- targetPath,
336
- outputDir,
337
- env,
338
- homeDir,
339
- });
340
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
341
-
342
- const queueItem = findQueueItem(queue, normalizedWorkItemId);
343
- if (!queueItem) {
344
- throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
345
- }
346
-
347
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
348
- const existingAssignment = assignmentIndex >= 0 ? ledger.assignments[assignmentIndex] : null;
349
- if (
350
- existingAssignment &&
351
- ACTIVE_ASSIGNMENT_STATUSES.has(existingAssignment.status) &&
352
- !isAssignmentExpired(existingAssignment, normalizedNow) &&
353
- existingAssignment.assignedAgentIdentity !== normalizedAgentIdentity
354
- ) {
355
- throw new Error(
356
- `Work item '${normalizedWorkItemId}' is currently leased by '${existingAssignment.assignedAgentIdentity}'.`
357
- );
358
- }
359
-
360
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
361
- const nextRecord = normalizeAssignmentRecord(
362
- {
363
- workItemId: normalizedWorkItemId,
364
- assignedAgentIdentity: normalizedAgentIdentity,
365
- leasedAt: normalizedNow,
366
- leaseTtlSeconds: normalizedTtl,
367
- leaseExpiresAt,
368
- status: "CLAIMED",
369
- stage,
370
- runId,
371
- jiraIssueKey,
372
- budgetSnapshot: normalizeMetadata(budgetSnapshot),
373
- heartbeatAt: null,
374
- releasedAt: null,
375
- releaseReason: null,
376
- updatedAt: normalizedNow,
377
- },
378
- normalizedNow
379
- );
380
-
381
- if (assignmentIndex >= 0) {
382
- ledger.assignments[assignmentIndex] = nextRecord;
383
- } else {
384
- ledger.assignments.push(nextRecord);
385
- }
386
- updateQueueItem({
387
- queue,
388
- workItemId: normalizedWorkItemId,
389
- status: "ASSIGNED",
390
- assignedAgentIdentity: normalizedAgentIdentity,
391
- stage,
392
- runId,
393
- jiraIssueKey,
394
- nowIso: normalizedNow,
395
- });
396
-
397
- const [savedLedger, savedQueue] = await Promise.all([
398
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
399
- writeQueue(storage.queuePath, queue, normalizedNow),
400
- ]);
401
-
402
- await appendEvent(storage.eventsPath, {
403
- timestamp: normalizedNow,
404
- eventType: "claim",
405
- workItemId: normalizedWorkItemId,
406
- agentIdentity: normalizedAgentIdentity,
407
- leaseTtlSeconds: normalizedTtl,
408
- leaseExpiresAt,
409
- stage: normalizeString(stage) || "triage",
410
- runId: normalizeString(runId) || null,
411
- jiraIssueKey: normalizeString(jiraIssueKey) || null,
412
- });
413
-
414
- return {
415
- ...storage,
416
- ledger: savedLedger,
417
- queue: savedQueue,
418
- assignment: nextRecord,
419
- };
420
- }
421
-
422
- export async function heartbeatAssignment({
423
- targetPath = ".",
424
- outputDir = "",
425
- workItemId,
426
- agentIdentity,
427
- leaseTtlSeconds = 1800,
428
- stage = "",
429
- runId = "",
430
- jiraIssueKey = "",
431
- budgetSnapshot = {},
432
- env,
433
- homeDir,
434
- nowIso = new Date().toISOString(),
435
- } = {}) {
436
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
437
- const normalizedWorkItemId = normalizeString(workItemId);
438
- if (!normalizedWorkItemId) {
439
- throw new Error("workItemId is required.");
440
- }
441
- const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
442
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
443
- const storage = await resolveAssignmentLedgerStorage({
444
- targetPath,
445
- outputDir,
446
- env,
447
- homeDir,
448
- });
449
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
450
-
451
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
452
- if (assignmentIndex < 0) {
453
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
454
- }
455
- const existing = ledger.assignments[assignmentIndex];
456
- if (existing.assignedAgentIdentity !== normalizedAgentIdentity) {
457
- throw new Error(
458
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
459
- );
460
- }
461
-
462
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
463
- const next = normalizeAssignmentRecord(
464
- {
465
- ...existing,
466
- status: "IN_PROGRESS",
467
- leaseTtlSeconds: normalizedTtl,
468
- leaseExpiresAt,
469
- heartbeatAt: normalizedNow,
470
- stage: normalizeString(stage) || existing.stage,
471
- runId: normalizeString(runId) || existing.runId,
472
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
473
- budgetSnapshot:
474
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
475
- ? normalizeMetadata(budgetSnapshot)
476
- : existing.budgetSnapshot,
477
- updatedAt: normalizedNow,
478
- },
479
- normalizedNow
480
- );
481
- ledger.assignments[assignmentIndex] = next;
482
- updateQueueItem({
483
- queue,
484
- workItemId: normalizedWorkItemId,
485
- status: "IN_PROGRESS",
486
- assignedAgentIdentity: normalizedAgentIdentity,
487
- stage: next.stage,
488
- runId: next.runId,
489
- jiraIssueKey: next.jiraIssueKey,
490
- nowIso: normalizedNow,
491
- });
492
-
493
- const [savedLedger, savedQueue] = await Promise.all([
494
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
495
- writeQueue(storage.queuePath, queue, normalizedNow),
496
- ]);
497
-
498
- await appendEvent(storage.eventsPath, {
499
- timestamp: normalizedNow,
500
- eventType: "heartbeat",
501
- workItemId: normalizedWorkItemId,
502
- agentIdentity: normalizedAgentIdentity,
503
- stage: next.stage,
504
- leaseExpiresAt,
505
- });
506
-
507
- return {
508
- ...storage,
509
- ledger: savedLedger,
510
- queue: savedQueue,
511
- assignment: next,
512
- };
513
- }
514
-
515
- export async function releaseAssignment({
516
- targetPath = ".",
517
- outputDir = "",
518
- workItemId,
519
- agentIdentity = "",
520
- status = "QUEUED",
521
- stage = "",
522
- runId = "",
523
- jiraIssueKey = "",
524
- reason = "",
525
- budgetSnapshot = {},
526
- env,
527
- homeDir,
528
- nowIso = new Date().toISOString(),
529
- } = {}) {
530
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
531
- const normalizedWorkItemId = normalizeString(workItemId);
532
- if (!normalizedWorkItemId) {
533
- throw new Error("workItemId is required.");
534
- }
535
- const normalizedStatus = normalizeReleaseTargetStatus(status);
536
- const normalizedAgentIdentity = normalizeString(agentIdentity) || null;
537
- const storage = await resolveAssignmentLedgerStorage({
538
- targetPath,
539
- outputDir,
540
- env,
541
- homeDir,
542
- });
543
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
544
-
545
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
546
- if (assignmentIndex < 0) {
547
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
548
- }
549
- const existing = ledger.assignments[assignmentIndex];
550
- if (
551
- normalizedAgentIdentity &&
552
- normalizeString(existing.assignedAgentIdentity) &&
553
- existing.assignedAgentIdentity !== normalizedAgentIdentity
554
- ) {
555
- throw new Error(
556
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
557
- );
558
- }
559
-
560
- const next = normalizeAssignmentRecord(
561
- {
562
- ...existing,
563
- status: normalizedStatus,
564
- stage: normalizeString(stage) || existing.stage,
565
- runId: normalizeString(runId) || existing.runId,
566
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
567
- budgetSnapshot:
568
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
569
- ? normalizeMetadata(budgetSnapshot)
570
- : existing.budgetSnapshot,
571
- releasedAt: normalizedNow,
572
- releaseReason: normalizeString(reason) || null,
573
- updatedAt: normalizedNow,
574
- },
575
- normalizedNow
576
- );
577
- ledger.assignments[assignmentIndex] = next;
578
- updateQueueItem({
579
- queue,
580
- workItemId: normalizedWorkItemId,
581
- status: normalizedStatus,
582
- assignedAgentIdentity: next.assignedAgentIdentity,
583
- stage: next.stage,
584
- runId: next.runId,
585
- jiraIssueKey: next.jiraIssueKey,
586
- nowIso: normalizedNow,
587
- });
588
-
589
- const [savedLedger, savedQueue] = await Promise.all([
590
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
591
- writeQueue(storage.queuePath, queue, normalizedNow),
592
- ]);
593
-
594
- await appendEvent(storage.eventsPath, {
595
- timestamp: normalizedNow,
596
- eventType: "release",
597
- workItemId: normalizedWorkItemId,
598
- agentIdentity: next.assignedAgentIdentity,
599
- status: normalizedStatus,
600
- reason: next.releaseReason,
601
- });
602
-
603
- return {
604
- ...storage,
605
- ledger: savedLedger,
606
- queue: savedQueue,
607
- assignment: next,
608
- };
609
- }
610
-
611
- export async function reassignAssignment({
612
- targetPath = ".",
613
- outputDir = "",
614
- workItemId,
615
- fromAgentIdentity = "",
616
- toAgentIdentity,
617
- leaseTtlSeconds = 1800,
618
- stage = "triage",
619
- runId = "",
620
- jiraIssueKey = "",
621
- budgetSnapshot = {},
622
- env,
623
- homeDir,
624
- nowIso = new Date().toISOString(),
625
- } = {}) {
626
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
627
- const normalizedWorkItemId = normalizeString(workItemId);
628
- if (!normalizedWorkItemId) {
629
- throw new Error("workItemId is required.");
630
- }
631
- const normalizedToAgent = requireAgentIdentity(toAgentIdentity, "toAgentIdentity");
632
- const normalizedFromAgent = normalizeString(fromAgentIdentity) || null;
633
- const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
634
- const storage = await resolveAssignmentLedgerStorage({
635
- targetPath,
636
- outputDir,
637
- env,
638
- homeDir,
639
- });
640
- const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
641
-
642
- const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
643
- if (assignmentIndex < 0) {
644
- throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
645
- }
646
- const existing = ledger.assignments[assignmentIndex];
647
- if (
648
- normalizedFromAgent &&
649
- normalizeString(existing.assignedAgentIdentity) &&
650
- existing.assignedAgentIdentity !== normalizedFromAgent
651
- ) {
652
- throw new Error(
653
- `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedFromAgent}'.`
654
- );
655
- }
656
-
657
- const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
658
- const next = normalizeAssignmentRecord(
659
- {
660
- ...existing,
661
- assignedAgentIdentity: normalizedToAgent,
662
- leasedAt: normalizedNow,
663
- leaseTtlSeconds: normalizedTtl,
664
- leaseExpiresAt,
665
- status: "CLAIMED",
666
- stage: normalizeString(stage) || existing.stage,
667
- runId: normalizeString(runId) || existing.runId,
668
- jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
669
- budgetSnapshot:
670
- Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
671
- ? normalizeMetadata(budgetSnapshot)
672
- : existing.budgetSnapshot,
673
- heartbeatAt: null,
674
- releasedAt: null,
675
- releaseReason: null,
676
- updatedAt: normalizedNow,
677
- },
678
- normalizedNow
679
- );
680
- ledger.assignments[assignmentIndex] = next;
681
- updateQueueItem({
682
- queue,
683
- workItemId: normalizedWorkItemId,
684
- status: "ASSIGNED",
685
- assignedAgentIdentity: normalizedToAgent,
686
- stage: next.stage,
687
- runId: next.runId,
688
- jiraIssueKey: next.jiraIssueKey,
689
- nowIso: normalizedNow,
690
- });
691
-
692
- const [savedLedger, savedQueue] = await Promise.all([
693
- writeLedger(storage.ledgerPath, ledger, normalizedNow),
694
- writeQueue(storage.queuePath, queue, normalizedNow),
695
- ]);
696
-
697
- await appendEvent(storage.eventsPath, {
698
- timestamp: normalizedNow,
699
- eventType: "reassign",
700
- workItemId: normalizedWorkItemId,
701
- fromAgentIdentity: existing.assignedAgentIdentity,
702
- toAgentIdentity: normalizedToAgent,
703
- leaseTtlSeconds: normalizedTtl,
704
- leaseExpiresAt,
705
- stage: next.stage,
706
- });
707
-
708
- return {
709
- ...storage,
710
- ledger: savedLedger,
711
- queue: savedQueue,
712
- assignment: next,
713
- };
714
- }
715
-
716
- export async function listAssignments({
717
- targetPath = ".",
718
- outputDir = "",
719
- statuses = [],
720
- agentIdentity = "",
721
- includeExpired = true,
722
- limit = 50,
723
- env,
724
- homeDir,
725
- nowIso = new Date().toISOString(),
726
- } = {}) {
727
- const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
728
- const normalizedLimit = normalizePositiveInteger(limit, 50);
729
- const normalizedAgent = normalizeString(agentIdentity);
730
- const statusFilter = parseStatusList(statuses);
731
- const storage = await resolveAssignmentLedgerStorage({
732
- targetPath,
733
- outputDir,
734
- env,
735
- homeDir,
736
- });
737
- const ledger = await loadLedger(storage.ledgerPath, normalizedNow);
738
- const records = ledger.assignments
739
- .map((record) => {
740
- const expired = isAssignmentExpired(record, normalizedNow);
741
- return {
742
- ...record,
743
- expired,
744
- };
745
- })
746
- .filter((record) => {
747
- if (statusFilter && !statusFilter.has(record.status)) {
748
- return false;
749
- }
750
- if (normalizedAgent && record.assignedAgentIdentity !== normalizedAgent) {
751
- return false;
752
- }
753
- if (!includeExpired && record.expired) {
754
- return false;
755
- }
756
- return true;
757
- })
758
- .sort((left, right) => {
759
- const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
760
- const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
761
- return rightEpoch - leftEpoch;
762
- });
763
-
764
- return {
765
- ...storage,
766
- totalCount: ledger.assignments.length,
767
- visibleCount: records.length,
768
- assignments: records.slice(0, normalizedLimit),
769
- };
770
- }
1
+ import { createHash } from "node:crypto";
2
+ import fsp from "node:fs/promises";
3
+ import path from "node:path";
4
+
5
+ import { WORK_ITEM_STATUSES, resolveErrorDaemonStorage } from "./error-worker.js";
6
+
7
+ const LEDGER_SCHEMA_VERSION = "1.0.0";
8
+ const QUEUE_SCHEMA_VERSION = "1.0.0";
9
+
10
+ export const ASSIGNMENT_STATUSES = Object.freeze([
11
+ "QUEUED",
12
+ "CLAIMED",
13
+ "IN_PROGRESS",
14
+ "RELEASED",
15
+ "DONE",
16
+ "BLOCKED",
17
+ "SQUASHED",
18
+ ]);
19
+
20
+ const ASSIGNMENT_STATUS_SET = new Set(ASSIGNMENT_STATUSES);
21
+ const WORK_ITEM_STATUS_SET = new Set(WORK_ITEM_STATUSES);
22
+ const ACTIVE_ASSIGNMENT_STATUSES = new Set(["CLAIMED", "IN_PROGRESS"]);
23
+ const RELEASE_TARGET_STATUSES = new Set(["QUEUED", "DONE", "BLOCKED", "SQUASHED"]);
24
+
25
+ function normalizeString(value) {
26
+ return String(value || "").trim();
27
+ }
28
+
29
+ function normalizeIsoTimestamp(value, fallbackIso = new Date().toISOString()) {
30
+ const normalized = normalizeString(value);
31
+ if (!normalized) {
32
+ return fallbackIso;
33
+ }
34
+ const epoch = Date.parse(normalized);
35
+ if (!Number.isFinite(epoch)) {
36
+ return fallbackIso;
37
+ }
38
+ return new Date(epoch).toISOString();
39
+ }
40
+
41
+ function normalizePositiveInteger(value, fallbackValue = 1) {
42
+ if (value === undefined || value === null || normalizeString(value) === "") {
43
+ return fallbackValue;
44
+ }
45
+ const normalized = Number(value);
46
+ if (!Number.isFinite(normalized) || normalized <= 0) {
47
+ throw new Error("Value must be a positive integer.");
48
+ }
49
+ return Math.floor(normalized);
50
+ }
51
+
52
+ function normalizeMetadata(value) {
53
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
54
+ return {};
55
+ }
56
+ return { ...value };
57
+ }
58
+
59
+ function normalizeSeverity(value, fallbackValue = "P2") {
60
+ const normalized = normalizeString(value).toUpperCase();
61
+ if (normalized === "P0" || normalized === "P1" || normalized === "P2" || normalized === "P3") {
62
+ return normalized;
63
+ }
64
+ return fallbackValue;
65
+ }
66
+
67
+ function normalizeAssignmentStatus(value, fallbackValue = "QUEUED") {
68
+ const normalized = normalizeString(value).toUpperCase();
69
+ if (ASSIGNMENT_STATUS_SET.has(normalized)) {
70
+ return normalized;
71
+ }
72
+ return fallbackValue;
73
+ }
74
+
75
+ function normalizeWorkItemStatus(value, fallbackValue = "QUEUED") {
76
+ const normalized = normalizeString(value).toUpperCase();
77
+ if (WORK_ITEM_STATUS_SET.has(normalized)) {
78
+ return normalized;
79
+ }
80
+ return fallbackValue;
81
+ }
82
+
83
+ function toIsoAfterSeconds(nowIso, seconds) {
84
+ const baseEpoch = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString())) || Date.now();
85
+ return new Date(baseEpoch + seconds * 1000).toISOString();
86
+ }
87
+
88
+ function parseStatusList(statuses = []) {
89
+ if (!Array.isArray(statuses)) {
90
+ return null;
91
+ }
92
+ const normalized = statuses
93
+ .map((item) => normalizeString(item).toUpperCase())
94
+ .filter(Boolean)
95
+ .filter((item) => ASSIGNMENT_STATUS_SET.has(item));
96
+ if (normalized.length === 0) {
97
+ return null;
98
+ }
99
+ return new Set(normalized);
100
+ }
101
+
102
+ function createInitialLedger(nowIso = new Date().toISOString()) {
103
+ return {
104
+ schemaVersion: LEDGER_SCHEMA_VERSION,
105
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
106
+ assignments: [],
107
+ };
108
+ }
109
+
110
+ function createInitialQueue(nowIso = new Date().toISOString()) {
111
+ return {
112
+ schemaVersion: QUEUE_SCHEMA_VERSION,
113
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
114
+ items: [],
115
+ };
116
+ }
117
+
118
+ function normalizeAssignmentRecord(record = {}, nowIso = new Date().toISOString()) {
119
+ const updatedAt = normalizeIsoTimestamp(record.updatedAt, nowIso);
120
+ return {
121
+ sessionId: normalizeString(record.sessionId) || null,
122
+ workItemId: normalizeString(record.workItemId),
123
+ assignedAgentIdentity: normalizeString(record.assignedAgentIdentity) || null,
124
+ leasedAt: record.leasedAt ? normalizeIsoTimestamp(record.leasedAt, updatedAt) : null,
125
+ leaseTtlSeconds: Math.max(1, normalizePositiveInteger(record.leaseTtlSeconds, 1800)),
126
+ leaseExpiresAt: record.leaseExpiresAt ? normalizeIsoTimestamp(record.leaseExpiresAt, updatedAt) : null,
127
+ status: normalizeAssignmentStatus(record.status),
128
+ stage: normalizeString(record.stage) || "triage",
129
+ runId: normalizeString(record.runId) || null,
130
+ jiraIssueKey: normalizeString(record.jiraIssueKey) || null,
131
+ budgetSnapshot: normalizeMetadata(record.budgetSnapshot),
132
+ heartbeatAt: record.heartbeatAt ? normalizeIsoTimestamp(record.heartbeatAt, updatedAt) : null,
133
+ releasedAt: record.releasedAt ? normalizeIsoTimestamp(record.releasedAt, updatedAt) : null,
134
+ releaseReason: normalizeString(record.releaseReason) || null,
135
+ updatedAt,
136
+ };
137
+ }
138
+
139
+ function isAssignmentExpired(record = {}, nowIso = new Date().toISOString()) {
140
+ if (!record || !ACTIVE_ASSIGNMENT_STATUSES.has(normalizeAssignmentStatus(record.status))) {
141
+ return false;
142
+ }
143
+ const expiry = Date.parse(String(record.leaseExpiresAt || ""));
144
+ const now = Date.parse(normalizeIsoTimestamp(nowIso, new Date().toISOString()));
145
+ if (!Number.isFinite(expiry) || !Number.isFinite(now)) {
146
+ return false;
147
+ }
148
+ return expiry <= now;
149
+ }
150
+
151
+ function normalizeQueueItem(item = {}, nowIso = new Date().toISOString()) {
152
+ return {
153
+ ...item,
154
+ workItemId: normalizeString(item.workItemId),
155
+ status: normalizeWorkItemStatus(item.status),
156
+ updatedAt: normalizeIsoTimestamp(item.updatedAt, nowIso),
157
+ metadata: normalizeMetadata(item.metadata),
158
+ };
159
+ }
160
+
161
+ async function loadJsonFile(filePath, defaultFactory) {
162
+ try {
163
+ const raw = await fsp.readFile(filePath, "utf-8");
164
+ return JSON.parse(raw);
165
+ } catch (error) {
166
+ if (error && typeof error === "object" && error.code === "ENOENT") {
167
+ return defaultFactory();
168
+ }
169
+ throw error;
170
+ }
171
+ }
172
+
173
+ async function writeJsonFile(filePath, payload = {}) {
174
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
175
+ await fsp.writeFile(filePath, `${JSON.stringify(payload, null, 2)}\n`, "utf-8");
176
+ }
177
+
178
+ async function appendEvent(filePath, payload = {}) {
179
+ await fsp.mkdir(path.dirname(filePath), { recursive: true });
180
+ await fsp.appendFile(filePath, `${JSON.stringify(payload)}\n`, "utf-8");
181
+ }
182
+
183
+ async function loadLedger(ledgerPath, nowIso = new Date().toISOString()) {
184
+ const parsed = await loadJsonFile(ledgerPath, () => createInitialLedger(nowIso));
185
+ return {
186
+ schemaVersion: normalizeString(parsed.schemaVersion) || LEDGER_SCHEMA_VERSION,
187
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
188
+ assignments: Array.isArray(parsed.assignments)
189
+ ? parsed.assignments
190
+ .map((record) => normalizeAssignmentRecord(record, nowIso))
191
+ .filter((record) => normalizeString(record.workItemId))
192
+ : [],
193
+ };
194
+ }
195
+
196
+ async function writeLedger(ledgerPath, ledger = {}, nowIso = new Date().toISOString()) {
197
+ const normalized = {
198
+ schemaVersion: LEDGER_SCHEMA_VERSION,
199
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
200
+ assignments: Array.isArray(ledger.assignments)
201
+ ? ledger.assignments
202
+ .map((record) => normalizeAssignmentRecord(record, nowIso))
203
+ .filter((record) => normalizeString(record.workItemId))
204
+ : [],
205
+ };
206
+ await writeJsonFile(ledgerPath, normalized);
207
+ return normalized;
208
+ }
209
+
210
+ async function loadQueue(queuePath, nowIso = new Date().toISOString()) {
211
+ const parsed = await loadJsonFile(queuePath, () => createInitialQueue(nowIso));
212
+ return {
213
+ schemaVersion: normalizeString(parsed.schemaVersion) || QUEUE_SCHEMA_VERSION,
214
+ generatedAt: normalizeIsoTimestamp(parsed.generatedAt, nowIso),
215
+ items: Array.isArray(parsed.items)
216
+ ? parsed.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
217
+ : [],
218
+ };
219
+ }
220
+
221
+ async function writeQueue(queuePath, queue = {}, nowIso = new Date().toISOString()) {
222
+ const normalized = {
223
+ schemaVersion: QUEUE_SCHEMA_VERSION,
224
+ generatedAt: normalizeIsoTimestamp(nowIso, nowIso),
225
+ items: Array.isArray(queue.items)
226
+ ? queue.items.map((item) => normalizeQueueItem(item, nowIso)).filter((item) => item.workItemId)
227
+ : [],
228
+ };
229
+ await writeJsonFile(queuePath, normalized);
230
+ return normalized;
231
+ }
232
+
233
+ function getAssignmentStoragePaths(baseStorage = {}) {
234
+ return {
235
+ ...baseStorage,
236
+ ledgerPath: path.join(baseStorage.baseDir, "assignment-ledger.json"),
237
+ eventsPath: path.join(baseStorage.baseDir, "assignment-events.ndjson"),
238
+ };
239
+ }
240
+
241
+ async function loadLedgerAndQueue(storage, nowIso) {
242
+ const [ledger, queue] = await Promise.all([
243
+ loadLedger(storage.ledgerPath, nowIso),
244
+ loadQueue(storage.queuePath, nowIso),
245
+ ]);
246
+ return { ledger, queue };
247
+ }
248
+
249
+ function findQueueItem(queue = {}, workItemId = "") {
250
+ return queue.items.find((item) => item.workItemId === workItemId) || null;
251
+ }
252
+
253
+ function updateQueueItem({
254
+ queue,
255
+ workItemId,
256
+ status,
257
+ assignedAgentIdentity = null,
258
+ stage = "",
259
+ runId = null,
260
+ jiraIssueKey = null,
261
+ nowIso,
262
+ } = {}) {
263
+ const index = queue.items.findIndex((item) => item.workItemId === workItemId);
264
+ if (index < 0) {
265
+ throw new Error(`Work item '${workItemId}' was not found in daemon queue.`);
266
+ }
267
+ const existing = queue.items[index];
268
+ queue.items[index] = normalizeQueueItem(
269
+ {
270
+ ...existing,
271
+ status: normalizeWorkItemStatus(status, existing.status),
272
+ updatedAt: nowIso,
273
+ metadata: {
274
+ ...normalizeMetadata(existing.metadata),
275
+ assignedAgentIdentity: assignedAgentIdentity || null,
276
+ stage: normalizeString(stage) || null,
277
+ runId: normalizeString(runId) || null,
278
+ jiraIssueKey: normalizeString(jiraIssueKey) || null,
279
+ },
280
+ },
281
+ nowIso
282
+ );
283
+ return queue.items[index];
284
+ }
285
+
286
+ function findAssignmentIndex(ledger = {}, workItemId = "") {
287
+ return ledger.assignments.findIndex((record) => record.workItemId === workItemId);
288
+ }
289
+
290
+ function requireAgentIdentity(value, fieldName = "agentIdentity") {
291
+ const normalized = normalizeString(value);
292
+ if (!normalized) {
293
+ throw new Error(`${fieldName} is required.`);
294
+ }
295
+ return normalized;
296
+ }
297
+
298
+ function normalizeSessionId(value) {
299
+ const normalized = normalizeString(value);
300
+ return normalized || null;
301
+ }
302
+
303
+ function requireSessionId(value, fieldName = "sessionId") {
304
+ const normalized = normalizeString(value);
305
+ if (!normalized) {
306
+ throw new Error(`${fieldName} is required.`);
307
+ }
308
+ return normalized;
309
+ }
310
+
311
+ function assertSessionBinding(existingAssignment, expectedSessionId, workItemId) {
312
+ const normalizedExpected = normalizeSessionId(expectedSessionId);
313
+ if (!normalizedExpected) {
314
+ return;
315
+ }
316
+ const normalizedExisting = normalizeSessionId(existingAssignment?.sessionId);
317
+ if (!normalizedExisting || normalizedExisting === normalizedExpected) {
318
+ return;
319
+ }
320
+ throw new Error(
321
+ `Work item '${normalizeString(workItemId)}' is bound to session '${normalizedExisting}', not '${normalizedExpected}'.`
322
+ );
323
+ }
324
+
325
+ function normalizeReleaseTargetStatus(value) {
326
+ const normalized = normalizeString(value).toUpperCase();
327
+ if (!RELEASE_TARGET_STATUSES.has(normalized)) {
328
+ throw new Error(
329
+ `status must be one of: ${[...RELEASE_TARGET_STATUSES].join(", ")}.`
330
+ );
331
+ }
332
+ return normalized;
333
+ }
334
+
335
+ export async function resolveAssignmentLedgerStorage({
336
+ targetPath = ".",
337
+ outputDir = "",
338
+ env,
339
+ homeDir,
340
+ } = {}) {
341
+ const daemonStorage = await resolveErrorDaemonStorage({
342
+ targetPath,
343
+ outputDir,
344
+ env,
345
+ homeDir,
346
+ });
347
+ return getAssignmentStoragePaths(daemonStorage);
348
+ }
349
+
350
+ export async function claimAssignment({
351
+ targetPath = ".",
352
+ outputDir = "",
353
+ sessionId = "",
354
+ workItemId,
355
+ agentIdentity,
356
+ leaseTtlSeconds = 1800,
357
+ stage = "triage",
358
+ runId = "",
359
+ jiraIssueKey = "",
360
+ budgetSnapshot = {},
361
+ env,
362
+ homeDir,
363
+ nowIso = new Date().toISOString(),
364
+ } = {}) {
365
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
366
+ const normalizedWorkItemId = normalizeString(workItemId);
367
+ if (!normalizedWorkItemId) {
368
+ throw new Error("workItemId is required.");
369
+ }
370
+ const normalizedSessionId = normalizeSessionId(sessionId);
371
+ const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
372
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
373
+ const storage = await resolveAssignmentLedgerStorage({
374
+ targetPath,
375
+ outputDir,
376
+ env,
377
+ homeDir,
378
+ });
379
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
380
+
381
+ const queueItem = findQueueItem(queue, normalizedWorkItemId);
382
+ if (!queueItem) {
383
+ throw new Error(`Work item '${normalizedWorkItemId}' was not found in daemon queue.`);
384
+ }
385
+
386
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
387
+ const existingAssignment = assignmentIndex >= 0 ? ledger.assignments[assignmentIndex] : null;
388
+ assertSessionBinding(existingAssignment, normalizedSessionId, normalizedWorkItemId);
389
+ if (
390
+ existingAssignment &&
391
+ ACTIVE_ASSIGNMENT_STATUSES.has(existingAssignment.status) &&
392
+ !isAssignmentExpired(existingAssignment, normalizedNow) &&
393
+ existingAssignment.assignedAgentIdentity !== normalizedAgentIdentity
394
+ ) {
395
+ throw new Error(
396
+ `Work item '${normalizedWorkItemId}' is currently leased by '${existingAssignment.assignedAgentIdentity}'.`
397
+ );
398
+ }
399
+
400
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
401
+ const nextRecord = normalizeAssignmentRecord(
402
+ {
403
+ workItemId: normalizedWorkItemId,
404
+ sessionId: normalizedSessionId || normalizeSessionId(existingAssignment?.sessionId),
405
+ assignedAgentIdentity: normalizedAgentIdentity,
406
+ leasedAt: normalizedNow,
407
+ leaseTtlSeconds: normalizedTtl,
408
+ leaseExpiresAt,
409
+ status: "CLAIMED",
410
+ stage,
411
+ runId,
412
+ jiraIssueKey,
413
+ budgetSnapshot: normalizeMetadata(budgetSnapshot),
414
+ heartbeatAt: null,
415
+ releasedAt: null,
416
+ releaseReason: null,
417
+ updatedAt: normalizedNow,
418
+ },
419
+ normalizedNow
420
+ );
421
+
422
+ if (assignmentIndex >= 0) {
423
+ ledger.assignments[assignmentIndex] = nextRecord;
424
+ } else {
425
+ ledger.assignments.push(nextRecord);
426
+ }
427
+ updateQueueItem({
428
+ queue,
429
+ workItemId: normalizedWorkItemId,
430
+ status: "ASSIGNED",
431
+ assignedAgentIdentity: normalizedAgentIdentity,
432
+ stage,
433
+ runId,
434
+ jiraIssueKey,
435
+ nowIso: normalizedNow,
436
+ });
437
+
438
+ const [savedLedger, savedQueue] = await Promise.all([
439
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
440
+ writeQueue(storage.queuePath, queue, normalizedNow),
441
+ ]);
442
+
443
+ await appendEvent(storage.eventsPath, {
444
+ timestamp: normalizedNow,
445
+ eventType: "claim",
446
+ sessionId: nextRecord.sessionId,
447
+ workItemId: normalizedWorkItemId,
448
+ agentIdentity: normalizedAgentIdentity,
449
+ leaseTtlSeconds: normalizedTtl,
450
+ leaseExpiresAt,
451
+ stage: normalizeString(stage) || "triage",
452
+ runId: normalizeString(runId) || null,
453
+ jiraIssueKey: normalizeString(jiraIssueKey) || null,
454
+ });
455
+
456
+ return {
457
+ ...storage,
458
+ ledger: savedLedger,
459
+ queue: savedQueue,
460
+ assignment: nextRecord,
461
+ };
462
+ }
463
+
464
+ export async function heartbeatAssignment({
465
+ targetPath = ".",
466
+ outputDir = "",
467
+ sessionId = "",
468
+ workItemId,
469
+ agentIdentity,
470
+ leaseTtlSeconds = 1800,
471
+ stage = "",
472
+ runId = "",
473
+ jiraIssueKey = "",
474
+ budgetSnapshot = {},
475
+ env,
476
+ homeDir,
477
+ nowIso = new Date().toISOString(),
478
+ } = {}) {
479
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
480
+ const normalizedWorkItemId = normalizeString(workItemId);
481
+ if (!normalizedWorkItemId) {
482
+ throw new Error("workItemId is required.");
483
+ }
484
+ const normalizedSessionId = normalizeSessionId(sessionId);
485
+ const normalizedAgentIdentity = requireAgentIdentity(agentIdentity);
486
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
487
+ const storage = await resolveAssignmentLedgerStorage({
488
+ targetPath,
489
+ outputDir,
490
+ env,
491
+ homeDir,
492
+ });
493
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
494
+
495
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
496
+ if (assignmentIndex < 0) {
497
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
498
+ }
499
+ const existing = ledger.assignments[assignmentIndex];
500
+ if (existing.assignedAgentIdentity !== normalizedAgentIdentity) {
501
+ throw new Error(
502
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
503
+ );
504
+ }
505
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
506
+
507
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
508
+ const next = normalizeAssignmentRecord(
509
+ {
510
+ ...existing,
511
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
512
+ status: "IN_PROGRESS",
513
+ leaseTtlSeconds: normalizedTtl,
514
+ leaseExpiresAt,
515
+ heartbeatAt: normalizedNow,
516
+ stage: normalizeString(stage) || existing.stage,
517
+ runId: normalizeString(runId) || existing.runId,
518
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
519
+ budgetSnapshot:
520
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
521
+ ? normalizeMetadata(budgetSnapshot)
522
+ : existing.budgetSnapshot,
523
+ updatedAt: normalizedNow,
524
+ },
525
+ normalizedNow
526
+ );
527
+ ledger.assignments[assignmentIndex] = next;
528
+ updateQueueItem({
529
+ queue,
530
+ workItemId: normalizedWorkItemId,
531
+ status: "IN_PROGRESS",
532
+ assignedAgentIdentity: normalizedAgentIdentity,
533
+ stage: next.stage,
534
+ runId: next.runId,
535
+ jiraIssueKey: next.jiraIssueKey,
536
+ nowIso: normalizedNow,
537
+ });
538
+
539
+ const [savedLedger, savedQueue] = await Promise.all([
540
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
541
+ writeQueue(storage.queuePath, queue, normalizedNow),
542
+ ]);
543
+
544
+ await appendEvent(storage.eventsPath, {
545
+ timestamp: normalizedNow,
546
+ eventType: "heartbeat",
547
+ sessionId: next.sessionId,
548
+ workItemId: normalizedWorkItemId,
549
+ agentIdentity: normalizedAgentIdentity,
550
+ stage: next.stage,
551
+ leaseExpiresAt,
552
+ });
553
+
554
+ return {
555
+ ...storage,
556
+ ledger: savedLedger,
557
+ queue: savedQueue,
558
+ assignment: next,
559
+ };
560
+ }
561
+
562
+ export async function releaseAssignment({
563
+ targetPath = ".",
564
+ outputDir = "",
565
+ sessionId = "",
566
+ workItemId,
567
+ agentIdentity = "",
568
+ status = "QUEUED",
569
+ stage = "",
570
+ runId = "",
571
+ jiraIssueKey = "",
572
+ reason = "",
573
+ budgetSnapshot = {},
574
+ env,
575
+ homeDir,
576
+ nowIso = new Date().toISOString(),
577
+ } = {}) {
578
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
579
+ const normalizedWorkItemId = normalizeString(workItemId);
580
+ if (!normalizedWorkItemId) {
581
+ throw new Error("workItemId is required.");
582
+ }
583
+ const normalizedStatus = normalizeReleaseTargetStatus(status);
584
+ const normalizedAgentIdentity = normalizeString(agentIdentity) || null;
585
+ const normalizedSessionId = normalizeSessionId(sessionId);
586
+ const storage = await resolveAssignmentLedgerStorage({
587
+ targetPath,
588
+ outputDir,
589
+ env,
590
+ homeDir,
591
+ });
592
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
593
+
594
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
595
+ if (assignmentIndex < 0) {
596
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
597
+ }
598
+ const existing = ledger.assignments[assignmentIndex];
599
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
600
+ if (
601
+ normalizedAgentIdentity &&
602
+ normalizeString(existing.assignedAgentIdentity) &&
603
+ existing.assignedAgentIdentity !== normalizedAgentIdentity
604
+ ) {
605
+ throw new Error(
606
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedAgentIdentity}'.`
607
+ );
608
+ }
609
+
610
+ const next = normalizeAssignmentRecord(
611
+ {
612
+ ...existing,
613
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
614
+ status: normalizedStatus,
615
+ stage: normalizeString(stage) || existing.stage,
616
+ runId: normalizeString(runId) || existing.runId,
617
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
618
+ budgetSnapshot:
619
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
620
+ ? normalizeMetadata(budgetSnapshot)
621
+ : existing.budgetSnapshot,
622
+ releasedAt: normalizedNow,
623
+ releaseReason: normalizeString(reason) || null,
624
+ updatedAt: normalizedNow,
625
+ },
626
+ normalizedNow
627
+ );
628
+ ledger.assignments[assignmentIndex] = next;
629
+ updateQueueItem({
630
+ queue,
631
+ workItemId: normalizedWorkItemId,
632
+ status: normalizedStatus,
633
+ assignedAgentIdentity: next.assignedAgentIdentity,
634
+ stage: next.stage,
635
+ runId: next.runId,
636
+ jiraIssueKey: next.jiraIssueKey,
637
+ nowIso: normalizedNow,
638
+ });
639
+
640
+ const [savedLedger, savedQueue] = await Promise.all([
641
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
642
+ writeQueue(storage.queuePath, queue, normalizedNow),
643
+ ]);
644
+
645
+ await appendEvent(storage.eventsPath, {
646
+ timestamp: normalizedNow,
647
+ eventType: "release",
648
+ sessionId: next.sessionId,
649
+ workItemId: normalizedWorkItemId,
650
+ agentIdentity: next.assignedAgentIdentity,
651
+ status: normalizedStatus,
652
+ reason: next.releaseReason,
653
+ });
654
+
655
+ return {
656
+ ...storage,
657
+ ledger: savedLedger,
658
+ queue: savedQueue,
659
+ assignment: next,
660
+ };
661
+ }
662
+
663
+ export async function reassignAssignment({
664
+ targetPath = ".",
665
+ outputDir = "",
666
+ sessionId = "",
667
+ workItemId,
668
+ fromAgentIdentity = "",
669
+ toAgentIdentity,
670
+ leaseTtlSeconds = 1800,
671
+ stage = "triage",
672
+ runId = "",
673
+ jiraIssueKey = "",
674
+ budgetSnapshot = {},
675
+ env,
676
+ homeDir,
677
+ nowIso = new Date().toISOString(),
678
+ } = {}) {
679
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
680
+ const normalizedWorkItemId = normalizeString(workItemId);
681
+ if (!normalizedWorkItemId) {
682
+ throw new Error("workItemId is required.");
683
+ }
684
+ const normalizedSessionId = normalizeSessionId(sessionId);
685
+ const normalizedToAgent = requireAgentIdentity(toAgentIdentity, "toAgentIdentity");
686
+ const normalizedFromAgent = normalizeString(fromAgentIdentity) || null;
687
+ const normalizedTtl = normalizePositiveInteger(leaseTtlSeconds, 1800);
688
+ const storage = await resolveAssignmentLedgerStorage({
689
+ targetPath,
690
+ outputDir,
691
+ env,
692
+ homeDir,
693
+ });
694
+ const { ledger, queue } = await loadLedgerAndQueue(storage, normalizedNow);
695
+
696
+ const assignmentIndex = findAssignmentIndex(ledger, normalizedWorkItemId);
697
+ if (assignmentIndex < 0) {
698
+ throw new Error(`No assignment exists for work item '${normalizedWorkItemId}'.`);
699
+ }
700
+ const existing = ledger.assignments[assignmentIndex];
701
+ assertSessionBinding(existing, normalizedSessionId, normalizedWorkItemId);
702
+ if (
703
+ normalizedFromAgent &&
704
+ normalizeString(existing.assignedAgentIdentity) &&
705
+ existing.assignedAgentIdentity !== normalizedFromAgent
706
+ ) {
707
+ throw new Error(
708
+ `Work item '${normalizedWorkItemId}' is assigned to '${existing.assignedAgentIdentity}', not '${normalizedFromAgent}'.`
709
+ );
710
+ }
711
+
712
+ const leaseExpiresAt = toIsoAfterSeconds(normalizedNow, normalizedTtl);
713
+ const next = normalizeAssignmentRecord(
714
+ {
715
+ ...existing,
716
+ sessionId: normalizedSessionId || normalizeSessionId(existing.sessionId),
717
+ assignedAgentIdentity: normalizedToAgent,
718
+ leasedAt: normalizedNow,
719
+ leaseTtlSeconds: normalizedTtl,
720
+ leaseExpiresAt,
721
+ status: "CLAIMED",
722
+ stage: normalizeString(stage) || existing.stage,
723
+ runId: normalizeString(runId) || existing.runId,
724
+ jiraIssueKey: normalizeString(jiraIssueKey) || existing.jiraIssueKey,
725
+ budgetSnapshot:
726
+ Object.keys(normalizeMetadata(budgetSnapshot)).length > 0
727
+ ? normalizeMetadata(budgetSnapshot)
728
+ : existing.budgetSnapshot,
729
+ heartbeatAt: null,
730
+ releasedAt: null,
731
+ releaseReason: null,
732
+ updatedAt: normalizedNow,
733
+ },
734
+ normalizedNow
735
+ );
736
+ ledger.assignments[assignmentIndex] = next;
737
+ updateQueueItem({
738
+ queue,
739
+ workItemId: normalizedWorkItemId,
740
+ status: "ASSIGNED",
741
+ assignedAgentIdentity: normalizedToAgent,
742
+ stage: next.stage,
743
+ runId: next.runId,
744
+ jiraIssueKey: next.jiraIssueKey,
745
+ nowIso: normalizedNow,
746
+ });
747
+
748
+ const [savedLedger, savedQueue] = await Promise.all([
749
+ writeLedger(storage.ledgerPath, ledger, normalizedNow),
750
+ writeQueue(storage.queuePath, queue, normalizedNow),
751
+ ]);
752
+
753
+ await appendEvent(storage.eventsPath, {
754
+ timestamp: normalizedNow,
755
+ eventType: "reassign",
756
+ sessionId: next.sessionId,
757
+ workItemId: normalizedWorkItemId,
758
+ fromAgentIdentity: existing.assignedAgentIdentity,
759
+ toAgentIdentity: normalizedToAgent,
760
+ leaseTtlSeconds: normalizedTtl,
761
+ leaseExpiresAt,
762
+ stage: next.stage,
763
+ });
764
+
765
+ return {
766
+ ...storage,
767
+ ledger: savedLedger,
768
+ queue: savedQueue,
769
+ assignment: next,
770
+ };
771
+ }
772
+
773
+ export async function listAssignments({
774
+ targetPath = ".",
775
+ outputDir = "",
776
+ sessionId = "",
777
+ statuses = [],
778
+ agentIdentity = "",
779
+ includeExpired = true,
780
+ limit = 50,
781
+ env,
782
+ homeDir,
783
+ nowIso = new Date().toISOString(),
784
+ } = {}) {
785
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
786
+ const normalizedLimit = normalizePositiveInteger(limit, 50);
787
+ const normalizedAgent = normalizeString(agentIdentity);
788
+ const normalizedSessionId = normalizeSessionId(sessionId);
789
+ const statusFilter = parseStatusList(statuses);
790
+ const storage = await resolveAssignmentLedgerStorage({
791
+ targetPath,
792
+ outputDir,
793
+ env,
794
+ homeDir,
795
+ });
796
+ const ledger = await loadLedger(storage.ledgerPath, normalizedNow);
797
+ const records = ledger.assignments
798
+ .map((record) => {
799
+ const expired = isAssignmentExpired(record, normalizedNow);
800
+ return {
801
+ ...record,
802
+ expired,
803
+ };
804
+ })
805
+ .filter((record) => {
806
+ if (statusFilter && !statusFilter.has(record.status)) {
807
+ return false;
808
+ }
809
+ if (normalizedAgent && record.assignedAgentIdentity !== normalizedAgent) {
810
+ return false;
811
+ }
812
+ if (normalizedSessionId && record.sessionId !== normalizedSessionId) {
813
+ return false;
814
+ }
815
+ if (!includeExpired && record.expired) {
816
+ return false;
817
+ }
818
+ return true;
819
+ })
820
+ .sort((left, right) => {
821
+ const leftEpoch = Date.parse(String(left.updatedAt || "")) || 0;
822
+ const rightEpoch = Date.parse(String(right.updatedAt || "")) || 0;
823
+ return rightEpoch - leftEpoch;
824
+ });
825
+
826
+ return {
827
+ ...storage,
828
+ totalCount: ledger.assignments.length,
829
+ visibleCount: records.length,
830
+ assignments: records.slice(0, normalizedLimit),
831
+ };
832
+ }
833
+
834
+ function normalizeLeaseTtlMs(value, fallbackValue = 1_800_000) {
835
+ return normalizePositiveInteger(value, fallbackValue);
836
+ }
837
+
838
+ export async function leaseWorkItem({
839
+ targetPath = ".",
840
+ outputDir = "",
841
+ sessionId,
842
+ workItemId,
843
+ agentIdentity,
844
+ leaseTtlMs = 1_800_000,
845
+ stage = "triage",
846
+ runId = "",
847
+ jiraIssueKey = "",
848
+ budgetSnapshot = {},
849
+ env,
850
+ homeDir,
851
+ nowIso = new Date().toISOString(),
852
+ } = {}) {
853
+ const normalizedSessionId = requireSessionId(sessionId);
854
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
855
+ return claimAssignment({
856
+ targetPath,
857
+ outputDir,
858
+ sessionId: normalizedSessionId,
859
+ workItemId,
860
+ agentIdentity,
861
+ leaseTtlSeconds,
862
+ stage,
863
+ runId,
864
+ jiraIssueKey,
865
+ budgetSnapshot,
866
+ env,
867
+ homeDir,
868
+ nowIso,
869
+ });
870
+ }
871
+
872
+ export async function heartbeatLease({
873
+ targetPath = ".",
874
+ outputDir = "",
875
+ sessionId,
876
+ workItemId,
877
+ agentIdentity,
878
+ leaseTtlMs = 1_800_000,
879
+ stage = "",
880
+ runId = "",
881
+ jiraIssueKey = "",
882
+ budgetSnapshot = {},
883
+ env,
884
+ homeDir,
885
+ nowIso = new Date().toISOString(),
886
+ } = {}) {
887
+ const normalizedSessionId = requireSessionId(sessionId);
888
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
889
+ return heartbeatAssignment({
890
+ targetPath,
891
+ outputDir,
892
+ sessionId: normalizedSessionId,
893
+ workItemId,
894
+ agentIdentity,
895
+ leaseTtlSeconds,
896
+ stage,
897
+ runId,
898
+ jiraIssueKey,
899
+ budgetSnapshot,
900
+ env,
901
+ homeDir,
902
+ nowIso,
903
+ });
904
+ }
905
+
906
+ export async function releaseLease({
907
+ targetPath = ".",
908
+ outputDir = "",
909
+ sessionId,
910
+ workItemId,
911
+ agentIdentity = "",
912
+ status = "QUEUED",
913
+ stage = "",
914
+ runId = "",
915
+ jiraIssueKey = "",
916
+ reason = "",
917
+ budgetSnapshot = {},
918
+ env,
919
+ homeDir,
920
+ nowIso = new Date().toISOString(),
921
+ } = {}) {
922
+ const normalizedSessionId = requireSessionId(sessionId);
923
+ return releaseAssignment({
924
+ targetPath,
925
+ outputDir,
926
+ sessionId: normalizedSessionId,
927
+ workItemId,
928
+ agentIdentity,
929
+ status,
930
+ stage,
931
+ runId,
932
+ jiraIssueKey,
933
+ reason,
934
+ budgetSnapshot,
935
+ env,
936
+ homeDir,
937
+ nowIso,
938
+ });
939
+ }
940
+
941
+ export async function reassignLease({
942
+ targetPath = ".",
943
+ outputDir = "",
944
+ sessionId,
945
+ workItemId,
946
+ from = "",
947
+ to,
948
+ leaseTtlMs = 1_800_000,
949
+ stage = "triage",
950
+ runId = "",
951
+ jiraIssueKey = "",
952
+ budgetSnapshot = {},
953
+ env,
954
+ homeDir,
955
+ nowIso = new Date().toISOString(),
956
+ } = {}) {
957
+ const normalizedSessionId = requireSessionId(sessionId);
958
+ const leaseTtlSeconds = Math.max(1, Math.ceil(normalizeLeaseTtlMs(leaseTtlMs) / 1000));
959
+ return reassignAssignment({
960
+ targetPath,
961
+ outputDir,
962
+ sessionId: normalizedSessionId,
963
+ workItemId,
964
+ fromAgentIdentity: from,
965
+ toAgentIdentity: to,
966
+ leaseTtlSeconds,
967
+ stage,
968
+ runId,
969
+ jiraIssueKey,
970
+ budgetSnapshot,
971
+ env,
972
+ homeDir,
973
+ nowIso,
974
+ });
975
+ }
976
+
977
+ function buildQueueFingerprint(seed = "") {
978
+ return createHash("sha256").update(normalizeString(seed) || "session-task").digest("hex");
979
+ }
980
+
981
+ export async function ensureWorkItemQueued({
982
+ targetPath = ".",
983
+ outputDir = "",
984
+ workItemId,
985
+ sessionId = "",
986
+ status = "QUEUED",
987
+ severity = "P2",
988
+ service = "session",
989
+ endpoint = "",
990
+ errorCode = "SESSION_TASK_ASSIGNMENT",
991
+ source = "session_task",
992
+ message = "",
993
+ dedupKey = "",
994
+ metadata = {},
995
+ env,
996
+ homeDir,
997
+ nowIso = new Date().toISOString(),
998
+ } = {}) {
999
+ const normalizedNow = normalizeIsoTimestamp(nowIso, new Date().toISOString());
1000
+ const normalizedWorkItemId = normalizeString(workItemId);
1001
+ if (!normalizedWorkItemId) {
1002
+ throw new Error("workItemId is required.");
1003
+ }
1004
+ const normalizedSessionId = normalizeSessionId(sessionId);
1005
+ const normalizedStatus = normalizeWorkItemStatus(status, "QUEUED");
1006
+ const normalizedService = normalizeString(service) || "session";
1007
+ const normalizedEndpoint =
1008
+ normalizeString(endpoint) ||
1009
+ (normalizedSessionId
1010
+ ? `/sessions/${normalizedSessionId}/tasks`
1011
+ : "/sessions/global/tasks");
1012
+ const normalizedErrorCode = normalizeString(errorCode) || "SESSION_TASK_ASSIGNMENT";
1013
+ const normalizedSource = normalizeString(source) || "session_task";
1014
+ const normalizedMessage = normalizeString(message) || "Session task assignment";
1015
+ const normalizedDedupKey =
1016
+ normalizeString(dedupKey) ||
1017
+ `session|${normalizedSessionId || "none"}|${normalizedWorkItemId}`;
1018
+ const normalizedMetadata = {
1019
+ ...normalizeMetadata(metadata),
1020
+ sessionId: normalizedSessionId,
1021
+ source: normalizedSource,
1022
+ workItemType: "session_task",
1023
+ };
1024
+
1025
+ const storage = await resolveAssignmentLedgerStorage({
1026
+ targetPath,
1027
+ outputDir,
1028
+ env,
1029
+ homeDir,
1030
+ });
1031
+ const queue = await loadQueue(storage.queuePath, normalizedNow);
1032
+ const existingIndex = queue.items.findIndex(
1033
+ (item) => normalizeString(item.workItemId) === normalizedWorkItemId
1034
+ );
1035
+ const existing = existingIndex >= 0 ? queue.items[existingIndex] : null;
1036
+ const fingerprintSeed = `${normalizedDedupKey}|${normalizedService}|${normalizedEndpoint}|${normalizedErrorCode}`;
1037
+ const normalizedItem = normalizeQueueItem(
1038
+ {
1039
+ ...existing,
1040
+ workItemId: normalizedWorkItemId,
1041
+ fingerprint:
1042
+ normalizeString(existing?.fingerprint) || buildQueueFingerprint(fingerprintSeed),
1043
+ source: normalizedSource,
1044
+ service: normalizedService,
1045
+ endpoint: normalizedEndpoint,
1046
+ errorCode: normalizedErrorCode,
1047
+ severity: normalizeSeverity(existing?.severity || severity, "P2"),
1048
+ status: normalizedStatus,
1049
+ message: normalizedMessage,
1050
+ stackFingerprint:
1051
+ normalizeString(existing?.stackFingerprint) ||
1052
+ buildQueueFingerprint(`${normalizedWorkItemId}|stack`).slice(0, 64),
1053
+ commitSha: existing?.commitSha || null,
1054
+ dedupKey: normalizedDedupKey,
1055
+ firstSeenAt: normalizeIsoTimestamp(existing?.firstSeenAt, normalizedNow),
1056
+ lastSeenAt: normalizedNow,
1057
+ latestEventId: normalizeString(existing?.latestEventId) || null,
1058
+ occurrenceCount: Math.max(1, Number(existing?.occurrenceCount || 1)),
1059
+ requestIds: Array.isArray(existing?.requestIds) ? [...existing.requestIds] : [],
1060
+ createdAt: normalizeIsoTimestamp(existing?.createdAt, normalizedNow),
1061
+ updatedAt: normalizedNow,
1062
+ metadata: {
1063
+ ...normalizeMetadata(existing?.metadata),
1064
+ ...normalizedMetadata,
1065
+ },
1066
+ },
1067
+ normalizedNow
1068
+ );
1069
+
1070
+ if (existingIndex >= 0) {
1071
+ queue.items[existingIndex] = normalizedItem;
1072
+ } else {
1073
+ queue.items.push(normalizedItem);
1074
+ }
1075
+
1076
+ const savedQueue = await writeQueue(storage.queuePath, queue, normalizedNow);
1077
+ const queueItem = savedQueue.items.find((item) => item.workItemId === normalizedWorkItemId) || normalizedItem;
1078
+ return {
1079
+ ...storage,
1080
+ queue: savedQueue,
1081
+ queueItem,
1082
+ };
1083
+ }