@indigoai-us/hq-cli 5.124.0 → 5.126.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +149 -0
  2. package/assets/bot-workers/setup/skills/joining-a-team.md +125 -0
  3. package/assets/bot-workers/setup/skills/your-business.md +270 -0
  4. package/assets/bot-workers/setup/worker.yaml +189 -58
  5. package/dist/command-catalog.generated.d.ts +414 -5
  6. package/dist/command-catalog.generated.js +531 -5
  7. package/dist/command-registration-plan.d.ts +6 -0
  8. package/dist/command-registration-plan.js +1 -0
  9. package/dist/commands/bot.d.ts +10 -0
  10. package/dist/commands/bot.js +6 -0
  11. package/dist/commands/lanes.d.ts +75 -0
  12. package/dist/commands/lanes.js +2032 -0
  13. package/dist/commands/login.js +49 -6
  14. package/dist/commands/mesh.js +133 -28
  15. package/dist/commands/onboard-create-identity.d.ts +26 -0
  16. package/dist/commands/onboard-create-identity.js +23 -0
  17. package/dist/commands/onboard.js +13 -4
  18. package/dist/lib/bot/progress.d.ts +6 -0
  19. package/dist/lib/bot/progress.js +16 -0
  20. package/dist/lib/bot/runtime/grok.d.ts +30 -7
  21. package/dist/lib/bot/runtime/grok.js +86 -8
  22. package/dist/lib/bot/runtime/index.js +15 -8
  23. package/dist/lib/bot/runtime/messages-stream.d.ts +12 -3
  24. package/dist/lib/bot/runtime/messages-stream.js +49 -3
  25. package/dist/lib/doctor/checks/work-context.js +4 -2
  26. package/dist/lib/lanes/accounts.d.ts +43 -0
  27. package/dist/lib/lanes/accounts.js +128 -0
  28. package/dist/lib/lanes/config.d.ts +56 -0
  29. package/dist/lib/lanes/config.js +351 -0
  30. package/dist/lib/lanes/errors.d.ts +39 -0
  31. package/dist/lib/lanes/errors.js +72 -0
  32. package/dist/lib/lanes/index.d.ts +19 -0
  33. package/dist/lib/lanes/index.js +12 -0
  34. package/dist/lib/lanes/liveness.d.ts +89 -0
  35. package/dist/lib/lanes/liveness.js +273 -0
  36. package/dist/lib/lanes/registry.d.ts +103 -0
  37. package/dist/lib/lanes/registry.js +247 -0
  38. package/dist/lib/lanes/store.d.ts +64 -0
  39. package/dist/lib/lanes/store.js +627 -0
  40. package/dist/lib/lanes/throttle.d.ts +89 -0
  41. package/dist/lib/lanes/throttle.js +297 -0
  42. package/dist/lib/lanes/types.d.ts +193 -0
  43. package/dist/lib/lanes/types.js +217 -0
  44. package/dist/lib/mesh/live/backfill-held.d.ts +2 -0
  45. package/dist/lib/mesh/live/backfill-held.js +8 -4
  46. package/dist/lib/mesh/live/daemon/board-refresh.d.ts +3 -0
  47. package/dist/lib/mesh/live/daemon/board-refresh.js +6 -0
  48. package/dist/lib/mesh/live/daemon/config.d.ts +27 -0
  49. package/dist/lib/mesh/live/daemon/config.js +75 -0
  50. package/dist/lib/mesh/live/daemon/doctor.d.ts +3 -0
  51. package/dist/lib/mesh/live/daemon/doctor.js +21 -1
  52. package/dist/lib/mesh/live/daemon/index.d.ts +4 -3
  53. package/dist/lib/mesh/live/daemon/index.js +3 -3
  54. package/dist/lib/mesh/live/daemon/install.d.ts +143 -1
  55. package/dist/lib/mesh/live/daemon/install.js +444 -2
  56. package/dist/lib/mesh/live/daemon/paths.d.ts +2 -0
  57. package/dist/lib/mesh/live/daemon/paths.js +2 -0
  58. package/dist/lib/mesh/live/daemon/run.d.ts +11 -0
  59. package/dist/lib/mesh/live/daemon/run.js +129 -10
  60. package/dist/lib/mesh/live/daemon/state.d.ts +2 -0
  61. package/dist/lib/mesh/live/flush.d.ts +3 -0
  62. package/dist/lib/mesh/live/flush.js +11 -0
  63. package/dist/lib/scan-packages/index.js +17 -12
  64. package/dist/lib/work-context/company.d.ts +8 -0
  65. package/dist/lib/work-context/company.js +62 -18
  66. package/dist/lib/work-context/config.d.ts +55 -0
  67. package/dist/lib/work-context/config.js +333 -67
  68. package/dist/lib/work-context/contract.d.ts +2 -0
  69. package/dist/lib/work-context/default-company.d.ts +43 -0
  70. package/dist/lib/work-context/default-company.js +83 -0
  71. package/dist/lib/work-context/outbox.d.ts +5 -1
  72. package/dist/lib/work-context/outbox.js +5 -0
  73. package/dist/lib/work-context/reconcile.d.ts +4 -0
  74. package/dist/lib/work-context/reconcile.js +86 -9
  75. package/dist/lib/work-context/state.d.ts +2 -0
  76. package/dist/lib/work-context/state.js +14 -0
  77. package/dist/lib/work-context/windows-acl.d.ts +123 -0
  78. package/dist/lib/work-context/windows-acl.js +425 -0
  79. package/dist/utils/pack-contributions.js +5 -4
  80. package/package.json +1 -1
@@ -0,0 +1,627 @@
1
+ /**
2
+ * File-backed lane / question record store (spec §10, §10.1).
3
+ *
4
+ * Root: workspace/lanes/ under the HQ root. One stable path per record;
5
+ * `status` is the pending/answered discriminator — files are never moved
6
+ * between directories. Every mutation is temp-file-plus-rename and a
7
+ * compare-and-set on `version`. Histories are capped at 50 at the append site.
8
+ */
9
+ import { randomBytes } from "node:crypto";
10
+ import * as fs from "node:fs";
11
+ import * as os from "node:os";
12
+ import * as path from "node:path";
13
+ import { generateUlid } from "../mesh/live/ulid.js";
14
+ import { findHqRoot } from "../../utils/manifest.js";
15
+ import { LaneNotFoundError, LaneSchemaError, LaneVersionConflict, LanesError, } from "./errors.js";
16
+ import { HISTORY_CAP, HOST_KINDS, LANE_SCHEMA_VERSION, QUESTION_SCHEMA_VERSION, SENIOR_KINDS, isHostKind, isLaneProvider, isLaneState, isQuestionStatus, isSeniorKind, parseMajorSchema, } from "./types.js";
17
+ export const LANES_STORE_REL = path.join("workspace", "lanes");
18
+ export const LANE_RECORDS_DIR = "lanes";
19
+ export const QUESTION_RECORDS_DIR = "questions";
20
+ export const PENDING_INDEX_DIR = path.join("questions", "index", "pending");
21
+ const LOCK_STALE_MS = 30_000;
22
+ const LOCK_RETRY_MS = 10;
23
+ const LOCK_TIMEOUT_MS = 5_000;
24
+ function defaultStoreDeps() {
25
+ return {
26
+ now: () => new Date(),
27
+ hostname: () => os.hostname(),
28
+ mkdirSync: fs.mkdirSync.bind(fs),
29
+ readFileSync: fs.readFileSync.bind(fs),
30
+ writeFileSync: fs.writeFileSync.bind(fs),
31
+ renameSync: fs.renameSync.bind(fs),
32
+ unlinkSync: fs.unlinkSync.bind(fs),
33
+ existsSync: fs.existsSync.bind(fs),
34
+ readdirSync: fs.readdirSync.bind(fs),
35
+ openSync: fs.openSync.bind(fs),
36
+ closeSync: fs.closeSync.bind(fs),
37
+ fsyncSync: fs.fsyncSync.bind(fs),
38
+ chmodSync: fs.chmodSync.bind(fs),
39
+ };
40
+ }
41
+ export function resolveStoreHqRoot(hqRoot) {
42
+ return hqRoot ?? findHqRoot();
43
+ }
44
+ export function lanesStoreRoot(hqRoot) {
45
+ return path.join(resolveStoreHqRoot(hqRoot), LANES_STORE_REL);
46
+ }
47
+ export function laneRecordPath(hqRoot, laneId) {
48
+ return path.join(lanesStoreRoot(hqRoot), LANE_RECORDS_DIR, `${laneId}.json`);
49
+ }
50
+ export function questionRecordPath(hqRoot, questionId) {
51
+ return path.join(lanesStoreRoot(hqRoot), QUESTION_RECORDS_DIR, `${questionId}.json`);
52
+ }
53
+ export function pendingMarkerPath(hqRoot, questionId) {
54
+ return path.join(lanesStoreRoot(hqRoot), PENDING_INDEX_DIR, questionId);
55
+ }
56
+ export function sanitizeHostComponent(hostname) {
57
+ const cleaned = hostname
58
+ .toLowerCase()
59
+ .replace(/[^a-z0-9]+/g, "-")
60
+ .replace(/^-+|-+$/g, "");
61
+ return (cleaned || "host").slice(0, 32);
62
+ }
63
+ /** Collision-safe across machines: ULID plus a host component. */
64
+ export function mintLaneId(deps = defaultStoreDeps()) {
65
+ const host = sanitizeHostComponent(deps.hostname());
66
+ return `${generateUlid(deps.now().getTime())}_${host}`;
67
+ }
68
+ export function mintQuestionId(deps = defaultStoreDeps()) {
69
+ const host = sanitizeHostComponent(deps.hostname());
70
+ const extra = randomBytes(2).toString("hex");
71
+ return `q_${generateUlid(deps.now().getTime())}_${host}_${extra}`;
72
+ }
73
+ export function appendCappedHistory(history, entry, cap = HISTORY_CAP) {
74
+ const next = [...history, entry];
75
+ if (next.length <= cap)
76
+ return next;
77
+ return next.slice(next.length - cap);
78
+ }
79
+ function ensureDir(dir, deps) {
80
+ deps.mkdirSync(dir, { recursive: true });
81
+ }
82
+ function fsyncDir(dir, deps) {
83
+ try {
84
+ const fd = deps.openSync(dir, "r");
85
+ try {
86
+ deps.fsyncSync(fd);
87
+ }
88
+ finally {
89
+ deps.closeSync(fd);
90
+ }
91
+ }
92
+ catch (err) {
93
+ const code = err.code;
94
+ if (code === "EISDIR" || code === "EINVAL" || code === "ENOTSUP")
95
+ return;
96
+ // Directory fsync is best-effort on platforms that reject it; log once.
97
+ process.stderr.write(`lanes store: directory fsync failed for ${dir}: ${err instanceof Error ? err.message : String(err)}\n`);
98
+ }
99
+ }
100
+ function atomicWriteJson(target, value, deps) {
101
+ const dir = path.dirname(target);
102
+ ensureDir(dir, deps);
103
+ const tmp = path.join(dir, `.${path.basename(target)}.tmp.${process.pid}.${Date.now()}.${randomBytes(4).toString("hex")}`);
104
+ let fd;
105
+ try {
106
+ fd = deps.openSync(tmp, "wx");
107
+ const buf = Buffer.from(`${JSON.stringify(value, null, 2)}\n`, "utf8");
108
+ fs.writeSync(fd, buf);
109
+ deps.fsyncSync(fd);
110
+ deps.closeSync(fd);
111
+ fd = undefined;
112
+ deps.renameSync(tmp, target);
113
+ fsyncDir(dir, deps);
114
+ try {
115
+ deps.chmodSync(target, 0o600);
116
+ }
117
+ catch (err) {
118
+ process.stderr.write(`lanes store: chmod 0600 failed for ${target}: ${err instanceof Error ? err.message : String(err)}\n`);
119
+ }
120
+ }
121
+ catch (err) {
122
+ if (fd !== undefined) {
123
+ try {
124
+ deps.closeSync(fd);
125
+ }
126
+ catch (closeErr) {
127
+ process.stderr.write(`lanes store: close failed for ${tmp}: ${closeErr instanceof Error ? closeErr.message : String(closeErr)}\n`);
128
+ }
129
+ }
130
+ try {
131
+ deps.unlinkSync(tmp);
132
+ }
133
+ catch (unlinkErr) {
134
+ const code = unlinkErr.code;
135
+ if (code !== "ENOENT") {
136
+ process.stderr.write(`lanes store: unlink tmp failed for ${tmp}: ${unlinkErr instanceof Error ? unlinkErr.message : String(unlinkErr)}\n`);
137
+ }
138
+ }
139
+ throw err;
140
+ }
141
+ }
142
+ function wait(ms) {
143
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
144
+ }
145
+ function lockPathFor(recordPath) {
146
+ return `${recordPath}.lock`;
147
+ }
148
+ function withRecordLock(recordPath, deps, fn) {
149
+ const lockPath = lockPathFor(recordPath);
150
+ ensureDir(path.dirname(recordPath), deps);
151
+ const started = Date.now();
152
+ while (true) {
153
+ let fd;
154
+ try {
155
+ fd = deps.openSync(lockPath, "wx");
156
+ try {
157
+ fs.writeSync(fd, Buffer.from(`${process.pid}\n${Date.now()}\n`, "utf8"));
158
+ }
159
+ catch (err) {
160
+ deps.closeSync(fd);
161
+ fd = undefined;
162
+ throw err;
163
+ }
164
+ try {
165
+ return fn();
166
+ }
167
+ finally {
168
+ try {
169
+ deps.closeSync(fd);
170
+ }
171
+ catch (err) {
172
+ process.stderr.write(`lanes store: lock close failed for ${lockPath}: ${err instanceof Error ? err.message : String(err)}\n`);
173
+ }
174
+ try {
175
+ deps.unlinkSync(lockPath);
176
+ }
177
+ catch (err) {
178
+ const code = err.code;
179
+ if (code !== "ENOENT") {
180
+ process.stderr.write(`lanes store: lock unlink failed for ${lockPath}: ${err instanceof Error ? err.message : String(err)}\n`);
181
+ }
182
+ }
183
+ }
184
+ }
185
+ catch (err) {
186
+ const code = err.code;
187
+ if (code !== "EEXIST")
188
+ throw err;
189
+ if (Date.now() - started > LOCK_TIMEOUT_MS) {
190
+ throw new LanesError("store_lock_timeout", `Timed out waiting for lock ${lockPath}`, { path: lockPath });
191
+ }
192
+ try {
193
+ const raw = deps.readFileSync(lockPath, "utf8");
194
+ const tsLine = raw.split("\n")[1];
195
+ const ts = tsLine ? Number(tsLine) : NaN;
196
+ if (Number.isFinite(ts) && Date.now() - ts > LOCK_STALE_MS) {
197
+ try {
198
+ deps.unlinkSync(lockPath);
199
+ }
200
+ catch (unlinkErr) {
201
+ const unlinkCode = unlinkErr.code;
202
+ if (unlinkCode !== "ENOENT")
203
+ throw unlinkErr;
204
+ }
205
+ continue;
206
+ }
207
+ }
208
+ catch (statErr) {
209
+ const statCode = statErr.code;
210
+ if (statCode !== "ENOENT") {
211
+ process.stderr.write(`lanes store: stale-lock probe failed for ${lockPath}: ${statErr instanceof Error ? statErr.message : String(statErr)}\n`);
212
+ }
213
+ }
214
+ wait(LOCK_RETRY_MS);
215
+ }
216
+ }
217
+ }
218
+ function readJsonFile(filePath, deps) {
219
+ let text;
220
+ try {
221
+ text = deps.readFileSync(filePath, "utf8");
222
+ }
223
+ catch (err) {
224
+ const code = err.code;
225
+ if (code === "ENOENT")
226
+ return null;
227
+ throw err;
228
+ }
229
+ try {
230
+ return JSON.parse(text);
231
+ }
232
+ catch (err) {
233
+ throw new LaneSchemaError(`Invalid JSON in ${filePath}: ${err instanceof Error ? err.message : String(err)}`, { path: filePath });
234
+ }
235
+ }
236
+ function isPlainObject(value) {
237
+ return value !== null && typeof value === "object" && !Array.isArray(value);
238
+ }
239
+ function requireString(value, field) {
240
+ if (typeof value !== "string" || value.length === 0) {
241
+ throw new LaneSchemaError(`Expected non-empty string for ${field}`, {
242
+ field,
243
+ });
244
+ }
245
+ return value;
246
+ }
247
+ function requireInt(value, field) {
248
+ if (typeof value !== "number" || !Number.isInteger(value)) {
249
+ throw new LaneSchemaError(`Expected integer for ${field}`, { field });
250
+ }
251
+ return value;
252
+ }
253
+ export function parseLaneRecord(raw, filePath) {
254
+ if (!isPlainObject(raw)) {
255
+ throw new LaneSchemaError("Lane record must be a JSON object", {
256
+ path: filePath,
257
+ });
258
+ }
259
+ const schema_version = requireString(raw.schema_version, "schema_version");
260
+ parseMajorSchema(schema_version, "hq-lane", 1);
261
+ requireString(raw.lane_id, "lane_id");
262
+ requireInt(raw.version, "version");
263
+ requireInt(raw.depth, "depth");
264
+ requireInt(raw.priority, "priority");
265
+ requireString(raw.project_id, "project_id");
266
+ requireString(raw.story_id, "story_id");
267
+ if (!isLaneState(raw.state)) {
268
+ throw new LaneSchemaError(`Unknown lane state ${JSON.stringify(raw.state)}`, { path: filePath, value: raw.state });
269
+ }
270
+ if (!isLaneProvider(raw.provider)) {
271
+ throw new LaneSchemaError(`Unknown provider ${JSON.stringify(raw.provider)}`, { path: filePath, value: raw.provider });
272
+ }
273
+ if (!isPlainObject(raw.company)) {
274
+ throw new LaneSchemaError("company must be an object", { path: filePath });
275
+ }
276
+ requireString(raw.company.slug, "company.slug");
277
+ requireString(raw.company.uid, "company.uid");
278
+ if (!isPlainObject(raw.senior)) {
279
+ throw new LaneSchemaError("senior must be an object", { path: filePath });
280
+ }
281
+ if (!isSeniorKind(raw.senior.kind)) {
282
+ throw new LaneSchemaError(`Unknown senior kind ${JSON.stringify(raw.senior.kind)}`, {
283
+ path: filePath,
284
+ field: "senior.kind",
285
+ value: raw.senior.kind,
286
+ accepted: [...SENIOR_KINDS],
287
+ });
288
+ }
289
+ if (raw.senior.kind !== "user") {
290
+ requireString(raw.senior.id, "senior.id");
291
+ }
292
+ if (!isPlainObject(raw.host)) {
293
+ throw new LaneSchemaError("host must be an object", { path: filePath });
294
+ }
295
+ if (!isHostKind(raw.host.kind)) {
296
+ throw new LaneSchemaError(`Unknown host kind ${JSON.stringify(raw.host.kind)}`, {
297
+ path: filePath,
298
+ field: "host.kind",
299
+ value: raw.host.kind,
300
+ accepted: [...HOST_KINDS],
301
+ });
302
+ }
303
+ requireString(raw.host.id, "host.id");
304
+ if (!Array.isArray(raw.senior_history)) {
305
+ throw new LaneSchemaError("senior_history must be an array", {
306
+ path: filePath,
307
+ });
308
+ }
309
+ if (!Array.isArray(raw.attribution_history)) {
310
+ throw new LaneSchemaError("attribution_history must be an array", {
311
+ path: filePath,
312
+ });
313
+ }
314
+ // Spread-preserving: return the original object so unknown keys survive
315
+ // a parse/rewrite cycle (spec §5.1 field-preservation).
316
+ return raw;
317
+ }
318
+ export function parseQuestionRecord(raw, filePath) {
319
+ if (!isPlainObject(raw)) {
320
+ throw new LaneSchemaError("Question record must be a JSON object", {
321
+ path: filePath,
322
+ });
323
+ }
324
+ const schema_version = requireString(raw.schema_version, "schema_version");
325
+ parseMajorSchema(schema_version, "hq-lane-question", 1);
326
+ if (!isQuestionStatus(raw.status)) {
327
+ throw new LaneSchemaError(`Unknown question status ${JSON.stringify(raw.status)}`, { path: filePath, value: raw.status });
328
+ }
329
+ requireString(raw.question_id, "question_id");
330
+ requireString(raw.lane_id, "lane_id");
331
+ requireInt(raw.version, "version");
332
+ requireInt(raw.hop, "hop");
333
+ if (!isPlainObject(raw.body)) {
334
+ throw new LaneSchemaError("body must be an object", { path: filePath });
335
+ }
336
+ if (!Array.isArray(raw.routing_history)) {
337
+ throw new LaneSchemaError("routing_history must be an array", {
338
+ path: filePath,
339
+ });
340
+ }
341
+ return raw;
342
+ }
343
+ /**
344
+ * HQ Sync sibling-twin grammar from `@indigoai-us/hq-cloud` `buildConflictPath`:
345
+ * `<file>.json.conflict-<ISO-with-dashes>-<machine>.json`
346
+ * (legacy twins; current engines park losers under `.hq/conflict-backups/`,
347
+ * but merge-on-read still has to recover the ones already on disk).
348
+ */
349
+ export function isConflictSidecarName(recordBasename, name) {
350
+ if (name === recordBasename || name.startsWith("."))
351
+ return false;
352
+ return name.startsWith(`${recordBasename}.conflict-`);
353
+ }
354
+ function sidecarPathsFor(recordPath, deps) {
355
+ const dir = path.dirname(recordPath);
356
+ const base = path.basename(recordPath);
357
+ if (!deps.existsSync(dir))
358
+ return [];
359
+ const names = deps.readdirSync(dir);
360
+ const sidecars = [];
361
+ for (const name of names) {
362
+ if (typeof name !== "string")
363
+ continue;
364
+ if (!isConflictSidecarName(base, name))
365
+ continue;
366
+ sidecars.push(path.join(dir, name));
367
+ }
368
+ return sidecars;
369
+ }
370
+ function canonicalJson(value) {
371
+ if (value === null || typeof value !== "object")
372
+ return JSON.stringify(value);
373
+ if (Array.isArray(value)) {
374
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
375
+ }
376
+ const obj = value;
377
+ const keys = Object.keys(obj).sort();
378
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${canonicalJson(obj[key])}`).join(",")}}`;
379
+ }
380
+ function historyTimestamp(entry) {
381
+ if (!isPlainObject(entry) || typeof entry.at !== "string")
382
+ return "";
383
+ return entry.at;
384
+ }
385
+ /**
386
+ * Attribution identity is the message that caused the re-point (spec §2).
387
+ * Senior and routing entries have no named id; union is by canonical entry.
388
+ */
389
+ function attributionIdentity(entry) {
390
+ if (typeof entry.message_id === "string" && entry.message_id.length > 0) {
391
+ return `message_id:${entry.message_id}`;
392
+ }
393
+ return `entry:${canonicalJson(entry)}`;
394
+ }
395
+ function entryIdentity(entry) {
396
+ return canonicalJson(entry);
397
+ }
398
+ function unionHistory(lists, identity, preferred) {
399
+ const map = new Map();
400
+ for (const entry of preferred) {
401
+ map.set(identity(entry), entry);
402
+ }
403
+ for (const list of lists) {
404
+ for (const entry of list) {
405
+ const id = identity(entry);
406
+ if (!map.has(id))
407
+ map.set(id, entry);
408
+ }
409
+ }
410
+ const merged = [...map.values()].sort((a, b) => historyTimestamp(a).localeCompare(historyTimestamp(b)));
411
+ if (merged.length <= HISTORY_CAP)
412
+ return merged;
413
+ return merged.slice(merged.length - HISTORY_CAP);
414
+ }
415
+ function higherVersionRecord(live, others) {
416
+ let best = live;
417
+ for (const other of others) {
418
+ if (other.version > best.version)
419
+ best = other;
420
+ }
421
+ return best;
422
+ }
423
+ export function mergeLaneRecords(live, sidecars) {
424
+ if (sidecars.length === 0)
425
+ return live;
426
+ const all = [live, ...sidecars];
427
+ const base = higherVersionRecord(live, sidecars);
428
+ return {
429
+ ...base,
430
+ senior_history: unionHistory(all.map((record) => record.senior_history), entryIdentity, base.senior_history),
431
+ attribution_history: unionHistory(all.map((record) => record.attribution_history), attributionIdentity, base.attribution_history),
432
+ };
433
+ }
434
+ export function mergeQuestionRecords(live, sidecars) {
435
+ if (sidecars.length === 0)
436
+ return live;
437
+ const all = [live, ...sidecars];
438
+ const base = higherVersionRecord(live, sidecars);
439
+ return {
440
+ ...base,
441
+ routing_history: unionHistory(all.map((record) => record.routing_history), entryIdentity, base.routing_history),
442
+ };
443
+ }
444
+ function loadSidecarRecords(recordPath, parse, deps) {
445
+ const paths = sidecarPathsFor(recordPath, deps);
446
+ const records = [];
447
+ for (const sidecarPath of paths) {
448
+ try {
449
+ const raw = readJsonFile(sidecarPath, deps);
450
+ if (raw === null)
451
+ continue;
452
+ records.push(parse(raw, sidecarPath));
453
+ }
454
+ catch (err) {
455
+ process.stderr.write(`lanes store: skipping unreadable conflict sidecar ${sidecarPath}: ${err instanceof Error ? err.message : String(err)}\n`);
456
+ }
457
+ }
458
+ return records;
459
+ }
460
+ function readMergedRecord(filePath, parse, merge, deps) {
461
+ const raw = readJsonFile(filePath, deps);
462
+ if (raw === null)
463
+ return null;
464
+ const live = parse(raw, filePath);
465
+ const sidecars = loadSidecarRecords(filePath, parse, deps);
466
+ if (sidecars.length === 0)
467
+ return live;
468
+ return merge(live, sidecars);
469
+ }
470
+ export function tryReadLane(hqRoot, laneId, deps = defaultStoreDeps()) {
471
+ const filePath = laneRecordPath(hqRoot, laneId);
472
+ return readMergedRecord(filePath, parseLaneRecord, mergeLaneRecords, deps);
473
+ }
474
+ export function readLane(hqRoot, laneId, deps = defaultStoreDeps()) {
475
+ const record = tryReadLane(hqRoot, laneId, deps);
476
+ if (!record)
477
+ throw new LaneNotFoundError("lane", laneId);
478
+ return record;
479
+ }
480
+ export function tryReadQuestion(hqRoot, questionId, deps = defaultStoreDeps()) {
481
+ const filePath = questionRecordPath(hqRoot, questionId);
482
+ return readMergedRecord(filePath, parseQuestionRecord, mergeQuestionRecords, deps);
483
+ }
484
+ export function readQuestion(hqRoot, questionId, deps = defaultStoreDeps()) {
485
+ const record = tryReadQuestion(hqRoot, questionId, deps);
486
+ if (!record)
487
+ throw new LaneNotFoundError("question", questionId);
488
+ return record;
489
+ }
490
+ function casWrite(filePath, expectedVersion, parse, merge, updater, deps) {
491
+ return withRecordLock(filePath, deps, () => {
492
+ const current = readMergedRecord(filePath, parse, merge, deps);
493
+ if (current === null) {
494
+ throw new LaneSchemaError(`Record disappeared under lock: ${filePath}`, {
495
+ path: filePath,
496
+ });
497
+ }
498
+ if (current.version !== expectedVersion) {
499
+ throw new LaneVersionConflict({
500
+ path: filePath,
501
+ expectedVersion,
502
+ actualVersion: current.version,
503
+ });
504
+ }
505
+ const updated = updater(current);
506
+ const next = {
507
+ ...current,
508
+ ...updated,
509
+ version: current.version + 1,
510
+ updated_at: deps.now().toISOString(),
511
+ };
512
+ atomicWriteJson(filePath, next, deps);
513
+ return next;
514
+ });
515
+ }
516
+ export function createLane(hqRoot, init, deps = defaultStoreDeps()) {
517
+ const now = deps.now().toISOString();
518
+ const lane_id = init.lane_id ?? mintLaneId(deps);
519
+ const filePath = laneRecordPath(hqRoot, lane_id);
520
+ const record = {
521
+ ...init,
522
+ schema_version: init.schema_version ?? LANE_SCHEMA_VERSION,
523
+ lane_id,
524
+ version: 1,
525
+ created_at: init.created_at ?? now,
526
+ updated_at: init.updated_at ?? now,
527
+ senior_history: init.senior_history ?? [],
528
+ attribution_history: init.attribution_history ?? [],
529
+ };
530
+ parseLaneRecord(record, filePath);
531
+ return withRecordLock(filePath, deps, () => {
532
+ if (deps.existsSync(filePath)) {
533
+ throw new LanesError("lane_exists", `Lane ${lane_id} already exists`, { lane_id });
534
+ }
535
+ atomicWriteJson(filePath, record, deps);
536
+ return record;
537
+ });
538
+ }
539
+ export function updateLane(hqRoot, laneId, expectedVersion, updater, deps = defaultStoreDeps()) {
540
+ return casWrite(laneRecordPath(hqRoot, laneId), expectedVersion, parseLaneRecord, mergeLaneRecords, updater, deps);
541
+ }
542
+ export function appendLaneSeniorHistory(hqRoot, laneId, expectedVersion, entry, deps = defaultStoreDeps()) {
543
+ return updateLane(hqRoot, laneId, expectedVersion, (current) => ({
544
+ ...current,
545
+ senior_history: appendCappedHistory(current.senior_history, entry),
546
+ }), deps);
547
+ }
548
+ export function appendLaneAttribution(hqRoot, laneId, expectedVersion, entry, deps = defaultStoreDeps()) {
549
+ return updateLane(hqRoot, laneId, expectedVersion, (current) => ({
550
+ ...current,
551
+ attribution_history: appendCappedHistory(current.attribution_history, entry),
552
+ }), deps);
553
+ }
554
+ function syncPendingMarker(hqRoot, question, deps) {
555
+ const marker = pendingMarkerPath(hqRoot, question.question_id);
556
+ if (question.status === "pending") {
557
+ ensureDir(path.dirname(marker), deps);
558
+ if (!deps.existsSync(marker)) {
559
+ deps.writeFileSync(marker, "", { encoding: "utf8" });
560
+ }
561
+ return;
562
+ }
563
+ try {
564
+ deps.unlinkSync(marker);
565
+ }
566
+ catch (err) {
567
+ const code = err.code;
568
+ if (code !== "ENOENT")
569
+ throw err;
570
+ }
571
+ }
572
+ export function createQuestion(hqRoot, init, deps = defaultStoreDeps()) {
573
+ const question_id = init.question_id ?? mintQuestionId(deps);
574
+ const filePath = questionRecordPath(hqRoot, question_id);
575
+ const record = {
576
+ ...init,
577
+ schema_version: init.schema_version ?? QUESTION_SCHEMA_VERSION,
578
+ question_id,
579
+ version: 1,
580
+ routing_history: init.routing_history ?? [],
581
+ };
582
+ parseQuestionRecord(record, filePath);
583
+ return withRecordLock(filePath, deps, () => {
584
+ if (deps.existsSync(filePath)) {
585
+ throw new LanesError("question_exists", `Question ${question_id} already exists`, { question_id });
586
+ }
587
+ atomicWriteJson(filePath, record, deps);
588
+ syncPendingMarker(hqRoot, record, deps);
589
+ return record;
590
+ });
591
+ }
592
+ export function updateQuestion(hqRoot, questionId, expectedVersion, updater, deps = defaultStoreDeps()) {
593
+ const next = casWrite(questionRecordPath(hqRoot, questionId), expectedVersion, parseQuestionRecord, mergeQuestionRecords, updater, deps);
594
+ syncPendingMarker(hqRoot, next, deps);
595
+ return next;
596
+ }
597
+ export function appendQuestionRouting(hqRoot, questionId, expectedVersion, entry, deps = defaultStoreDeps()) {
598
+ return updateQuestion(hqRoot, questionId, expectedVersion, (current) => ({
599
+ ...current,
600
+ routing_history: appendCappedHistory(current.routing_history, entry),
601
+ }), deps);
602
+ }
603
+ export function listLaneIds(hqRoot, deps = defaultStoreDeps()) {
604
+ const dir = path.join(lanesStoreRoot(hqRoot), LANE_RECORDS_DIR);
605
+ if (!deps.existsSync(dir))
606
+ return [];
607
+ return deps
608
+ .readdirSync(dir)
609
+ .filter((name) => typeof name === "string" &&
610
+ name.endsWith(".json") &&
611
+ !name.startsWith(".") &&
612
+ !name.includes(".conflict-"))
613
+ .map((name) => name.slice(0, -".json".length));
614
+ }
615
+ export function listQuestionIds(hqRoot, deps = defaultStoreDeps()) {
616
+ const dir = path.join(lanesStoreRoot(hqRoot), QUESTION_RECORDS_DIR);
617
+ if (!deps.existsSync(dir))
618
+ return [];
619
+ return deps
620
+ .readdirSync(dir)
621
+ .filter((name) => typeof name === "string" &&
622
+ name.endsWith(".json") &&
623
+ !name.startsWith(".") &&
624
+ !name.includes(".conflict-"))
625
+ .map((name) => name.slice(0, -".json".length));
626
+ }
627
+ //# sourceMappingURL=store.js.map