@open-tomato/rafa 0.47.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 (73) hide show
  1. package/README.md +5 -2
  2. package/dist/bugs/places.d.ts +1 -1
  3. package/dist/bundled/skills/dev-planner/SKILL.md +1 -1
  4. package/dist/cli.js +58833 -58857
  5. package/dist/config/index.js +4 -5
  6. package/dist/config/shape.d.ts +13 -11
  7. package/dist/config-schema-board-project.d.ts +3 -3
  8. package/dist/config-schema-checks.d.ts +3 -3
  9. package/dist/config-schema-hub.d.ts +3 -3
  10. package/dist/config-schema-issues.d.ts +4 -4
  11. package/dist/config-schema-loop-continue.d.ts +3 -3
  12. package/dist/config-schema-loop-retries.d.ts +4 -4
  13. package/dist/config-schema-release.d.ts +13 -13
  14. package/dist/config-schema-tests.d.ts +3 -3
  15. package/dist/config-schema-triage.d.ts +3 -3
  16. package/dist/config-schema-wrap-up.d.ts +4 -4
  17. package/dist/core/command/global-flags.d.ts +25 -0
  18. package/dist/core/command/index.d.ts +31 -25
  19. package/dist/core/command/registry-types.d.ts +4 -4
  20. package/dist/core/command/shared-flags.d.ts +6 -6
  21. package/dist/core/command/types.d.ts +3 -2
  22. package/dist/core/config/branch-template.d.ts +2 -0
  23. package/dist/core/config/config-items.d.ts +1 -1
  24. package/dist/core/config/config-schema.d.ts +6 -0
  25. package/dist/core/config/config-sections.d.ts +15 -14
  26. package/dist/core/config/config.d.ts +1 -1
  27. package/dist/core/config/core-section.d.ts +1 -1
  28. package/dist/core/config/default-routing.d.ts +1 -1
  29. package/dist/core/config/index.d.ts +4 -4
  30. package/dist/core/config/merge-method.d.ts +4 -4
  31. package/dist/core/config/sections.d.ts +6 -3
  32. package/dist/core/git/gh-runner.d.ts +1 -1
  33. package/dist/core/git/git.d.ts +34 -0
  34. package/dist/core/git/index.d.ts +13 -8
  35. package/dist/core/loop/claude.d.ts +11 -5
  36. package/dist/core/loop/index.d.ts +3 -2
  37. package/dist/core/loop/sessions.d.ts +1 -1
  38. package/dist/core/loop/suite-failure.d.ts +8 -6
  39. package/dist/core/output/active.d.ts +1 -1
  40. package/dist/core/runtime/identity.d.ts +13 -0
  41. package/dist/core/runtime/index.d.ts +12 -6
  42. package/dist/effort/store/check-rows.d.ts +1 -1
  43. package/dist/effort/store/commit-stats.d.ts +1 -1
  44. package/dist/effort/store/index.js +8 -9
  45. package/dist/effort/store/merge-commit-gaps.d.ts +1 -1
  46. package/dist/effort/store/plan-stubs.d.ts +1 -1
  47. package/dist/effort/store/session-row-types.d.ts +2 -2
  48. package/dist/{index-f1y86zbb.js → index-2a7nb3an.js} +31 -31
  49. package/dist/index-2xzkzwm6.js +670 -0
  50. package/dist/index-ajv88fkm.js +448 -0
  51. package/dist/{index-r5q2pdky.js → index-fpgmdmww.js} +4 -1
  52. package/dist/{index-pzpb1rf7.js → index-g91ys6kw.js} +97 -1
  53. package/dist/{index-eay1bd2w.js → index-jx3x70xh.js} +1090 -652
  54. package/dist/{index-cbqvgda6.js → index-m672ptpg.js} +3 -1
  55. package/dist/{index-nwzx41g1.js → index-w5qbpdtp.js} +416 -843
  56. package/dist/{index-7dgc5g1t.js → index-z4r20zwr.js} +8696 -11193
  57. package/dist/{index-n3e31fmw.js → index-zsak0jy6.js} +172 -254
  58. package/dist/index.js +24857 -18957
  59. package/dist/learning/index.js +221 -12
  60. package/dist/plan/index.js +11 -10
  61. package/dist/ports/index.d.ts +6 -6
  62. package/dist/ports/learning.d.ts +5 -4
  63. package/dist/ports/spec-review.d.ts +1 -1
  64. package/dist/ready-gax3hhtt.js +241 -0
  65. package/dist/release-templates/release-bot-fragment.yml +6 -6
  66. package/dist/release-templates/release-publish.yml +8 -8
  67. package/dist/release-templates/release-settle.yml +8 -7
  68. package/dist/release-templates/release-tag.yml +8 -7
  69. package/package.json +32 -2
  70. package/dist/index-38ktnyvz.js +0 -223
  71. package/dist/index-3mwsr6wg.js +0 -1070
  72. package/dist/index-z1w83f81.js +0 -4
  73. package/dist/ready-6p40c3gw.js +0 -2007
@@ -1,518 +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
- } from "./index-f1y86zbb.js";
16
+ } from "./index-2a7nb3an.js";
7
17
  import {
8
- CORE_SECTION,
9
18
  SCOPE_DIR,
10
19
  scopeAt
11
- } from "./index-cbqvgda6.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-r5q2pdky.js";
21
-
22
- // packages/rafa/src/core/command/spends.ts
23
- var SPENDS_GLYPH = "\uD83E\uDE99";
25
+ } from "./index-fpgmdmww.js";
24
26
 
25
- // packages/rafa/src/core/command/command.ts
26
- var MAX_EXIT_CODE = 255;
27
-
28
- class CommandExit extends Error {
29
- exitCode;
30
- constructor(exitCode, message = "", options) {
31
- super(message, options);
32
- if (!Number.isInteger(exitCode) || exitCode < 0 || exitCode > MAX_EXIT_CODE) {
33
- throw new TypeError(`CommandExit: exit code is ${describeValue(exitCode)}, expected a whole number from 0 to ${MAX_EXIT_CODE}`);
34
- }
35
- this.name = "CommandExit";
36
- this.exitCode = exitCode;
37
- }
38
- }
39
- function isTopLevel(command) {
40
- return command.subject === command.action;
41
- }
42
- function commandSpelling(command) {
43
- return isTopLevel(command) ? command.subject : `${command.subject} ${command.action}`;
44
- }
45
-
46
- // packages/rafa/src/core/command/confirm.ts
47
- import { createInterface } from "readline";
48
- var YES_ANSWERS = Object.freeze(["y", "yes"]);
49
- function createLinePrompter(input, output) {
50
- const buffered = [];
51
- const waiting = [];
52
- let ended = false;
53
- const lines = createInterface({ input, terminal: false, crlfDelay: Infinity });
54
- lines.on("line", (line) => {
55
- const reader = waiting.shift();
56
- if (reader === undefined)
57
- buffered.push(line);
58
- else
59
- reader(line);
60
- });
61
- lines.on("close", () => {
62
- ended = true;
63
- for (const reader of waiting.splice(0))
64
- reader(null);
65
- });
66
- return {
67
- say: (text) => {
68
- output.write(`${text}
69
- `);
70
- },
71
- ask: async (question) => {
72
- output.write(question);
73
- const next = buffered.shift();
74
- if (next !== undefined)
75
- return next;
76
- if (ended)
77
- return null;
78
- return new Promise((settle) => {
79
- waiting.push(settle);
80
- });
81
- },
82
- close: () => {
83
- lines.close();
84
- }
85
- };
86
- }
87
- function lazyPrompter(open) {
88
- let prompter = null;
89
- const askLine = async (question) => {
90
- prompter ??= open();
91
- return prompter.ask(question);
92
- };
93
- return {
94
- askLine,
95
- ask: async (question) => {
96
- const answer = await askLine(question);
97
- return answer !== null && YES_ANSWERS.includes(answer.trim().toLowerCase());
98
- },
99
- close: () => {
100
- prompter?.close();
101
- prompter = null;
102
- }
103
- };
104
- }
105
- // packages/rafa/src/core/command/running.ts
106
- import { AsyncLocalStorage } from "async_hooks";
107
- var scopes = new AsyncLocalStorage;
108
- var running = null;
109
- function runningCommand() {
110
- return scopes.getStore() ?? running;
111
- }
112
- // packages/rafa/src/core/command/shared-flags.ts
113
- var HINT_FLAG = "hint";
114
- var HINT_FLAG_SPEC = Object.freeze({
115
- name: HINT_FLAG,
116
- description: "Ends by naming the one step that follows, asking it where there is a terminal to answer on;" + " `--no-hint` reads nothing and prints nothing.",
117
- type: "boolean",
118
- default: true
119
- });
120
- var DEFAULT_CI_TIMEOUT_MIN = 20;
121
- // package.json
122
- var version = "0.47.0";
123
-
124
- // packages/rafa/src/core/command/version.ts
125
- var RAFA_VERSION = version;
126
- // packages/rafa/src/core/adapters/registry.ts
127
- var REFUSAL = "adapter registry";
128
- var PORT_VERSIONS = Object.freeze({
129
- tracker: 1,
130
- store: 1,
131
- learning: 1,
132
- output: 1,
133
- planner: 1,
134
- sync: 1,
135
- logger: 1
136
- });
137
- var SERVED_VERSIONS = new Map(Object.entries(PORT_VERSIONS));
138
- var PORT_TYPE_LIST = [...SERVED_VERSIONS.keys()].join(", ");
139
- function checkPortType(port) {
140
- if (!SERVED_VERSIONS.has(port)) {
141
- throw new TypeError(`${REFUSAL}: port is ${describeValue(port)}, expected one of: ${PORT_TYPE_LIST}`);
142
- }
143
- }
144
- function accept(adapter, held) {
145
- if (typeof adapter !== "object" || adapter === null) {
146
- throw new TypeError(`${REFUSAL}: an adapter is ${describeValue(adapter)}, expected a mapping`);
147
- }
148
- const { port, kind, portVersion, create } = adapter;
149
- checkPortType(port);
150
- if (typeof kind !== "string" || kind === "") {
151
- throw new TypeError(`${REFUSAL}: a ${port} adapter has kind ${describeValue(kind)}, expected a non-empty name`);
152
- }
153
- const key = `${port}/${kind}`;
154
- if (typeof create !== "function") {
155
- throw new TypeError(`${REFUSAL}: ${key} has create ${describeValue(create)}, expected a function`);
156
- }
157
- const served = SERVED_VERSIONS.get(port);
158
- if (portVersion !== served) {
159
- throw new Error(`${REFUSAL}: ${key} implements ${port} port version ${describeValue(portVersion)},` + ` and core serves ${port} port version ${served}`);
160
- }
161
- if (held.some((other) => other.port === port && other.kind === kind)) {
162
- throw new Error(`${REFUSAL}: ${key} is already registered`);
163
- }
164
- return Object.freeze({ port, kind, portVersion, create });
165
- }
166
- function indexByPort(adapters) {
167
- const only = (port) => new Map(adapters.filter((adapter) => adapter.port === port).map((adapter) => [adapter.kind, adapter]));
168
- return {
169
- tracker: only("tracker"),
170
- store: only("store"),
171
- learning: only("learning"),
172
- output: only("output"),
173
- planner: only("planner"),
174
- sync: only("sync"),
175
- logger: only("logger")
176
- };
177
- }
178
- function createAdapterRegistry(adapters = []) {
179
- const held = adapters.reduce((accepted, adapter) => [...accepted, accept(adapter, accepted)], []);
180
- const byPort = indexByPort(held);
181
- const registry = {
182
- register: (adapter) => createAdapterRegistry([...held, adapter]),
183
- find: (port, kind) => SERVED_VERSIONS.has(port) ? byPort[port].get(kind) : undefined,
184
- resolve: (port, kind) => {
185
- checkPortType(port);
186
- const adapter = byPort[port].get(kind);
187
- if (adapter !== undefined)
188
- return adapter;
189
- const registered = [...byPort[port].keys()];
190
- const listed = registered.length === 0 ? "none" : registered.join(", ");
191
- throw new Error(`${REFUSAL}: no ${port} adapter is registered as ${describeValue(kind)};` + ` registered: ${listed}`);
192
- },
193
- kinds: (port) => {
194
- checkPortType(port);
195
- return [...byPort[port].keys()];
196
- }
197
- };
198
- return Object.freeze(registry);
199
- }
200
- var EMPTY_ADAPTER_REGISTRY = createAdapterRegistry();
201
- var COMPOSITION_ROOT = "src/adapter-registry.ts";
202
- var active = EMPTY_ADAPTER_REGISTRY;
203
- function holdsNone(registry) {
204
- return [...SERVED_VERSIONS.keys()].every((port) => registry.kinds(port).length === 0);
205
- }
206
- function registerAdapters(adapters) {
207
- const previous = active;
208
- active = adapters.reduce((registry, adapter) => registry.register(adapter), previous);
209
- return previous;
210
- }
211
- function restoreAdapters(registry) {
212
- if (registry === CORE_ADAPTER_REGISTRY) {
213
- throw new TypeError(`${REFUSAL}: CORE_ADAPTER_REGISTRY reads the active registry and cannot be made the active one;` + " restore what registerAdapters or activeAdapterRegistry answered");
214
- }
215
- active = registry;
216
- }
217
- function activeAdapterRegistry() {
218
- return active;
219
- }
220
- function registered() {
221
- if (holdsNone(active)) {
222
- throw new Error(`${REFUSAL}: no adapter is registered: call registerCoreAdapters() from ${COMPOSITION_ROOT}` + " before reading CORE_ADAPTER_REGISTRY");
223
- }
224
- return active;
225
- }
226
- var CORE_ADAPTER_REGISTRY = Object.freeze({
227
- register: (adapter) => registered().register(adapter),
228
- find: (port, kind) => registered().find(port, kind),
229
- resolve: (port, kind) => registered().resolve(port, kind),
230
- kinds: (port) => registered().kinds(port)
231
- });
232
- // packages/rafa/src/core/git/git.ts
233
- import { spawnSync } from "child_process";
234
- function createGitRunner(cwd) {
235
- return (args) => {
236
- const result = spawnSync("git", [...args], {
237
- cwd,
238
- encoding: "utf8",
239
- env: { ...process.env, LC_ALL: "C" }
240
- });
241
- if (result.error !== undefined) {
242
- return { ok: false, stdout: "", stderr: `could not run git in ${cwd}: ${messageOf(result.error)}` };
243
- }
244
- return { ok: result.status === 0, stdout: result.stdout ?? "", stderr: result.stderr ?? "" };
245
- };
246
- }
247
- function gitSaid(result) {
248
- return [result.stderr, result.stdout].map((stream) => stream.trim()).filter((stream) => stream !== "").join(`
249
- `);
250
- }
251
- // packages/rafa/src/core/git/commit.ts
252
- import { spawnSync as spawnSync2 } from "child_process";
253
- var DEFAULT_COMMIT_TYPE = "chore";
254
- var TEST_NOUN_WINDOW = 40;
255
- var FIX_VERBS = ["fix", "repair", "correct", "resolve"];
256
- var REFACTOR_VERBS = [
257
- "remove",
258
- "delete",
259
- "drop",
260
- "move",
261
- "rename",
262
- "relocate",
263
- "extract",
264
- "split",
265
- "inline",
266
- "collapse"
267
- ];
268
- var FEAT_VERBS = [
269
- "add",
270
- "implement",
271
- "introduce",
272
- "register",
273
- "extend",
274
- "call",
275
- "wire",
276
- "expose",
277
- "parse",
278
- "strip",
279
- "enforce",
280
- "generate"
281
- ];
282
- var CHORE_VERBS = [
283
- "capture",
284
- "measure",
285
- "run",
286
- "sweep",
287
- "verify",
288
- "ensure",
289
- "regenerate",
290
- "update",
291
- "gitignore",
292
- "take",
293
- "bump",
294
- "pin"
295
- ];
296
- function openingVerbs(verbs) {
297
- return new RegExp(`^(?:${verbs.join("|")})\\b`, "i");
298
- }
299
- var COMMIT_TYPE_RULES = [
300
- {
301
- type: "test",
302
- pattern: new RegExp(`^.{0,${TEST_NOUN_WINDOW}}?\\btests?\\b`, "i")
303
- },
304
- { type: "docs", pattern: /\.md\b/i },
305
- { type: "fix", pattern: openingVerbs(FIX_VERBS) },
306
- { type: "refactor", pattern: openingVerbs(REFACTOR_VERBS) },
307
- { type: "feat", pattern: openingVerbs(FEAT_VERBS) },
308
- { type: "chore", pattern: openingVerbs(CHORE_VERBS) }
309
- ];
310
- var MAX_SUBJECT_LENGTH = 72;
311
- var FALLBACK_DESCRIPTION = "complete the scoped task";
312
- var MAX_MESSAGE_CHARS = 4000;
313
- function normaliseTaskText(taskText) {
314
- return taskText.replace(/\s+/g, " ").trim();
315
- }
316
- function inferCommitType(taskText) {
317
- const text = normaliseTaskText(taskText);
318
- for (const rule of COMMIT_TYPE_RULES) {
319
- if (rule.pattern.test(text))
320
- return rule.type;
321
- }
322
- return DEFAULT_COMMIT_TYPE;
323
- }
324
- function countBackticks(text) {
325
- let count = 0;
326
- for (const character of text) {
327
- if (character === "`")
328
- count += 1;
329
- }
330
- return count;
331
- }
332
- function balanceCodeSpans(text) {
333
- let result = text;
334
- while (countBackticks(result) % 2 === 1) {
335
- const lastSpace = result.lastIndexOf(" ");
336
- if (lastSpace <= 0)
337
- return result.replace(/`/g, "");
338
- result = result.slice(0, lastSpace).trimEnd();
339
- }
340
- return result;
341
- }
342
- function stripTrailingPeriod(text) {
343
- if (!text.endsWith("."))
344
- return text;
345
- const withoutDot = text.slice(0, -1);
346
- const lastToken = withoutDot.slice(withoutDot.lastIndexOf(" ") + 1);
347
- if (lastToken.includes("."))
348
- return text;
349
- return withoutDot;
350
- }
351
- function lowerFirstWord(text) {
352
- const match = text.match(/^[A-Za-z]+/);
353
- const word = match?.[0];
354
- if (word === undefined)
355
- return text;
356
- if (word.length > 1 && word === word.toUpperCase())
357
- return text;
358
- return text.slice(0, 1).toLowerCase() + text.slice(1);
359
- }
360
- var CLAUSE_ENDINGS = new Set([",", ":", "(", ")"]);
361
- function backtickRunLength(text, start) {
362
- let end = start;
363
- while (text.charAt(end) === "`")
364
- end += 1;
365
- return end - start;
366
- }
367
- function codeSpanEnd(text, from, length) {
368
- let index = text.indexOf("`", from);
369
- while (index !== -1) {
370
- const run = backtickRunLength(text, index);
371
- if (run === length)
372
- return index + run;
373
- index = text.indexOf("`", index + run);
374
- }
375
- return -1;
376
- }
377
- function firstClause(text) {
378
- let index = 0;
379
- while (index < text.length) {
380
- const character = text.charAt(index);
381
- if (character === "`") {
382
- const run = backtickRunLength(text, index);
383
- const end = codeSpanEnd(text, index + run, run);
384
- index = end === -1 ? index + run : end;
385
- continue;
386
- }
387
- if (CLAUSE_ENDINGS.has(character))
388
- return text.slice(0, index).trimEnd();
389
- index += 1;
390
- }
391
- return text.trimEnd();
392
- }
393
- function truncateDescription(description, budget) {
394
- if (budget <= 0)
395
- return "";
396
- if (description.length <= budget)
397
- return description;
398
- const window = description.slice(0, budget + 1);
399
- const lastSpace = window.lastIndexOf(" ");
400
- const cut = lastSpace > 0 ? window.slice(0, lastSpace) : window.slice(0, budget);
401
- return balanceCodeSpans(cut.trimEnd()).replace(/[\s,;:-]+$/, "");
402
- }
403
- function subjectDescription(normalised) {
404
- const clause = firstClause(normalised);
405
- const description = clause.length === 0 ? normalised : clause;
406
- return lowerFirstWord(stripTrailingPeriod(description));
407
- }
408
- function deriveCommitSubject(taskText, options = {}) {
409
- const type = inferCommitType(taskText);
410
- const scope = options.scope;
411
- const prefix = scope === undefined || scope.length === 0 ? `${type}: ` : `${type}(${scope}): `;
412
- const normalised = normaliseTaskText(taskText);
413
- const uncut = normalised.length === 0 ? FALLBACK_DESCRIPTION : subjectDescription(normalised);
414
- const maxLength = options.maxLength ?? MAX_SUBJECT_LENGTH;
415
- const description = truncateDescription(uncut, maxLength - prefix.length);
416
- const truncated = description !== uncut;
417
- return {
418
- subject: `${prefix}${description}`,
419
- type,
420
- truncated
421
- };
422
- }
423
- function buildCommitMessage(taskText, options = {}) {
424
- const derived = deriveCommitSubject(taskText, options);
425
- const body = normaliseTaskText(taskText);
426
- return { ...derived, body };
427
- }
428
- function stageAllArgs() {
429
- return ["add", "-A"];
430
- }
431
- function stagedChangesArgs() {
432
- return ["diff", "--cached", "--quiet"];
433
- }
434
- function commitArgs(subject, body = "") {
435
- const args = ["commit", "--cleanup=whitespace", "-m", subject];
436
- if (body.length > 0)
437
- args.push("-m", body);
438
- return args;
439
- }
440
- function headShaArgs() {
441
- return ["rev-parse", "HEAD"];
442
- }
443
- var MAX_GIT_BUFFER = 16 * 1024 * 1024;
444
- function failureMessage(result) {
445
- const combined = [result.stderr, result.stdout].map((stream) => stream.trim()).filter((stream) => stream.length > 0).join(`
446
- `);
447
- if (combined.length <= MAX_MESSAGE_CHARS)
448
- return combined;
449
- return `${combined.slice(0, MAX_MESSAGE_CHARS)}
450
- [truncated]`;
451
- }
452
- function failed(step, subject, result) {
453
- return {
454
- outcome: "failed",
455
- subject,
456
- sha: null,
457
- failedStep: step,
458
- exitCode: result.status,
459
- message: failureMessage(result)
460
- };
461
- }
462
- function spawnGit(cwd) {
463
- return (args) => {
464
- const result = spawnSync2("git", args, {
465
- cwd,
466
- encoding: "utf8",
467
- maxBuffer: MAX_GIT_BUFFER
468
- });
469
- if (result.error !== undefined) {
470
- return { status: null, stdout: "", stderr: result.error.message };
471
- }
472
- return {
473
- status: result.status,
474
- stdout: result.stdout ?? "",
475
- stderr: result.stderr ?? ""
476
- };
477
- };
478
- }
479
- function commitTaskWork(options) {
480
- const run = options.runGit ?? spawnGit(options.cwd ?? process.cwd());
481
- const message = buildCommitMessage(options.taskText, {
482
- scope: options.scope,
483
- maxLength: options.maxLength
484
- });
485
- const { subject } = message;
486
- const staged = run(stageAllArgs());
487
- if (staged.status !== 0)
488
- return failed("stage", subject, staged);
489
- const pending = run(stagedChangesArgs());
490
- if (pending.status === 0) {
491
- return {
492
- outcome: "nothing-to-commit",
493
- subject,
494
- sha: null,
495
- failedStep: null,
496
- exitCode: 0,
497
- message: ""
498
- };
499
- }
500
- if (pending.status !== 1)
501
- return failed("inspect", subject, pending);
502
- const committed = run(commitArgs(subject, message.body));
503
- if (committed.status !== 0)
504
- return failed("commit", subject, committed);
505
- const head = run(headShaArgs());
506
- const sha = head.status === 0 ? head.stdout.trim() : null;
507
- return {
508
- outcome: "committed",
509
- subject,
510
- sha,
511
- failedStep: null,
512
- exitCode: 0,
513
- message: ""
514
- };
515
- }
516
27
  // packages/rafa/src/effort/store/types.ts
517
28
  function keyOrNull(value) {
518
29
  return typeof value === "string" && value.length > 0 ? value : null;
@@ -545,66 +56,6 @@ import { dirname, join } from "path";
545
56
 
546
57
  // packages/rafa/src/core/loop/session-record-parse.ts
547
58
  import { basename, isAbsolute } from "path";
548
-
549
- // packages/rafa/src/core/loop/hop-record.ts
550
- var HOP_KINDS = ["blocker", "dry"];
551
- var HOP_STATES = ["away", "waiting", "merged", "halted"];
552
- function isRecord(value) {
553
- return typeof value === "object" && value !== null && !Array.isArray(value);
554
- }
555
- function isIssueNumber(value) {
556
- return typeof value === "number" && Number.isInteger(value) && value > 0;
557
- }
558
- function asPlace(value) {
559
- if (!isRecord(value) || !isIssueNumber(value.board))
560
- return null;
561
- if (value.epic !== null && !isIssueNumber(value.epic))
562
- return null;
563
- return { board: value.board, epic: value.epic };
564
- }
565
- function isIssueOrNull(value) {
566
- return value === null || isIssueNumber(value);
567
- }
568
- function isTimestamp(value) {
569
- return typeof value === "string" && !Number.isNaN(Date.parse(value));
570
- }
571
- function issuesMatchKind(kind, blocked, target) {
572
- return kind === "blocker" ? blocked !== null && target !== null : blocked === null && target === null;
573
- }
574
- function asHopRecord(value) {
575
- if (!isRecord(value))
576
- return null;
577
- const { kind, blocked, target, targetEpic, targetBoard, state, pullRequest, startedAt } = value;
578
- const home = asPlace(value.home);
579
- const from = asPlace(value.from);
580
- if (typeof kind !== "string" || !HOP_KINDS.includes(kind))
581
- return null;
582
- if (typeof state !== "string" || !HOP_STATES.includes(state))
583
- return null;
584
- if (home === null || from === null)
585
- return null;
586
- if (!isIssueOrNull(blocked) || !isIssueOrNull(target) || !isIssueOrNull(pullRequest))
587
- return null;
588
- if (!isIssueNumber(targetEpic) || !isIssueNumber(targetBoard) || !isTimestamp(startedAt))
589
- return null;
590
- const hopKind = kind;
591
- if (!issuesMatchKind(hopKind, blocked, target))
592
- return null;
593
- return {
594
- kind: hopKind,
595
- home,
596
- from,
597
- blocked,
598
- target,
599
- targetEpic,
600
- targetBoard,
601
- state,
602
- pullRequest,
603
- startedAt
604
- };
605
- }
606
-
607
- // packages/rafa/src/core/loop/session-record-parse.ts
608
59
  var SESSION_STATES = Object.freeze(["running", "paused", "stopped", "done"]);
609
60
  var SESSION_PHASES = Object.freeze(["task", "wrap-up", "pull-request", "ci", "repair"]);
610
61
  var RECORD_EXTENSION = ".json";
@@ -625,7 +76,7 @@ class SessionRecordError extends Error {
625
76
  function isSessionId(value) {
626
77
  return SESSION_ID_PATTERN.test(value);
627
78
  }
628
- function describeValue2(value) {
79
+ function describeValue(value) {
629
80
  return value === undefined ? "missing" : JSON.stringify(value) ?? String(value);
630
81
  }
631
82
  function field(fields, key) {
@@ -644,23 +95,23 @@ function taskProblem(task) {
644
95
  if (task === null)
645
96
  return null;
646
97
  if (!isObject(task))
647
- return `task is ${describeValue2(task)}, expected null or an object`;
98
+ return `task is ${describeValue(task)}, expected null or an object`;
648
99
  if (!isPositiveWhole(field(task, "line"))) {
649
- 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`;
650
101
  }
651
- 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`;
652
103
  }
653
104
  function hopProblem(fields) {
654
105
  if (!Object.hasOwn(fields, "hop"))
655
106
  return null;
656
107
  const hop = field(fields, "hop");
657
- 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;
658
109
  }
659
110
  function worktreeProblem(fields) {
660
111
  if (!Object.hasOwn(fields, "worktree"))
661
112
  return null;
662
113
  const worktree = field(fields, "worktree");
663
- 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`;
664
115
  }
665
116
  function isTextList(value) {
666
117
  return Array.isArray(value) && value.every(isText);
@@ -678,50 +129,50 @@ function stepFailuresProblem(step, at) {
678
129
  const failures = field(step, "failures");
679
130
  const newFailures = field(step, "newFailures");
680
131
  if (!isFailureList(failures))
681
- 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`;
682
133
  if (!isFailureList(newFailures)) {
683
- 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`;
684
135
  }
685
136
  const known = new Set(failures.map(failureKey));
686
137
  const stray = newFailures.find((failure) => !known.has(failureKey(failure)));
687
- 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`;
688
139
  }
689
140
  function stepInterruptedProblem(step, at) {
690
141
  if (!Object.hasOwn(step, "interrupted"))
691
142
  return null;
692
143
  const interrupted = field(step, "interrupted");
693
- 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`;
694
145
  }
695
146
  function stepScopeProblem(scope, at) {
696
- return TEST_SCOPES.includes(scope) || scope === NONE_STEP_SCOPE || isTextList(scope) ? null : `${at}.scope is ${describeValue2(scope)}, expected one of ${TEST_SCOPES.join(", ")}, ${NONE_STEP_SCOPE} or a list of paths`;
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`;
697
148
  }
698
149
  function stepCommandProblem(command, scope, at) {
699
150
  if (scope === NONE_STEP_SCOPE) {
700
- return Array.isArray(command) && command.length === 0 ? null : `${at}.command is ${describeValue2(command)}, expected an empty list on a ${NONE_STEP_SCOPE} step`;
151
+ return Array.isArray(command) && command.length === 0 ? null : `${at}.command is ${describeValue(command)}, expected an empty list on a ${NONE_STEP_SCOPE} step`;
701
152
  }
702
- return isTextList(command) && command.length > 0 ? null : `${at}.command is ${describeValue2(command)}, expected a non-empty list of arguments`;
153
+ return isTextList(command) && command.length > 0 ? null : `${at}.command is ${describeValue(command)}, expected a non-empty list of arguments`;
703
154
  }
704
155
  function noneStepProblems(step, at) {
705
156
  const exitCode = field(step, "exitCode");
706
157
  const failures = field(step, "failures");
707
158
  return [
708
- Number.isSafeInteger(exitCode) && exitCode !== 0 ? `${at}.exitCode is ${describeValue2(exitCode)}, expected 0 on a ${NONE_STEP_SCOPE} step` : null,
709
- Array.isArray(failures) && failures.length > 0 ? `${at}.failures is ${describeValue2(failures)}, expected none on a ${NONE_STEP_SCOPE} step` : null
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
710
161
  ].filter((problem) => problem !== null);
711
162
  }
712
163
  function stepProblems(step, at) {
713
164
  if (!isObject(step))
714
- return [`${at} is ${describeValue2(step)}, expected a step`];
165
+ return [`${at} is ${describeValue(step)}, expected a step`];
715
166
  const kind = field(step, "kind");
716
167
  const scope = field(step, "scope");
717
168
  const exitCode = field(step, "exitCode");
718
169
  const summary = field(step, "summary");
719
170
  const problems = [
720
- SESSION_STEP_KINDS.includes(kind) ? null : `${at}.kind is ${describeValue2(kind)}, expected one of ${SESSION_STEP_KINDS.join(", ")}`,
171
+ SESSION_STEP_KINDS.includes(kind) ? null : `${at}.kind is ${describeValue(kind)}, expected one of ${SESSION_STEP_KINDS.join(", ")}`,
721
172
  stepScopeProblem(scope, at),
722
173
  stepCommandProblem(field(step, "command"), scope, at),
723
- typeof exitCode === "number" && Number.isSafeInteger(exitCode) ? null : `${at}.exitCode is ${describeValue2(exitCode)}, expected a whole number`,
724
- summary === null || typeof summary === "string" ? null : `${at}.summary is ${describeValue2(summary)}, expected null or a string`,
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`,
725
176
  stepFailuresProblem(step, at),
726
177
  ...scope === NONE_STEP_SCOPE ? noneStepProblems(step, at) : [],
727
178
  stepInterruptedProblem(step, at)
@@ -733,14 +184,14 @@ function isLineIndex(value) {
733
184
  }
734
185
  function taskRefProblems(ref, at) {
735
186
  if (!isObject(ref))
736
- return [`${at} is ${describeValue2(ref)}, expected a task`];
187
+ return [`${at} is ${describeValue(ref)}, expected a task`];
737
188
  const lineNum = field(ref, "lineNum");
738
189
  const task = field(ref, "task");
739
190
  const ordinal = field(ref, "ordinal");
740
191
  return [
741
- isLineIndex(lineNum) ? null : `${at}.lineNum is ${describeValue2(lineNum)}, expected a whole number from 0`,
742
- isText(task) ? null : `${at}.task is ${describeValue2(task)}, expected a non-empty string`,
743
- 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`
744
195
  ].filter((problem) => problem !== null);
745
196
  }
746
197
  function afterProblems(decision, strategy, at) {
@@ -748,17 +199,17 @@ function afterProblems(decision, strategy, at) {
748
199
  if (strategy === "defer") {
749
200
  return after === undefined ? [`${at}.after is missing, expected the task a defer waits on`] : taskRefProblems(after, `${at}.after`);
750
201
  }
751
- 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`];
752
203
  }
753
204
  function decisionProblems(decision, at) {
754
205
  if (!isObject(decision))
755
- return [`${at} is ${describeValue2(decision)}, expected a decision`];
206
+ return [`${at} is ${describeValue(decision)}, expected a decision`];
756
207
  const strategy = field(decision, "strategy");
757
208
  const reason = field(decision, "reason");
758
209
  const problems = [
759
210
  ...taskRefProblems(field(decision, "task"), `${at}.task`),
760
- SESSION_DECISION_STRATEGIES.includes(strategy) ? null : `${at}.strategy is ${describeValue2(strategy)}, expected one of ${SESSION_DECISION_STRATEGIES.join(", ")}`,
761
- 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`,
762
213
  ...afterProblems(decision, strategy, at)
763
214
  ];
764
215
  return problems.filter((problem) => problem !== null);
@@ -768,7 +219,7 @@ function decisionsProblems(fields) {
768
219
  return [];
769
220
  const decisions = field(fields, "decisions");
770
221
  if (!Array.isArray(decisions))
771
- return [`decisions is ${describeValue2(decisions)}, expected a list of decisions`];
222
+ return [`decisions is ${describeValue(decisions)}, expected a list of decisions`];
772
223
  return decisions.flatMap((decision, index) => decisionProblems(decision, `decisions[${index}]`));
773
224
  }
774
225
  function stepsProblems(fields) {
@@ -776,20 +227,20 @@ function stepsProblems(fields) {
776
227
  return [];
777
228
  const steps = field(fields, "steps");
778
229
  if (!Array.isArray(steps))
779
- return [`steps is ${describeValue2(steps)}, expected a list of steps`];
230
+ return [`steps is ${describeValue(steps)}, expected a list of steps`];
780
231
  return steps.flatMap((step, index) => stepProblems(step, `steps[${index}]`));
781
232
  }
782
233
  function sessionIdProblem(sessionId, file) {
783
234
  if (typeof sessionId !== "string" || !isSessionId(sessionId)) {
784
- return `sessionId is ${describeValue2(sessionId)}, expected a plain file name`;
235
+ return `sessionId is ${describeValue(sessionId)}, expected a plain file name`;
785
236
  }
786
237
  return basename(file) === `${sessionId}${RECORD_EXTENSION}` ? null : `sessionId ${JSON.stringify(sessionId)} is not the file's name`;
787
238
  }
788
239
  function planStubProblem(planStub) {
789
- 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`;
790
241
  }
791
242
  function textProblems(fields) {
792
- 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`);
793
244
  }
794
245
  function recordProblems(fields, file) {
795
246
  const pid = field(fields, "pid");
@@ -799,9 +250,9 @@ function recordProblems(fields, file) {
799
250
  sessionIdProblem(field(fields, "sessionId"), file),
800
251
  planStubProblem(field(fields, "planStub")),
801
252
  ...textProblems(fields),
802
- isPositiveWhole(pid) ? null : `pid is ${describeValue2(pid)}, expected a whole number from 1`,
803
- typeof startedAt === "string" && !Number.isNaN(Date.parse(startedAt)) ? null : `startedAt is ${describeValue2(startedAt)}, expected a timestamp`,
804
- 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(", ")}`,
805
256
  taskProblem(field(fields, "task")),
806
257
  hopProblem(fields),
807
258
  worktreeProblem(fields),
@@ -1112,6 +563,7 @@ var CLAUDE_BASE_ARGS = [
1112
563
  "--dangerously-skip-permissions"
1113
564
  ];
1114
565
  var SETTING_SOURCES_FLAG = "--setting-sources";
566
+ var SESSION_ID_FLAG = "--session-id";
1115
567
  function claudeArgs(settingSources, flags = [], served = []) {
1116
568
  return [...CLAUDE_BASE_ARGS, SETTING_SOURCES_FLAG, settingSources.join(","), ...served, ...flags];
1117
569
  }
@@ -1128,10 +580,10 @@ function carriesFlag(flags, flag) {
1128
580
  return true;
1129
581
  return name.startsWith("no-") && flags[name.slice(3)] === false;
1130
582
  }
1131
- function spendWarning(running2) {
1132
- if (running2 === null)
583
+ function spendWarning(running) {
584
+ if (running === null)
1133
585
  return null;
1134
- const { command, flags } = running2;
586
+ const { command, flags } = running;
1135
587
  const spend = command.spends;
1136
588
  const named = `rafa ${commandSpelling(command)}`;
1137
589
  const remedy = "declare spends on the command to cover this run";
@@ -1238,6 +690,7 @@ function runClaudeCaptured(prompt, settingSources, flags = [], spawn = spawnClau
1238
690
  import { existsSync, readFileSync as readFileSync2, realpathSync } from "fs";
1239
691
  import { dirname as dirname2, join as join2, resolve } from "path";
1240
692
  var RAFA_PACKAGE_NAME = "@open-tomato/rafa";
693
+ var RUNTIME_SUBDIR = join2(".rafa", "runtime");
1241
694
  var MANIFEST = "package.json";
1242
695
  var CHECKOUT_ENTRY = join2("src", "rafa.ts");
1243
696
  function realOrResolved(path) {
@@ -2152,25 +1605,6 @@ function stampedValues(table) {
2152
1605
  return `${nextSeq}, ${STORE_ID}, CASE WHEN ${STORE_ID} IS NULL THEN NULL ELSE ${nextSeq} END`;
2153
1606
  }
2154
1607
 
2155
- // packages/rafa/src/effort/store/settings.ts
2156
- var DEFAULT_STORE_SETTINGS = Object.freeze({
2157
- busyTimeoutMs: CORE_SECTION.defaults.effortBusyTimeoutMs
2158
- });
2159
- var active2 = DEFAULT_STORE_SETTINGS;
2160
- function setActiveStoreSettings(settings) {
2161
- if (settings === null) {
2162
- active2 = DEFAULT_STORE_SETTINGS;
2163
- return;
2164
- }
2165
- if (!isBusyTimeoutMs(settings.busyTimeoutMs)) {
2166
- 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)}`);
2167
- }
2168
- active2 = Object.freeze({ busyTimeoutMs: settings.busyTimeoutMs });
2169
- }
2170
- function activeStoreSettings() {
2171
- return active2;
2172
- }
2173
-
2174
1608
  // packages/rafa/src/effort/store/store-meta.ts
2175
1609
  import { randomUUID as randomUUID2 } from "crypto";
2176
1610
  import { dirname as dirname6 } from "path";
@@ -2218,38 +1652,10 @@ function writeStoreGeneration(storePath, generation) {
2218
1652
  }
2219
1653
 
2220
1654
  // packages/rafa/src/effort/store/store-identity.ts
2221
- import { spawnSync as spawnSync4 } from "child_process";
1655
+ import { spawnSync } from "child_process";
2222
1656
  import { createHmac } from "crypto";
2223
1657
  import { readFileSync as readFileSync5, realpathSync as realpathSync3, statSync } from "fs";
2224
1658
  import { hostname, platform as currentPlatform } from "os";
2225
-
2226
- // packages/rafa/src/schema/project-id.ts
2227
- import { spawnSync as spawnSync3 } from "child_process";
2228
- var PROJECT_ID_LENGTH = 12;
2229
- var PROJECT_ID_PATTERN = new RegExp(`^[0-9a-f]{${PROJECT_ID_LENGTH}}$`);
2230
- function hasColonAfterAt(url) {
2231
- const at = url.indexOf("@");
2232
- return at !== -1 && url.lastIndexOf(":") > at;
2233
- }
2234
- function normalizeRemote(url) {
2235
- const stripped = url.replace(/:\/\/[^@]+@/, "://");
2236
- const network = !stripped.startsWith("file://") && (stripped.includes("://") || hasColonAfterAt(stripped));
2237
- const trimmed = stripped.replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//, "").replace(/^[^@/:]+@([^:/]+):/, "$1/").replace(/\.git\/?$/, "").replace(/\/+$/, "");
2238
- return network ? trimmed.toLowerCase() : trimmed;
2239
- }
2240
- function gitRemoteUrl(dir) {
2241
- const result = spawnSync3("git", ["remote", "get-url", "origin"], {
2242
- cwd: dir,
2243
- encoding: "utf8",
2244
- env: { ...process.env, LC_ALL: "C" }
2245
- });
2246
- if (result.error !== undefined || result.status !== 0)
2247
- return null;
2248
- const url = result.stdout.trim();
2249
- return url === "" ? null : url;
2250
- }
2251
-
2252
- // packages/rafa/src/effort/store/store-identity.ts
2253
1659
  var HOST_ID_KEY = "rafa effort store host id";
2254
1660
  var MACHINE_ID_PATH = "/etc/machine-id";
2255
1661
  var IOREG_PATH = "/usr/sbin/ioreg";
@@ -2270,7 +1676,7 @@ function parseIoregPlatformUuid(output) {
2270
1676
  return match?.[1] ?? null;
2271
1677
  }
2272
1678
  function readIoregPlatformUuid() {
2273
- const result = spawnSync4(IOREG_PATH, [...IOREG_ARGS], { encoding: "utf8" });
1679
+ const result = spawnSync(IOREG_PATH, [...IOREG_ARGS], { encoding: "utf8" });
2274
1680
  if (result.error !== undefined || result.status !== 0)
2275
1681
  return null;
2276
1682
  return parseIoregPlatformUuid(result.stdout);
@@ -2626,7 +2032,1039 @@ function openSqliteStore(repoRoot) {
2626
2032
  };
2627
2033
  }
2628
2034
 
2629
- // packages/rafa/src/effort/store/trusted-permissions.ts
2630
- 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
+ }
2631
3069
 
2632
- export { SPENDS_GLYPH, CommandExit, commandSpelling, createLinePrompter, lazyPrompter, HINT_FLAG, HINT_FLAG_SPEC, DEFAULT_CI_TIMEOUT_MIN, RAFA_VERSION, setActiveStoreSettings, activeStoreSettings, PORT_VERSIONS, createAdapterRegistry, registerAdapters, restoreAdapters, activeAdapterRegistry, CORE_ADAPTER_REGISTRY, readRuntimeIdentity, isRecord, asPlace, asHopRecord, SessionRecordError, isSessionId, sessionSteps, sessionDecisions, SessionConflictError, runsDir, sessionFilePath, errorCode, isPidAlive, readSessions, readSession, samePlan, beginSession, updateSession, claudeArgs, interruptClaudeSessions, spawnClaude, runClaude, spawnClaudeCaptured, runClaudeCaptured, effortStoreFileName, readStoreRows, collectedKeys, appendRows, EFFORT_DIR_VARIABLE, effortStoreDir, guardTestProcess, DEVELOPMENT_NEXT_STEP, appliedByName, DevelopmentBuildRefusedError, storeProjectRoot, refuseUnownedDevelopmentWrite, SQLITE_MIGRATIONS, sqliteCatalogue, planSchema, MIGRATION_LOG_TABLE, bringForward, readStoreSchema, writeNames, ACROSS_STORES_ORDER, STAMPED_COLUMNS, stampedValues, writeStoreGeneration, createGitRunner, gitSaid, commitTaskWork, PROJECT_ID_LENGTH, PROJECT_ID_PATTERN, normalizeRemote, gitRemoteUrl, readProjectIdentity, readReplacedStoreIds, readStoreMeta, carryStoreIdentity, EFFORT_KEY_PROJECTIONS, 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 };