@open-tomato/rafa 0.46.0 → 0.48.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 (94) hide show
  1. package/README.md +70 -37
  2. package/dist/adapters/logger/settings.d.ts +2 -2
  3. package/dist/bugs/places.d.ts +1 -1
  4. package/dist/bugs/record.d.ts +1 -1
  5. package/dist/bundled/skills/dev-planner/SKILL.md +2 -2
  6. package/dist/cli.js +73457 -72996
  7. package/dist/config/index.d.ts +5 -0
  8. package/dist/config/index.js +6 -4
  9. package/dist/config/shape.d.ts +20 -15
  10. package/dist/config/templates.d.ts +64 -0
  11. package/dist/config-registry.d.ts +21 -12
  12. package/dist/config-schema-board-project.d.ts +3 -3
  13. package/dist/config-schema-bugs.d.ts +3 -3
  14. package/dist/config-schema-checks.d.ts +114 -0
  15. package/dist/config-schema-errors.d.ts +3 -3
  16. package/dist/config-schema-features.d.ts +4 -4
  17. package/dist/config-schema-hub.d.ts +6 -4
  18. package/dist/config-schema-issues.d.ts +2 -2
  19. package/dist/config-schema-logger.d.ts +3 -3
  20. package/dist/config-schema-loop-continue.d.ts +3 -3
  21. package/dist/config-schema-loop-retries.d.ts +4 -4
  22. package/dist/config-schema-release.d.ts +23 -24
  23. package/dist/config-schema-tests.d.ts +35 -27
  24. package/dist/config-schema-triage.d.ts +3 -3
  25. package/dist/config-schema-wrap-up.d.ts +4 -4
  26. package/dist/core/command/command.d.ts +1 -1
  27. package/dist/core/command/confirm.d.ts +11 -5
  28. package/dist/core/command/global-flags.d.ts +25 -0
  29. package/dist/core/command/index.d.ts +47 -23
  30. package/dist/core/command/registry-types.d.ts +4 -4
  31. package/dist/core/command/shared-flags.d.ts +40 -0
  32. package/dist/core/command/types.d.ts +3 -2
  33. package/dist/core/config/branch-template.d.ts +2 -0
  34. package/dist/core/config/config-items.d.ts +1 -1
  35. package/dist/core/config/config-load-module.d.ts +43 -0
  36. package/dist/core/config/config-load.d.ts +43 -12
  37. package/dist/core/config/config-origins.d.ts +31 -30
  38. package/dist/core/config/config-schema.d.ts +11 -0
  39. package/dist/core/config/config-sections.d.ts +15 -14
  40. package/dist/core/config/config.d.ts +90 -25
  41. package/dist/core/config/core-section.d.ts +1 -1
  42. package/dist/core/config/default-routing.d.ts +1 -1
  43. package/dist/core/config/index.d.ts +14 -10
  44. package/dist/core/config/merge-method.d.ts +40 -0
  45. package/dist/core/config/scope.d.ts +2 -2
  46. package/dist/core/config/section.d.ts +81 -1
  47. package/dist/core/config/sections.d.ts +17 -6
  48. package/dist/core/git/gh-runner.d.ts +1 -1
  49. package/dist/core/git/git.d.ts +34 -0
  50. package/dist/core/git/index.d.ts +13 -8
  51. package/dist/core/loop/claude.d.ts +11 -5
  52. package/dist/core/loop/hop-record.d.ts +6 -6
  53. package/dist/core/loop/index.d.ts +9 -8
  54. package/dist/core/loop/session-record-parse.d.ts +9 -2
  55. package/dist/core/loop/sessions.d.ts +23 -11
  56. package/dist/core/loop/suite-failure.d.ts +8 -6
  57. package/dist/core/output/active.d.ts +1 -1
  58. package/dist/core/plan/block-reader.d.ts +1 -1
  59. package/dist/core/runtime/identity.d.ts +13 -0
  60. package/dist/core/runtime/index.d.ts +12 -6
  61. package/dist/effort/store/check-rows.d.ts +1 -1
  62. package/dist/effort/store/commit-stats.d.ts +1 -1
  63. package/dist/effort/store/index.js +7 -8
  64. package/dist/effort/store/merge-commit-gaps.d.ts +1 -1
  65. package/dist/effort/store/plan-stubs.d.ts +1 -1
  66. package/dist/effort/store/session-row-types.d.ts +2 -2
  67. package/dist/errors/rafa-codes.d.ts +1 -1
  68. package/dist/index-2xzkzwm6.js +670 -0
  69. package/dist/index-ajv88fkm.js +448 -0
  70. package/dist/{index-ykggr043.js → index-fpgmdmww.js} +13 -5
  71. package/dist/index-g91ys6kw.js +249 -0
  72. package/dist/{index-cy98y87p.js → index-jx3x70xh.js} +1111 -638
  73. package/dist/{index-gvek4r8m.js → index-m672ptpg.js} +84 -26
  74. package/dist/{index-39kbcw68.js → index-w5qbpdtp.js} +415 -842
  75. package/dist/{index-gqz4jn6j.js → index-z4r20zwr.js} +8974 -11438
  76. package/dist/{index-j4k2vdz3.js → index-zsak0jy6.js} +124 -290
  77. package/dist/index.js +24940 -18766
  78. package/dist/learning/index.js +221 -12
  79. package/dist/plan/index.js +10 -9
  80. package/dist/ports/index.d.ts +7 -7
  81. package/dist/ports/learning.d.ts +5 -4
  82. package/dist/ports/spec-review.d.ts +1 -1
  83. package/dist/ready-gax3hhtt.js +241 -0
  84. package/dist/release-templates/release-bot-fragment.yml +6 -6
  85. package/dist/release-templates/release-publish.yml +8 -8
  86. package/dist/release-templates/release-settle.yml +8 -7
  87. package/dist/release-templates/release-tag.yml +8 -7
  88. package/package.json +53 -2
  89. package/dist/index-77ajfffn.js +0 -223
  90. package/dist/index-jh1r4kcn.js +0 -1067
  91. package/dist/index-z1w83f81.js +0 -4
  92. package/dist/pr/checks.d.ts +0 -133
  93. package/dist/pr/types.d.ts +0 -422
  94. package/dist/ready-4f8edezt.js +0 -2016
@@ -1,130 +1,29 @@
1
1
  // @bun
2
+ import {
3
+ CORE_ADAPTER_REGISTRY,
4
+ RAFA_VERSION,
5
+ activeStoreSettings,
6
+ asHopRecord,
7
+ commandSpelling,
8
+ createGitRunner,
9
+ normalizeRemote,
10
+ runningCommand
11
+ } from "./index-2xzkzwm6.js";
2
12
  import {
3
13
  activeOutput,
4
14
  activeOutputMode,
5
15
  isStampableStub
6
16
  } from "./index-2a7nb3an.js";
7
17
  import {
8
- CORE_SECTION,
9
18
  SCOPE_DIR,
10
19
  scopeAt
11
- } from "./index-gvek4r8m.js";
20
+ } from "./index-m672ptpg.js";
12
21
  import {
13
- BUSY_TIMEOUT_MAX_MS,
14
- BUSY_TIMEOUT_MIN_MS,
15
22
  TEST_SCOPES,
16
23
  bundledBinDirectory,
17
- describeValue,
18
- isBusyTimeoutMs,
19
24
  messageOf
20
- } from "./index-ykggr043.js";
21
-
22
- // packages/rafa/src/core/adapters/registry.ts
23
- var REFUSAL = "adapter registry";
24
- var PORT_VERSIONS = Object.freeze({
25
- tracker: 1,
26
- store: 1,
27
- learning: 1,
28
- output: 1,
29
- planner: 1,
30
- sync: 1,
31
- logger: 1
32
- });
33
- var SERVED_VERSIONS = new Map(Object.entries(PORT_VERSIONS));
34
- var PORT_TYPE_LIST = [...SERVED_VERSIONS.keys()].join(", ");
35
- function checkPortType(port) {
36
- if (!SERVED_VERSIONS.has(port)) {
37
- throw new TypeError(`${REFUSAL}: port is ${describeValue(port)}, expected one of: ${PORT_TYPE_LIST}`);
38
- }
39
- }
40
- function accept(adapter, held) {
41
- if (typeof adapter !== "object" || adapter === null) {
42
- throw new TypeError(`${REFUSAL}: an adapter is ${describeValue(adapter)}, expected a mapping`);
43
- }
44
- const { port, kind, portVersion, create } = adapter;
45
- checkPortType(port);
46
- if (typeof kind !== "string" || kind === "") {
47
- throw new TypeError(`${REFUSAL}: a ${port} adapter has kind ${describeValue(kind)}, expected a non-empty name`);
48
- }
49
- const key = `${port}/${kind}`;
50
- if (typeof create !== "function") {
51
- throw new TypeError(`${REFUSAL}: ${key} has create ${describeValue(create)}, expected a function`);
52
- }
53
- const served = SERVED_VERSIONS.get(port);
54
- if (portVersion !== served) {
55
- throw new Error(`${REFUSAL}: ${key} implements ${port} port version ${describeValue(portVersion)},` + ` and core serves ${port} port version ${served}`);
56
- }
57
- if (held.some((other) => other.port === port && other.kind === kind)) {
58
- throw new Error(`${REFUSAL}: ${key} is already registered`);
59
- }
60
- return Object.freeze({ port, kind, portVersion, create });
61
- }
62
- function indexByPort(adapters) {
63
- const only = (port) => new Map(adapters.filter((adapter) => adapter.port === port).map((adapter) => [adapter.kind, adapter]));
64
- return {
65
- tracker: only("tracker"),
66
- store: only("store"),
67
- learning: only("learning"),
68
- output: only("output"),
69
- planner: only("planner"),
70
- sync: only("sync"),
71
- logger: only("logger")
72
- };
73
- }
74
- function createAdapterRegistry(adapters = []) {
75
- const held = adapters.reduce((accepted, adapter) => [...accepted, accept(adapter, accepted)], []);
76
- const byPort = indexByPort(held);
77
- const registry = {
78
- register: (adapter) => createAdapterRegistry([...held, adapter]),
79
- find: (port, kind) => SERVED_VERSIONS.has(port) ? byPort[port].get(kind) : undefined,
80
- resolve: (port, kind) => {
81
- checkPortType(port);
82
- const adapter = byPort[port].get(kind);
83
- if (adapter !== undefined)
84
- return adapter;
85
- const registered = [...byPort[port].keys()];
86
- const listed = registered.length === 0 ? "none" : registered.join(", ");
87
- throw new Error(`${REFUSAL}: no ${port} adapter is registered as ${describeValue(kind)};` + ` registered: ${listed}`);
88
- },
89
- kinds: (port) => {
90
- checkPortType(port);
91
- return [...byPort[port].keys()];
92
- }
93
- };
94
- return Object.freeze(registry);
95
- }
96
- var EMPTY_ADAPTER_REGISTRY = createAdapterRegistry();
97
- var COMPOSITION_ROOT = "src/adapter-registry.ts";
98
- var active = EMPTY_ADAPTER_REGISTRY;
99
- function holdsNone(registry) {
100
- return [...SERVED_VERSIONS.keys()].every((port) => registry.kinds(port).length === 0);
101
- }
102
- function registerAdapters(adapters) {
103
- const previous = active;
104
- active = adapters.reduce((registry, adapter) => registry.register(adapter), previous);
105
- return previous;
106
- }
107
- function restoreAdapters(registry) {
108
- if (registry === CORE_ADAPTER_REGISTRY) {
109
- throw new TypeError(`${REFUSAL}: CORE_ADAPTER_REGISTRY reads the active registry and cannot be made the active one;` + " restore what registerAdapters or activeAdapterRegistry answered");
110
- }
111
- active = registry;
112
- }
113
- function activeAdapterRegistry() {
114
- return active;
115
- }
116
- function registered() {
117
- if (holdsNone(active)) {
118
- throw new Error(`${REFUSAL}: no adapter is registered: call registerCoreAdapters() from ${COMPOSITION_ROOT}` + " before reading CORE_ADAPTER_REGISTRY");
119
- }
120
- return active;
121
- }
122
- var CORE_ADAPTER_REGISTRY = Object.freeze({
123
- register: (adapter) => registered().register(adapter),
124
- find: (port, kind) => registered().find(port, kind),
125
- resolve: (port, kind) => registered().resolve(port, kind),
126
- kinds: (port) => registered().kinds(port)
127
- });
25
+ } from "./index-fpgmdmww.js";
26
+
128
27
  // packages/rafa/src/effort/store/types.ts
129
28
  function keyOrNull(value) {
130
29
  return typeof value === "string" && value.length > 0 ? value : null;
@@ -134,381 +33,6 @@ var EFFORT_KEY_PROJECTIONS = {
134
33
  commits: (row) => keyOrNull(row.sha)
135
34
  };
136
35
 
137
- // packages/rafa/src/core/command/spends.ts
138
- var SPENDS_GLYPH = "\uD83E\uDE99";
139
-
140
- // packages/rafa/src/core/command/command.ts
141
- var MAX_EXIT_CODE = 255;
142
-
143
- class CommandExit extends Error {
144
- exitCode;
145
- constructor(exitCode, message = "", options) {
146
- super(message, options);
147
- if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > MAX_EXIT_CODE) {
148
- throw new TypeError(`CommandExit: exit code is ${describeValue(exitCode)}, expected a whole number from 0 to ${MAX_EXIT_CODE}`);
149
- }
150
- this.name = "CommandExit";
151
- this.exitCode = exitCode;
152
- }
153
- }
154
- function isTopLevel(command) {
155
- return command.subject === command.action;
156
- }
157
- function commandSpelling(command) {
158
- return isTopLevel(command) ? command.subject : `${command.subject} ${command.action}`;
159
- }
160
-
161
- // packages/rafa/src/core/command/confirm.ts
162
- import { createInterface } from "readline";
163
- var YES_ANSWERS = Object.freeze(["y", "yes"]);
164
- function createLinePrompter(input, output) {
165
- const buffered = [];
166
- const waiting = [];
167
- let ended = false;
168
- const lines = createInterface({ input, terminal: false, crlfDelay: Infinity });
169
- lines.on("line", (line) => {
170
- const reader = waiting.shift();
171
- if (reader === undefined)
172
- buffered.push(line);
173
- else
174
- reader(line);
175
- });
176
- lines.on("close", () => {
177
- ended = true;
178
- for (const reader of waiting.splice(0))
179
- reader(null);
180
- });
181
- return {
182
- say: (text) => {
183
- output.write(`${text}
184
- `);
185
- },
186
- ask: async (question) => {
187
- output.write(question);
188
- const next = buffered.shift();
189
- if (next !== undefined)
190
- return next;
191
- if (ended)
192
- return null;
193
- return new Promise((settle) => {
194
- waiting.push(settle);
195
- });
196
- },
197
- close: () => {
198
- lines.close();
199
- }
200
- };
201
- }
202
- function lazyPrompter(open) {
203
- let prompter = null;
204
- return {
205
- ask: async (question) => {
206
- prompter ??= open();
207
- const answer = await prompter.ask(question);
208
- return answer !== null && YES_ANSWERS.includes(answer.trim().toLowerCase());
209
- },
210
- close: () => {
211
- prompter?.close();
212
- prompter = null;
213
- }
214
- };
215
- }
216
- // packages/rafa/src/core/command/running.ts
217
- import { AsyncLocalStorage } from "async_hooks";
218
- var scopes = new AsyncLocalStorage;
219
- var running = null;
220
- function runningCommand() {
221
- return scopes.getStore() ?? running;
222
- }
223
- // package.json
224
- var version = "0.46.0";
225
-
226
- // packages/rafa/src/core/command/version.ts
227
- var RAFA_VERSION = version;
228
- // packages/rafa/src/core/git/git.ts
229
- import { spawnSync } from "child_process";
230
- function createGitRunner(cwd) {
231
- return (args) => {
232
- const result = spawnSync("git", [...args], {
233
- cwd,
234
- encoding: "utf8",
235
- env: { ...process.env, LC_ALL: "C" }
236
- });
237
- if (result.error !== undefined) {
238
- return { ok: false, stdout: "", stderr: `could not run git in ${cwd}: ${messageOf(result.error)}` };
239
- }
240
- return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
241
- };
242
- }
243
- function gitSaid(result) {
244
- return [result.stderr, result.stdout].map((stream) => stream.trim()).filter((stream) => stream !== "").join(`
245
- `);
246
- }
247
- // packages/rafa/src/core/git/commit.ts
248
- import { spawnSync as spawnSync2 } from "child_process";
249
- var DEFAULT_COMMIT_TYPE = "chore";
250
- var TEST_NOUN_WINDOW = 40;
251
- var FIX_VERBS = ["fix", "repair", "correct", "resolve"];
252
- var REFACTOR_VERBS = [
253
- "remove",
254
- "delete",
255
- "drop",
256
- "move",
257
- "rename",
258
- "relocate",
259
- "extract",
260
- "split",
261
- "inline",
262
- "collapse"
263
- ];
264
- var FEAT_VERBS = [
265
- "add",
266
- "implement",
267
- "introduce",
268
- "register",
269
- "extend",
270
- "call",
271
- "wire",
272
- "expose",
273
- "parse",
274
- "strip",
275
- "enforce",
276
- "generate"
277
- ];
278
- var CHORE_VERBS = [
279
- "capture",
280
- "measure",
281
- "run",
282
- "sweep",
283
- "verify",
284
- "ensure",
285
- "regenerate",
286
- "update",
287
- "gitignore",
288
- "take",
289
- "bump",
290
- "pin"
291
- ];
292
- function openingVerbs(verbs) {
293
- return new RegExp(`^(?:${verbs.join("|")})\\b`, "i");
294
- }
295
- var COMMIT_TYPE_RULES = [
296
- {
297
- type: "test",
298
- pattern: new RegExp(`^.{0,${TEST_NOUN_WINDOW}}?\\btests?\\b`, "i")
299
- },
300
- { type: "docs", pattern: /\.md\b/i },
301
- { type: "fix", pattern: openingVerbs(FIX_VERBS) },
302
- { type: "refactor", pattern: openingVerbs(REFACTOR_VERBS) },
303
- { type: "feat", pattern: openingVerbs(FEAT_VERBS) },
304
- { type: "chore", pattern: openingVerbs(CHORE_VERBS) }
305
- ];
306
- var MAX_SUBJECT_LENGTH = 72;
307
- var FALLBACK_DESCRIPTION = "complete the scoped task";
308
- var MAX_MESSAGE_CHARS = 4000;
309
- function normaliseTaskText(taskText) {
310
- return taskText.replace(/\s+/g, " ").trim();
311
- }
312
- function inferCommitType(taskText) {
313
- const text = normaliseTaskText(taskText);
314
- for (const rule of COMMIT_TYPE_RULES) {
315
- if (rule.pattern.test(text))
316
- return rule.type;
317
- }
318
- return DEFAULT_COMMIT_TYPE;
319
- }
320
- function countBackticks(text) {
321
- let count = 0;
322
- for (const character of text) {
323
- if (character === "`")
324
- count += 1;
325
- }
326
- return count;
327
- }
328
- function balanceCodeSpans(text) {
329
- let result = text;
330
- while (countBackticks(result) % 2 === 1) {
331
- const lastSpace = result.lastIndexOf(" ");
332
- if (lastSpace <= 0)
333
- return result.replace(/`/g, "");
334
- result = result.slice(0, lastSpace).trimEnd();
335
- }
336
- return result;
337
- }
338
- function stripTrailingPeriod(text) {
339
- if (!text.endsWith("."))
340
- return text;
341
- const withoutDot = text.slice(0, -1);
342
- const lastToken = withoutDot.slice(withoutDot.lastIndexOf(" ") + 1);
343
- if (lastToken.includes("."))
344
- return text;
345
- return withoutDot;
346
- }
347
- function lowerFirstWord(text) {
348
- const match = text.match(/^[A-Za-z]+/);
349
- const word = match?.[0];
350
- if (word === undefined)
351
- return text;
352
- if (word.length > 1 && word === word.toUpperCase())
353
- return text;
354
- return text.slice(0, 1).toLowerCase() + text.slice(1);
355
- }
356
- var CLAUSE_ENDINGS = new Set([",", ":", "(", ")"]);
357
- function backtickRunLength(text, start) {
358
- let end = start;
359
- while (text.charAt(end) === "`")
360
- end += 1;
361
- return end - start;
362
- }
363
- function codeSpanEnd(text, from, length) {
364
- let index = text.indexOf("`", from);
365
- while (index !== -1) {
366
- const run = backtickRunLength(text, index);
367
- if (run === length)
368
- return index + run;
369
- index = text.indexOf("`", index + run);
370
- }
371
- return -1;
372
- }
373
- function firstClause(text) {
374
- let index = 0;
375
- while (index < text.length) {
376
- const character = text.charAt(index);
377
- if (character === "`") {
378
- const run = backtickRunLength(text, index);
379
- const end = codeSpanEnd(text, index + run, run);
380
- index = end === -1 ? index + run : end;
381
- continue;
382
- }
383
- if (CLAUSE_ENDINGS.has(character))
384
- return text.slice(0, index).trimEnd();
385
- index += 1;
386
- }
387
- return text.trimEnd();
388
- }
389
- function truncateDescription(description, budget) {
390
- if (budget <= 0)
391
- return "";
392
- if (description.length <= budget)
393
- return description;
394
- const window = description.slice(0, budget + 1);
395
- const lastSpace = window.lastIndexOf(" ");
396
- const cut = lastSpace > 0 ? window.slice(0, lastSpace) : window.slice(0, budget);
397
- return balanceCodeSpans(cut.trimEnd()).replace(/[\s,;:-]+$/, "");
398
- }
399
- function subjectDescription(normalised) {
400
- const clause = firstClause(normalised);
401
- const description = clause.length === 0 ? normalised : clause;
402
- return lowerFirstWord(stripTrailingPeriod(description));
403
- }
404
- function deriveCommitSubject(taskText, options = {}) {
405
- const type = inferCommitType(taskText);
406
- const scope = options.scope;
407
- const prefix = scope === undefined || scope.length === 0 ? `${type}: ` : `${type}(${scope}): `;
408
- const normalised = normaliseTaskText(taskText);
409
- const uncut = normalised.length === 0 ? FALLBACK_DESCRIPTION : subjectDescription(normalised);
410
- const maxLength = options.maxLength ?? MAX_SUBJECT_LENGTH;
411
- const description = truncateDescription(uncut, maxLength - prefix.length);
412
- const truncated = description !== uncut;
413
- return {
414
- subject: `${prefix}${description}`,
415
- type,
416
- truncated
417
- };
418
- }
419
- function buildCommitMessage(taskText, options = {}) {
420
- const derived = deriveCommitSubject(taskText, options);
421
- const body = normaliseTaskText(taskText);
422
- return { ...derived, body };
423
- }
424
- function stageAllArgs() {
425
- return ["add", "-A"];
426
- }
427
- function stagedChangesArgs() {
428
- return ["diff", "--cached", "--quiet"];
429
- }
430
- function commitArgs(subject, body = "") {
431
- const args = ["commit", "--cleanup=whitespace", "-m", subject];
432
- if (body.length > 0)
433
- args.push("-m", body);
434
- return args;
435
- }
436
- function headShaArgs() {
437
- return ["rev-parse", "HEAD"];
438
- }
439
- var MAX_GIT_BUFFER = 16 * 1024 * 1024;
440
- function failureMessage(result) {
441
- const combined = [result.stderr, result.stdout].map((stream) => stream.trim()).filter((stream) => stream.length > 0).join(`
442
- `);
443
- if (combined.length <= MAX_MESSAGE_CHARS)
444
- return combined;
445
- return `${combined.slice(0, MAX_MESSAGE_CHARS)}
446
- [truncated]`;
447
- }
448
- function failed(step, subject, result) {
449
- return {
450
- outcome: "failed",
451
- subject,
452
- sha: null,
453
- failedStep: step,
454
- exitCode: result.status,
455
- message: failureMessage(result)
456
- };
457
- }
458
- function spawnGit(cwd) {
459
- return (args) => {
460
- const result = spawnSync2("git", args, {
461
- cwd,
462
- encoding: "utf8",
463
- maxBuffer: MAX_GIT_BUFFER
464
- });
465
- if (result.error !== undefined) {
466
- return { status: null, stdout: "", stderr: result.error.message };
467
- }
468
- return {
469
- status: result.status,
470
- stdout: result.stdout ?? "",
471
- stderr: result.stderr ?? ""
472
- };
473
- };
474
- }
475
- function commitTaskWork(options) {
476
- const run = options.runGit ?? spawnGit(options.cwd ?? process.cwd());
477
- const message = buildCommitMessage(options.taskText, {
478
- scope: options.scope,
479
- maxLength: options.maxLength
480
- });
481
- const { subject } = message;
482
- const staged = run(stageAllArgs());
483
- if (staged.status !== 0)
484
- return failed("stage", subject, staged);
485
- const pending = run(stagedChangesArgs());
486
- if (pending.status === 0) {
487
- return {
488
- outcome: "nothing-to-commit",
489
- subject,
490
- sha: null,
491
- failedStep: null,
492
- exitCode: 0,
493
- message: ""
494
- };
495
- }
496
- if (pending.status !== 1)
497
- return failed("inspect", subject, pending);
498
- const committed = run(commitArgs(subject, message.body));
499
- if (committed.status !== 0)
500
- return failed("commit", subject, committed);
501
- const head = run(headShaArgs());
502
- const sha = head.status === 0 ? head.stdout.trim() : null;
503
- return {
504
- outcome: "committed",
505
- subject,
506
- sha,
507
- failedStep: null,
508
- exitCode: 0,
509
- message: ""
510
- };
511
- }
512
36
  // packages/rafa/src/effort/store/sqlite.ts
513
37
  import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
514
38
  import { dirname as dirname7, join as join5 } from "path";
@@ -532,72 +56,13 @@ import { dirname, join } from "path";
532
56
 
533
57
  // packages/rafa/src/core/loop/session-record-parse.ts
534
58
  import { basename, isAbsolute } from "path";
535
-
536
- // packages/rafa/src/core/loop/hop-record.ts
537
- var HOP_KINDS = ["blocker", "dry"];
538
- var HOP_STATES = ["away", "waiting", "merged", "halted"];
539
- function isRecord(value) {
540
- return typeof value === "object" && value !== null && !Array.isArray(value);
541
- }
542
- function isIssueNumber(value) {
543
- return typeof value === "number" && Number.isInteger(value) && value > 0;
544
- }
545
- function asPlace(value) {
546
- if (!isRecord(value) || !isIssueNumber(value.board))
547
- return null;
548
- if (value.epic !== null && !isIssueNumber(value.epic))
549
- return null;
550
- return { board: value.board, epic: value.epic };
551
- }
552
- function isIssueOrNull(value) {
553
- return value === null || isIssueNumber(value);
554
- }
555
- function isTimestamp(value) {
556
- return typeof value === "string" && !Number.isNaN(Date.parse(value));
557
- }
558
- function issuesMatchKind(kind, blocked, target) {
559
- return kind === "blocker" ? blocked !== null && target !== null : blocked === null && target === null;
560
- }
561
- function asHopRecord(value) {
562
- if (!isRecord(value))
563
- return null;
564
- const { kind, blocked, target, targetEpic, targetBoard, state, pullRequest, startedAt } = value;
565
- const home = asPlace(value.home);
566
- const from = asPlace(value.from);
567
- if (typeof kind !== "string" || !HOP_KINDS.includes(kind))
568
- return null;
569
- if (typeof state !== "string" || !HOP_STATES.includes(state))
570
- return null;
571
- if (home === null || from === null)
572
- return null;
573
- if (!isIssueOrNull(blocked) || !isIssueOrNull(target) || !isIssueOrNull(pullRequest))
574
- return null;
575
- if (!isIssueNumber(targetEpic) || !isIssueNumber(targetBoard) || !isTimestamp(startedAt))
576
- return null;
577
- const hopKind = kind;
578
- if (!issuesMatchKind(hopKind, blocked, target))
579
- return null;
580
- return {
581
- kind: hopKind,
582
- home,
583
- from,
584
- blocked,
585
- target,
586
- targetEpic,
587
- targetBoard,
588
- state,
589
- pullRequest,
590
- startedAt
591
- };
592
- }
593
-
594
- // packages/rafa/src/core/loop/session-record-parse.ts
595
59
  var SESSION_STATES = Object.freeze(["running", "paused", "stopped", "done"]);
596
60
  var SESSION_PHASES = Object.freeze(["task", "wrap-up", "pull-request", "ci", "repair"]);
597
61
  var RECORD_EXTENSION = ".json";
598
62
  var SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
599
63
  var SESSION_STEP_KINDS = Object.freeze(["baseline", "task", "stage", "pre-wrap-up"]);
600
- var SESSION_STEP_REASONS = Object.freeze(["declared", "trigger", "fallback", "no-module-tests", "stage"]);
64
+ var SESSION_STEP_REASONS = Object.freeze(["declared", "trigger", "fallback", "no-module-tests", "stage", "no-check", "unit"]);
65
+ var NONE_STEP_SCOPE = "none";
601
66
  var SESSION_DECISION_STRATEGIES = Object.freeze(["jump", "defer"]);
602
67
 
603
68
  class SessionRecordError extends Error {
@@ -611,7 +76,7 @@ class SessionRecordError extends Error {
611
76
  function isSessionId(value) {
612
77
  return SESSION_ID_PATTERN.test(value);
613
78
  }
614
- function describeValue2(value) {
79
+ function describeValue(value) {
615
80
  return value === undefined ? "missing" : JSON.stringify(value) ?? String(value);
616
81
  }
617
82
  function field(fields, key) {
@@ -630,23 +95,23 @@ function taskProblem(task) {
630
95
  if (task === null)
631
96
  return null;
632
97
  if (!isObject(task))
633
- return `task is ${describeValue2(task)}, expected null or an object`;
98
+ return `task is ${describeValue(task)}, expected null or an object`;
634
99
  if (!isPositiveWhole(field(task, "line"))) {
635
- return `task.line is ${describeValue2(field(task, "line"))}, expected a whole number from 1`;
100
+ return `task.line is ${describeValue(field(task, "line"))}, expected a whole number from 1`;
636
101
  }
637
- return isText(field(task, "text")) ? null : `task.text is ${describeValue2(field(task, "text"))}, expected a non-empty string`;
102
+ return isText(field(task, "text")) ? null : `task.text is ${describeValue(field(task, "text"))}, expected a non-empty string`;
638
103
  }
639
104
  function hopProblem(fields) {
640
105
  if (!Object.hasOwn(fields, "hop"))
641
106
  return null;
642
107
  const hop = field(fields, "hop");
643
- return asHopRecord(hop) === null ? `hop is ${describeValue2(hop)}, expected a hop record` : null;
108
+ return asHopRecord(hop) === null ? `hop is ${describeValue(hop)}, expected a hop record` : null;
644
109
  }
645
110
  function worktreeProblem(fields) {
646
111
  if (!Object.hasOwn(fields, "worktree"))
647
112
  return null;
648
113
  const worktree = field(fields, "worktree");
649
- return isText(worktree) && isAbsolute(worktree) ? null : `worktree is ${describeValue2(worktree)}, expected an absolute path`;
114
+ return isText(worktree) && isAbsolute(worktree) ? null : `worktree is ${describeValue(worktree)}, expected an absolute path`;
650
115
  }
651
116
  function isTextList(value) {
652
117
  return Array.isArray(value) && value.every(isText);
@@ -664,35 +129,52 @@ function stepFailuresProblem(step, at) {
664
129
  const failures = field(step, "failures");
665
130
  const newFailures = field(step, "newFailures");
666
131
  if (!isFailureList(failures))
667
- return `${at}.failures is ${describeValue2(failures)}, expected a list of failing tests`;
132
+ return `${at}.failures is ${describeValue(failures)}, expected a list of failing tests`;
668
133
  if (!isFailureList(newFailures)) {
669
- return `${at}.newFailures is ${describeValue2(newFailures)}, expected a list of failing tests`;
134
+ return `${at}.newFailures is ${describeValue(newFailures)}, expected a list of failing tests`;
670
135
  }
671
136
  const known = new Set(failures.map(failureKey));
672
137
  const stray = newFailures.find((failure) => !known.has(failureKey(failure)));
673
- return stray === undefined ? null : `${at}.newFailures names ${describeValue2(stray)}, which ${at}.failures does not`;
138
+ return stray === undefined ? null : `${at}.newFailures names ${describeValue(stray)}, which ${at}.failures does not`;
674
139
  }
675
140
  function stepInterruptedProblem(step, at) {
676
141
  if (!Object.hasOwn(step, "interrupted"))
677
142
  return null;
678
143
  const interrupted = field(step, "interrupted");
679
- return interrupted === true ? null : `${at}.interrupted is ${describeValue2(interrupted)}, expected true or no key`;
144
+ return interrupted === true ? null : `${at}.interrupted is ${describeValue(interrupted)}, expected true or no key`;
145
+ }
146
+ function stepScopeProblem(scope, at) {
147
+ return TEST_SCOPES.includes(scope) || scope === NONE_STEP_SCOPE || isTextList(scope) ? null : `${at}.scope is ${describeValue(scope)}, expected one of ${TEST_SCOPES.join(", ")}, ${NONE_STEP_SCOPE} or a list of paths`;
148
+ }
149
+ function stepCommandProblem(command, scope, at) {
150
+ if (scope === NONE_STEP_SCOPE) {
151
+ return Array.isArray(command) && command.length === 0 ? null : `${at}.command is ${describeValue(command)}, expected an empty list on a ${NONE_STEP_SCOPE} step`;
152
+ }
153
+ return isTextList(command) && command.length > 0 ? null : `${at}.command is ${describeValue(command)}, expected a non-empty list of arguments`;
154
+ }
155
+ function noneStepProblems(step, at) {
156
+ const exitCode = field(step, "exitCode");
157
+ const failures = field(step, "failures");
158
+ return [
159
+ Number.isSafeInteger(exitCode) && exitCode !== 0 ? `${at}.exitCode is ${describeValue(exitCode)}, expected 0 on a ${NONE_STEP_SCOPE} step` : null,
160
+ Array.isArray(failures) && failures.length > 0 ? `${at}.failures is ${describeValue(failures)}, expected none on a ${NONE_STEP_SCOPE} step` : null
161
+ ].filter((problem) => problem !== null);
680
162
  }
681
163
  function stepProblems(step, at) {
682
164
  if (!isObject(step))
683
- return [`${at} is ${describeValue2(step)}, expected a step`];
165
+ return [`${at} is ${describeValue(step)}, expected a step`];
684
166
  const kind = field(step, "kind");
685
167
  const scope = field(step, "scope");
686
- const command = field(step, "command");
687
168
  const exitCode = field(step, "exitCode");
688
169
  const summary = field(step, "summary");
689
170
  const problems = [
690
- SESSION_STEP_KINDS.includes(kind) ? null : `${at}.kind is ${describeValue2(kind)}, expected one of ${SESSION_STEP_KINDS.join(", ")}`,
691
- TEST_SCOPES.includes(scope) || isTextList(scope) ? null : `${at}.scope is ${describeValue2(scope)}, expected one of ${TEST_SCOPES.join(", ")} or a list of paths`,
692
- isTextList(command) && command.length > 0 ? null : `${at}.command is ${describeValue2(command)}, expected a non-empty list of arguments`,
693
- typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? null : `${at}.exitCode is ${describeValue2(exitCode)}, expected a whole number`,
694
- summary === null || typeof summary === "string" ? null : `${at}.summary is ${describeValue2(summary)}, expected null or a string`,
171
+ SESSION_STEP_KINDS.includes(kind) ? null : `${at}.kind is ${describeValue(kind)}, expected one of ${SESSION_STEP_KINDS.join(", ")}`,
172
+ stepScopeProblem(scope, at),
173
+ stepCommandProblem(field(step, "command"), scope, at),
174
+ typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? null : `${at}.exitCode is ${describeValue(exitCode)}, expected a whole number`,
175
+ summary === null || typeof summary === "string" ? null : `${at}.summary is ${describeValue(summary)}, expected null or a string`,
695
176
  stepFailuresProblem(step, at),
177
+ ...scope === NONE_STEP_SCOPE ? noneStepProblems(step, at) : [],
696
178
  stepInterruptedProblem(step, at)
697
179
  ];
698
180
  return problems.filter((problem) => problem !== null);
@@ -702,14 +184,14 @@ function isLineIndex(value) {
702
184
  }
703
185
  function taskRefProblems(ref, at) {
704
186
  if (!isObject(ref))
705
- return [`${at} is ${describeValue2(ref)}, expected a task`];
187
+ return [`${at} is ${describeValue(ref)}, expected a task`];
706
188
  const lineNum = field(ref, "lineNum");
707
189
  const task = field(ref, "task");
708
190
  const ordinal = field(ref, "ordinal");
709
191
  return [
710
- isLineIndex(lineNum) ? null : `${at}.lineNum is ${describeValue2(lineNum)}, expected a whole number from 0`,
711
- isText(task) ? null : `${at}.task is ${describeValue2(task)}, expected a non-empty string`,
712
- ordinal === undefined || isPositiveWhole(ordinal) ? null : `${at}.ordinal is ${describeValue2(ordinal)}, expected a whole number from 1`
192
+ isLineIndex(lineNum) ? null : `${at}.lineNum is ${describeValue(lineNum)}, expected a whole number from 0`,
193
+ isText(task) ? null : `${at}.task is ${describeValue(task)}, expected a non-empty string`,
194
+ ordinal === undefined || isPositiveWhole(ordinal) ? null : `${at}.ordinal is ${describeValue(ordinal)}, expected a whole number from 1`
713
195
  ].filter((problem) => problem !== null);
714
196
  }
715
197
  function afterProblems(decision, strategy, at) {
@@ -717,17 +199,17 @@ function afterProblems(decision, strategy, at) {
717
199
  if (strategy === "defer") {
718
200
  return after === undefined ? [`${at}.after is missing, expected the task a defer waits on`] : taskRefProblems(after, `${at}.after`);
719
201
  }
720
- return after === undefined ? [] : [`${at}.after is ${describeValue2(after)}, expected no key on a jump`];
202
+ return after === undefined ? [] : [`${at}.after is ${describeValue(after)}, expected no key on a jump`];
721
203
  }
722
204
  function decisionProblems(decision, at) {
723
205
  if (!isObject(decision))
724
- return [`${at} is ${describeValue2(decision)}, expected a decision`];
206
+ return [`${at} is ${describeValue(decision)}, expected a decision`];
725
207
  const strategy = field(decision, "strategy");
726
208
  const reason = field(decision, "reason");
727
209
  const problems = [
728
210
  ...taskRefProblems(field(decision, "task"), `${at}.task`),
729
- SESSION_DECISION_STRATEGIES.includes(strategy) ? null : `${at}.strategy is ${describeValue2(strategy)}, expected one of ${SESSION_DECISION_STRATEGIES.join(", ")}`,
730
- isText(reason) ? null : `${at}.reason is ${describeValue2(reason)}, expected a non-empty string`,
211
+ SESSION_DECISION_STRATEGIES.includes(strategy) ? null : `${at}.strategy is ${describeValue(strategy)}, expected one of ${SESSION_DECISION_STRATEGIES.join(", ")}`,
212
+ isText(reason) ? null : `${at}.reason is ${describeValue(reason)}, expected a non-empty string`,
731
213
  ...afterProblems(decision, strategy, at)
732
214
  ];
733
215
  return problems.filter((problem) => problem !== null);
@@ -737,7 +219,7 @@ function decisionsProblems(fields) {
737
219
  return [];
738
220
  const decisions = field(fields, "decisions");
739
221
  if (!Array.isArray(decisions))
740
- return [`decisions is ${describeValue2(decisions)}, expected a list of decisions`];
222
+ return [`decisions is ${describeValue(decisions)}, expected a list of decisions`];
741
223
  return decisions.flatMap((decision, index) => decisionProblems(decision, `decisions[${index}]`));
742
224
  }
743
225
  function stepsProblems(fields) {
@@ -745,20 +227,20 @@ function stepsProblems(fields) {
745
227
  return [];
746
228
  const steps = field(fields, "steps");
747
229
  if (!Array.isArray(steps))
748
- return [`steps is ${describeValue2(steps)}, expected a list of steps`];
230
+ return [`steps is ${describeValue(steps)}, expected a list of steps`];
749
231
  return steps.flatMap((step, index) => stepProblems(step, `steps[${index}]`));
750
232
  }
751
233
  function sessionIdProblem(sessionId, file) {
752
234
  if (typeof sessionId !== "string" || !isSessionId(sessionId)) {
753
- return `sessionId is ${describeValue2(sessionId)}, expected a plain file name`;
235
+ return `sessionId is ${describeValue(sessionId)}, expected a plain file name`;
754
236
  }
755
237
  return basename(file) === `${sessionId}${RECORD_EXTENSION}` ? null : `sessionId ${JSON.stringify(sessionId)} is not the file's name`;
756
238
  }
757
239
  function planStubProblem(planStub) {
758
- return planStub === null || typeof planStub === "string" && isStampableStub(planStub) ? null : `planStub is ${describeValue2(planStub)}, expected null or a plan stub`;
240
+ return planStub === null || typeof planStub === "string" && isStampableStub(planStub) ? null : `planStub is ${describeValue(planStub)}, expected null or a plan stub`;
759
241
  }
760
242
  function textProblems(fields) {
761
- return ["plan", "branch"].filter((key) => !isText(field(fields, key))).map((key) => `${key} is ${describeValue2(field(fields, key))}, expected a non-empty string`);
243
+ return ["plan", "branch"].filter((key) => !isText(field(fields, key))).map((key) => `${key} is ${describeValue(field(fields, key))}, expected a non-empty string`);
762
244
  }
763
245
  function recordProblems(fields, file) {
764
246
  const pid = field(fields, "pid");
@@ -768,9 +250,9 @@ function recordProblems(fields, file) {
768
250
  sessionIdProblem(field(fields, "sessionId"), file),
769
251
  planStubProblem(field(fields, "planStub")),
770
252
  ...textProblems(fields),
771
- isPositiveWhole(pid) ? null : `pid is ${describeValue2(pid)}, expected a whole number from 1`,
772
- typeof startedAt === "string" && !Number.isNaN(Date.parse(startedAt)) ? null : `startedAt is ${describeValue2(startedAt)}, expected a timestamp`,
773
- SESSION_STATES.includes(state) ? null : `state is ${describeValue2(state)}, expected one of ${SESSION_STATES.join(", ")}`,
253
+ isPositiveWhole(pid) ? null : `pid is ${describeValue(pid)}, expected a whole number from 1`,
254
+ typeof startedAt === "string" && !Number.isNaN(Date.parse(startedAt)) ? null : `startedAt is ${describeValue(startedAt)}, expected a timestamp`,
255
+ SESSION_STATES.includes(state) ? null : `state is ${describeValue(state)}, expected one of ${SESSION_STATES.join(", ")}`,
774
256
  taskProblem(field(fields, "task")),
775
257
  hopProblem(fields),
776
258
  worktreeProblem(fields),
@@ -833,11 +315,15 @@ function isSessionStepReason(value) {
833
315
  function reasonEntry(reason) {
834
316
  return isSessionStepReason(reason) ? { reason } : {};
835
317
  }
318
+ function declaredEntry(scope, declared) {
319
+ return scope === NONE_STEP_SCOPE && TEST_SCOPES.includes(declared) ? { declared } : {};
320
+ }
836
321
  function freezeStep(step) {
837
322
  return Object.freeze({
838
323
  kind: step.kind,
839
324
  scope: typeof step.scope === "string" ? step.scope : Object.freeze([...step.scope]),
840
325
  ...reasonEntry(field(step, "reason")),
326
+ ...declaredEntry(step.scope, field(step, "declared")),
841
327
  command: Object.freeze([...step.command]),
842
328
  exitCode: step.exitCode,
843
329
  summary: step.summary,
@@ -1077,6 +563,7 @@ var CLAUDE_BASE_ARGS = [
1077
563
  "--dangerously-skip-permissions"
1078
564
  ];
1079
565
  var SETTING_SOURCES_FLAG = "--setting-sources";
566
+ var SESSION_ID_FLAG = "--session-id";
1080
567
  function claudeArgs(settingSources, flags = [], served = []) {
1081
568
  return [...CLAUDE_BASE_ARGS, SETTING_SOURCES_FLAG, settingSources.join(","), ...served, ...flags];
1082
569
  }
@@ -1093,10 +580,10 @@ function carriesFlag(flags, flag) {
1093
580
  return true;
1094
581
  return name.startsWith("no-") && flags[name.slice(3)] === false;
1095
582
  }
1096
- function spendWarning(running2) {
1097
- if (running2 === null)
583
+ function spendWarning(running) {
584
+ if (running === null)
1098
585
  return null;
1099
- const { command, flags } = running2;
586
+ const { command, flags } = running;
1100
587
  const spend = command.spends;
1101
588
  const named = `rafa ${commandSpelling(command)}`;
1102
589
  const remedy = "declare spends on the command to cover this run";
@@ -1203,6 +690,7 @@ function runClaudeCaptured(prompt, settingSources, flags = [], spawn = spawnClau
1203
690
  import { existsSync, readFileSync as readFileSync2, realpathSync } from "fs";
1204
691
  import { dirname as dirname2, join as join2, resolve } from "path";
1205
692
  var RAFA_PACKAGE_NAME = "@open-tomato/rafa";
693
+ var RUNTIME_SUBDIR = join2(".rafa", "runtime");
1206
694
  var MANIFEST = "package.json";
1207
695
  var CHECKOUT_ENTRY = join2("src", "rafa.ts");
1208
696
  function realOrResolved(path) {
@@ -2117,25 +1605,6 @@ function stampedValues(table) {
2117
1605
  return `${nextSeq}, ${STORE_ID}, CASE WHEN ${STORE_ID} IS NULL THEN NULL ELSE ${nextSeq} END`;
2118
1606
  }
2119
1607
 
2120
- // packages/rafa/src/effort/store/settings.ts
2121
- var DEFAULT_STORE_SETTINGS = Object.freeze({
2122
- busyTimeoutMs: CORE_SECTION.defaults.effortBusyTimeoutMs
2123
- });
2124
- var active2 = DEFAULT_STORE_SETTINGS;
2125
- function setActiveStoreSettings(settings) {
2126
- if (settings === null) {
2127
- active2 = DEFAULT_STORE_SETTINGS;
2128
- return;
2129
- }
2130
- if (!isBusyTimeoutMs(settings.busyTimeoutMs)) {
2131
- throw new RangeError(`effort store: busy timeout ${String(settings.busyTimeoutMs)} is not a whole number ` + `of milliseconds from ${String(BUSY_TIMEOUT_MIN_MS)} to ${String(BUSY_TIMEOUT_MAX_MS)}`);
2132
- }
2133
- active2 = Object.freeze({ busyTimeoutMs: settings.busyTimeoutMs });
2134
- }
2135
- function activeStoreSettings() {
2136
- return active2;
2137
- }
2138
-
2139
1608
  // packages/rafa/src/effort/store/store-meta.ts
2140
1609
  import { randomUUID as randomUUID2 } from "crypto";
2141
1610
  import { dirname as dirname6 } from "path";
@@ -2183,38 +1652,10 @@ function writeStoreGeneration(storePath, generation) {
2183
1652
  }
2184
1653
 
2185
1654
  // packages/rafa/src/effort/store/store-identity.ts
2186
- import { spawnSync as spawnSync4 } from "child_process";
1655
+ import { spawnSync } from "child_process";
2187
1656
  import { createHmac } from "crypto";
2188
1657
  import { readFileSync as readFileSync5, realpathSync as realpathSync3, statSync } from "fs";
2189
1658
  import { hostname, platform as currentPlatform } from "os";
2190
-
2191
- // packages/rafa/src/schema/project-id.ts
2192
- import { spawnSync as spawnSync3 } from "child_process";
2193
- var PROJECT_ID_LENGTH = 12;
2194
- var PROJECT_ID_PATTERN = new RegExp(`^[0-9a-f]{${PROJECT_ID_LENGTH}}$`);
2195
- function hasColonAfterAt(url) {
2196
- const at = url.indexOf("@");
2197
- return at !== -1 && url.lastIndexOf(":") > at;
2198
- }
2199
- function normalizeRemote(url) {
2200
- const stripped = url.replace(/:\/\/[^@]+@/, "://");
2201
- const network = !stripped.startsWith("file://") && (stripped.includes("://") || hasColonAfterAt(stripped));
2202
- const trimmed = stripped.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//, "").replace(/^[^@/:]+@([^:/]+):/, "$1/").replace(/\.git\/?$/, "").replace(/\/+$/, "");
2203
- return network ? trimmed.toLowerCase() : trimmed;
2204
- }
2205
- function gitRemoteUrl(dir) {
2206
- const result = spawnSync3("git", ["remote", "get-url", "origin"], {
2207
- cwd: dir,
2208
- encoding: "utf8",
2209
- env: { ...process.env, LC_ALL: "C" }
2210
- });
2211
- if (result.error !== undefined || result.status !== 0)
2212
- return null;
2213
- const url = result.stdout.trim();
2214
- return url === "" ? null : url;
2215
- }
2216
-
2217
- // packages/rafa/src/effort/store/store-identity.ts
2218
1659
  var HOST_ID_KEY = "rafa effort store host id";
2219
1660
  var MACHINE_ID_PATH = "/etc/machine-id";
2220
1661
  var IOREG_PATH = "/usr/sbin/ioreg";
@@ -2235,7 +1676,7 @@ function parseIoregPlatformUuid(output) {
2235
1676
  return match?.[1] ?? null;
2236
1677
  }
2237
1678
  function readIoregPlatformUuid() {
2238
- const result = spawnSync4(IOREG_PATH, [...IOREG_ARGS], { encoding: "utf8" });
1679
+ const result = spawnSync(IOREG_PATH, [...IOREG_ARGS], { encoding: "utf8" });
2239
1680
  if (result.error !== undefined || result.status !== 0)
2240
1681
  return null;
2241
1682
  return parseIoregPlatformUuid(result.stdout);
@@ -2591,7 +2032,1039 @@ function openSqliteStore(repoRoot) {
2591
2032
  };
2592
2033
  }
2593
2034
 
2594
- // packages/rafa/src/effort/store/trusted-permissions.ts
2595
- var TRUSTED_PERMISSIONS = ["admin", "maintain", "write"];
2035
+ // packages/rafa/src/effort/store/wire.ts
2036
+ import { existsSync as existsSync7, mkdtempSync, rmSync as rmSync5 } from "fs";
2037
+ import { tmpdir as tmpdir3 } from "os";
2038
+ import { join as join7 } from "path";
2039
+ import { Database as Database4, SQLiteError } from "bun:sqlite";
2040
+
2041
+ // packages/rafa/src/effort/store/merge-rules.ts
2042
+ var SET_ONCE = "set-once";
2043
+ var RECOMPUTED = "recomputed";
2044
+ var APPEND_ONLY = {};
2045
+ function appendOnly(...identity) {
2046
+ return { scope: "merged", identity, edited: APPEND_ONLY };
2047
+ }
2048
+ var MERGE_RULES = {
2049
+ sessions: appendOnly("session_id"),
2050
+ commits: { scope: "merged", identity: ["sha"], edited: { row_json: RECOMPUTED } },
2051
+ findings: { scope: "merged", identity: ["id"], edited: { tracker_ref: SET_ONCE } },
2052
+ blockers: appendOnly("id"),
2053
+ out_of_scope_bugs: appendOnly("id"),
2054
+ report_absences: appendOnly("id"),
2055
+ task_reports: appendOnly("id"),
2056
+ preflight: appendOnly("run_id", "position"),
2057
+ dispatches: appendOnly("session_id"),
2058
+ changes: appendOnly("id"),
2059
+ skill_invocations: appendOnly("session_id", "name", "sidechain"),
2060
+ plan_ci: appendOnly("pr", "head_sha", "read_at"),
2061
+ stale_docs: appendOnly("id"),
2062
+ bug_routes: appendOnly("id"),
2063
+ schema_migrations: { scope: "local" },
2064
+ store_meta: { scope: "local" },
2065
+ store_replaced: { scope: "local" },
2066
+ merges: { scope: "local" },
2067
+ merge_conflicts: { scope: "local" }
2068
+ };
2069
+
2070
+ // packages/rafa/src/effort/store/rebuild-aside.ts
2071
+ import { closeSync, existsSync as existsSync6, fsyncSync, openSync, renameSync as renameSync3, rmSync as rmSync4 } from "fs";
2072
+
2073
+ // packages/rafa/src/effort/store/copy.ts
2074
+ import { copyFileSync, constants, existsSync as existsSync5, mkdirSync as mkdirSync4, readdirSync as readdirSync2, rmSync as rmSync3, statSync as statSync2 } from "fs";
2075
+ import { join as join6, resolve as resolve3 } from "path";
2076
+ import { Database as Database3 } from "bun:sqlite";
2077
+ var NDJSON_KINDS = { sessions: true, commits: true };
2078
+ var EFFORT_COPY_FILE_NAMES = [
2079
+ SQLITE_STORE_FILE_NAME,
2080
+ ...Object.keys(NDJSON_KINDS).map((kind) => effortStoreFileName(kind))
2081
+ ];
2082
+
2083
+ class EffortCopyRefusal extends Error {
2084
+ name = "EffortCopyRefusal";
2085
+ }
2086
+
2087
+ class EffortCopyFailure extends Error {
2088
+ name = "EffortCopyFailure";
2089
+ }
2090
+ function refuseUsedTarget(target) {
2091
+ if (!existsSync5(target))
2092
+ return;
2093
+ let entries;
2094
+ try {
2095
+ if (!statSync2(target).isDirectory()) {
2096
+ throw new EffortCopyRefusal(`${target} is a file, not a directory; name an empty or absent directory with --to=<dir>.`);
2097
+ }
2098
+ entries = readdirSync2(target);
2099
+ } catch (error) {
2100
+ if (error instanceof EffortCopyRefusal)
2101
+ throw error;
2102
+ throw new EffortCopyFailure(`${target} cannot be read: ${String(error)}`);
2103
+ }
2104
+ if (entries.length === 0)
2105
+ return;
2106
+ throw new EffortCopyRefusal(`${target} is not empty (${String(entries.length)} entries); nothing was copied.` + " Name an empty or absent directory with --to=<dir>.");
2107
+ }
2108
+ function vacuumInto(source, target) {
2109
+ const db = new Database3(source, { readonly: true });
2110
+ try {
2111
+ db.run(`PRAGMA busy_timeout = ${String(activeStoreSettings().busyTimeoutMs)}`);
2112
+ db.run("VACUUM INTO ?", [target]);
2113
+ } finally {
2114
+ db.close();
2115
+ }
2116
+ }
2117
+ function copyOne(name, source, target) {
2118
+ if (name === SQLITE_STORE_FILE_NAME) {
2119
+ vacuumInto(join6(source, name), join6(target, name));
2120
+ return;
2121
+ }
2122
+ copyFileSync(join6(source, name), join6(target, name), constants.COPYFILE_EXCL);
2123
+ }
2124
+ function undo(target, written, madeDir) {
2125
+ try {
2126
+ if (madeDir === undefined) {
2127
+ for (const name of written)
2128
+ rmSync3(join6(target, name), { force: true });
2129
+ } else {
2130
+ rmSync3(madeDir, { recursive: true, force: true });
2131
+ }
2132
+ return "";
2133
+ } catch (error) {
2134
+ return ` Removing what it made failed too: ${String(error)}`;
2135
+ }
2136
+ }
2137
+ function copyEffortStore(request) {
2138
+ const source = resolve3(request.source);
2139
+ const target = resolve3(request.target);
2140
+ guardTestProcess(source);
2141
+ guardTestProcess(target);
2142
+ const files = EFFORT_COPY_FILE_NAMES.filter((name) => existsSync5(join6(source, name)));
2143
+ if (files.length === 0) {
2144
+ throw new EffortCopyRefusal(`no effort store at ${source}: it holds none of ${EFFORT_COPY_FILE_NAMES.join(", ")}. Nothing to copy.`);
2145
+ }
2146
+ refuseUsedTarget(target);
2147
+ const written = [];
2148
+ let madeDir;
2149
+ try {
2150
+ madeDir = mkdirSync4(target, { recursive: true });
2151
+ for (const name of files) {
2152
+ written.push(name);
2153
+ copyOne(name, source, target);
2154
+ }
2155
+ } catch (error) {
2156
+ const left = undo(target, written, madeDir);
2157
+ throw new EffortCopyFailure(`copying ${source} to ${target} failed: ${String(error)}.${left}`);
2158
+ }
2159
+ return Object.freeze({ source, directory: target, files: Object.freeze(files) });
2160
+ }
2161
+
2162
+ // packages/rafa/src/effort/store/rebuild-aside.ts
2163
+ class RebuildRefusal extends Error {
2164
+ constructor(message, options) {
2165
+ super(message, options);
2166
+ this.name = "RebuildRefusal";
2167
+ }
2168
+ }
2169
+ function quoted(name) {
2170
+ return `"${name.replaceAll('"', '""')}"`;
2171
+ }
2172
+ function count(db, sql) {
2173
+ return db.query(sql).get()?.n ?? 0;
2174
+ }
2175
+ function refuseInFlight(path) {
2176
+ for (const suffix of ["-journal", "-wal"]) {
2177
+ if (existsSync6(`${path}${suffix}`)) {
2178
+ throw new RebuildRefusal(`${path}${suffix} is there, so a write is in flight or was interrupted; stop whatever uses the store` + " and open it once with rafa before repairing it");
2179
+ }
2180
+ }
2181
+ }
2182
+ function checkedCounts(db, tables, original, added = {}) {
2183
+ return tables.map((table) => {
2184
+ const rows = count(db, `SELECT count(*) AS n FROM main.${quoted(table)}`);
2185
+ const originalRows = count(db, `SELECT count(*) AS n FROM ${original}.${quoted(table)}`);
2186
+ const addedRows = added[table] ?? 0;
2187
+ if (rows !== originalRows + addedRows) {
2188
+ const plus = addedRows === 0 ? "" : ` plus ${String(addedRows)} added`;
2189
+ throw new RebuildRefusal(`the rebuilt ${table} holds ${String(rows)} rows, the store ${String(originalRows)}${plus}`);
2190
+ }
2191
+ return { table, rows };
2192
+ });
2193
+ }
2194
+ function refuseCorrupt(db) {
2195
+ const answer = db.query("PRAGMA main.integrity_check").get()?.integrity_check;
2196
+ if (answer !== "ok")
2197
+ throw new RebuildRefusal(`the rebuilt store failed integrity_check: ${answer ?? "no answer"}`);
2198
+ }
2199
+ function removeParallel(parallelPath) {
2200
+ rmSync4(parallelPath, { force: true });
2201
+ rmSync4(`${parallelPath}-journal`, { force: true });
2202
+ }
2203
+ var STEP_TEXT = {
2204
+ backup: ({ path, backupPath }) => ({
2205
+ doing: `writing ${path} out to the backup ${backupPath}`,
2206
+ backup: `any part of the backup written at ${backupPath}`
2207
+ }),
2208
+ carry: ({ path, parallelPath, backupPath }) => ({
2209
+ doing: `carrying the store id of ${path} onto ${parallelPath}`,
2210
+ backup: `the whole backup at ${backupPath}`
2211
+ }),
2212
+ record: ({ path, parallelPath, backupPath }) => ({
2213
+ doing: `writing the generation carried onto ${parallelPath} to the side record of ${path}`,
2214
+ backup: `the whole backup at ${backupPath}`
2215
+ }),
2216
+ rename: ({ path, parallelPath, backupPath }) => ({
2217
+ doing: `renaming ${parallelPath} over ${path}`,
2218
+ backup: `the whole backup at ${backupPath}`
2219
+ })
2220
+ };
2221
+
2222
+ class SwapFailure extends RebuildRefusal {
2223
+ step;
2224
+ parallelPath;
2225
+ backupPath;
2226
+ constructor(step, files, cause) {
2227
+ const { doing, backup } = STEP_TEXT[step](files);
2228
+ const reason = cause instanceof Error ? cause.message : String(cause);
2229
+ super(`${doing} failed (${reason}), so ${files.path} was not replaced and is unchanged.` + ` The rebuilt store is left at ${files.parallelPath}, and ${backup}.`, { cause });
2230
+ this.name = "SwapFailure";
2231
+ this.step = step;
2232
+ this.parallelPath = files.parallelPath;
2233
+ this.backupPath = files.backupPath;
2234
+ }
2235
+ }
2236
+ function writeBackup(path, backupPath) {
2237
+ vacuumInto(path, backupPath);
2238
+ const backup = openSync(backupPath, "r");
2239
+ try {
2240
+ fsyncSync(backup);
2241
+ } finally {
2242
+ closeSync(backup);
2243
+ }
2244
+ }
2245
+ var SWAP_STEPS = {
2246
+ backup: writeBackup,
2247
+ carry: (path, parallelPath) => carryStoreIdentity(path, parallelPath),
2248
+ record: writeStoreGeneration,
2249
+ rename: renameSync3
2250
+ };
2251
+ function runStep(step, files, act) {
2252
+ try {
2253
+ return act();
2254
+ } catch (error) {
2255
+ throw new SwapFailure(step, files, error);
2256
+ }
2257
+ }
2258
+ function swapIn(path, parallelPath, backupPath, steps = {}) {
2259
+ const { backup, carry, record, rename } = { ...SWAP_STEPS, ...steps };
2260
+ const files = { path, parallelPath, backupPath };
2261
+ runStep("backup", files, () => backup(path, backupPath));
2262
+ const carried = runStep("carry", files, () => carry(path, parallelPath));
2263
+ if (carried.action === "carried" && carried.generation !== null) {
2264
+ const { generation } = carried;
2265
+ runStep("record", files, () => record(path, generation));
2266
+ }
2267
+ runStep("rename", files, () => rename(parallelPath, path));
2268
+ }
2269
+ function refuseTaken(paths) {
2270
+ for (const taken of paths) {
2271
+ if (existsSync6(taken))
2272
+ throw new RebuildRefusal(`${taken} is already there; move it aside or pass another stamp`);
2273
+ }
2274
+ }
2275
+ function rebuildAside(options) {
2276
+ const { path, parallelPath, backupPath, dryRun, build } = options;
2277
+ refuseInFlight(path);
2278
+ refuseTaken([parallelPath, backupPath]);
2279
+ let built;
2280
+ try {
2281
+ built = build(parallelPath);
2282
+ } catch (error) {
2283
+ removeParallel(parallelPath);
2284
+ throw error;
2285
+ }
2286
+ if (dryRun) {
2287
+ removeParallel(parallelPath);
2288
+ return { built, backupPath: null };
2289
+ }
2290
+ swapIn(path, parallelPath, backupPath);
2291
+ return { built, backupPath };
2292
+ }
2293
+
2294
+ // packages/rafa/src/effort/store/wire.ts
2295
+ var WIRE_FORMAT = "rafa-effort-wire";
2296
+ var WIRE_VERSION = 1;
2297
+
2298
+ class WireFormatError extends Error {
2299
+ name = "WireFormatError";
2300
+ }
2301
+
2302
+ class WireExportRefusal extends Error {
2303
+ name = "WireExportRefusal";
2304
+ }
2305
+ var MERGED_TABLES = Object.entries(MERGE_RULES).filter(([, rule]) => rule.scope === "merged").map(([table]) => table);
2306
+ var ORIGIN_COLUMNS = ["origin_store", "origin_seq"];
2307
+ function isRecord(value) {
2308
+ return typeof value === "object" && value !== null && !Array.isArray(value);
2309
+ }
2310
+ function isCount(value) {
2311
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
2312
+ }
2313
+ function isMergedTable(name) {
2314
+ return MERGED_TABLES.includes(name);
2315
+ }
2316
+ function checkCursor(value) {
2317
+ if (!isRecord(value))
2318
+ throw new WireFormatError("wire: cursor is not an object");
2319
+ const entries = Object.entries(value).map(([table, seq]) => {
2320
+ if (!isMergedTable(table))
2321
+ throw new WireFormatError(`wire: cursor names ${JSON.stringify(table)}, which is no merged table`);
2322
+ if (!isCount(seq))
2323
+ throw new WireFormatError(`wire: cursor for ${table} is ${JSON.stringify(seq)}, expected a whole number of 0 or more`);
2324
+ return [table, seq];
2325
+ });
2326
+ return Object.freeze(Object.fromEntries(entries));
2327
+ }
2328
+ function checkRow(table, value, index) {
2329
+ const where = `wire: ${table} row ${String(index)}`;
2330
+ if (!isRecord(value))
2331
+ throw new WireFormatError(`${where} is not an object`);
2332
+ for (const [column, cell] of Object.entries(value)) {
2333
+ const carried = cell === null || typeof cell === "string" || typeof cell === "number" && Number.isFinite(cell);
2334
+ if (!carried)
2335
+ throw new WireFormatError(`${where} holds ${JSON.stringify(cell) ?? typeof cell} in ${column}, expected a string, a number or null`);
2336
+ }
2337
+ const seq = value.seq;
2338
+ if (!isCount(seq) || seq === 0)
2339
+ throw new WireFormatError(`${where} has seq ${JSON.stringify(seq) ?? "undefined"}, expected a whole number above 0`);
2340
+ return Object.freeze({ ...value });
2341
+ }
2342
+ function checkMigrations(value) {
2343
+ if (!Array.isArray(value))
2344
+ throw new WireFormatError("wire: migrations is not a list");
2345
+ const ids = value.map((id) => {
2346
+ if (typeof id !== "string" || id === "")
2347
+ throw new WireFormatError(`wire: migration id ${JSON.stringify(id)} is not a name`);
2348
+ return id;
2349
+ });
2350
+ const twice = ids.filter((id, index) => ids.indexOf(id) !== index);
2351
+ if (twice.length > 0)
2352
+ throw new WireFormatError(`wire: migrations name ${twice.join(", ")} more than once`);
2353
+ return Object.freeze(ids);
2354
+ }
2355
+ function checkTables(value) {
2356
+ if (!isRecord(value))
2357
+ throw new WireFormatError("wire: tables is not an object");
2358
+ const entries = Object.entries(value).map(([table, rows]) => {
2359
+ if (!isMergedTable(table))
2360
+ throw new WireFormatError(`wire: tables names ${JSON.stringify(table)}, which is no merged table`);
2361
+ if (!Array.isArray(rows))
2362
+ throw new WireFormatError(`wire: tables.${table} is not a list`);
2363
+ return [table, Object.freeze(rows.map((row, index) => checkRow(table, row, index)))];
2364
+ });
2365
+ return Object.freeze(Object.fromEntries(entries));
2366
+ }
2367
+ function checkPayload(value) {
2368
+ if (!isRecord(value))
2369
+ throw new WireFormatError("wire: the payload is not an object");
2370
+ if (value.format !== WIRE_FORMAT)
2371
+ throw new WireFormatError(`wire: format is ${JSON.stringify(value.format) ?? "undefined"}, expected ${JSON.stringify(WIRE_FORMAT)}`);
2372
+ if (value.version !== WIRE_VERSION)
2373
+ throw new WireFormatError(`wire: version is ${JSON.stringify(value.version) ?? "undefined"}; this rafa reads version ${String(WIRE_VERSION)}`);
2374
+ return Object.freeze({
2375
+ format: WIRE_FORMAT,
2376
+ version: WIRE_VERSION,
2377
+ migrations: checkMigrations(value.migrations),
2378
+ tables: checkTables(value.tables),
2379
+ cursor: checkCursor(value.cursor)
2380
+ });
2381
+ }
2382
+ function encodeWirePayload(payload) {
2383
+ return JSON.stringify(payload);
2384
+ }
2385
+ function decodeWirePayload(text) {
2386
+ let parsed;
2387
+ try {
2388
+ parsed = JSON.parse(text);
2389
+ } catch (error) {
2390
+ const reason = error instanceof Error ? error.message : String(error);
2391
+ throw new WireFormatError(`wire: the payload is not JSON (${reason})`);
2392
+ }
2393
+ return checkPayload(parsed);
2394
+ }
2395
+ function readLoggedIds(db) {
2396
+ const hasLog = db.query("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(MIGRATION_LOG_TABLE) !== null;
2397
+ if (!hasLog)
2398
+ return null;
2399
+ return db.query(`SELECT id FROM ${MIGRATION_LOG_TABLE} ORDER BY seq`).all().map(({ id }) => id);
2400
+ }
2401
+ function columnsOf(db, table) {
2402
+ return db.query(`PRAGMA table_info(${quoted(table)})`).all().map(({ name }) => name);
2403
+ }
2404
+ function wireValue(value, where) {
2405
+ if (typeof value === "bigint") {
2406
+ const number = Number(value);
2407
+ if (Number.isSafeInteger(number))
2408
+ return number;
2409
+ throw new WireExportRefusal(`wire: ${where} holds ${String(value)}, past the whole numbers JSON carries exactly`);
2410
+ }
2411
+ if (value instanceof Uint8Array)
2412
+ throw new WireExportRefusal(`wire: ${where} holds a BLOB, which the wire does not carry`);
2413
+ return value;
2414
+ }
2415
+ function readRows(db, table, columns, after, path) {
2416
+ const named = columns.map(quoted).join(", ");
2417
+ return db.query(`SELECT ${named} FROM ${quoted(table)} WHERE seq > ? ORDER BY seq`).all(after).map((row) => Object.freeze(Object.fromEntries(Object.entries(row).map(([column, value]) => [
2418
+ column,
2419
+ wireValue(value, `${path} ${table}.${column} at seq ${String(row.seq)}`)
2420
+ ]))));
2421
+ }
2422
+ function readPayload(db, path, cursor) {
2423
+ const migrations = readLoggedIds(db);
2424
+ if (migrations === null) {
2425
+ throw new WireExportRefusal(`wire: ${path} has no migration log; any rafa command that writes the store brings it forward`);
2426
+ }
2427
+ const tables = {};
2428
+ const next = { ...cursor };
2429
+ for (const table of MERGED_TABLES) {
2430
+ const columns = columnsOf(db, table);
2431
+ if (columns.length === 0)
2432
+ continue;
2433
+ const missing = ORIGIN_COLUMNS.filter((column) => !columns.includes(column));
2434
+ if (missing.length > 0) {
2435
+ throw new WireExportRefusal(`wire: ${path} holds no ${missing.map((column) => `${table}.${column}`).join(", ")}, so its rows carry no origin pair`);
2436
+ }
2437
+ const rows = readRows(db, table, columns, cursor[table] ?? 0, path);
2438
+ tables[table] = Object.freeze(rows);
2439
+ const last = rows[rows.length - 1];
2440
+ next[table] = last === undefined ? cursor[table] ?? 0 : Number(last.seq);
2441
+ }
2442
+ return Object.freeze({
2443
+ format: WIRE_FORMAT,
2444
+ version: WIRE_VERSION,
2445
+ migrations: Object.freeze([...migrations]),
2446
+ tables: Object.freeze(tables),
2447
+ cursor: Object.freeze(next)
2448
+ });
2449
+ }
2450
+ function exportWirePayload(options) {
2451
+ const { path } = options;
2452
+ const cursor = checkCursor(options.cursor ?? {});
2453
+ guardTestProcess(path);
2454
+ if (!existsSync7(path))
2455
+ throw new WireExportRefusal(`wire: ${path} is not there`);
2456
+ const db = new Database4(path, { readonly: true, safeIntegers: true });
2457
+ try {
2458
+ db.run(`PRAGMA busy_timeout = ${String(activeStoreSettings().busyTimeoutMs)}`);
2459
+ return db.transaction(() => readPayload(db, path, cursor))();
2460
+ } finally {
2461
+ db.close();
2462
+ }
2463
+ }
2464
+ function namedMigrations(ids, catalogue) {
2465
+ const known = new Set(catalogue.map(({ id }) => id));
2466
+ const unknown = ids.filter((id) => !known.has(id));
2467
+ if (unknown.length > 0) {
2468
+ throw new WireFormatError(`wire: the payload's store holds migration ${unknown.join(", ")}, which this rafa does not know; update rafa to take its rows`);
2469
+ }
2470
+ return catalogue.filter(({ id }) => ids.includes(id));
2471
+ }
2472
+ function insertRows(db, table, rows) {
2473
+ const columns = columnsOf(db, table);
2474
+ if (columns.length === 0)
2475
+ throw new WireFormatError(`wire: the payload carries ${table}, which its migrations do not make`);
2476
+ const statement = db.query(`INSERT INTO ${quoted(table)} (${columns.map(quoted).join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`);
2477
+ const expected = [...columns].sort().join(",");
2478
+ rows.forEach((row, index) => {
2479
+ const where = `wire: ${table} row ${String(index)}`;
2480
+ const held = Object.keys(row);
2481
+ if ([...held].sort().join(",") !== expected) {
2482
+ throw new WireFormatError(`${where} holds columns ${held.join(", ")}; its migrations make ${columns.join(", ")}`);
2483
+ }
2484
+ try {
2485
+ statement.run(...columns.map((column) => row[column] ?? null));
2486
+ } catch (error) {
2487
+ if (!(error instanceof SQLiteError))
2488
+ throw error;
2489
+ throw new WireFormatError(`${where} (seq ${String(row.seq)}) is refused by the table: ${error.message}`);
2490
+ }
2491
+ });
2492
+ }
2493
+ function buildStore(path, payload, options) {
2494
+ const migrations = namedMigrations(payload.migrations, options.migrations ?? SQLITE_MIGRATIONS);
2495
+ const db = new Database4(path, { create: true, readwrite: true });
2496
+ try {
2497
+ bringForward(db, path, "write", "open", {
2498
+ migrations,
2499
+ appliedBy: appliedByName(options.identity ?? readRuntimeIdentity()),
2500
+ now: options.now,
2501
+ builtAside: true
2502
+ });
2503
+ db.transaction(() => {
2504
+ for (const [table, rows] of Object.entries(payload.tables))
2505
+ insertRows(db, table, rows);
2506
+ })();
2507
+ } finally {
2508
+ db.close();
2509
+ }
2510
+ }
2511
+ function materialiseWirePayload(payload, options = {}) {
2512
+ const checked = checkPayload(payload);
2513
+ const directory = mkdtempSync(join7(options.tempDir ?? tmpdir3(), "rafa-wire-"));
2514
+ const release = () => rmSync5(directory, { recursive: true, force: true });
2515
+ const path = join7(directory, SQLITE_STORE_FILE_NAME);
2516
+ try {
2517
+ guardTestProcess(path);
2518
+ buildStore(path, checked, options);
2519
+ } catch (error) {
2520
+ release();
2521
+ throw error;
2522
+ }
2523
+ return Object.freeze({ directory, path, release });
2524
+ }
2525
+
2526
+ // packages/rafa/src/effort/store/merge-store.ts
2527
+ import { randomUUID as randomUUID3 } from "crypto";
2528
+ import { existsSync as existsSync8, mkdtempSync as mkdtempSync2, rmSync as rmSync6 } from "fs";
2529
+ import { tmpdir as tmpdir4 } from "os";
2530
+ import { dirname as dirname8, join as join8 } from "path";
2531
+ import { Database as Database6, SQLiteError as SQLiteError3 } from "bun:sqlite";
2532
+
2533
+ // packages/rafa/src/effort/store/fix-schema.ts
2534
+ import { Database as Database5 } from "bun:sqlite";
2535
+ function tableNames(db, schema) {
2536
+ return db.query(`SELECT name FROM ${schema}.sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' AND name <> ? ORDER BY name`).all(MIGRATION_LOG_TABLE).map((row) => row.name);
2537
+ }
2538
+ function readOnlySchema(path) {
2539
+ const db = new Database5(path, { readonly: true });
2540
+ try {
2541
+ return readStoreSchema(db, path);
2542
+ } finally {
2543
+ db.close();
2544
+ }
2545
+ }
2546
+ function refuseUnusable(db, parallelPath, migrations) {
2547
+ const plan = planSchema(readStoreSchema(db, parallelPath), sqliteCatalogue(migrations), "write", "open");
2548
+ if (plan.verdict === "refuse")
2549
+ throw new RebuildRefusal(`the rebuilt store is refused as ${plan.reason}: ${plan.message}`);
2550
+ const needs = writeNames(plan);
2551
+ if (needs.length > 0)
2552
+ throw new RebuildRefusal(`the rebuilt store still needs ${needs.join(", ")}`);
2553
+ }
2554
+
2555
+ // packages/rafa/src/effort/store/commit-stats.ts
2556
+ var MS_PER_MINUTE = 60000;
2557
+ var ELAPSED_DECIMALS = 3;
2558
+ function minutesBetween(earlier, later) {
2559
+ const from = Date.parse(earlier);
2560
+ const to = Date.parse(later);
2561
+ if (Number.isNaN(from) || Number.isNaN(to))
2562
+ return null;
2563
+ const minutes = (to - from) / MS_PER_MINUTE;
2564
+ return Number(minutes.toFixed(ELAPSED_DECIMALS));
2565
+ }
2566
+
2567
+ // packages/rafa/src/effort/store/merge-commit-gaps.ts
2568
+ var GAP_FIELD = "minutesSincePrevious";
2569
+ var UPDATE_GAP = "UPDATE commits SET row_json = ? WHERE seq = ?";
2570
+ function parsedObject2(text) {
2571
+ try {
2572
+ const value = JSON.parse(text);
2573
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
2574
+ } catch {
2575
+ return null;
2576
+ }
2577
+ }
2578
+ function withoutGap(rowJson) {
2579
+ const row = parsedObject2(rowJson);
2580
+ if (row === null)
2581
+ return rowJson;
2582
+ const rest = Object.fromEntries(Object.entries(row).filter(([key]) => key !== GAP_FIELD));
2583
+ return JSON.stringify(rest);
2584
+ }
2585
+ function readCommits(db) {
2586
+ return db.query("SELECT seq, sha, row_json FROM commits").all().map(({ seq, sha, row_json: rowJson }) => {
2587
+ const row = parsedObject2(rowJson);
2588
+ const timestamp = typeof row?.timestamp === "string" ? row.timestamp : null;
2589
+ return { seq, sha, row, timestamp, epoch: timestamp === null ? Number.NaN : Date.parse(timestamp) };
2590
+ });
2591
+ }
2592
+ function timeOrder(entries) {
2593
+ return entries.filter((entry) => !Number.isNaN(entry.epoch)).sort((left, right) => left.epoch - right.epoch || compareText(left.sha, right.sha));
2594
+ }
2595
+ function compareText(left, right) {
2596
+ if (left === right)
2597
+ return 0;
2598
+ return left < right ? -1 : 1;
2599
+ }
2600
+ function storedGap(entry) {
2601
+ const value = entry.row?.[GAP_FIELD];
2602
+ return typeof value === "number" ? value : null;
2603
+ }
2604
+ function namedRows(inserted, positions, order) {
2605
+ const position = positions.get(inserted.seq);
2606
+ if (position === undefined)
2607
+ return [inserted.seq];
2608
+ const next = order[position + 1];
2609
+ return next === undefined ? [inserted.seq] : [inserted.seq, next.seq];
2610
+ }
2611
+ function recomputedGap(entry, positions, order) {
2612
+ const position = positions.get(entry.seq);
2613
+ if (position === undefined || position === 0)
2614
+ return null;
2615
+ const previous = order[position - 1];
2616
+ if (previous?.timestamp == null || entry.timestamp === null)
2617
+ return null;
2618
+ return minutesBetween(previous.timestamp, entry.timestamp);
2619
+ }
2620
+ function recomputeCommitGaps(db, inserted) {
2621
+ return db.transaction(() => {
2622
+ const entries = readCommits(db);
2623
+ const bySeq = new Map(entries.map((entry) => [entry.seq, entry]));
2624
+ const order = timeOrder(entries);
2625
+ const positions = new Map(order.map((entry, position) => [entry.seq, position]));
2626
+ const named = new Set(inserted.flatMap((seq) => {
2627
+ const entry = bySeq.get(seq);
2628
+ return entry === undefined ? [] : namedRows(entry, positions, order);
2629
+ }));
2630
+ const targets = [...named].map((seq) => bySeq.get(seq)).filter((entry) => entry?.row != null).sort((left, right) => (positions.get(left.seq) ?? -1) - (positions.get(right.seq) ?? -1));
2631
+ return targets.flatMap((entry) => {
2632
+ const before = storedGap(entry);
2633
+ const after = recomputedGap(entry, positions, order);
2634
+ if (before === after && entry.row !== null && Object.hasOwn(entry.row, GAP_FIELD))
2635
+ return [];
2636
+ db.query(UPDATE_GAP).run(JSON.stringify({ ...entry.row, [GAP_FIELD]: after }), entry.seq);
2637
+ return [{ seq: entry.seq, sha: entry.sha, before, after }];
2638
+ });
2639
+ })();
2640
+ }
2641
+
2642
+ // packages/rafa/src/effort/store/merge-union.ts
2643
+ import { SQLiteError as SQLiteError2 } from "bun:sqlite";
2644
+ class UnionSchemaMismatch extends Error {
2645
+ constructor(message) {
2646
+ super(message);
2647
+ this.name = "UnionSchemaMismatch";
2648
+ }
2649
+ }
2650
+ var UNIQUE_REFUSAL = "SQLITE_CONSTRAINT_UNIQUE";
2651
+ function mergedTables() {
2652
+ return Object.entries(MERGE_RULES).flatMap(([table, rule]) => rule.scope === "merged" ? [{ table, identity: rule.identity }] : []);
2653
+ }
2654
+ function carriedColumns(db, table) {
2655
+ return db.query(`PRAGMA table_info(${quoted(table)})`).all().map(({ name }) => name).filter((name) => name !== "seq");
2656
+ }
2657
+ function refuseColumnMismatch(local, other, tables) {
2658
+ const faults = tables.flatMap(({ table }) => {
2659
+ const here = new Set(carriedColumns(local, table));
2660
+ const there = new Set(carriedColumns(other, table));
2661
+ const onlyHere = [...here].filter((column) => !there.has(column)).map((column) => `${table}.${column} only here`);
2662
+ const onlyThere = [...there].filter((column) => !here.has(column)).map((column) => `${table}.${column} only there`);
2663
+ return [...onlyHere, ...onlyThere];
2664
+ });
2665
+ if (faults.length > 0) {
2666
+ throw new UnionSchemaMismatch(`the two stores hold different columns (${faults.join(", ")}); bring both to the same migrations first`);
2667
+ }
2668
+ }
2669
+ function valueOf(row, column) {
2670
+ return row[column] ?? null;
2671
+ }
2672
+ function byOrigin(local, table, row) {
2673
+ const store = valueOf(row, "origin_store");
2674
+ const seq = valueOf(row, "origin_seq");
2675
+ if (store === null || seq === null)
2676
+ return null;
2677
+ return local.query(`SELECT seq FROM ${quoted(table)} WHERE origin_store = ? AND origin_seq = ?`).get(store, seq)?.seq ?? null;
2678
+ }
2679
+ function byIdentity(local, { table, identity }, row) {
2680
+ const where = identity.map((column) => `${quoted(column)} IS ?`).join(" AND ");
2681
+ return local.query(`SELECT seq FROM ${quoted(table)} WHERE ${where} ORDER BY seq LIMIT 1`).get(...identity.map((column) => valueOf(row, column)))?.seq ?? null;
2682
+ }
2683
+ function insertRow(local, table, columns, row, incomingSeq) {
2684
+ const columnList = columns.map(quoted).join(", ");
2685
+ const placeholders = columns.map(() => "?").join(", ");
2686
+ const nextSeq = `(SELECT COALESCE(MAX(seq), 0) + 1 FROM ${quoted(table)})`;
2687
+ try {
2688
+ const inserted = local.query(`INSERT INTO ${quoted(table)} (seq, ${columnList}) VALUES (${nextSeq}, ${placeholders}) RETURNING seq`).get(...columns.map((column) => valueOf(row, column)));
2689
+ if (inserted === null)
2690
+ throw new Error(`the insert into ${table} returned no seq`);
2691
+ return { kind: "added", localSeq: inserted.seq };
2692
+ } catch (error) {
2693
+ if (!(error instanceof SQLiteError2) || error.code !== UNIQUE_REFUSAL)
2694
+ throw error;
2695
+ return { kind: "collided", collision: { incomingSeq, reason: error.message } };
2696
+ }
2697
+ }
2698
+ function placeRow(local, merged, columns, row) {
2699
+ const incomingSeq = Number(valueOf(row, "seq"));
2700
+ const origin = byOrigin(local, merged.table, row);
2701
+ if (origin !== null)
2702
+ return { kind: "matched", match: { localSeq: origin, incomingSeq, by: "origin" } };
2703
+ const identity = byIdentity(local, merged, row);
2704
+ if (identity !== null)
2705
+ return { kind: "matched", match: { localSeq: identity, incomingSeq, by: "identity" } };
2706
+ return insertRow(local, merged.table, columns, row, incomingSeq);
2707
+ }
2708
+ function unionTable(local, other, merged) {
2709
+ const columns = carriedColumns(local, merged.table);
2710
+ const incoming = other.query(`SELECT seq, ${columns.map(quoted).join(", ")} FROM ${quoted(merged.table)} ORDER BY seq`).all();
2711
+ const outcomes = incoming.map((row) => placeRow(local, merged, columns, row));
2712
+ return {
2713
+ table: merged.table,
2714
+ added: outcomes.flatMap((outcome) => outcome.kind === "added" ? [outcome.localSeq] : []),
2715
+ matched: outcomes.flatMap((outcome) => outcome.kind === "matched" ? [outcome.match] : []),
2716
+ collided: outcomes.flatMap((outcome) => outcome.kind === "collided" ? [outcome.collision] : [])
2717
+ };
2718
+ }
2719
+ function unionStores(local, other) {
2720
+ const tables = mergedTables();
2721
+ refuseColumnMismatch(local, other, tables);
2722
+ return local.transaction(() => tables.map((merged) => unionTable(local, other, merged)))();
2723
+ }
2724
+
2725
+ // packages/rafa/src/effort/store/merge-conflicts.ts
2726
+ var SET_ONCE_FILLS = {
2727
+ "findings.tracker_ref": "UPDATE findings SET tracker_ref = ? WHERE seq = ? AND tracker_ref IS NULL"
2728
+ };
2729
+ var RECOMPUTED_COMPARISONS = {
2730
+ "commits.row_json": withoutGap
2731
+ };
2732
+ var NOT_CONTENT = new Set(["seq", "origin_store", "origin_seq"]);
2733
+ var INSERT_CONFLICT = `INSERT INTO merge_conflicts (merge_id, table_name, local_seq, field, incoming, recorded_at)
2734
+ VALUES (?, ?, ?, ?, ?, ?)`;
2735
+ function rowAt(db, table, columns, seq, side) {
2736
+ const row = db.query(`SELECT seq, ${columns.map(quoted).join(", ")} FROM ${quoted(table)} WHERE seq = ?`).get(seq);
2737
+ if (row === null)
2738
+ throw new Error(`the union matched ${table} row ${seq} ${side}, which that store does not hold`);
2739
+ return row;
2740
+ }
2741
+ function sameValue(left, right) {
2742
+ if (left instanceof Uint8Array && right instanceof Uint8Array)
2743
+ return Buffer.from(left).equals(right);
2744
+ return (left ?? null) === (right ?? null);
2745
+ }
2746
+ function fillStatement(table, field2) {
2747
+ const statement = SET_ONCE_FILLS[`${table}.${field2}`];
2748
+ if (statement === undefined) {
2749
+ throw new Error(`${table}.${field2} is set-once in MERGE_RULES and has no statement in SET_ONCE_FILLS`);
2750
+ }
2751
+ return statement;
2752
+ }
2753
+ function settleSetOnce(local, table, field2, here, there) {
2754
+ const incoming = there[field2] ?? null;
2755
+ if (incoming === null)
2756
+ return { skipped: true, filled: [], conflictFields: [] };
2757
+ if ((here[field2] ?? null) !== null)
2758
+ return { skipped: false, filled: [], conflictFields: [field2] };
2759
+ local.query(fillStatement(table, field2)).run(incoming, Number(here.seq));
2760
+ return { skipped: true, filled: [field2], conflictFields: [] };
2761
+ }
2762
+ function settleRecomputed(table, field2, here, there) {
2763
+ const comparable = RECOMPUTED_COMPARISONS[`${table}.${field2}`];
2764
+ if (comparable === undefined) {
2765
+ throw new Error(`${table}.${field2} is recomputed in MERGE_RULES and has no entry in RECOMPUTED_COMPARISONS`);
2766
+ }
2767
+ const hereValue = here[field2];
2768
+ const thereValue = there[field2];
2769
+ const same = typeof hereValue === "string" && typeof thereValue === "string" && comparable(hereValue) === comparable(thereValue);
2770
+ return same ? { skipped: true, filled: [], conflictFields: [] } : { skipped: false, filled: [], conflictFields: [null] };
2771
+ }
2772
+ function settlePair(local, table, edited, here, there) {
2773
+ const differing = Object.keys(here).filter((column) => !NOT_CONTENT.has(column) && !sameValue(here[column], there[column]));
2774
+ if (differing.length === 0)
2775
+ return { skipped: true, filled: [], conflictFields: [] };
2776
+ if (differing.some((column) => !Object.hasOwn(edited, column)))
2777
+ return { skipped: false, filled: [], conflictFields: [null] };
2778
+ const outcomes = differing.map((field2) => {
2779
+ if (edited[field2] === SET_ONCE)
2780
+ return settleSetOnce(local, table, field2, here, there);
2781
+ if (edited[field2] === RECOMPUTED)
2782
+ return settleRecomputed(table, field2, here, there);
2783
+ throw new Error(`${table}.${field2} has the rule ${edited[field2]}, which the merge does not apply`);
2784
+ });
2785
+ return {
2786
+ skipped: outcomes.every((outcome) => outcome.skipped),
2787
+ filled: outcomes.flatMap((outcome) => outcome.filled),
2788
+ conflictFields: outcomes.flatMap((outcome) => outcome.conflictFields)
2789
+ };
2790
+ }
2791
+ function settleTable(local, other, union, trail) {
2792
+ const rule = MERGE_RULES[union.table];
2793
+ if (rule?.scope !== "merged")
2794
+ throw new Error(`${union.table} is not a merged table in MERGE_RULES`);
2795
+ const columns = carriedColumns(local, union.table);
2796
+ const settled = union.matched.map((match) => {
2797
+ const here = rowAt(local, union.table, columns, match.localSeq, "here");
2798
+ const there = rowAt(other, union.table, columns, match.incomingSeq, "in the other store");
2799
+ const outcome = settlePair(local, union.table, rule.edited, here, there);
2800
+ const conflicts = outcome.conflictFields.map((field2) => {
2801
+ local.query(INSERT_CONFLICT).run(trail.mergeId, union.table, match.localSeq, field2, JSON.stringify(there), trail.recordedAt);
2802
+ return { localSeq: match.localSeq, incomingSeq: match.incomingSeq, field: field2 };
2803
+ });
2804
+ return { match, outcome, conflicts };
2805
+ });
2806
+ return {
2807
+ table: union.table,
2808
+ skipped: settled.flatMap(({ match, outcome }) => outcome.skipped ? [match.localSeq] : []),
2809
+ filled: settled.flatMap(({ match, outcome }) => outcome.filled.map((field2) => ({ localSeq: match.localSeq, field: field2 }))),
2810
+ conflicts: settled.flatMap(({ conflicts }) => conflicts)
2811
+ };
2812
+ }
2813
+ function settleMatches(local, other, unions, trail) {
2814
+ return local.transaction(() => unions.map((union) => settleTable(local, other, union, trail)))();
2815
+ }
2816
+ // packages/rafa/src/effort/store/migrate.ts
2817
+ function liveLoop(path, options, nothingDone = "Nothing was migrated.", ownSessionId = null) {
2818
+ const root = storeProjectRoot(path);
2819
+ if (root === null)
2820
+ return;
2821
+ let records;
2822
+ try {
2823
+ records = readSessions(root, { isAlive: options.isAlive ?? isPidAlive });
2824
+ } catch (error) {
2825
+ throw new RebuildRefusal(`the loop's run records cannot be read, so a live loop on ${path} cannot be ruled out` + ` (${messageOf(error)}). ${nothingDone}`);
2826
+ }
2827
+ return records.find((record) => (record.state === "running" || record.state === "paused") && record.sessionId !== ownSessionId);
2828
+ }
2829
+
2830
+ // packages/rafa/src/effort/store/merge-store.ts
2831
+ var MOVE_TO_SQLITE = "rafa effort move --to=sqlite";
2832
+
2833
+ class MergeRefusal extends RebuildRefusal {
2834
+ reason;
2835
+ constructor(reason, message) {
2836
+ super(message);
2837
+ this.name = "MergeRefusal";
2838
+ this.reason = reason;
2839
+ }
2840
+ }
2841
+ var LIVE = "live";
2842
+ var MERGES_TABLE = "merges";
2843
+ var INSERT_MERGE = `INSERT INTO merges (id, other_store, merged_at, rows_added, rows_skipped, rows_in_conflict)
2844
+ VALUES (?, ?, ?, ?, ?, ?)`;
2845
+ var NOTHING_MERGED = "Nothing was merged.";
2846
+ function refuseNdjson(backend) {
2847
+ if (backend !== "ndjson")
2848
+ return;
2849
+ throw new MergeRefusal("ndjson", `REFUSED \u2014 this project keeps its sessions and commits as NDJSON (store: ndjson), and a merge needs the SQLite store. ${NOTHING_MERGED}` + ` Next safe step: ${MOVE_TO_SQLITE}`);
2850
+ }
2851
+ function refuseMissing(path, which) {
2852
+ if (existsSync8(path))
2853
+ return;
2854
+ throw new MergeRefusal("missing", `REFUSED \u2014 ${which} ${path} is not there. ${NOTHING_MERGED}`);
2855
+ }
2856
+ function refuseDamaged(path) {
2857
+ let answers;
2858
+ try {
2859
+ const db = new Database6(path, { readonly: true });
2860
+ try {
2861
+ answers = db.query("PRAGMA integrity_check").all().map((row) => row.integrity_check);
2862
+ } finally {
2863
+ db.close();
2864
+ }
2865
+ } catch (error) {
2866
+ if (!(error instanceof SQLiteError3))
2867
+ throw error;
2868
+ throw new MergeRefusal("damaged", `REFUSED \u2014 ${path} cannot be read as a SQLite store (${error.message}). ${NOTHING_MERGED}` + " Take a consistent copy on its device with rafa effort copy, and merge that.");
2869
+ }
2870
+ if (answers.length === 1 && answers[0] === "ok")
2871
+ return;
2872
+ throw new MergeRefusal("damaged", `REFUSED \u2014 ${path} failed integrity_check: ${answers.join("; ")}. ${NOTHING_MERGED}` + " Take a consistent copy on its device with rafa effort copy, and merge that.");
2873
+ }
2874
+ function writablePlan(path, migrations) {
2875
+ const plan = planSchema(readOnlySchema(path), sqliteCatalogue(migrations), "write", "open");
2876
+ if (plan.verdict === "refuse")
2877
+ throw new MergeRefusal("schema", `REFUSED \u2014 ${path}: ${plan.message}`);
2878
+ return plan;
2879
+ }
2880
+ function recordedMeta(path) {
2881
+ const db = new Database6(path, { readonly: true });
2882
+ try {
2883
+ const hasTable = db.query("SELECT count(*) AS n FROM sqlite_master WHERE type = 'table' AND name = 'store_meta'").get()?.n === 1;
2884
+ return hasTable ? readStoreMeta(db) : null;
2885
+ } finally {
2886
+ db.close();
2887
+ }
2888
+ }
2889
+ function refuseOtherProject(options) {
2890
+ const other = recordedMeta(options.otherPath);
2891
+ const here = recordedMeta(options.path)?.projectRootCommit ?? (options.readProject ?? readProjectIdentity)(dirname8(options.path)).rootCommit;
2892
+ const there = other?.projectRootCommit ?? null;
2893
+ if (here !== null && there !== null && here !== there) {
2894
+ throw new MergeRefusal("other-project", `REFUSED \u2014 ${options.otherPath} is the effort store of another project (root commit ${there});` + ` this store's project has root commit ${here}. ${NOTHING_MERGED}`);
2895
+ }
2896
+ return other?.storeId ?? null;
2897
+ }
2898
+ function refuseLiveLoop(path, options, sessionId) {
2899
+ const loop = liveLoop(path, options, NOTHING_MERGED, sessionId);
2900
+ if (loop === undefined)
2901
+ return;
2902
+ throw new MergeRefusal("live-loop", `REFUSED \u2014 loop ${loop.sessionId} (pid ${String(loop.pid)}, plan ${loop.planStub ?? loop.plan}) is running on this store,` + ` and swapping the merged store in under it would lose what it writes. ${NOTHING_MERGED}` + " Finish or stop that loop, then run it again.");
2903
+ }
2904
+ function openOther(otherPath, plan, stamp, tempRoot) {
2905
+ const needs = writeNames(plan);
2906
+ if (needs.length === 0) {
2907
+ const db = new Database6(otherPath, { readonly: true });
2908
+ return { db, broughtForward: [], release: () => db.close() };
2909
+ }
2910
+ const dir = mkdtempSync2(join8(tempRoot, "rafa-merge-other-"));
2911
+ const release = (db) => {
2912
+ db?.close();
2913
+ rmSync6(dir, { recursive: true, force: true });
2914
+ };
2915
+ try {
2916
+ const copyPath = join8(dir, "other.sqlite");
2917
+ vacuumInto(otherPath, copyPath);
2918
+ const db = new Database6(copyPath, { readwrite: true });
2919
+ try {
2920
+ bringForward(db, copyPath, "write", "open", { ...stamp, builtAside: true });
2921
+ } catch (error) {
2922
+ release(db);
2923
+ throw error;
2924
+ }
2925
+ return { db, broughtForward: needs, release: () => release(db) };
2926
+ } catch (error) {
2927
+ release();
2928
+ throw error;
2929
+ }
2930
+ }
2931
+ function mergeInto(db, other, mergeId, otherStore, mergedAt) {
2932
+ return db.transaction(() => {
2933
+ const unions = unionStores(db, other);
2934
+ const settlements = settleMatches(db, other, unions, { mergeId, recordedAt: mergedAt });
2935
+ const gaps = recomputeCommitGaps(db, unions.find(({ table }) => table === "commits")?.added ?? []);
2936
+ const tables = unions.map((union, index) => {
2937
+ const settled = settlements[index];
2938
+ return {
2939
+ table: union.table,
2940
+ added: union.added.length,
2941
+ skipped: settled?.skipped.length ?? 0,
2942
+ inConflict: settled?.conflicts.length ?? 0,
2943
+ filled: settled?.filled.length ?? 0,
2944
+ collided: union.collided.length
2945
+ };
2946
+ });
2947
+ const sum = (field2) => tables.reduce((total, entry) => total + entry[field2], 0);
2948
+ const totals = { rowsAdded: sum("added"), rowsSkipped: sum("skipped"), rowsInConflict: sum("inConflict") };
2949
+ db.query(INSERT_MERGE).run(mergeId, otherStore, mergedAt, totals.rowsAdded, totals.rowsSkipped, totals.rowsInConflict);
2950
+ return { tables, ...totals, gapsRewritten: gaps.length };
2951
+ })();
2952
+ }
2953
+ function addedRows(merged) {
2954
+ return {
2955
+ ...Object.fromEntries(merged.tables.map(({ table, added }) => [table, added])),
2956
+ [MERGES_TABLE]: 1,
2957
+ merge_conflicts: merged.rowsInConflict
2958
+ };
2959
+ }
2960
+ function buildMerged(path, parallelPath, other, merge) {
2961
+ vacuumInto(path, parallelPath);
2962
+ const db = new Database6(parallelPath, { readwrite: true });
2963
+ try {
2964
+ bringForward(db, parallelPath, "write", "open", { ...merge.stamp, builtAside: true });
2965
+ const merged = mergeInto(db, other, merge.id, merge.otherStore, merge.stamp.now().toISOString());
2966
+ db.run(`ATTACH DATABASE ? AS ${LIVE}`, [path]);
2967
+ const live = new Set(tableNames(db, LIVE));
2968
+ checkedCounts(db, tableNames(db, "main").filter((table) => live.has(table)), LIVE, addedRows(merged));
2969
+ db.run(`DETACH DATABASE ${LIVE}`);
2970
+ refuseCorrupt(db);
2971
+ refuseUnusable(db, parallelPath, merge.stamp.migrations);
2972
+ return merged;
2973
+ } finally {
2974
+ db.close();
2975
+ }
2976
+ }
2977
+ function refuseUnmergeable(options, migrations) {
2978
+ const { path, otherPath } = options;
2979
+ refuseNdjson(options.backend);
2980
+ refuseMissing(path, "this store");
2981
+ refuseMissing(otherPath, "the other store");
2982
+ refuseInFlight(path);
2983
+ refuseInFlight(otherPath);
2984
+ refuseDamaged(otherPath);
2985
+ const otherPlan = writablePlan(otherPath, migrations);
2986
+ const localPlan = writablePlan(path, migrations);
2987
+ const otherStore = refuseOtherProject(options);
2988
+ if (!options.dryRun) {
2989
+ refuseUnownedDevelopmentWrite(path, [...writeNames(localPlan), MERGES_TABLE], options);
2990
+ refuseLiveLoop(path, options, options.sessionId ?? null);
2991
+ }
2992
+ return { otherPlan, otherStore };
2993
+ }
2994
+ function mergeStore(options) {
2995
+ const { path, otherPath, dryRun, stamp } = options;
2996
+ guardTestProcess(path);
2997
+ guardTestProcess(otherPath);
2998
+ const migrations = options.migrations ?? SQLITE_MIGRATIONS;
2999
+ const { otherPlan, otherStore } = refuseUnmergeable(options, migrations);
3000
+ const mergeStamp = {
3001
+ migrations,
3002
+ appliedBy: appliedByName(options.identity ?? readRuntimeIdentity()),
3003
+ now: options.now ?? (() => new Date)
3004
+ };
3005
+ const mergeId = (options.newMergeId ?? randomUUID3)();
3006
+ const other = openOther(otherPath, otherPlan, mergeStamp, options.tempDir ?? tmpdir4());
3007
+ try {
3008
+ const { built, backupPath } = rebuildAside({
3009
+ path,
3010
+ parallelPath: `${path}.merge-${stamp}`,
3011
+ backupPath: `${path}.before-merge-${stamp}.bak`,
3012
+ dryRun,
3013
+ build: (parallelPath) => buildMerged(path, parallelPath, other.db, { id: mergeId, otherStore, stamp: mergeStamp })
3014
+ });
3015
+ const status = dryRun ? "would-merge" : "merged";
3016
+ return { path, otherPath, status, mergeId, otherStore, otherBroughtForward: other.broughtForward, ...built, backupPath };
3017
+ } finally {
3018
+ other.release();
3019
+ }
3020
+ }
3021
+
3022
+ // packages/rafa/src/effort/store/ndjson.ts
3023
+ import { join as join9 } from "path";
3024
+ function kindPath(repoRoot, kind) {
3025
+ return join9(effortStoreDir(repoRoot), effortStoreFileName(kind));
3026
+ }
3027
+ function openedKindPath(repoRoot, kind) {
3028
+ const path = kindPath(repoRoot, kind);
3029
+ guardTestProcess(path);
3030
+ return path;
3031
+ }
3032
+ function readKind2(repoRoot, kind) {
3033
+ return readStoreRows(openedKindPath(repoRoot, kind));
3034
+ }
3035
+ function keysOfKind2(repoRoot, kind) {
3036
+ const path = openedKindPath(repoRoot, kind);
3037
+ return collectedKeys(path, EFFORT_KEY_PROJECTIONS[kind]);
3038
+ }
3039
+ function appendKind2(repoRoot, kind, rows) {
3040
+ const path = openedKindPath(repoRoot, kind);
3041
+ return appendRows(path, rows, EFFORT_KEY_PROJECTIONS[kind]);
3042
+ }
3043
+ function openNdjsonStore(repoRoot) {
3044
+ return {
3045
+ append: (kind, rows) => appendKind2(repoRoot, kind, rows),
3046
+ keys: (kind) => keysOfKind2(repoRoot, kind),
3047
+ read: (kind) => readKind2(repoRoot, kind).rows,
3048
+ path: (kind) => kindPath(repoRoot, kind),
3049
+ readRows: (kind) => readKind2(repoRoot, kind)
3050
+ };
3051
+ }
3052
+
3053
+ // packages/rafa/src/effort/store/index.ts
3054
+ function describeValue2(value) {
3055
+ if (typeof value === "string")
3056
+ return JSON.stringify(value);
3057
+ if (typeof value === "object" && value !== null)
3058
+ return "an object";
3059
+ return String(value);
3060
+ }
3061
+ function selectEffortStore(repoRoot, config) {
3062
+ const adapter = CORE_ADAPTER_REGISTRY.find("store", config.store);
3063
+ if (adapter === undefined) {
3064
+ const expected = CORE_ADAPTER_REGISTRY.kinds("store").join(", ");
3065
+ throw new TypeError(`effort store: store is ${describeValue2(config.store)},` + ` expected one of: ${expected}`);
3066
+ }
3067
+ return adapter.create({ repoRoot });
3068
+ }
2596
3069
 
2597
- export { PORT_VERSIONS, createAdapterRegistry, registerAdapters, restoreAdapters, activeAdapterRegistry, CORE_ADAPTER_REGISTRY, effortStoreFileName, readStoreRows, collectedKeys, appendRows, EFFORT_DIR_VARIABLE, effortStoreDir, guardTestProcess, EFFORT_KEY_PROJECTIONS, SPENDS_GLYPH, CommandExit, commandSpelling, createLinePrompter, lazyPrompter, version, RAFA_VERSION, isRecord, asPlace, asHopRecord, SessionRecordError, isSessionId, sessionSteps, sessionDecisions, SessionConflictError, runsDir, sessionFilePath, errorCode, isPidAlive, readSessions, readSession, samePlan, beginSession, updateSession, claudeArgs, interruptClaudeSessions, spawnClaude, runClaude, spawnClaudeCaptured, runClaudeCaptured, readRuntimeIdentity, DEVELOPMENT_NEXT_STEP, appliedByName, DevelopmentBuildRefusedError, storeProjectRoot, refuseUnownedDevelopmentWrite, SQLITE_MIGRATIONS, sqliteCatalogue, planSchema, MIGRATION_LOG_TABLE, bringForward, readStoreSchema, writeNames, ACROSS_STORES_ORDER, STAMPED_COLUMNS, stampedValues, setActiveStoreSettings, activeStoreSettings, writeStoreGeneration, createGitRunner, gitSaid, commitTaskWork, PROJECT_ID_LENGTH, PROJECT_ID_PATTERN, normalizeRemote, gitRemoteUrl, readProjectIdentity, readReplacedStoreIds, readStoreMeta, carryStoreIdentity, SQLITE_STORE_FILE_NAME, sqliteStorePath, LONE_SURROGATE, withSqliteStore, writeSqliteStore, openSqliteStore, TRUSTED_PERMISSIONS };
3070
+ export { RUNTIME_SUBDIR, SessionRecordError, isSessionId, sessionSteps, sessionDecisions, SessionConflictError, runsDir, sessionFilePath, errorCode, isPidAlive, readSessions, readSession, samePlan, beginSession, updateSession, SESSION_ID_FLAG, claudeArgs, interruptClaudeSessions, spawnClaude, runClaude, spawnClaudeCaptured, runClaudeCaptured, EFFORT_DIR_VARIABLE, effortStoreDir, guardTestProcess, DEVELOPMENT_NEXT_STEP, DevelopmentBuildRefusedError, refuseUnownedDevelopmentWrite, SQLITE_MIGRATIONS, sqliteCatalogue, planSchema, readStoreSchema, writeNames, ACROSS_STORES_ORDER, STAMPED_COLUMNS, stampedValues, readReplacedStoreIds, readStoreMeta, EFFORT_KEY_PROJECTIONS, SQLITE_STORE_FILE_NAME, sqliteStorePath, LONE_SURROGATE, withSqliteStore, writeSqliteStore, openSqliteStore, copyEffortStore, WIRE_FORMAT, WIRE_VERSION, WireFormatError, WireExportRefusal, encodeWirePayload, decodeWirePayload, exportWirePayload, materialiseWirePayload, minutesBetween, MOVE_TO_SQLITE, mergeStore, openNdjsonStore, selectEffortStore };