@open-tomato/rafa 0.52.1 → 0.54.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 (40) hide show
  1. package/dist/PROMPT.md +7 -0
  2. package/dist/bundled/agents/loop-implementer.md +7 -1
  3. package/dist/bundled/operators/skills/rafa-stretch-gap-log/SKILL.md +16 -0
  4. package/dist/bundled/operators/skills/rafa-stretch-pit-stop/SKILL.md +14 -8
  5. package/dist/bundled/operators/skills/rafa-stretch-sweep/SKILL.md +4 -2
  6. package/dist/cli.js +4401 -2084
  7. package/dist/config/index.js +2 -2
  8. package/dist/config/shape.d.ts +7 -5
  9. package/dist/config-registry.d.ts +5 -5
  10. package/dist/config-schema-collaborate.d.ts +85 -0
  11. package/dist/config-schema-features.d.ts +2 -2
  12. package/dist/config-schema-hints.d.ts +53 -0
  13. package/dist/config-schema-hub.d.ts +5 -4
  14. package/dist/core/command/shared-flags.d.ts +1 -1
  15. package/dist/core/config/config-schema.d.ts +1 -1
  16. package/dist/core/config/config.d.ts +1 -1
  17. package/dist/core/git/index.d.ts +12 -5
  18. package/dist/core/git/placed-line.d.ts +86 -0
  19. package/dist/effort/session-log-path.d.ts +34 -0
  20. package/dist/effort/store/answered-rows.d.ts +38 -0
  21. package/dist/effort/store/index.js +5 -3
  22. package/dist/effort/store/merge-conflicts.d.ts +8 -4
  23. package/dist/effort/store/merge-rules.d.ts +16 -5
  24. package/dist/effort/store/merge-store.d.ts +14 -3
  25. package/dist/effort/store/origins.d.ts +5 -4
  26. package/dist/effort/store/repository-facts.d.ts +147 -0
  27. package/dist/effort/store/session-row-types.d.ts +6 -1
  28. package/dist/effort/store/sqlite.d.ts +11 -6
  29. package/dist/{index-4dwaxd5r.js → index-8rr1etrx.js} +10 -3
  30. package/dist/{index-nqaqh4zz.js → index-d772zq3m.js} +44 -4
  31. package/dist/{index-m672ptpg.js → index-dj8en7fg.js} +1 -1
  32. package/dist/{index-1tdzcheq.js → index-mkhbaye7.js} +306 -43
  33. package/dist/{index-4wy2nmyt.js → index-waawdjq2.js} +140 -119
  34. package/dist/index.js +1622 -564
  35. package/dist/learning/index.js +112 -53
  36. package/dist/ports/index.d.ts +5 -5
  37. package/dist/ports/learning.d.ts +28 -2
  38. package/dist/{ready-kac4ty0p.js → ready-9e1pyxdh.js} +3 -3
  39. package/dist/utils/shell.d.ts +17 -0
  40. package/package.json +12 -5
@@ -8,7 +8,7 @@ import {
8
8
  createGitRunner,
9
9
  normalizeRemote,
10
10
  runningCommand
11
- } from "./index-4dwaxd5r.js";
11
+ } from "./index-8rr1etrx.js";
12
12
  import {
13
13
  activeOutput,
14
14
  activeOutputMode,
@@ -17,7 +17,7 @@ import {
17
17
  import {
18
18
  SCOPE_DIR,
19
19
  scopeAt
20
- } from "./index-m672ptpg.js";
20
+ } from "./index-dj8en7fg.js";
21
21
  import {
22
22
  TEST_SCOPES,
23
23
  bundledBinDirectory,
@@ -35,12 +35,64 @@ var EFFORT_KEY_PROJECTIONS = {
35
35
 
36
36
  // packages/rafa/src/effort/store/sqlite.ts
37
37
  import { existsSync as existsSync4, mkdirSync as mkdirSync3 } from "fs";
38
- import { dirname as dirname7, join as join5 } from "path";
38
+ import { dirname as dirname7, join as join6 } from "path";
39
39
  import { Database as Database2 } from "bun:sqlite";
40
40
 
41
+ // packages/rafa/src/effort/session-log-path.ts
42
+ import { posix } from "path";
43
+ var { isAbsolute, join, normalize } = posix;
44
+ var PROJECT_LOG_SEGMENTS = [".claude", "projects"];
45
+ var PROJECT_LOG_MARKER = `/${PROJECT_LOG_SEGMENTS.join("/")}/`;
46
+ var WINDOWS_SEPARATOR = "\\";
47
+ var PARENT_SEGMENT = "..";
48
+ function isStoredRelative(value) {
49
+ if (value === "" || value.includes(WINDOWS_SEPARATOR))
50
+ return false;
51
+ if (isAbsolute(value))
52
+ return false;
53
+ const normalized = normalize(value);
54
+ if (normalized === "." || normalized === PARENT_SEGMENT)
55
+ return false;
56
+ return !normalized.startsWith(`${PARENT_SEGMENT}/`);
57
+ }
58
+ function projectLogRoot(home) {
59
+ return join(home, ...PROJECT_LOG_SEGMENTS);
60
+ }
61
+ function storedLogPath(absolutePath, home) {
62
+ if (!isAbsolute(absolutePath) || !isAbsolute(home))
63
+ return absolutePath;
64
+ const prefix = `${projectLogRoot(home)}/`;
65
+ if (!absolutePath.startsWith(prefix))
66
+ return absolutePath;
67
+ const rest = absolutePath.slice(prefix.length);
68
+ return isStoredRelative(rest) ? rest : absolutePath;
69
+ }
70
+ function storedLogPathOf(value) {
71
+ if (typeof value !== "string" || !isAbsolute(value))
72
+ return value;
73
+ const at = value.lastIndexOf(PROJECT_LOG_MARKER);
74
+ if (at === -1)
75
+ return value;
76
+ const rest = value.slice(at + PROJECT_LOG_MARKER.length);
77
+ return isStoredRelative(rest) ? rest : value;
78
+ }
79
+
80
+ // packages/rafa/src/effort/store/answered-rows.ts
81
+ function answeredSession(row) {
82
+ if (!("filePath" in row))
83
+ return row;
84
+ const filePath = storedLogPathOf(row.filePath);
85
+ return filePath === row.filePath ? row : { ...row, filePath };
86
+ }
87
+ function answeredRows(kind, rows) {
88
+ if (kind !== "sessions")
89
+ return [...rows];
90
+ return rows.map(answeredSession);
91
+ }
92
+
41
93
  // packages/rafa/src/effort/store/development-build.ts
42
94
  import { tmpdir as tmpdir2 } from "os";
43
- import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute3 } from "path";
95
+ import { basename as basename3, dirname as dirname5, isAbsolute as isAbsolute4 } from "path";
44
96
 
45
97
  // packages/rafa/src/core/loop/sessions.ts
46
98
  import {
@@ -52,10 +104,10 @@ import {
52
104
  rmSync,
53
105
  writeFileSync
54
106
  } from "fs";
55
- import { dirname, join } from "path";
107
+ import { dirname, join as join2 } from "path";
56
108
 
57
109
  // packages/rafa/src/core/loop/session-record-parse.ts
58
- import { basename, isAbsolute } from "path";
110
+ import { basename, isAbsolute as isAbsolute2 } from "path";
59
111
  var SESSION_STATES = Object.freeze(["running", "paused", "stopped", "done"]);
60
112
  var SESSION_PHASES = Object.freeze(["task", "wrap-up", "pull-request", "ci", "repair"]);
61
113
  var RECORD_EXTENSION = ".json";
@@ -111,7 +163,7 @@ function worktreeProblem(fields) {
111
163
  if (!Object.hasOwn(fields, "worktree"))
112
164
  return null;
113
165
  const worktree = field(fields, "worktree");
114
- return isText(worktree) && isAbsolute(worktree) ? null : `worktree is ${describeValue(worktree)}, expected an absolute path`;
166
+ return isText(worktree) && isAbsolute2(worktree) ? null : `worktree is ${describeValue(worktree)}, expected an absolute path`;
115
167
  }
116
168
  function isTextList(value) {
117
169
  return Array.isArray(value) && value.every(isText);
@@ -425,13 +477,13 @@ class SessionStateError extends Error {
425
477
  }
426
478
  }
427
479
  function runsDir(root) {
428
- return join(scopeAt(root).dir, RUNS_DIR);
480
+ return join2(scopeAt(root).dir, RUNS_DIR);
429
481
  }
430
482
  function sessionFilePath(root, sessionId) {
431
483
  if (!isSessionId(sessionId)) {
432
484
  throw new Error(`session record: unusable session id ${JSON.stringify(sessionId)}`);
433
485
  }
434
- return join(runsDir(root), `${sessionId}${RECORD_EXTENSION}`);
486
+ return join2(runsDir(root), `${sessionId}${RECORD_EXTENSION}`);
435
487
  }
436
488
  function errorCode(error) {
437
489
  return typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : null;
@@ -475,7 +527,7 @@ function byStart(a, b) {
475
527
  function readSessions(root, seams = {}) {
476
528
  const dir = runsDir(root);
477
529
  const isAlive = seams.isAlive ?? isPidAlive;
478
- const records = recordNames(dir).filter((name) => name.endsWith(RECORD_EXTENSION)).map((name) => readRecordFile(join(dir, name))).map((record) => Object.freeze({ ...record, state: readState(record, isAlive) }));
530
+ const records = recordNames(dir).filter((name) => name.endsWith(RECORD_EXTENSION)).map((name) => readRecordFile(join2(dir, name))).map((record) => Object.freeze({ ...record, state: readState(record, isAlive) }));
479
531
  return Object.freeze(records.sort(byStart));
480
532
  }
481
533
  function readSession(root, sessionId, seams = {}) {
@@ -688,11 +740,11 @@ function runClaudeCaptured(prompt, settingSources, flags = [], spawn = spawnClau
688
740
  }
689
741
  // packages/rafa/src/core/runtime/identity.ts
690
742
  import { existsSync, readFileSync as readFileSync2, realpathSync } from "fs";
691
- import { dirname as dirname2, join as join2, resolve } from "path";
743
+ import { dirname as dirname2, join as join3, resolve } from "path";
692
744
  var RAFA_PACKAGE_NAME = "@open-tomato/rafa";
693
- var RUNTIME_SUBDIR = join2(".rafa", "runtime");
745
+ var RUNTIME_SUBDIR = join3(".rafa", "runtime");
694
746
  var MANIFEST = "package.json";
695
- var CHECKOUT_ENTRY = join2("src", "rafa.ts");
747
+ var CHECKOUT_ENTRY = join3("src", "rafa.ts");
696
748
  function realOrResolved(path) {
697
749
  const resolved = resolve(path);
698
750
  return existsSync(resolved) ? realpathSync(resolved) : resolved;
@@ -712,7 +764,7 @@ function manifestName(file) {
712
764
  function nearestRafaPackage(start) {
713
765
  let dir = start;
714
766
  for (;; ) {
715
- const manifest = join2(dir, MANIFEST);
767
+ const manifest = join3(dir, MANIFEST);
716
768
  if (existsSync(manifest) && manifestName(manifest) === RAFA_PACKAGE_NAME)
717
769
  return dir;
718
770
  const parent = dirname2(dir);
@@ -724,7 +776,7 @@ function nearestRafaPackage(start) {
724
776
  function readRuntimeIdentity(entry = Bun.main) {
725
777
  const real = realOrResolved(entry);
726
778
  const packageDir = nearestRafaPackage(dirname2(real));
727
- if (packageDir !== null && existsSync(join2(packageDir, CHECKOUT_ENTRY))) {
779
+ if (packageDir !== null && existsSync(join3(packageDir, CHECKOUT_ENTRY))) {
728
780
  return { kind: "development", entry: real, checkout: packageDir };
729
781
  }
730
782
  return { kind: "installed", entry: real };
@@ -732,7 +784,7 @@ function readRuntimeIdentity(entry = Bun.main) {
732
784
  // packages/rafa/src/effort/store/location.ts
733
785
  import { existsSync as existsSync3, realpathSync as realpathSync2 } from "fs";
734
786
  import { tmpdir } from "os";
735
- import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute2, join as join4, relative, resolve as resolve2, sep } from "path";
787
+ import { basename as basename2, dirname as dirname4, isAbsolute as isAbsolute3, join as join5, relative, resolve as resolve2, sep } from "path";
736
788
 
737
789
  // packages/rafa/src/effort/store/ndjson-files.ts
738
790
  import {
@@ -741,8 +793,8 @@ import {
741
793
  mkdirSync as mkdirSync2,
742
794
  readFileSync as readFileSync3
743
795
  } from "fs";
744
- import { dirname as dirname3, join as join3 } from "path";
745
- var EFFORT_STORE_DIR = join3(".rafa", "effort");
796
+ import { dirname as dirname3, join as join4 } from "path";
797
+ var EFFORT_STORE_DIR = join4(".rafa", "effort");
746
798
  var STORE_FILE_NAMES = {
747
799
  sessions: "sessions.ndjson",
748
800
  commits: "commits.ndjson"
@@ -854,27 +906,27 @@ function realPathOf(path) {
854
906
  if (existsSync3(resolved))
855
907
  return realpathSync2(resolved);
856
908
  const parent = dirname4(resolved);
857
- return parent === resolved ? resolved : join4(realPathOf(parent), basename2(resolved));
909
+ return parent === resolved ? resolved : join5(realPathOf(parent), basename2(resolved));
858
910
  }
859
911
  function isWithin(path, dir) {
860
912
  const between = relative(resolve2(dir), resolve2(path));
861
913
  const climbsOut = between === ".." || between.startsWith(`..${sep}`);
862
- return !climbsOut && !isAbsolute2(between);
914
+ return !climbsOut && !isAbsolute3(between);
863
915
  }
864
916
  function readEffortDirOverride(repoRoot, env = process.env) {
865
917
  const value = env[EFFORT_DIR_VARIABLE];
866
918
  if (value === undefined || value === "")
867
919
  return null;
868
- if (!isAbsolute2(value)) {
920
+ if (!isAbsolute3(value)) {
869
921
  throw new Error(`effort store: ${EFFORT_DIR_VARIABLE} is not an absolute path (${value}); run this command again` + ` with ${EFFORT_DIR_VARIABLE} set to the absolute path 'rafa effort copy' printed.`);
870
922
  }
871
- if (canonical(value) === canonical(join4(repoRoot, EFFORT_STORE_DIR))) {
923
+ if (canonical(value) === canonical(join5(repoRoot, EFFORT_STORE_DIR))) {
872
924
  throw new Error(`effort store: ${EFFORT_DIR_VARIABLE} names this project's own store (${value}); it points a command` + " at a copy only. Copy the store with 'rafa effort copy' and run this command with" + ` ${EFFORT_DIR_VARIABLE}=<the copy>.`);
873
925
  }
874
926
  return value;
875
927
  }
876
928
  function effortStoreDir(repoRoot, env = process.env) {
877
- return readEffortDirOverride(repoRoot, env) ?? join4(repoRoot, EFFORT_STORE_DIR);
929
+ return readEffortDirOverride(repoRoot, env) ?? join5(repoRoot, EFFORT_STORE_DIR);
878
930
  }
879
931
  function isTestProcess(main = Bun.main, env = process.env) {
880
932
  return main.endsWith(TEST_ENTRY_SUFFIX) || env[TEST_PROCESS_VARIABLE] === "1";
@@ -923,7 +975,7 @@ function isOwnedStore(path, env, tempDir) {
923
975
  if (isUnderTempDir(path, tempDir))
924
976
  return true;
925
977
  const override = env[EFFORT_DIR_VARIABLE];
926
- if (override === undefined || override === "" || !isAbsolute3(override))
978
+ if (override === undefined || override === "" || !isAbsolute4(override))
927
979
  return false;
928
980
  return storeProjectRoot(path) === null && isUnderTempDir(path, override);
929
981
  }
@@ -1394,6 +1446,28 @@ var SQLITE_MIGRATIONS = [
1394
1446
  ON bug_routes (origin_store, origin_seq)
1395
1447
  WHERE origin_store IS NOT NULL;
1396
1448
  `
1449
+ },
1450
+ {
1451
+ id: "reading-supersedes",
1452
+ breaks: [],
1453
+ sql: `
1454
+ CREATE TABLE reading_supersedes (
1455
+ seq INTEGER PRIMARY KEY,
1456
+ table_name TEXT NOT NULL CHECK (table_name <> ''),
1457
+ canonical_key TEXT NOT NULL CHECK (canonical_key <> ''),
1458
+ superseded_key TEXT NOT NULL CHECK (superseded_key <> ''),
1459
+ rule TEXT NOT NULL CHECK (rule <> ''),
1460
+ origin_store TEXT CHECK (origin_store <> ''),
1461
+ origin_seq INTEGER
1462
+ );
1463
+
1464
+ CREATE UNIQUE INDEX reading_supersedes_by_fact
1465
+ ON reading_supersedes (table_name, canonical_key, superseded_key);
1466
+
1467
+ CREATE UNIQUE INDEX reading_supersedes_by_origin
1468
+ ON reading_supersedes (origin_store, origin_seq)
1469
+ WHERE origin_store IS NOT NULL;
1470
+ `
1397
1471
  }
1398
1472
  ];
1399
1473
  var SQLITE_SCHEMA_VERSION = SQLITE_MIGRATIONS.length;
@@ -1918,7 +1992,7 @@ function carryStoreIdentity(livePath, parallelPath, seams = {}) {
1918
1992
  // packages/rafa/src/effort/store/sqlite.ts
1919
1993
  var SQLITE_STORE_FILE_NAME = "effort.sqlite";
1920
1994
  function sqliteStorePath(repoRoot) {
1921
- return join5(effortStoreDir(repoRoot), SQLITE_STORE_FILE_NAME);
1995
+ return join6(effortStoreDir(repoRoot), SQLITE_STORE_FILE_NAME);
1922
1996
  }
1923
1997
  var KIND_TABLES = {
1924
1998
  sessions: {
@@ -2020,7 +2094,7 @@ function readKind(path, kind) {
2020
2094
  return [];
2021
2095
  const { name } = KIND_TABLES[kind];
2022
2096
  const stored = withSqliteStore(path, "read", false, (db) => db.query(`SELECT seq, row_json AS body FROM ${name} ORDER BY seq`).all());
2023
- return stored.map(({ seq, body }) => rowOf(body, `${path}: ${name} row ${seq}`));
2097
+ return answeredRows(kind, stored.map(({ seq, body }) => rowOf(body, `${path}: ${name} row ${seq}`)));
2024
2098
  }
2025
2099
  function openSqliteStore(repoRoot) {
2026
2100
  const path = sqliteStorePath(repoRoot);
@@ -2035,7 +2109,7 @@ function openSqliteStore(repoRoot) {
2035
2109
  // packages/rafa/src/effort/store/wire.ts
2036
2110
  import { existsSync as existsSync7, mkdtempSync, rmSync as rmSync5 } from "fs";
2037
2111
  import { tmpdir as tmpdir3 } from "os";
2038
- import { join as join7 } from "path";
2112
+ import { join as join8 } from "path";
2039
2113
  import { Database as Database4, SQLiteError } from "bun:sqlite";
2040
2114
 
2041
2115
  // packages/rafa/src/effort/store/merge-rules.ts
@@ -2046,7 +2120,7 @@ function appendOnly(...identity) {
2046
2120
  return { scope: "merged", identity, edited: APPEND_ONLY };
2047
2121
  }
2048
2122
  var MERGE_RULES = {
2049
- sessions: appendOnly("session_id"),
2123
+ sessions: { scope: "merged", identity: ["session_id"], edited: { row_json: RECOMPUTED } },
2050
2124
  commits: { scope: "merged", identity: ["sha"], edited: { row_json: RECOMPUTED } },
2051
2125
  findings: { scope: "merged", identity: ["id"], edited: { tracker_ref: SET_ONCE } },
2052
2126
  blockers: appendOnly("id"),
@@ -2060,6 +2134,7 @@ var MERGE_RULES = {
2060
2134
  plan_ci: appendOnly("pr", "head_sha", "read_at"),
2061
2135
  stale_docs: appendOnly("id"),
2062
2136
  bug_routes: appendOnly("id"),
2137
+ reading_supersedes: appendOnly("table_name", "canonical_key", "superseded_key"),
2063
2138
  schema_migrations: { scope: "local" },
2064
2139
  store_meta: { scope: "local" },
2065
2140
  store_replaced: { scope: "local" },
@@ -2072,7 +2147,7 @@ import { closeSync, existsSync as existsSync6, fsyncSync, openSync, renameSync a
2072
2147
 
2073
2148
  // packages/rafa/src/effort/store/copy.ts
2074
2149
  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";
2150
+ import { join as join7, resolve as resolve3 } from "path";
2076
2151
  import { Database as Database3 } from "bun:sqlite";
2077
2152
  var NDJSON_KINDS = { sessions: true, commits: true };
2078
2153
  var EFFORT_COPY_FILE_NAMES = [
@@ -2116,16 +2191,16 @@ function vacuumInto(source, target) {
2116
2191
  }
2117
2192
  function copyOne(name, source, target) {
2118
2193
  if (name === SQLITE_STORE_FILE_NAME) {
2119
- vacuumInto(join6(source, name), join6(target, name));
2194
+ vacuumInto(join7(source, name), join7(target, name));
2120
2195
  return;
2121
2196
  }
2122
- copyFileSync(join6(source, name), join6(target, name), constants.COPYFILE_EXCL);
2197
+ copyFileSync(join7(source, name), join7(target, name), constants.COPYFILE_EXCL);
2123
2198
  }
2124
2199
  function undo(target, written, madeDir) {
2125
2200
  try {
2126
2201
  if (madeDir === undefined) {
2127
2202
  for (const name of written)
2128
- rmSync3(join6(target, name), { force: true });
2203
+ rmSync3(join7(target, name), { force: true });
2129
2204
  } else {
2130
2205
  rmSync3(madeDir, { recursive: true, force: true });
2131
2206
  }
@@ -2139,7 +2214,7 @@ function copyEffortStore(request) {
2139
2214
  const target = resolve3(request.target);
2140
2215
  guardTestProcess(source);
2141
2216
  guardTestProcess(target);
2142
- const files = EFFORT_COPY_FILE_NAMES.filter((name) => existsSync5(join6(source, name)));
2217
+ const files = EFFORT_COPY_FILE_NAMES.filter((name) => existsSync5(join7(source, name)));
2143
2218
  if (files.length === 0) {
2144
2219
  throw new EffortCopyRefusal(`no effort store at ${source}: it holds none of ${EFFORT_COPY_FILE_NAMES.join(", ")}. Nothing to copy.`);
2145
2220
  }
@@ -2292,6 +2367,7 @@ function rebuildAside(options) {
2292
2367
  }
2293
2368
 
2294
2369
  // packages/rafa/src/effort/store/wire.ts
2370
+ var WIRE_CONTRACT_VERSION = 1;
2295
2371
  var WIRE_FORMAT = "rafa-effort-wire";
2296
2372
  var WIRE_VERSION = 1;
2297
2373
 
@@ -2510,9 +2586,9 @@ function buildStore(path, payload, options) {
2510
2586
  }
2511
2587
  function materialiseWirePayload(payload, options = {}) {
2512
2588
  const checked = checkPayload(payload);
2513
- const directory = mkdtempSync(join7(options.tempDir ?? tmpdir3(), "rafa-wire-"));
2589
+ const directory = mkdtempSync(join8(options.tempDir ?? tmpdir3(), "rafa-wire-"));
2514
2590
  const release = () => rmSync5(directory, { recursive: true, force: true });
2515
- const path = join7(directory, SQLITE_STORE_FILE_NAME);
2591
+ const path = join8(directory, SQLITE_STORE_FILE_NAME);
2516
2592
  try {
2517
2593
  guardTestProcess(path);
2518
2594
  buildStore(path, checked, options);
@@ -2527,7 +2603,7 @@ function materialiseWirePayload(payload, options = {}) {
2527
2603
  import { randomUUID as randomUUID3 } from "crypto";
2528
2604
  import { existsSync as existsSync8, mkdtempSync as mkdtempSync2, rmSync as rmSync6 } from "fs";
2529
2605
  import { tmpdir as tmpdir4 } from "os";
2530
- import { dirname as dirname8, join as join8 } from "path";
2606
+ import { dirname as dirname8, join as join9 } from "path";
2531
2607
  import { Database as Database6, SQLiteError as SQLiteError3 } from "bun:sqlite";
2532
2608
 
2533
2609
  // packages/rafa/src/effort/store/fix-schema.ts
@@ -2726,7 +2802,21 @@ function unionStores(local, other) {
2726
2802
  var SET_ONCE_FILLS = {
2727
2803
  "findings.tracker_ref": "UPDATE findings SET tracker_ref = ? WHERE seq = ? AND tracker_ref IS NULL"
2728
2804
  };
2805
+ var LOG_PATH_FIELD = "filePath";
2806
+ function withStoredLogPath(rowJson) {
2807
+ let row;
2808
+ try {
2809
+ row = JSON.parse(rowJson);
2810
+ } catch {
2811
+ return rowJson;
2812
+ }
2813
+ if (typeof row !== "object" || row === null || Array.isArray(row) || !Object.hasOwn(row, LOG_PATH_FIELD))
2814
+ return rowJson;
2815
+ const entries = Object.entries(row).map(([key, value]) => key === LOG_PATH_FIELD ? [key, storedLogPathOf(value)] : [key, value]);
2816
+ return JSON.stringify(Object.fromEntries(entries));
2817
+ }
2729
2818
  var RECOMPUTED_COMPARISONS = {
2819
+ "sessions.row_json": withStoredLogPath,
2730
2820
  "commits.row_json": withoutGap
2731
2821
  };
2732
2822
  var NOT_CONTENT = new Set(["seq", "origin_store", "origin_seq"]);
@@ -2827,6 +2917,163 @@ function liveLoop(path, options, nothingDone = "Nothing was migrated.", ownSessi
2827
2917
  return records.find((record) => (record.state === "running" || record.state === "paused") && record.sessionId !== ownSessionId);
2828
2918
  }
2829
2919
 
2920
+ // packages/rafa/src/effort/store/repository-facts.ts
2921
+ var REPOSITORY_FACTS = {
2922
+ plan_ci: { facts: ["pr", "head_sha", "verdict", "failing"], time: "read_at" }
2923
+ };
2924
+ var SAME_FACT_RULE = "same-fact@1";
2925
+ var INSERT_SUPERSEDE = `
2926
+ INSERT INTO reading_supersedes (table_name, canonical_key, superseded_key, rule, ${STAMPED_COLUMNS})
2927
+ VALUES (?, ?, ?, ?, ${stampedValues("reading_supersedes")})
2928
+ ON CONFLICT (table_name, canonical_key, superseded_key) DO NOTHING
2929
+ `;
2930
+ var SUPERSEDED = `
2931
+ SELECT 1 AS held FROM reading_supersedes
2932
+ WHERE table_name = ? AND rule = ? AND superseded_key = ?
2933
+ LIMIT 1
2934
+ `;
2935
+ function refused2(table, reason) {
2936
+ return new Error(`effort store: repository facts of ${table} ${reason}`);
2937
+ }
2938
+ function factTableOf(table) {
2939
+ const columns = Object.hasOwn(REPOSITORY_FACTS, table) ? REPOSITORY_FACTS[table] : undefined;
2940
+ if (columns === undefined)
2941
+ throw refused2(table, "are not read: the table has no REPOSITORY_FACTS entry");
2942
+ const rule = MERGE_RULES[table];
2943
+ if (rule?.scope !== "merged")
2944
+ throw refused2(table, "are not read: the table is no merged table of MERGE_RULES");
2945
+ return { name: table, identity: rule.identity, facts: columns.facts, time: columns.time };
2946
+ }
2947
+ function jsonPart(table, column, value) {
2948
+ if (value === null || typeof value === "string")
2949
+ return value;
2950
+ if (typeof value === "number" && Number.isFinite(value))
2951
+ return value;
2952
+ throw refused2(table, `cannot name a reading by ${column}: its value is not text, a finite number or NULL`);
2953
+ }
2954
+ function encode(table, columns, row) {
2955
+ return JSON.stringify(columns.map((column) => jsonPart(table, column, row[column])));
2956
+ }
2957
+ function readingKey(table, row) {
2958
+ return encode(table, factTableOf(table).identity, row);
2959
+ }
2960
+ function decodeKey(shape, key) {
2961
+ let parsed;
2962
+ try {
2963
+ parsed = JSON.parse(key);
2964
+ } catch {
2965
+ parsed = undefined;
2966
+ }
2967
+ if (!Array.isArray(parsed) || parsed.length !== shape.identity.length) {
2968
+ throw refused2(shape.name, `cannot read key ${key}: not a JSON array of ${String(shape.identity.length)} identity values`);
2969
+ }
2970
+ return parsed.map((value, index) => jsonPart(shape.name, shape.identity[index] ?? "", value));
2971
+ }
2972
+ function selectedColumns(shape) {
2973
+ const columns = [...new Set([...shape.identity, ...shape.facts, shape.time])];
2974
+ return [...columns.map(quoted), "origin_store"].join(", ");
2975
+ }
2976
+ function readingsWhere(shape, columns) {
2977
+ const where = columns.map((column) => `${quoted(column)} IS ?`).join(" AND ");
2978
+ return `SELECT ${selectedColumns(shape)} FROM ${quoted(shape.name)} WHERE ${where}`;
2979
+ }
2980
+ function readingOf(shape, row) {
2981
+ const time = row[shape.time];
2982
+ if (typeof time !== "string")
2983
+ throw refused2(shape.name, `hold a reading whose ${shape.time} is not text`);
2984
+ const origin = row.origin_store;
2985
+ return {
2986
+ key: encode(shape.name, shape.identity, row),
2987
+ fact: Object.fromEntries(shape.facts.map((column) => [column, row[column] ?? null])),
2988
+ time,
2989
+ origin: typeof origin === "string" ? origin : null
2990
+ };
2991
+ }
2992
+ function readBefore(left, right) {
2993
+ if (left.time !== right.time)
2994
+ return left.time < right.time;
2995
+ return left.key < right.key;
2996
+ }
2997
+ function earliestOf(readings) {
2998
+ return readings.reduce((earliest, reading) => earliest === undefined || readBefore(reading, earliest) ? reading : earliest, undefined);
2999
+ }
3000
+ function writeSupersedes(db, table, touchedKeys) {
3001
+ const shape = factTableOf(table);
3002
+ const byKey = db.query(readingsWhere(shape, shape.identity));
3003
+ const byFact = db.query(readingsWhere(shape, shape.facts));
3004
+ const superseded = db.query(SUPERSEDED);
3005
+ const insert = db.query(INSERT_SUPERSEDE);
3006
+ const facts = new Map;
3007
+ for (const key of touchedKeys) {
3008
+ const row = byKey.get(...decodeKey(shape, key));
3009
+ if (row === null)
3010
+ throw refused2(table, `name no reading by key ${key}`);
3011
+ const reading = readingOf(shape, row);
3012
+ const fact = encode(table, shape.facts, row);
3013
+ if (!facts.has(fact))
3014
+ facts.set(fact, reading);
3015
+ }
3016
+ let added = 0;
3017
+ for (const touched of facts.values()) {
3018
+ const readings = byFact.all(...shape.facts.map((column) => touched.fact[column] ?? null)).map((row) => readingOf(shape, row));
3019
+ const canonical2 = earliestOf(readings) ?? touched;
3020
+ for (const reading of readings) {
3021
+ if (reading.key === canonical2.key)
3022
+ continue;
3023
+ if (superseded.get(table, SAME_FACT_RULE, reading.key) !== null)
3024
+ continue;
3025
+ added += insert.run(table, canonical2.key, reading.key, SAME_FACT_RULE).changes;
3026
+ }
3027
+ }
3028
+ return added;
3029
+ }
3030
+ function supersedeTargets(db, table, readings) {
3031
+ const rows = db.query("SELECT canonical_key, superseded_key FROM reading_supersedes WHERE table_name = ? AND rule = ? ORDER BY seq").all(table, SAME_FACT_RULE);
3032
+ const targets = new Map;
3033
+ for (const { canonical_key: canonicalKey, superseded_key: supersededKey } of rows) {
3034
+ const canonical2 = readings.get(canonicalKey);
3035
+ if (canonical2 === undefined || !readings.has(supersededKey) || canonicalKey === supersededKey)
3036
+ continue;
3037
+ targets.set(supersededKey, [...targets.get(supersededKey) ?? [], canonical2]);
3038
+ }
3039
+ return targets;
3040
+ }
3041
+ function chainEnd(start, targets) {
3042
+ const path = [start];
3043
+ for (;; ) {
3044
+ const current = path[path.length - 1] ?? start;
3045
+ const next = earliestOf(targets.get(current.key) ?? []);
3046
+ if (next === undefined)
3047
+ return current;
3048
+ const seen = path.findIndex(({ key }) => key === next.key);
3049
+ if (seen >= 0)
3050
+ return earliestOf(path.slice(seen)) ?? next;
3051
+ path.push(next);
3052
+ }
3053
+ }
3054
+ function factOf(table, canonical2, readings) {
3055
+ const origins = [...new Set(readings.flatMap(({ origin }) => origin === null ? [] : [origin]))].sort();
3056
+ const lastSighting = readings.reduce((latest, { time }) => time > latest ? time : latest, canonical2.time);
3057
+ return { table, canonical: canonical2, sightings: readings.length - 1, origins, lastSighting };
3058
+ }
3059
+ function readRepositoryFacts(db, table) {
3060
+ const shape = factTableOf(table);
3061
+ const rows = db.query(`SELECT ${selectedColumns(shape)} FROM ${quoted(table)}`).all();
3062
+ const readings = new Map(rows.map((row) => {
3063
+ const reading = readingOf(shape, row);
3064
+ return [reading.key, reading];
3065
+ }));
3066
+ const targets = supersedeTargets(db, table, readings);
3067
+ const groups = new Map;
3068
+ for (const reading of readings.values()) {
3069
+ const canonical2 = chainEnd(reading, targets);
3070
+ const group = groups.get(canonical2.key) ?? { canonical: canonical2, readings: [] };
3071
+ group.readings.push(reading);
3072
+ groups.set(canonical2.key, group);
3073
+ }
3074
+ return [...groups.values()].sort((left, right) => readBefore(left.canonical, right.canonical) ? -1 : 1).map(({ canonical: canonical2, readings: grouped }) => factOf(table, canonical2, grouped));
3075
+ }
3076
+
2830
3077
  // packages/rafa/src/effort/store/merge-store.ts
2831
3078
  var MOVE_TO_SQLITE = "rafa effort move --to=sqlite";
2832
3079
 
@@ -2840,6 +3087,7 @@ class MergeRefusal extends RebuildRefusal {
2840
3087
  }
2841
3088
  var LIVE = "live";
2842
3089
  var MERGES_TABLE = "merges";
3090
+ var SUPERSEDES_TABLE = "reading_supersedes";
2843
3091
  var INSERT_MERGE = `INSERT INTO merges (id, other_store, merged_at, rows_added, rows_skipped, rows_in_conflict)
2844
3092
  VALUES (?, ?, ?, ?, ?, ?)`;
2845
3093
  var NOTHING_MERGED = "Nothing was merged.";
@@ -2907,13 +3155,13 @@ function openOther(otherPath, plan, stamp, tempRoot) {
2907
3155
  const db = new Database6(otherPath, { readonly: true });
2908
3156
  return { db, broughtForward: [], release: () => db.close() };
2909
3157
  }
2910
- const dir = mkdtempSync2(join8(tempRoot, "rafa-merge-other-"));
3158
+ const dir = mkdtempSync2(join9(tempRoot, "rafa-merge-other-"));
2911
3159
  const release = (db) => {
2912
3160
  db?.close();
2913
3161
  rmSync6(dir, { recursive: true, force: true });
2914
3162
  };
2915
3163
  try {
2916
- const copyPath = join8(dir, "other.sqlite");
3164
+ const copyPath = join9(dir, "other.sqlite");
2917
3165
  vacuumInto(otherPath, copyPath);
2918
3166
  const db = new Database6(copyPath, { readwrite: true });
2919
3167
  try {
@@ -2928,16 +3176,31 @@ function openOther(otherPath, plan, stamp, tempRoot) {
2928
3176
  throw error;
2929
3177
  }
2930
3178
  }
3179
+ function addedKeys(db, { table, added }) {
3180
+ const columns = carriedColumns(db, table).map(quoted).join(", ");
3181
+ const bySeq = db.query(`SELECT ${columns} FROM ${quoted(table)} WHERE seq = ?`);
3182
+ return added.map((seq) => {
3183
+ const row = bySeq.get(seq);
3184
+ if (row === null)
3185
+ throw new Error(`effort store: the merge added ${table} row ${String(seq)} and cannot read it back`);
3186
+ return readingKey(table, row);
3187
+ });
3188
+ }
3189
+ function writeMergedSupersedes(db, unions) {
3190
+ return unions.filter((union) => Object.hasOwn(REPOSITORY_FACTS, union.table) && union.added.length > 0).reduce((written, union) => written + writeSupersedes(db, union.table, addedKeys(db, union)), 0);
3191
+ }
2931
3192
  function mergeInto(db, other, mergeId, otherStore, mergedAt) {
2932
3193
  return db.transaction(() => {
2933
3194
  const unions = unionStores(db, other);
2934
3195
  const settlements = settleMatches(db, other, unions, { mergeId, recordedAt: mergedAt });
2935
3196
  const gaps = recomputeCommitGaps(db, unions.find(({ table }) => table === "commits")?.added ?? []);
3197
+ const supersedes = writeMergedSupersedes(db, unions);
2936
3198
  const tables = unions.map((union, index) => {
2937
3199
  const settled = settlements[index];
3200
+ const written = union.table === SUPERSEDES_TABLE ? supersedes : 0;
2938
3201
  return {
2939
3202
  table: union.table,
2940
- added: union.added.length,
3203
+ added: union.added.length + written,
2941
3204
  skipped: settled?.skipped.length ?? 0,
2942
3205
  inConflict: settled?.conflicts.length ?? 0,
2943
3206
  filled: settled?.filled.length ?? 0,
@@ -3020,9 +3283,9 @@ function mergeStore(options) {
3020
3283
  }
3021
3284
 
3022
3285
  // packages/rafa/src/effort/store/ndjson.ts
3023
- import { join as join9 } from "path";
3286
+ import { join as join10 } from "path";
3024
3287
  function kindPath(repoRoot, kind) {
3025
- return join9(effortStoreDir(repoRoot), effortStoreFileName(kind));
3288
+ return join10(effortStoreDir(repoRoot), effortStoreFileName(kind));
3026
3289
  }
3027
3290
  function openedKindPath(repoRoot, kind) {
3028
3291
  const path = kindPath(repoRoot, kind);
@@ -3044,7 +3307,7 @@ function openNdjsonStore(repoRoot) {
3044
3307
  return {
3045
3308
  append: (kind, rows) => appendKind2(repoRoot, kind, rows),
3046
3309
  keys: (kind) => keysOfKind2(repoRoot, kind),
3047
- read: (kind) => readKind2(repoRoot, kind).rows,
3310
+ read: (kind) => answeredRows(kind, readKind2(repoRoot, kind).rows),
3048
3311
  path: (kind) => kindPath(repoRoot, kind),
3049
3312
  readRows: (kind) => readKind2(repoRoot, kind)
3050
3313
  };
@@ -3067,4 +3330,4 @@ function selectEffortStore(repoRoot, config) {
3067
3330
  return adapter.create({ repoRoot });
3068
3331
  }
3069
3332
 
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 };
3333
+ export { storedLogPath, ACROSS_STORES_ORDER, STAMPED_COLUMNS, stampedValues, SessionRecordError, isSessionId, sessionSteps, sessionDecisions, SessionConflictError, runsDir, sessionFilePath, errorCode, isPidAlive, readSessions, readSession, samePlan, beginSession, updateSession, SESSION_ID_FLAG, claudeArgs, interruptClaudeSessions, spawnClaude, runClaude, spawnClaudeCaptured, runClaudeCaptured, RUNTIME_SUBDIR, EFFORT_DIR_VARIABLE, effortStoreDir, guardTestProcess, DEVELOPMENT_NEXT_STEP, DevelopmentBuildRefusedError, refuseUnownedDevelopmentWrite, SQLITE_MIGRATIONS, sqliteCatalogue, planSchema, readStoreSchema, writeNames, readReplacedStoreIds, readStoreMeta, EFFORT_KEY_PROJECTIONS, SQLITE_STORE_FILE_NAME, sqliteStorePath, LONE_SURROGATE, withSqliteStore, writeSqliteStore, openSqliteStore, copyEffortStore, WIRE_CONTRACT_VERSION, WIRE_FORMAT, WIRE_VERSION, WireFormatError, WireExportRefusal, encodeWirePayload, decodeWirePayload, exportWirePayload, materialiseWirePayload, minutesBetween, readingKey, readRepositoryFacts, MOVE_TO_SQLITE, mergeStore, openNdjsonStore, selectEffortStore };