@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
package/dist/index.js CHANGED
@@ -37,6 +37,7 @@ import {
37
37
  STAMPED_COLUMNS,
38
38
  SessionConflictError,
39
39
  SessionRecordError,
40
+ WIRE_CONTRACT_VERSION,
40
41
  WIRE_FORMAT,
41
42
  WIRE_VERSION,
42
43
  WireExportRefusal,
@@ -60,10 +61,12 @@ import {
60
61
  openSqliteStore,
61
62
  planSchema,
62
63
  readReplacedStoreIds,
64
+ readRepositoryFacts,
63
65
  readSession,
64
66
  readSessions,
65
67
  readStoreMeta,
66
68
  readStoreSchema,
69
+ readingKey,
67
70
  refuseUnownedDevelopmentWrite,
68
71
  runClaude,
69
72
  runClaudeCaptured,
@@ -78,11 +81,12 @@ import {
78
81
  sqliteCatalogue,
79
82
  sqliteStorePath,
80
83
  stampedValues,
84
+ storedLogPath,
81
85
  updateSession,
82
86
  withSqliteStore,
83
87
  writeNames,
84
88
  writeSqliteStore
85
- } from "./index-1tdzcheq.js";
89
+ } from "./index-mkhbaye7.js";
86
90
  import {
87
91
  ACTION_SHAPE,
88
92
  CONFIG_DEFAULTS,
@@ -98,7 +102,7 @@ import {
98
102
  renderTitle,
99
103
  suggestedEnvironment,
100
104
  titleRoundTrips
101
- } from "./index-nqaqh4zz.js";
105
+ } from "./index-d772zq3m.js";
102
106
  import {
103
107
  ABSENT,
104
108
  ACCEPT_REFS_FLAG,
@@ -137,6 +141,7 @@ import {
137
141
  SPEC_READY_LABEL,
138
142
  ScopeError,
139
143
  UNREADABLE,
144
+ activeLogger,
140
145
  activeServices,
141
146
  addedNotFilledWarning,
142
147
  aheadClaimedLine,
@@ -269,7 +274,7 @@ import {
269
274
  writeHopRecord,
270
275
  writePositionFile,
271
276
  writeRefsBlock
272
- } from "./index-4wy2nmyt.js";
277
+ } from "./index-waawdjq2.js";
273
278
  import {
274
279
  BLOCKER_GAP,
275
280
  PLAN_BLOCK_KINDS,
@@ -320,8 +325,9 @@ import {
320
325
  normalizeRemote,
321
326
  parseWorkingTree,
322
327
  registerAdapters,
323
- restoreAdapters
324
- } from "./index-4dwaxd5r.js";
328
+ restoreAdapters,
329
+ shellQuote
330
+ } from "./index-8rr1etrx.js";
325
331
  import {
326
332
  activeOutput,
327
333
  activeOutputMode,
@@ -358,7 +364,7 @@ import {
358
364
  requiredPrerequisite,
359
365
  resolveConfig,
360
366
  scopeAt
361
- } from "./index-m672ptpg.js";
367
+ } from "./index-dj8en7fg.js";
362
368
  import {
363
369
  BOARD_PROJECT_TEMPLATE_DEFAULT,
364
370
  BOARD_RELATIONSHIP_MODES,
@@ -402,7 +408,7 @@ import {
402
408
  } from "./index-fpgmdmww.js";
403
409
 
404
410
  // src/adapter-registry.ts
405
- import { homedir as homedir5 } from "os";
411
+ import { homedir as homedir6 } from "os";
406
412
  // packages/rafa-board/src/adapters/tracker/local.ts
407
413
  import { mkdir, readdir, readFile, writeFile } from "fs/promises";
408
414
  import { join } from "path";
@@ -3159,6 +3165,7 @@ function resolvePlanStub(branchStub, planStubs) {
3159
3165
 
3160
3166
  // packages/rafa/src/effort/session-log.ts
3161
3167
  import { createReadStream } from "fs";
3168
+ import { homedir } from "os";
3162
3169
  import { basename } from "path";
3163
3170
  import { createInterface } from "readline";
3164
3171
  function emptyUsageTotals() {
@@ -3324,10 +3331,10 @@ function parseRecord(line) {
3324
3331
  return null;
3325
3332
  }
3326
3333
  }
3327
- async function readSessionLog(filePath) {
3334
+ async function readSessionLog(filePath, home = homedir()) {
3328
3335
  return accumulateSessionStats(readLines(filePath), {
3329
3336
  sessionId: sessionIdFromPath(filePath),
3330
- filePath
3337
+ filePath: storedLogPath(filePath, home)
3331
3338
  });
3332
3339
  }
3333
3340
 
@@ -3426,6 +3433,7 @@ async function findFirstEnqueue(lines, scanWindow = ENQUEUE_SCAN_WINDOW) {
3426
3433
  }
3427
3434
  return { content: null, recordIndex: null, linesScanned };
3428
3435
  }
3436
+ var ABSENT_LOG_CODES = new Set(["ENOENT", "ENOTDIR"]);
3429
3437
 
3430
3438
  // packages/rafa-effort/src/effort/attribution.ts
3431
3439
  var ISSUE_TEAM_KEYS = ["OPT"];
@@ -3547,14 +3555,128 @@ function attributeSession(stats, enqueueContent, planStubs) {
3547
3555
  taskText: taskTextFromPrompt(enqueueContent)
3548
3556
  };
3549
3557
  }
3558
+ // packages/rafa-effort/src/effort/bug-fix-rows.ts
3559
+ import { existsSync } from "fs";
3560
+ var IS_BUG = "tracker_ref IS NOT NULL AND resolution IS NULL";
3561
+ var SELECT_BUGS = `
3562
+ SELECT *
3563
+ FROM findings
3564
+ WHERE ${IS_BUG}
3565
+ ORDER BY ${ACROSS_STORES_ORDER}
3566
+ `;
3567
+ var SELECT_OUT_OF_SCOPE = `
3568
+ SELECT session_id, what, artifact
3569
+ FROM out_of_scope_bugs
3570
+ WHERE session_id IN (SELECT session_id FROM findings WHERE ${IS_BUG})
3571
+ ORDER BY ${ACROSS_STORES_ORDER}
3572
+ `;
3573
+ var SELECT_RESOLVED = `
3574
+ SELECT session_id, plan_stub, task_line, artifact, resolution
3575
+ FROM findings
3576
+ WHERE resolution IS NOT NULL
3577
+ ORDER BY ${ACROSS_STORES_ORDER}
3578
+ `;
3579
+ var SELECT_DONE_REPORTS = `
3580
+ SELECT session_id, plan_stub, task_line, outcome, collected_at
3581
+ FROM task_reports
3582
+ WHERE status = 'done'
3583
+ ORDER BY ${ACROSS_STORES_ORDER}
3584
+ `;
3585
+ var NO_ROWS = Object.freeze({
3586
+ bugs: [],
3587
+ outOfScope: [],
3588
+ resolved: [],
3589
+ reports: []
3590
+ });
3591
+ function unreadableRow(path2, seq, reason) {
3592
+ return new Error(`effort store: ${path2}: findings row ${String(seq)} ${reason}`);
3593
+ }
3594
+ function stringField(value, key) {
3595
+ const field2 = value[key];
3596
+ return typeof field2 === "string" ? field2 : null;
3597
+ }
3598
+ function parseRefJson(json) {
3599
+ try {
3600
+ const value = JSON.parse(json);
3601
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
3602
+ } catch {
3603
+ return null;
3604
+ }
3605
+ }
3606
+ function trackerRefOf(path2, row) {
3607
+ const value = parseRefJson(row.tracker_ref);
3608
+ if (value === null)
3609
+ throw unreadableRow(path2, row.seq, "holds a tracker_ref that is no JSON object");
3610
+ const kind = stringField(value, "kind");
3611
+ const externalId = stringField(value, "externalId");
3612
+ if (kind === null || externalId === null) {
3613
+ throw unreadableRow(path2, row.seq, "holds a tracker_ref with no string kind and externalId");
3614
+ }
3615
+ return { kind, externalId, url: stringField(value, "url") };
3616
+ }
3617
+ function bugOf(path2, row) {
3618
+ if (row.artifact === null)
3619
+ throw unreadableRow(path2, row.seq, "holds a tracker_ref and no artifact");
3620
+ return {
3621
+ id: row.id,
3622
+ sessionId: row.session_id,
3623
+ planStub: row.plan_stub,
3624
+ taskLine: row.task_line,
3625
+ artifact: row.artifact,
3626
+ trackerRef: trackerRefOf(path2, row),
3627
+ outcome: row.outcome,
3628
+ collectedAt: row.collected_at
3629
+ };
3630
+ }
3631
+ function selectRows(db, path2) {
3632
+ const bugs = db.query(SELECT_BUGS).all();
3633
+ const outOfScope = db.query(SELECT_OUT_OF_SCOPE).all();
3634
+ const resolved = db.query(SELECT_RESOLVED).all();
3635
+ const reports = db.query(SELECT_DONE_REPORTS).all();
3636
+ return {
3637
+ bugs: bugs.map((row) => bugOf(path2, row)),
3638
+ outOfScope: outOfScope.map((row) => ({
3639
+ sessionId: row.session_id,
3640
+ what: row.what,
3641
+ artifact: row.artifact
3642
+ })),
3643
+ resolved: resolved.map((row) => ({
3644
+ sessionId: row.session_id,
3645
+ planStub: row.plan_stub,
3646
+ taskLine: row.task_line,
3647
+ artifact: row.artifact,
3648
+ resolution: row.resolution
3649
+ })),
3650
+ reports: reports.map((row) => ({
3651
+ sessionId: row.session_id,
3652
+ planStub: row.plan_stub,
3653
+ taskLine: row.task_line,
3654
+ outcome: row.outcome,
3655
+ collectedAt: row.collected_at
3656
+ }))
3657
+ };
3658
+ }
3659
+ function readBugFixRows(repoRoot) {
3660
+ const path2 = sqliteStorePath(repoRoot);
3661
+ if (!existsSync(path2)) {
3662
+ return {
3663
+ rows: NO_ROWS,
3664
+ note: `no effort store at ${path2}, so no bug findings to pair;` + " a store: ndjson project keeps its findings and reports in this file too"
3665
+ };
3666
+ }
3667
+ return {
3668
+ rows: withSqliteStore(path2, "read", false, (db) => selectRows(db, path2)),
3669
+ note: null
3670
+ };
3671
+ }
3550
3672
  // packages/rafa-effort/src/effort/collect.ts
3551
- import { existsSync as existsSync5, readdirSync as readdirSync6 } from "fs";
3552
- import { homedir as homedir2 } from "os";
3673
+ import { existsSync as existsSync6, readdirSync as readdirSync6 } from "fs";
3674
+ import { homedir as homedir3 } from "os";
3553
3675
  import { resolve as resolve7 } from "path";
3554
3676
 
3555
3677
  // packages/rafa/src/effort/session-log-dirs.ts
3556
- import { existsSync, readdirSync, statSync as statSync2 } from "fs";
3557
- import { homedir } from "os";
3678
+ import { existsSync as existsSync2, readdirSync, statSync as statSync2 } from "fs";
3679
+ import { homedir as homedir2 } from "os";
3558
3680
  import { join as join8, resolve as resolve2 } from "path";
3559
3681
  var LOG_DIR_SEPARATORS = /[/\\.]/g;
3560
3682
  var SESSION_LOG_NAME = /\.jsonl$/i;
@@ -3562,13 +3684,13 @@ var PROJECT_LOG_ROOT = [".claude", "projects"];
3562
3684
  function projectLogDirName(repoRoot) {
3563
3685
  return repoRoot.replace(LOG_DIR_SEPARATORS, "-");
3564
3686
  }
3565
- function sessionLogDir(repoRoot, home = homedir()) {
3687
+ function sessionLogDir(repoRoot, home = homedir2()) {
3566
3688
  return join8(home, ...PROJECT_LOG_ROOT, projectLogDirName(repoRoot));
3567
3689
  }
3568
- function projectLogDirs(repoRoot, worktreeDir, home = homedir()) {
3690
+ function projectLogDirs(repoRoot, worktreeDir, home = homedir2()) {
3569
3691
  const main = { dir: sessionLogDir(repoRoot, home), worktree: null };
3570
3692
  const root = join8(home, ...PROJECT_LOG_ROOT);
3571
- if (!existsSync(root))
3693
+ if (!existsSync2(root))
3572
3694
  return [main];
3573
3695
  const worktreeRoot = resolve2(repoRoot, worktreeDir);
3574
3696
  const prefix = `${projectLogDirName(worktreeRoot)}-`;
@@ -3583,7 +3705,7 @@ function projectLogDirs(repoRoot, worktreeDir, home = homedir()) {
3583
3705
  ];
3584
3706
  }
3585
3707
  function listProjectSessionLogs(dirs) {
3586
- const present = dirs.filter(({ dir }) => existsSync(dir));
3708
+ const present = dirs.filter(({ dir }) => existsSync2(dir));
3587
3709
  const first = dirs[0];
3588
3710
  if (present.length === 0 && first !== undefined)
3589
3711
  listSessionLogs(first.dir);
@@ -3601,7 +3723,7 @@ function listProjectSessionLogs(dirs) {
3601
3723
  return { candidates: sortCandidates([...kept.values()]), duplicates };
3602
3724
  }
3603
3725
  function listSessionLogs(dir, worktree = null) {
3604
- if (!existsSync(dir)) {
3726
+ if (!existsSync2(dir)) {
3605
3727
  throw new Error(`effort collect: no session log directory at ${dir}` + " (pass logDir, or run with --no-sessions)");
3606
3728
  }
3607
3729
  const candidates = [];
@@ -3688,7 +3810,7 @@ function parseCollectArgs(args) {
3688
3810
  }
3689
3811
 
3690
3812
  // packages/rafa/src/effort/store/skill-invocations.ts
3691
- import { existsSync as existsSync2 } from "fs";
3813
+ import { existsSync as existsSync3 } from "fs";
3692
3814
 
3693
3815
  // packages/rafa/src/effort/store/findings.ts
3694
3816
  import { randomUUID } from "crypto";
@@ -3908,21 +4030,71 @@ function invocationOf(row) {
3908
4030
  }
3909
4031
  function readSkillInvocations(repoRoot) {
3910
4032
  const path2 = sqliteStorePath(repoRoot);
3911
- if (!existsSync2(path2))
4033
+ if (!existsSync3(path2))
3912
4034
  return [];
3913
4035
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_ALL).all());
3914
4036
  return rows.map(invocationOf);
3915
4037
  }
3916
4038
 
3917
4039
  // packages/rafa-effort/src/effort/skill-use.ts
3918
- import { existsSync as existsSync4, readdirSync as readdirSync5 } from "fs";
3919
- import { dirname as dirname10, join as join21 } from "path";
4040
+ import { existsSync as existsSync5, readdirSync as readdirSync5 } from "fs";
4041
+ import { dirname as dirname10, join as join22 } from "path";
4042
+
4043
+ // packages/rafa-inventory/src/adapters/learning/bug-fix-push.ts
4044
+ import { readFile as readFile3 } from "fs/promises";
4045
+ import { join as join12 } from "path";
4046
+
4047
+ // packages/rafa-inventory/src/adapters/learning/local.ts
4048
+ import { appendFile, mkdir as mkdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
4049
+ import { join as join11 } from "path";
3920
4050
 
3921
4051
  // packages/rafa-inventory/src/learning/bless.ts
4052
+ import { createHash as createHash2 } from "crypto";
4053
+
4054
+ // packages/rafa-inventory/src/learning/identity.ts
3922
4055
  import { createHash } from "crypto";
4056
+ var GAP = 0.1;
4057
+ var SOURCE_STEP = 0.05;
4058
+ var CONFIDENCE_MIN = 0.3;
4059
+ var CONFIDENCE_MAX = 0.9;
4060
+ var WHITESPACE_RUN = /\s+/g;
4061
+ function actionHash(action) {
4062
+ return createHash("sha256").update(action.trim().toLowerCase()).digest("hex");
4063
+ }
4064
+ function triggerKey(trigger) {
4065
+ return trigger.trim().toLowerCase().replace(WHITESPACE_RUN, " ");
4066
+ }
4067
+
4068
+ // packages/rafa-inventory/src/learning/pool.ts
3923
4069
  var HUNDREDTHS = 100;
4070
+ var STEP_H = Math.round(SOURCE_STEP * HUNDREDTHS);
4071
+ var MIN_H = Math.round(CONFIDENCE_MIN * HUNDREDTHS);
4072
+ var MAX_H = Math.round(CONFIDENCE_MAX * HUNDREDTHS);
4073
+ function sourcesOf(record) {
4074
+ return record.sources !== undefined && record.sources.length > 0 ? [...new Set(record.sources)] : [record.id];
4075
+ }
4076
+ function pooledConfidence(ordered) {
4077
+ const seen = new Set;
4078
+ let weighted = 0;
4079
+ for (const member of ordered) {
4080
+ const own = sourcesOf(member);
4081
+ const fresh = own.filter((source) => !seen.has(source));
4082
+ const base = Math.round(member.confidence * HUNDREDTHS) - STEP_H * (own.length - 1);
4083
+ weighted += base * fresh.length;
4084
+ for (const source of fresh) {
4085
+ seen.add(source);
4086
+ }
4087
+ }
4088
+ const sources = [...seen].sort();
4089
+ const stepped = Math.round(weighted / sources.length + STEP_H * (sources.length - 1));
4090
+ const confidence = Math.min(MAX_H, Math.max(MIN_H, stepped)) / HUNDREDTHS;
4091
+ return { sources, confidence };
4092
+ }
4093
+
4094
+ // packages/rafa-inventory/src/learning/groups.ts
4095
+ var HUNDREDTHS2 = 100;
3924
4096
  function hundredths(confidence) {
3925
- return Math.round(confidence * HUNDREDTHS);
4097
+ return Math.round(confidence * HUNDREDTHS2);
3926
4098
  }
3927
4099
  function compareText(left, right) {
3928
4100
  if (left < right) {
@@ -3933,46 +4105,78 @@ function compareText(left, right) {
3933
4105
  }
3934
4106
  return 0;
3935
4107
  }
4108
+ function byAge(left, right) {
4109
+ return compareText(left.created_at, right.created_at) || compareText(left.id, right.id);
4110
+ }
3936
4111
  function byTrust(left, right) {
3937
4112
  return hundredths(right.confidence) - hundredths(left.confidence) || right.usage_count - left.usage_count || compareText(left.id, right.id);
3938
4113
  }
4114
+ function byGroupTrust(left, right) {
4115
+ return hundredths(right.confidence) - hundredths(left.confidence) || right.sources.length - left.sources.length || compareText(left.named.id, right.named.id);
4116
+ }
4117
+ function groupOf(hash, records) {
4118
+ const { sources, confidence } = pooledConfidence([...records].sort(byAge));
4119
+ const members = [...records].sort(byTrust);
4120
+ return { action_hash: hash, members, sources, confidence, named: members[0] };
4121
+ }
4122
+ function sameActionGroups(held) {
4123
+ const byAction = new Map;
4124
+ for (const record of held) {
4125
+ if (record.status === "flagged") {
4126
+ continue;
4127
+ }
4128
+ const found = byAction.get(record.action_hash);
4129
+ if (found === undefined) {
4130
+ byAction.set(record.action_hash, [record]);
4131
+ } else {
4132
+ found.push(record);
4133
+ }
4134
+ }
4135
+ return [...byAction].map(([hash, records]) => groupOf(hash, records)).sort(byGroupTrust);
4136
+ }
4137
+
4138
+ // packages/rafa-inventory/src/learning/bless.ts
4139
+ var HUNDREDTHS3 = 100;
4140
+ function hundredths2(confidence) {
4141
+ return Math.round(confidence * HUNDREDTHS3);
4142
+ }
4143
+ function compareText2(left, right) {
4144
+ if (left < right) {
4145
+ return -1;
4146
+ }
4147
+ if (left > right) {
4148
+ return 1;
4149
+ }
4150
+ return 0;
4151
+ }
4152
+ function byTrust2(left, right) {
4153
+ return hundredths2(right.confidence) - hundredths2(left.confidence) || right.usage_count - left.usage_count || compareText2(left.id, right.id);
4154
+ }
4155
+ function isUsable(record) {
4156
+ return record.status === "active" && record.promoted_to === undefined;
4157
+ }
3939
4158
  function blessedRecords(held, minConfidence) {
3940
- const floor = hundredths(minConfidence);
3941
- return held.filter((each) => each.status === "active" && each.promoted_to === undefined && hundredths(each.confidence) >= floor).sort(byTrust);
4159
+ const floor = hundredths2(minConfidence);
4160
+ return held.filter((each) => isUsable(each) && hundredths2(each.confidence) >= floor).sort(byTrust2);
3942
4161
  }
3943
4162
  function versionOf(instincts) {
3944
- return createHash("sha256").update(JSON.stringify(instincts)).digest("hex");
4163
+ return createHash2("sha256").update(JSON.stringify(instincts)).digest("hex");
3945
4164
  }
3946
4165
  function bless(held, options) {
3947
4166
  const instincts = blessedRecords(held, options.minConfidence);
3948
4167
  return { version: versionOf(instincts), instincts };
3949
4168
  }
3950
4169
  function promotable(held, options) {
3951
- return blessedRecords(held, options.minConfidence).filter((each) => each.usage_count >= options.after);
3952
- }
3953
- // packages/rafa-inventory/src/learning/identity.ts
3954
- import { createHash as createHash2 } from "crypto";
3955
- var GAP = 0.1;
3956
- var SOURCE_STEP = 0.05;
3957
- var CONFIDENCE_MIN = 0.3;
3958
- var CONFIDENCE_MAX = 0.9;
3959
- var WHITESPACE_RUN = /\s+/g;
3960
- function actionHash(action) {
3961
- return createHash2("sha256").update(action.trim().toLowerCase()).digest("hex");
3962
- }
3963
- function triggerKey(trigger) {
3964
- return trigger.trim().toLowerCase().replace(WHITESPACE_RUN, " ");
4170
+ const floor = hundredths2(options.minConfidence);
4171
+ return sameActionGroups(held.filter(isUsable)).filter((group) => group.sources.length >= options.after && hundredths2(group.confidence) >= floor).map((group) => group.named);
3965
4172
  }
3966
4173
  // packages/rafa-inventory/src/learning/merge.ts
3967
- var HUNDREDTHS2 = 100;
3968
- var GAP_H = Math.round(GAP * HUNDREDTHS2);
3969
- var STEP_H = Math.round(SOURCE_STEP * HUNDREDTHS2);
3970
- var MIN_H = Math.round(CONFIDENCE_MIN * HUNDREDTHS2);
3971
- var MAX_H = Math.round(CONFIDENCE_MAX * HUNDREDTHS2);
3972
- function hundredths2(confidence) {
3973
- return Math.round(confidence * HUNDREDTHS2);
4174
+ var HUNDREDTHS4 = 100;
4175
+ var GAP_H = Math.round(GAP * HUNDREDTHS4);
4176
+ function hundredths3(confidence) {
4177
+ return Math.round(confidence * HUNDREDTHS4);
3974
4178
  }
3975
- function compareText2(left, right) {
4179
+ function compareText3(left, right) {
3976
4180
  if (left < right) {
3977
4181
  return -1;
3978
4182
  }
@@ -3981,14 +4185,11 @@ function compareText2(left, right) {
3981
4185
  }
3982
4186
  return 0;
3983
4187
  }
3984
- function byAge(left, right) {
3985
- return compareText2(left.created_at, right.created_at) || compareText2(left.id, right.id);
4188
+ function byAge2(left, right) {
4189
+ return compareText3(left.created_at, right.created_at) || compareText3(left.id, right.id);
3986
4190
  }
3987
4191
  function byConfidence(left, right) {
3988
- return hundredths2(right.confidence) - hundredths2(left.confidence) || compareText2(left.id, right.id);
3989
- }
3990
- function sourcesOf(record) {
3991
- return record.sources !== undefined && record.sources.length > 0 ? [...new Set(record.sources)] : [record.id];
4192
+ return hundredths3(right.confidence) - hundredths3(left.confidence) || compareText3(left.id, right.id);
3992
4193
  }
3993
4194
  function withSource(record, sourceId) {
3994
4195
  const sources = [...new Set([...record.sources ?? [], sourceId])].sort();
@@ -3999,25 +4200,12 @@ function firstOptional(ordered, key) {
3999
4200
  return found === undefined ? {} : { [key]: found[key] };
4000
4201
  }
4001
4202
  function collapse(group) {
4002
- const ordered = [...[...group.held].sort(byAge), ...[...group.incoming].sort(byAge)];
4203
+ const ordered = [...[...group.held].sort(byAge2), ...[...group.incoming].sort(byAge2)];
4003
4204
  if (ordered.length === 1) {
4004
4205
  return ordered[0];
4005
4206
  }
4006
- const seen = new Set;
4007
- let weighted = 0;
4008
- for (const member of ordered) {
4009
- const own = sourcesOf(member);
4010
- const fresh = own.filter((source) => !seen.has(source));
4011
- const base = hundredths2(member.confidence) - STEP_H * (own.length - 1);
4012
- weighted += base * fresh.length;
4013
- for (const source of fresh) {
4014
- seen.add(source);
4015
- }
4016
- }
4017
- const sources = [...seen].sort();
4018
- const stepped = Math.round(weighted / sources.length + STEP_H * (sources.length - 1));
4019
- const confidence = Math.min(MAX_H, Math.max(MIN_H, stepped)) / HUNDREDTHS2;
4020
- const byAgeAll = [...ordered].sort(byAge);
4207
+ const { sources, confidence } = pooledConfidence(ordered);
4208
+ const byAgeAll = [...ordered].sort(byAge2);
4021
4209
  const lead = byAgeAll[0];
4022
4210
  const rest = {};
4023
4211
  for (const [key, value] of Object.entries(lead)) {
@@ -4054,7 +4242,7 @@ function withStatus(record, status) {
4054
4242
  }
4055
4243
  function groupByAction(held, incoming) {
4056
4244
  const groups = new Map;
4057
- const groupOf = (hash) => {
4245
+ const groupOf2 = (hash) => {
4058
4246
  const found = groups.get(hash);
4059
4247
  if (found !== undefined) {
4060
4248
  return found;
@@ -4064,10 +4252,10 @@ function groupByAction(held, incoming) {
4064
4252
  return made;
4065
4253
  };
4066
4254
  for (const record of held) {
4067
- groupOf(record.action_hash).held.push(record);
4255
+ groupOf2(record.action_hash).held.push(record);
4068
4256
  }
4069
4257
  for (const record of incoming) {
4070
- groupOf(record.action_hash).incoming.push(record);
4258
+ groupOf2(record.action_hash).incoming.push(record);
4071
4259
  }
4072
4260
  return groups;
4073
4261
  }
@@ -4083,11 +4271,11 @@ function settleOne(hash, group, held, now) {
4083
4271
  return { produced: [record], discarded: [], rules: new Map([[hash, "same-action"]]) };
4084
4272
  }
4085
4273
  function settleMany(collapsed, held, now) {
4086
- const leaderH = Math.max(...[...collapsed.values()].map((record) => hundredths2(record.confidence)));
4274
+ const leaderH = Math.max(...[...collapsed.values()].map((record) => hundredths3(record.confidence)));
4087
4275
  const kept = new Map;
4088
4276
  const discarded = [];
4089
4277
  for (const [hash, record] of collapsed) {
4090
- if (leaderH - hundredths2(record.confidence) > GAP_H) {
4278
+ if (leaderH - hundredths3(record.confidence) > GAP_H) {
4091
4279
  discarded.push(record);
4092
4280
  } else {
4093
4281
  kept.set(hash, record);
@@ -4139,83 +4327,6 @@ function merge(held, payload, now) {
4139
4327
  discarded: keys.flatMap((key) => outcomes.get(key).discarded)
4140
4328
  };
4141
4329
  }
4142
- // packages/rafa-inventory/src/adapters/learning/held.ts
4143
- function compareText3(left, right) {
4144
- if (left < right) {
4145
- return -1;
4146
- }
4147
- if (left > right) {
4148
- return 1;
4149
- }
4150
- return 0;
4151
- }
4152
- function byAge2(left, right) {
4153
- return compareText3(left.createdAt, right.createdAt) || compareText3(left.id, right.id);
4154
- }
4155
- function toHeldRecord(instinct) {
4156
- return {
4157
- id: instinct.id,
4158
- trigger: instinct.trigger,
4159
- action: instinct.action,
4160
- action_hash: instinct.actionHash,
4161
- confidence: instinct.confidence,
4162
- usage_count: instinct.usageCount,
4163
- ...instinct.sources.length > 0 ? { sources: [...instinct.sources] } : {},
4164
- ...instinct.artifact === null ? {} : { artifact: instinct.artifact },
4165
- signal: instinct.signal,
4166
- status: "active",
4167
- ...instinct.promotedTo === null ? {} : { promoted_to: instinct.promotedTo },
4168
- created_at: instinct.createdAt,
4169
- updated_at: instinct.updatedAt
4170
- };
4171
- }
4172
- function toHeldRecords(held) {
4173
- const actions = new Map;
4174
- for (const instinct of held) {
4175
- const key = triggerKey(instinct.trigger);
4176
- actions.set(key, (actions.get(key) ?? new Set).add(instinct.actionHash));
4177
- }
4178
- return held.map((instinct) => {
4179
- const record = toHeldRecord(instinct);
4180
- return actions.get(triggerKey(instinct.trigger)).size > 1 ? { ...record, status: "flagged" } : record;
4181
- });
4182
- }
4183
- function earliestHeldMember(record, held) {
4184
- const key = triggerKey(record.trigger);
4185
- const members = held.filter((instinct) => instinct.actionHash === record.action_hash && triggerKey(instinct.trigger) === key);
4186
- return [...members].sort(byAge2)[0] ?? null;
4187
- }
4188
- function toHeldInstinct(record, held, fallback) {
4189
- const description = earliestHeldMember(record, held) ?? fallback;
4190
- if (description === undefined) {
4191
- return null;
4192
- }
4193
- return {
4194
- id: record.id,
4195
- trigger: record.trigger,
4196
- kind: description.kind,
4197
- domain: description.domain,
4198
- confidence: record.confidence,
4199
- usageCount: record.usage_count,
4200
- sources: [...record.sources ?? []],
4201
- artifact: record.artifact ?? null,
4202
- signal: record.signal,
4203
- scope: description.scope,
4204
- projectId: description.projectId,
4205
- source: description.source,
4206
- evidence: [...description.evidence],
4207
- promotedTo: record.promoted_to ?? null,
4208
- createdAt: record.created_at,
4209
- updatedAt: record.updated_at,
4210
- action: record.action,
4211
- cause: description.cause,
4212
- actionHash: actionHash(record.action)
4213
- };
4214
- }
4215
- // packages/rafa-inventory/src/adapters/learning/local.ts
4216
- import { appendFile, mkdir as mkdir2, readFile as readFile2, rm, writeFile as writeFile2 } from "fs/promises";
4217
- import { join as join11 } from "path";
4218
-
4219
4330
  // packages/rafa/src/schema/frontmatter.ts
4220
4331
  var FRONTMATTER_FENCE = "---";
4221
4332
  var FRONTMATTER_INDENT = 2;
@@ -4902,10 +5013,123 @@ function readScopes(seams) {
4902
5013
  return resolveInstinctScopes(seams).map((location) => readScope(location.scope, location.dir));
4903
5014
  }
4904
5015
 
5016
+ // packages/rafa-inventory/src/adapters/learning/group-rule.ts
5017
+ var GROUPABLE = new Set(["new-trigger", "same-action"]);
5018
+ function withStatus2(record, status) {
5019
+ return record.status === status ? record : { ...record, status };
5020
+ }
5021
+ function heldAfterPush(before, result) {
5022
+ const touched = new Set(result.decisions.map((decision) => triggerKey(decision.incoming.trigger)));
5023
+ const produced = new Map;
5024
+ for (const record of result.decisions.flatMap((decision) => decision.produced)) {
5025
+ produced.set(record.id, record);
5026
+ }
5027
+ const held = [
5028
+ ...before.filter((record) => !touched.has(triggerKey(record.trigger))),
5029
+ ...produced.values()
5030
+ ];
5031
+ const actions = new Map;
5032
+ for (const record of held) {
5033
+ const key = triggerKey(record.trigger);
5034
+ actions.set(key, (actions.get(key) ?? new Set).add(record.action_hash));
5035
+ }
5036
+ return held.map((record) => withStatus2(record, actions.get(triggerKey(record.trigger)).size > 1 ? "flagged" : "active"));
5037
+ }
5038
+ function loggedRule(decision, after) {
5039
+ if (!GROUPABLE.has(decision.rule)) {
5040
+ return decision.rule;
5041
+ }
5042
+ const hash = decision.incoming.action_hash;
5043
+ const own = decision.produced.find((record) => record.action_hash === hash);
5044
+ if (own === undefined) {
5045
+ return decision.rule;
5046
+ }
5047
+ const [group] = sameActionGroups(after.filter((record) => record.action_hash === hash));
5048
+ if (group === undefined || !group.members.some((member) => member.id === own.id)) {
5049
+ return decision.rule;
5050
+ }
5051
+ const key = triggerKey(own.trigger);
5052
+ return group.members.some((member) => triggerKey(member.trigger) !== key) ? "same-action-group" : decision.rule;
5053
+ }
5054
+
5055
+ // packages/rafa-inventory/src/adapters/learning/held.ts
5056
+ function compareText4(left, right) {
5057
+ if (left < right) {
5058
+ return -1;
5059
+ }
5060
+ if (left > right) {
5061
+ return 1;
5062
+ }
5063
+ return 0;
5064
+ }
5065
+ function byAge3(left, right) {
5066
+ return compareText4(left.createdAt, right.createdAt) || compareText4(left.id, right.id);
5067
+ }
5068
+ function toHeldRecord(instinct) {
5069
+ return {
5070
+ id: instinct.id,
5071
+ trigger: instinct.trigger,
5072
+ action: instinct.action,
5073
+ action_hash: instinct.actionHash,
5074
+ confidence: instinct.confidence,
5075
+ usage_count: instinct.usageCount,
5076
+ ...instinct.sources.length > 0 ? { sources: [...instinct.sources] } : {},
5077
+ ...instinct.artifact === null ? {} : { artifact: instinct.artifact },
5078
+ signal: instinct.signal,
5079
+ status: "active",
5080
+ ...instinct.promotedTo === null ? {} : { promoted_to: instinct.promotedTo },
5081
+ created_at: instinct.createdAt,
5082
+ updated_at: instinct.updatedAt
5083
+ };
5084
+ }
5085
+ function toHeldRecords(held) {
5086
+ const actions = new Map;
5087
+ for (const instinct of held) {
5088
+ const key = triggerKey(instinct.trigger);
5089
+ actions.set(key, (actions.get(key) ?? new Set).add(instinct.actionHash));
5090
+ }
5091
+ return held.map((instinct) => {
5092
+ const record = toHeldRecord(instinct);
5093
+ return actions.get(triggerKey(instinct.trigger)).size > 1 ? { ...record, status: "flagged" } : record;
5094
+ });
5095
+ }
5096
+ function earliestHeldMember(record, held) {
5097
+ const key = triggerKey(record.trigger);
5098
+ const members = held.filter((instinct) => instinct.actionHash === record.action_hash && triggerKey(instinct.trigger) === key);
5099
+ return [...members].sort(byAge3)[0] ?? null;
5100
+ }
5101
+ function toHeldInstinct(record, held, fallback) {
5102
+ const description = earliestHeldMember(record, held) ?? fallback;
5103
+ if (description === undefined) {
5104
+ return null;
5105
+ }
5106
+ return {
5107
+ id: record.id,
5108
+ trigger: record.trigger,
5109
+ kind: description.kind,
5110
+ domain: description.domain,
5111
+ confidence: record.confidence,
5112
+ usageCount: record.usage_count,
5113
+ sources: [...record.sources ?? []],
5114
+ artifact: record.artifact ?? null,
5115
+ signal: record.signal,
5116
+ scope: description.scope,
5117
+ projectId: description.projectId,
5118
+ source: description.source,
5119
+ evidence: [...description.evidence],
5120
+ promotedTo: record.promoted_to ?? null,
5121
+ createdAt: record.created_at,
5122
+ updatedAt: record.updated_at,
5123
+ action: record.action,
5124
+ cause: description.cause,
5125
+ actionHash: actionHash(record.action)
5126
+ };
5127
+ }
5128
+
4905
5129
  // packages/rafa-inventory/src/adapters/learning/local.ts
4906
5130
  var PREFIX3 = "local learning";
4907
5131
  var PUSH_REFUSAL = `${PREFIX3}: refused to store a push`;
4908
- var INSTINCTS_FILE = "instincts.ndjson";
5132
+ var PUSH_LOG_FILE = "instincts.ndjson";
4909
5133
  var FLAGS_FILE = "flags.ndjson";
4910
5134
  var RECORD_EXTENSION = ".md";
4911
5135
  var MIN_CONFIDENCE = 0.3;
@@ -5073,7 +5297,7 @@ function userAdditions(userBlessed, projectHeld, flagged) {
5073
5297
  const heldIds = new Set(projectHeld.map((record) => record.id));
5074
5298
  return unflagged(userBlessed, flagged).filter((record) => !heldTriggers.has(triggerKey(record.trigger)) && !heldIds.has(record.id));
5075
5299
  }
5076
- function byAge3(left, right) {
5300
+ function byAge4(left, right) {
5077
5301
  if (left.created_at !== right.created_at) {
5078
5302
  return left.created_at < right.created_at ? -1 : 1;
5079
5303
  }
@@ -5084,7 +5308,7 @@ function byAge3(left, right) {
5084
5308
  function payloadDescription(record, described) {
5085
5309
  const key = triggerKey(record.trigger);
5086
5310
  const members = described.filter((candidate) => candidate.description !== undefined && candidate.action_hash === record.action_hash && triggerKey(candidate.trigger) === key);
5087
- return [...members].sort(byAge3)[0]?.description;
5311
+ return [...members].sort(byAge4)[0]?.description;
5088
5312
  }
5089
5313
  function producedRecords(result) {
5090
5314
  const byId = new Map;
@@ -5129,17 +5353,18 @@ function heldChanges(dir, held, result, described) {
5129
5353
  const removals = held.files.filter((file) => touched.has(triggerKey(file.instinct.trigger)) && !kept.has(file.path)).map((file) => file.path);
5130
5354
  return { writes, removals };
5131
5355
  }
5132
- function pushLogLines(sourceId, described, result) {
5356
+ function pushLogLines(sourceId, described, result, before, logLine) {
5357
+ const after = heldAfterPush(before, result);
5133
5358
  return result.decisions.map((decision, index) => {
5134
5359
  const key = triggerKey(decision.incoming.trigger);
5135
5360
  const line = {
5136
5361
  source_id: sourceId,
5137
- rule: decision.rule,
5362
+ rule: loggedRule(decision, after),
5138
5363
  incoming: loggedIncoming(described[index]),
5139
5364
  produced: decision.produced.map((record) => record.id),
5140
5365
  discarded: result.discarded.filter((record) => triggerKey(record.trigger) === key).map((record) => record.id)
5141
5366
  };
5142
- return JSON.stringify(line);
5367
+ return JSON.stringify(logLine(line, index));
5143
5368
  });
5144
5369
  }
5145
5370
  function localInstinctsDir(repoRoot) {
@@ -5153,7 +5378,8 @@ function createLocalLearning(options) {
5153
5378
  const userDir = userInstinctsDir(options.home);
5154
5379
  const now = options.now ?? (() => new Date().toISOString());
5155
5380
  const warn = options.warn ?? warnThroughActiveOutput2;
5156
- const instinctsPath = join11(instinctsDir, INSTINCTS_FILE);
5381
+ const logLine = options.logLine ?? ((line) => line);
5382
+ const instinctsPath = join11(instinctsDir, PUSH_LOG_FILE);
5157
5383
  const flagsPath = join11(instinctsDir, FLAGS_FILE);
5158
5384
  function readHeld(scope, dir) {
5159
5385
  const { records } = readScope(scope, dir);
@@ -5193,9 +5419,10 @@ function createLocalLearning(options) {
5193
5419
  }
5194
5420
  const described = payload.instincts;
5195
5421
  const held = heldSet();
5196
- const result = merge(toHeldRecords(held.files.map((file) => file.instinct)), { source_id: payload.source_id, instincts: described.map(copyInstinct) }, now());
5422
+ const before = toHeldRecords(held.files.map((file) => file.instinct));
5423
+ const result = merge(before, { source_id: payload.source_id, instincts: described.map(copyInstinct) }, now());
5197
5424
  const changes = heldChanges(instinctsDir, held, result, described);
5198
- const lines = pushLogLines(payload.source_id, described, result);
5425
+ const lines = pushLogLines(payload.source_id, described, result, before, logLine);
5199
5426
  if (lines.length > 0) {
5200
5427
  await mkdir2(instinctsDir, { recursive: true });
5201
5428
  await appendLines(instinctsPath, lines);
@@ -5229,25 +5456,121 @@ function createLocalLearning(options) {
5229
5456
  };
5230
5457
  return Object.freeze(learning);
5231
5458
  }
5459
+
5460
+ // packages/rafa-inventory/src/adapters/learning/bug-fix-push.ts
5461
+ var BUG_FIX_PAIR_RULE = "bug-fix-pair";
5462
+ function bugFixPairKey(pair) {
5463
+ const { trackerRef, sessionId } = pair.bug;
5464
+ return { ref: trackerRef.url ?? `${trackerRef.kind}:${trackerRef.externalId}`, filed_by: sessionId };
5465
+ }
5466
+ function keyText(key) {
5467
+ return JSON.stringify([key.ref, key.filed_by]);
5468
+ }
5469
+ function hasCode3(error, code) {
5470
+ return typeof error === "object" && error !== null && "code" in error && error.code === code;
5471
+ }
5472
+ function loggedKey(line) {
5473
+ let value;
5474
+ try {
5475
+ value = JSON.parse(line);
5476
+ } catch {
5477
+ return null;
5478
+ }
5479
+ if (!isMapping(value) || value.rule !== BUG_FIX_PAIR_RULE || !isMapping(value.pair))
5480
+ return null;
5481
+ const { ref, filed_by: filedBy } = value.pair;
5482
+ return typeof ref === "string" && typeof filedBy === "string" ? { ref, filed_by: filedBy } : null;
5483
+ }
5484
+ async function readLoggedPairs(dir) {
5485
+ let contents;
5486
+ try {
5487
+ contents = await readFile3(join12(dir, PUSH_LOG_FILE), "utf8");
5488
+ } catch (error) {
5489
+ if (hasCode3(error, "ENOENT"))
5490
+ return [];
5491
+ throw error;
5492
+ }
5493
+ const keys = new Map;
5494
+ for (const line of contents.split(`
5495
+ `)) {
5496
+ const key = line === "" ? null : loggedKey(line);
5497
+ if (key !== null && !keys.has(keyText(key)))
5498
+ keys.set(keyText(key), key);
5499
+ }
5500
+ return [...keys.values()];
5501
+ }
5502
+ function byFixingSession(pairs) {
5503
+ const groups = new Map;
5504
+ for (const pair of pairs) {
5505
+ const group = groups.get(pair.fix.sessionId);
5506
+ if (group === undefined)
5507
+ groups.set(pair.fix.sessionId, [pair]);
5508
+ else
5509
+ group.push(pair);
5510
+ }
5511
+ return [...groups.values()];
5512
+ }
5513
+ function problemLine(pair, refusal) {
5514
+ const key = bugFixPairKey(pair);
5515
+ return `bug-fix pair ${key.ref} filed by ${key.filed_by} was not pushed: ${refusal}`;
5516
+ }
5517
+ async function pushGroup(options, group, now) {
5518
+ const keys = group.map(bugFixPairKey);
5519
+ const learning = createLocalLearning({
5520
+ ...options,
5521
+ now: () => now,
5522
+ logLine: (line, index) => ({ ...line, rule: BUG_FIX_PAIR_RULE, pair: keys[index] })
5523
+ });
5524
+ try {
5525
+ await learning.push({ source_id: group[0].fix.sessionId, instincts: group.map((pair) => pair.lesson) });
5526
+ return null;
5527
+ } catch (error) {
5528
+ return messageOf(error);
5529
+ }
5530
+ }
5531
+ async function pushBugFixPairs(options, pairs, now) {
5532
+ const logged = new Set((await readLoggedPairs(options.instinctsDir)).map(keyText));
5533
+ const isLogged = (pair) => logged.has(keyText(bugFixPairKey(pair)));
5534
+ const stamp2 = now.toISOString();
5535
+ const pushed = [];
5536
+ const problems = [];
5537
+ for (const group of byFixingSession(pairs.filter((pair) => !isLogged(pair)))) {
5538
+ const refusal = await pushGroup(options, group, stamp2);
5539
+ if (refusal === null) {
5540
+ pushed.push(...group);
5541
+ } else if (group.length === 1) {
5542
+ problems.push(problemLine(group[0], refusal));
5543
+ } else {
5544
+ for (const pair of group) {
5545
+ const alone = await pushGroup(options, [pair], stamp2);
5546
+ if (alone === null)
5547
+ pushed.push(pair);
5548
+ else
5549
+ problems.push(problemLine(pair, alone));
5550
+ }
5551
+ }
5552
+ }
5553
+ return { pushed, skipped: pairs.filter(isLogged), problems };
5554
+ }
5232
5555
  // packages/rafa-inventory/src/agents/roster.ts
5233
5556
  import { readdirSync as readdirSync4, readFileSync as readFileSync12, statSync as statSync6 } from "fs";
5234
- import { join as join15 } from "path";
5557
+ import { join as join16 } from "path";
5235
5558
 
5236
5559
  // packages/rafa/src/utils/agent-definition.ts
5237
5560
  import { readFileSync as readFileSync7 } from "fs";
5238
- import { join as join12 } from "path";
5239
- var AGENT_DEFINITION_DIR = join12(".claude", "agents");
5561
+ import { join as join13 } from "path";
5562
+ var AGENT_DEFINITION_DIR = join13(".claude", "agents");
5240
5563
  function agentDefinitionCandidates(name, roots, settingSources) {
5241
5564
  if (!isAgentName(name))
5242
5565
  return [];
5243
5566
  const file = `${name}.md`;
5244
5567
  const project = {
5245
5568
  scope: "project",
5246
- path: join12(roots.repoRoot, AGENT_DEFINITION_DIR, file)
5569
+ path: join13(roots.repoRoot, AGENT_DEFINITION_DIR, file)
5247
5570
  };
5248
5571
  if (!settingSources.includes("user"))
5249
5572
  return [project];
5250
- return [project, { scope: "user", path: join12(roots.home, AGENT_DEFINITION_DIR, file) }];
5573
+ return [project, { scope: "user", path: join13(roots.home, AGENT_DEFINITION_DIR, file) }];
5251
5574
  }
5252
5575
  function readText(path2) {
5253
5576
  try {
@@ -5280,7 +5603,7 @@ function agentEffortLookup(roots, settingSources) {
5280
5603
 
5281
5604
  // packages/rafa-inventory/src/inventory/trees.ts
5282
5605
  import { readFileSync as readFileSync9 } from "fs";
5283
- import { dirname as dirname6, join as join13, relative as relative3 } from "path";
5606
+ import { dirname as dirname6, join as join14, relative as relative3 } from "path";
5284
5607
 
5285
5608
  // packages/rafa-inventory/src/check/run.ts
5286
5609
  import { readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
@@ -5826,7 +6149,7 @@ function checkSkillFrontmatter(data) {
5826
6149
  }
5827
6150
 
5828
6151
  // packages/rafa-inventory/src/check/references.ts
5829
- import { existsSync as existsSync3, statSync as statSync5 } from "fs";
6152
+ import { existsSync as existsSync4, statSync as statSync5 } from "fs";
5830
6153
  import { delimiter, isAbsolute, relative as relative2, resolve as resolve3 } from "path";
5831
6154
 
5832
6155
  // packages/rafa-inventory/src/check/shell-lines.ts
@@ -6169,7 +6492,7 @@ function issueOf2(code, ref, sentence) {
6169
6492
  };
6170
6493
  }
6171
6494
  function scriptIssue(ref, skillDir) {
6172
- if (existsSync3(resolve3(skillDir, ref.text)))
6495
+ if (existsSync4(resolve3(skillDir, ref.text)))
6173
6496
  return null;
6174
6497
  return issueOf2("missing-script", ref, `${ref.text} names nothing under the skill directory`);
6175
6498
  }
@@ -6177,17 +6500,17 @@ function isSkillPath(token, skillDir) {
6177
6500
  const target = resolve3(skillDir, token);
6178
6501
  if (!isInside(skillDir, target))
6179
6502
  return false;
6180
- if (existsSync3(target))
6503
+ if (existsSync4(target))
6181
6504
  return true;
6182
6505
  const head = token.split("/")[0] ?? "";
6183
- return head !== "" && head !== "." && head !== ".." && existsSync3(resolve3(skillDir, head));
6506
+ return head !== "" && head !== "." && head !== ".." && existsSync4(resolve3(skillDir, head));
6184
6507
  }
6185
6508
  function projectPathIssue(ref, projectRoot) {
6186
6509
  const target = resolve3(projectRoot, ref.text);
6187
6510
  if (!isInside(projectRoot, target)) {
6188
6511
  return issueOf2("unresolved-path", ref, `${ref.text} points outside the project root`);
6189
6512
  }
6190
- if (existsSync3(target))
6513
+ if (existsSync4(target))
6191
6514
  return null;
6192
6515
  return issueOf2("unresolved-path", ref, `${ref.text} names nothing under the project root`);
6193
6516
  }
@@ -6207,10 +6530,10 @@ function isSystemPath(token) {
6207
6530
  function absoluteIssue(ref, seams) {
6208
6531
  const { projectRoot, skillDir } = seams;
6209
6532
  if (skillDir !== null && isInside(skillDir, ref.text)) {
6210
- return existsSync3(ref.text) ? null : issueOf2("missing-script", ref, `${ref.text} names nothing under the skill directory`);
6533
+ return existsSync4(ref.text) ? null : issueOf2("missing-script", ref, `${ref.text} names nothing under the skill directory`);
6211
6534
  }
6212
6535
  if (projectRoot !== null && isInside(projectRoot, ref.text)) {
6213
- return existsSync3(ref.text) ? null : issueOf2("unresolved-path", ref, `${ref.text} names nothing under the project root`);
6536
+ return existsSync4(ref.text) ? null : issueOf2("unresolved-path", ref, `${ref.text} names nothing under the project root`);
6214
6537
  }
6215
6538
  if (HOME_ROOTS.some((root) => ref.text.startsWith(root))) {
6216
6539
  return issueOf2("home-path", ref, `${ref.text} is one machine home directory, outside both the project` + " and the skill directory");
@@ -6546,16 +6869,16 @@ function checkVerdict(issues) {
6546
6869
  }
6547
6870
 
6548
6871
  // packages/rafa-inventory/src/inventory/trees.ts
6549
- var BUNDLED_AGENTS_DIR = join13("bundled", "agents");
6872
+ var BUNDLED_AGENTS_DIR = join14("bundled", "agents");
6550
6873
  function bundledAgentsDirectory(entry) {
6551
- return join13(dirname6(realEntry(entry ?? Bun.main)), BUNDLED_AGENTS_DIR);
6874
+ return join14(dirname6(realEntry(entry ?? Bun.main)), BUNDLED_AGENTS_DIR);
6552
6875
  }
6553
6876
  function agentTreeDirectory(tier, seams) {
6554
6877
  if (tier === "user")
6555
- return join13(seams.home, AGENT_DEFINITION_DIR);
6878
+ return join14(seams.home, AGENT_DEFINITION_DIR);
6556
6879
  if (tier === "rafa")
6557
6880
  return bundledAgentsDirectory(seams.entry);
6558
- return seams.projectRoot === null ? null : join13(seams.projectRoot, AGENT_DEFINITION_DIR);
6881
+ return seams.projectRoot === null ? null : join14(seams.projectRoot, AGENT_DEFINITION_DIR);
6559
6882
  }
6560
6883
  function readText2(path2) {
6561
6884
  try {
@@ -6770,7 +7093,7 @@ function findTierItem(resolution, kind, name) {
6770
7093
 
6771
7094
  // packages/rafa-inventory/src/tiers/serve.ts
6772
7095
  import { cpSync, mkdirSync as mkdirSync2, readFileSync as readFileSync11, rmSync, writeFileSync as writeFileSync4 } from "fs";
6773
- import { basename as basename3, dirname as dirname7, join as join14 } from "path";
7096
+ import { basename as basename3, dirname as dirname7, join as join15 } from "path";
6774
7097
 
6775
7098
  // packages/rafa-inventory/src/tiers/delivery.ts
6776
7099
  var SKILL_DELIVERY = "add-dir";
@@ -6781,7 +7104,7 @@ var SERVED_AGENTS_FILE = "agents.json";
6781
7104
  var SERVED_PLUGIN_NAME = "rafa";
6782
7105
  var SKILL_FILE2 = "SKILL.md";
6783
7106
  var SERVED_SKILLS_PATH = {
6784
- "add-dir": join14(".claude", "skills"),
7107
+ "add-dir": join15(".claude", "skills"),
6785
7108
  "plugin-dir": "skills"
6786
7109
  };
6787
7110
  var SKILL_DELIVERY_FLAG = {
@@ -6792,7 +7115,7 @@ function servedDirectory(root, run) {
6792
7115
  if (!isSessionId(run)) {
6793
7116
  throw new Error(`served directory: unusable run id ${JSON.stringify(run)}`);
6794
7117
  }
6795
- return join14(runsDir(root), run, SERVED_DIR);
7118
+ return join15(runsDir(root), run, SERVED_DIR);
6796
7119
  }
6797
7120
  function rafaWinners(resolution) {
6798
7121
  return resolution.items.flatMap((item) => item.state === "served" && item.winner.source === "rafa" ? [item] : []);
@@ -6862,15 +7185,15 @@ function admit(row) {
6862
7185
  return block.ok ? read : block;
6863
7186
  }
6864
7187
  function copySkill(row, skills) {
6865
- const to = join14(skills, row.name);
7188
+ const to = join15(skills, row.name);
6866
7189
  cpSync(dirname7(row.path), to, { recursive: true, dereference: true });
6867
7190
  return { kind: "skill", name: row.name, from: row.path, to };
6868
7191
  }
6869
7192
  function writePluginManifest(dir) {
6870
- const manifestDir = join14(dir, ".claude-plugin");
7193
+ const manifestDir = join15(dir, ".claude-plugin");
6871
7194
  mkdirSync2(manifestDir, { recursive: true });
6872
7195
  const manifest = { name: SERVED_PLUGIN_NAME, description: "rafa-tier skills served to one loop session" };
6873
- writeFileSync4(join14(manifestDir, "plugin.json"), `${JSON.stringify(manifest, null, 2)}
7196
+ writeFileSync4(join15(manifestDir, "plugin.json"), `${JSON.stringify(manifest, null, 2)}
6874
7197
  `);
6875
7198
  }
6876
7199
  function servedFlags(dir, delivery, skillCount, agents) {
@@ -6890,11 +7213,11 @@ function serveResolution(resolution, options) {
6890
7213
  rmSync(dir, { recursive: true, force: true });
6891
7214
  mkdirSync2(dir, { recursive: true });
6892
7215
  const judged2 = rafaWinners(resolution).map((item) => ({ row: item.winner, verdict: serveVerdict(item.winner) }));
6893
- const skillsDir = join14(dir, SERVED_SKILLS_PATH[delivery]);
7216
+ const skillsDir = join15(dir, SERVED_SKILLS_PATH[delivery]);
6894
7217
  const skills = judged2.flatMap(({ row, verdict }) => verdict.ok && row.kind === "skill" ? [copySkill(row, skillsDir)] : []);
6895
7218
  if (skills.length > 0 && delivery === "plugin-dir")
6896
7219
  writePluginManifest(dir);
6897
- const agentsFile = join14(dir, SERVED_AGENTS_FILE);
7220
+ const agentsFile = join15(dir, SERVED_AGENTS_FILE);
6898
7221
  const admitted = judged2.flatMap(({ row, verdict }) => verdict.ok && verdict.value !== null ? [{ row, definition: verdict.value }] : []);
6899
7222
  const agentMap = Object.fromEntries(admitted.map(({ row, definition }) => [row.name, definition]));
6900
7223
  if (admitted.length > 0)
@@ -6931,7 +7254,7 @@ function isFileEntry(dir, entry) {
6931
7254
  return true;
6932
7255
  if (!entry.isSymbolicLink())
6933
7256
  return false;
6934
- return statSync6(join15(dir, entry.name), { throwIfNoEntry: false })?.isFile() === true;
7257
+ return statSync6(join16(dir, entry.name), { throwIfNoEntry: false })?.isFile() === true;
6935
7258
  }
6936
7259
  function markdownFiles(dir) {
6937
7260
  let entries;
@@ -6952,7 +7275,7 @@ function definitionName(text) {
6952
7275
  function readAgentDirectory(dir) {
6953
7276
  const found = [];
6954
7277
  for (const file of markdownFiles(dir)) {
6955
- const path2 = join15(dir, file);
7278
+ const path2 = join16(dir, file);
6956
7279
  const text = readText3(path2);
6957
7280
  if (text === null)
6958
7281
  continue;
@@ -7118,11 +7441,11 @@ function unresolvedSkillLine(unresolved) {
7118
7441
  return `skill "${unresolved.name}" (${linesClause(unresolved.lines)}) cannot be served: ${unresolved.message}`;
7119
7442
  }
7120
7443
  // packages/rafa-inventory/src/backfill/backup.ts
7121
- import { dirname as dirname8, isAbsolute as isAbsolute2, join as join17, relative as relative4, resolve as resolve4, sep } from "path";
7444
+ import { dirname as dirname8, isAbsolute as isAbsolute2, join as join18, relative as relative4, resolve as resolve4, sep } from "path";
7122
7445
 
7123
7446
  // packages/rafa-inventory/src/backfill/proposal-file.ts
7124
- import { join as join16 } from "path";
7125
- var BACKFILL_PATH = join16(".rafa", "backfill");
7447
+ import { join as join17 } from "path";
7448
+ var BACKFILL_PATH = join17(".rafa", "backfill");
7126
7449
  var PROPOSAL_FILE_HEADER = [
7127
7450
  "# Backfill proposals: one row per skill, written by one session.",
7128
7451
  "#",
@@ -7139,7 +7462,7 @@ var PROPOSAL_FILE_HEADER = [
7139
7462
  `);
7140
7463
 
7141
7464
  // packages/rafa-inventory/src/backfill/backup.ts
7142
- var BACKUP_PATH = join17(BACKFILL_PATH, "backup");
7465
+ var BACKUP_PATH = join18(BACKFILL_PATH, "backup");
7143
7466
  // packages/rafa-inventory/src/demote/classify.ts
7144
7467
  var RULE_VERDICTS = Object.freeze({
7145
7468
  "no-frontmatter": "unclassified",
@@ -7197,18 +7520,18 @@ var DEFAULT_APPLY_SEAMS = Object.freeze({
7197
7520
  pathDirs: []
7198
7521
  });
7199
7522
  // packages/rafa-inventory/src/demote/select.ts
7200
- import { basename as basename4, dirname as dirname9, join as join18 } from "path";
7201
- var DEMOTED_PATH = join18(".rafa", "demoted");
7202
- var INSTINCTS_PATH = join18(".rafa", "instincts");
7523
+ import { basename as basename4, dirname as dirname9, join as join19 } from "path";
7524
+ var DEMOTED_PATH = join19(".rafa", "demoted");
7525
+ var INSTINCTS_PATH = join19(".rafa", "instincts");
7203
7526
  // packages/rafa-inventory/src/inventory/disabled.ts
7204
- import { join as join19 } from "path";
7527
+ import { join as join20 } from "path";
7205
7528
  var SCOPE_FILES = {
7206
- local: join19(".claude", "settings.local.json"),
7207
- project: join19(".claude", "settings.json"),
7208
- user: join19(".claude", "settings.json")
7529
+ local: join20(".claude", "settings.local.json"),
7530
+ project: join20(".claude", "settings.json"),
7531
+ user: join20(".claude", "settings.json")
7209
7532
  };
7210
7533
  // packages/rafa-inventory/src/inventory/plugins.ts
7211
- import { isAbsolute as isAbsolute3, join as join20, relative as relative5, resolve as resolve5 } from "path";
7534
+ import { isAbsolute as isAbsolute3, join as join21, relative as relative5, resolve as resolve5 } from "path";
7212
7535
 
7213
7536
  // packages/rafa/src/modules/manifest.ts
7214
7537
  var MANIFEST_VERSION = 1;
@@ -7480,7 +7803,7 @@ function validateManifest(raw, label = "rafa", seams = RUNNING_MANIFEST_SEAMS) {
7480
7803
  }
7481
7804
 
7482
7805
  // packages/rafa-inventory/src/inventory/plugins.ts
7483
- var INSTALLED_PLUGINS_PATH = join20(".claude", "plugins", "installed_plugins.json");
7806
+ var INSTALLED_PLUGINS_PATH = join21(".claude", "plugins", "installed_plugins.json");
7484
7807
  // packages/rafa-inventory/src/inventory/search/prompt.ts
7485
7808
  var SEARCH_BLOCK_FENCE = "rafa:search";
7486
7809
  var EXAMPLE_BLOCK = [
@@ -8054,13 +8377,12 @@ function lessonId(trigger, action) {
8054
8377
  ${actionHash(action)}`).digest("hex").slice(0, LESSON_HASH_LENGTH);
8055
8378
  return `${slug === "" ? LESSON_ID_FALLBACK : slug}-${digest}`;
8056
8379
  }
8057
- function lessonEvidence(context) {
8058
- const { dispatch, outcome } = context;
8380
+ function lessonEvidence(session) {
8059
8381
  return {
8060
- ...dispatch.planStub === null ? {} : { plan: dispatch.planStub },
8061
- task: dispatch.taskLine,
8062
- session: dispatch.sessionId,
8063
- outcome
8382
+ ...session.planStub === null ? {} : { plan: session.planStub },
8383
+ task: session.taskLine,
8384
+ session: session.sessionId,
8385
+ outcome: session.outcome
8064
8386
  };
8065
8387
  }
8066
8388
  function toLesson(finding, context, at) {
@@ -8089,7 +8411,7 @@ function toLesson(finding, context, at) {
8089
8411
  domain: finding.domain ?? DEFAULT_LESSON_DOMAIN,
8090
8412
  scope: "project",
8091
8413
  source: "task-report",
8092
- evidence: [lessonEvidence(context)],
8414
+ evidence: [lessonEvidence({ ...context.dispatch, outcome: context.outcome })],
8093
8415
  cause,
8094
8416
  projectId: null
8095
8417
  }
@@ -8102,6 +8424,157 @@ function reportLessons(record, context, now) {
8102
8424
  const instincts = record.reading.report.findings.map((finding) => toLesson(finding, context, at)).filter((lesson) => lesson !== null);
8103
8425
  return instincts.length === 0 ? null : { source_id: context.dispatch.sessionId, instincts };
8104
8426
  }
8427
+
8428
+ // packages/rafa-inventory/src/report/bug-fix-pairs.ts
8429
+ var JOINED_KIND = "github";
8430
+ var ISSUE_NUMBER3 = /^\d+$/;
8431
+ function collapsed(text) {
8432
+ return text.replace(/\s+/g, " ").trim();
8433
+ }
8434
+ function sameArtifact(left, right) {
8435
+ return left !== null && collapsed(left) === collapsed(right);
8436
+ }
8437
+ function namesIssue(text, issue4) {
8438
+ return new RegExp(`(?<![\\w#])#${issue4}(?!\\w)`).test(text);
8439
+ }
8440
+ function isIssueStub(stub, issue4) {
8441
+ return stub === `rafa-${issue4}` || (stub?.startsWith(`rafa-${issue4}-`) ?? false);
8442
+ }
8443
+ function bugText(bug, outOfScope) {
8444
+ const key = collapsed(bug.artifact);
8445
+ let best = null;
8446
+ for (const row of outOfScope) {
8447
+ if (row.sessionId !== bug.sessionId || row.artifact === null)
8448
+ continue;
8449
+ const tail = collapsed(row.artifact);
8450
+ if (tail === "" || !key.endsWith(tail))
8451
+ continue;
8452
+ if (best === null || tail.length > collapsed(best.artifact ?? "").length)
8453
+ best = row;
8454
+ }
8455
+ return best === null || best.artifact === null ? { words: bug.artifact, artifact: bug.artifact } : { words: best.what, artifact: best.artifact };
8456
+ }
8457
+ function linkedUnits(issue4, links) {
8458
+ const byStub = new Map;
8459
+ for (const link of links) {
8460
+ if (!isIssueStub(link.stub, issue4))
8461
+ continue;
8462
+ const tasks = byStub.get(link.stub) ?? [];
8463
+ byStub.set(link.stub, [...tasks, ...link.tasks.map((line) => ({ line, stage: link.stage }))]);
8464
+ }
8465
+ if (byStub.size > 0) {
8466
+ return [...byStub].map(([stub, tasks]) => ({ link: "stub", stub, tasks }));
8467
+ }
8468
+ return links.filter((link) => link.context !== null && namesIssue(link.context, issue4)).map((link) => ({
8469
+ link: "stage-context",
8470
+ stub: link.stub,
8471
+ tasks: link.tasks.map((line) => ({ line, stage: link.stage }))
8472
+ }));
8473
+ }
8474
+ function unlinkedReason(issue4, links, rows) {
8475
+ const filed = new Set(links.map((link) => link.stub));
8476
+ const fileless = rows.reports.some((report) => report.planStub !== null && !filed.has(report.planStub) && (isIssueStub(report.planStub, issue4) || namesIssue(report.taskLine, issue4)));
8477
+ return fileless ? "no-plan-file" : "no-link";
8478
+ }
8479
+ function sameTaskLine(stored, planned) {
8480
+ return stripTaskDeclaration(stored) === stripTaskDeclaration(planned);
8481
+ }
8482
+ function matchingResolutions(rows, stub, line, artifact) {
8483
+ return rows.resolved.filter((row) => row.planStub === stub && sameTaskLine(row.taskLine, line) && sameArtifact(row.artifact, artifact));
8484
+ }
8485
+ function fixingTask(unit, issue4, artifact, rows) {
8486
+ const naming = unit.tasks.filter((task) => namesIssue(task.line, issue4));
8487
+ if (naming.length === 1)
8488
+ return naming[0] ?? null;
8489
+ if (unit.tasks.length === 1)
8490
+ return unit.tasks[0] ?? null;
8491
+ const holding = unit.tasks.filter((task) => matchingResolutions(rows, unit.stub, task.line, artifact).length > 0);
8492
+ return holding.length === 1 ? holding[0] ?? null : null;
8493
+ }
8494
+ function fixingReport(bug, stub, line, reports) {
8495
+ const filedAt = Date.parse(bug.collectedAt);
8496
+ const own = reports.filter((report) => report.planStub === stub && sameTaskLine(report.taskLine, line) && report.sessionId !== bug.sessionId);
8497
+ if (own.length === 0)
8498
+ return "no-done-report";
8499
+ const after = own.filter((report) => Date.parse(report.collectedAt) > filedAt).sort((left, right) => Date.parse(left.collectedAt) - Date.parse(right.collectedAt));
8500
+ return after[0] ?? "fixed-before-filed";
8501
+ }
8502
+ function fixAction(rows, fix, line, artifact) {
8503
+ const resolutions = matchingResolutions(rows, fix.planStub ?? "", line, artifact);
8504
+ const chosen = resolutions.find((row) => row.sessionId === fix.sessionId) ?? resolutions[0];
8505
+ return chosen?.resolution ?? stripTaskDeclaration(line);
8506
+ }
8507
+ function pairLesson(bug, text, fix, action, at) {
8508
+ return {
8509
+ id: lessonId(text.words, action),
8510
+ trigger: text.words,
8511
+ action,
8512
+ action_hash: actionHash(action),
8513
+ confidence: LESSON_CONFIDENCE,
8514
+ usage_count: 2,
8515
+ sources: [bug.sessionId, fix.sessionId],
8516
+ artifact: text.artifact,
8517
+ signal: "loud",
8518
+ status: "active",
8519
+ created_at: at,
8520
+ updated_at: at,
8521
+ description: {
8522
+ kind: "gotcha",
8523
+ domain: DEFAULT_LESSON_DOMAIN,
8524
+ scope: "project",
8525
+ source: "task-report",
8526
+ evidence: [lessonEvidence(bug), lessonEvidence(fix)],
8527
+ cause: text.words,
8528
+ projectId: null
8529
+ }
8530
+ };
8531
+ }
8532
+ function pairUnit(bug, issue4, text, unit, rows, at) {
8533
+ const task = fixingTask(unit, issue4, text.artifact, rows);
8534
+ if (task === null)
8535
+ return "ambiguous-stage";
8536
+ const fix = fixingReport(bug, unit.stub, task.line, rows.reports);
8537
+ if (typeof fix === "string")
8538
+ return fix;
8539
+ const action = fixAction(rows, fix, task.line, text.artifact);
8540
+ return {
8541
+ bug,
8542
+ issue: issue4,
8543
+ link: unit.link,
8544
+ plan: unit.stub,
8545
+ stage: task.stage,
8546
+ fix,
8547
+ lesson: pairLesson(bug, text, fix, action, at)
8548
+ };
8549
+ }
8550
+ function pairBug(bug, rows, links, at) {
8551
+ const issue4 = bug.trackerRef.externalId;
8552
+ if (bug.trackerRef.kind !== JOINED_KIND || !ISSUE_NUMBER3.test(issue4))
8553
+ return "local-ref";
8554
+ const units = linkedUnits(issue4, links);
8555
+ if (units.length === 0)
8556
+ return unlinkedReason(issue4, links, rows);
8557
+ const text = bugText(bug, rows.outOfScope);
8558
+ const answers = units.map((unit) => pairUnit(bug, issue4, text, unit, rows, at));
8559
+ const pairs = answers.filter((answer2) => typeof answer2 !== "string");
8560
+ if (pairs.length > 0)
8561
+ return pairs;
8562
+ return answers.find((answer2) => typeof answer2 === "string") ?? "no-link";
8563
+ }
8564
+ function pairBugFixes(rows, links, now) {
8565
+ const at = now.toISOString();
8566
+ const pairs = [];
8567
+ const unpaired = [];
8568
+ for (const bug of rows.bugs) {
8569
+ const answer2 = pairBug(bug, rows, links, at);
8570
+ if (typeof answer2 === "string") {
8571
+ unpaired.push({ bug, issue: bug.trackerRef.externalId, reason: answer2 });
8572
+ } else {
8573
+ pairs.push(...answer2);
8574
+ }
8575
+ }
8576
+ return { pairs, unpaired };
8577
+ }
8105
8578
  // packages/rafa-inventory/src/start/serving.ts
8106
8579
  function resolveSessionTiers(reading) {
8107
8580
  const rows = readTrees({
@@ -8308,13 +8781,34 @@ function triggerCandidate(lesson) {
8308
8781
  };
8309
8782
  return { record, description: null, body: "" };
8310
8783
  }
8311
- function triggerMatches(lesson, words) {
8312
- return scoreCandidate(triggerCandidate(lesson), words).words.length >= TRIGGER_WORD_FLOOR;
8784
+ function triggerWordCount(lesson, words) {
8785
+ return scoreCandidate(triggerCandidate(lesson), words).words.length;
8786
+ }
8787
+ function compareIds(a, b) {
8788
+ if (a < b)
8789
+ return -1;
8790
+ if (a > b)
8791
+ return 1;
8792
+ return 0;
8793
+ }
8794
+ function compareMatches(a, b) {
8795
+ if (a.byArtifact !== b.byArtifact) {
8796
+ return a.byArtifact ? -1 : 1;
8797
+ }
8798
+ if (a.triggerWords !== b.triggerWords)
8799
+ return b.triggerWords - a.triggerWords;
8800
+ if (a.lesson.confidence !== b.lesson.confidence)
8801
+ return b.lesson.confidence - a.lesson.confidence;
8802
+ return compareIds(a.lesson.id, b.lesson.id);
8313
8803
  }
8314
8804
  function selectLessons(task, bundle) {
8315
8805
  const words = questionWords(task.text);
8316
- const kept = bundle.instincts.filter((lesson) => artifactMatches(lesson, task) || triggerMatches(lesson, words));
8317
- return [...kept].sort((a, b) => b.confidence - a.confidence).slice(0, LESSON_LIMIT);
8806
+ const matches = bundle.instincts.map((lesson) => ({
8807
+ lesson,
8808
+ byArtifact: artifactMatches(lesson, task),
8809
+ triggerWords: triggerWordCount(lesson, words)
8810
+ }));
8811
+ return matches.filter((match) => match.byArtifact || match.triggerWords >= TRIGGER_WORD_FLOOR).sort(compareMatches).slice(0, LESSON_LIMIT).map((match) => match.lesson);
8318
8812
  }
8319
8813
  // packages/rafa-effort/src/effort/skill-use.ts
8320
8814
  var SKILL_USE_CLI_FLOOR = "2.1.280";
@@ -8333,10 +8827,10 @@ function parseRecord3(line) {
8333
8827
  }
8334
8828
  }
8335
8829
  function subagentLogPaths(sessionLogPath) {
8336
- const dir = join21(dirname10(sessionLogPath), sessionIdFromPath(sessionLogPath), "subagents");
8337
- if (!existsSync4(dir))
8830
+ const dir = join22(dirname10(sessionLogPath), sessionIdFromPath(sessionLogPath), "subagents");
8831
+ if (!existsSync5(dir))
8338
8832
  return [];
8339
- return readdirSync5(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && SUBAGENT_LOG_NAME.test(entry.name)).map((entry) => join21(dir, entry.name)).sort((a, b) => a.localeCompare(b));
8833
+ return readdirSync5(dir, { withFileTypes: true }).filter((entry) => entry.isFile() && SUBAGENT_LOG_NAME.test(entry.name)).map((entry) => join22(dir, entry.name)).sort((a, b) => a.localeCompare(b));
8340
8834
  }
8341
8835
  function versionFields(version) {
8342
8836
  if (typeof version !== "string")
@@ -8606,7 +9100,7 @@ function baseAdapterRegistry() {
8606
9100
 
8607
9101
  // packages/rafa/src/modules/load.ts
8608
9102
  import { readFileSync as readFileSync14 } from "fs";
8609
- import { isAbsolute as isAbsolute4, join as join22, relative as relative6, resolve as resolve6 } from "path";
9103
+ import { isAbsolute as isAbsolute4, join as join23, relative as relative6, resolve as resolve6 } from "path";
8610
9104
  import { pathToFileURL } from "url";
8611
9105
  var importModuleEntry = (entry) => import(pathToFileURL(entry).href);
8612
9106
  var ADAPTER_TYPES = ["tracker", "store", "planner", "output", "sync", "logger"];
@@ -8625,7 +9119,7 @@ function unread(name, directory, ...problems) {
8625
9119
  }
8626
9120
  function readPathSource(source, settings, seams) {
8627
9121
  const directory = resolve6(settings.base, source.location);
8628
- const file = join22(directory, "package.json");
9122
+ const file = join23(directory, "package.json");
8629
9123
  let parsed;
8630
9124
  try {
8631
9125
  parsed = JSON.parse((seams.readText ?? ((path2) => readFileSync14(path2, "utf8")))(file));
@@ -8840,10 +9334,14 @@ function selectSync(repoRoot, config, registry = CORE_ADAPTER_REGISTRY) {
8840
9334
 
8841
9335
  // packages/rafa-effort/src/effort/sync/contact.ts
8842
9336
  var HUB_UNREACHABLE = "HubUnreachable";
9337
+ var HUB_CONTRACT_MISMATCH = "HubContractMismatch";
8843
9338
  var OPENING = "effort sync";
8844
9339
  function isHubUnreachable(error) {
8845
9340
  return error instanceof Error && error.name === HUB_UNREACHABLE;
8846
9341
  }
9342
+ function isHubContractMismatch(error) {
9343
+ return error instanceof Error && error.name === HUB_CONTRACT_MISMATCH;
9344
+ }
8847
9345
  function firstLine3(text) {
8848
9346
  return text.split(`
8849
9347
  `).map((line) => line.trim()).find((line) => line !== "") ?? describeValue(text);
@@ -8872,6 +9370,7 @@ function createHubContact(input, seams = {}) {
8872
9370
  const strategy = strategyOf(config.effortSync);
8873
9371
  let selection = null;
8874
9372
  let toldUnreachable = false;
9373
+ let toldMismatch = false;
8875
9374
  const pullRequest = Object.freeze({
8876
9375
  from: null,
8877
9376
  dryRun: false,
@@ -8890,6 +9389,13 @@ function createHubContact(input, seams = {}) {
8890
9389
  return { outcome: "done", result: await run2() };
8891
9390
  } catch (error) {
8892
9391
  const problem = messageOf(error);
9392
+ if (isHubContractMismatch(error)) {
9393
+ const line = firstLine3(problem);
9394
+ if (!toldMismatch)
9395
+ input.warn(line);
9396
+ toldMismatch = true;
9397
+ return { outcome: "mismatch", problem: line };
9398
+ }
8893
9399
  if (!isHubUnreachable(error)) {
8894
9400
  input.warn(`${OPENING}: ${direction} over ${strategy} failed: ${problem}`);
8895
9401
  return { outcome: "failed", problem };
@@ -8908,7 +9414,7 @@ function createHubContact(input, seams = {}) {
8908
9414
  return { state: "unselected", strategy, problem: answer2.problem };
8909
9415
  const { sync } = answer2;
8910
9416
  const push = direction === "push-then-pull" ? await attempt("push", () => sync.push({ to: null })) : null;
8911
- const pull = push?.outcome === "unreachable" ? { outcome: "skipped" } : await attempt("pull", () => sync.pull(pullRequest));
9417
+ const pull = push?.outcome === "unreachable" || push?.outcome === "mismatch" ? { outcome: "skipped" } : await attempt("pull", () => sync.pull(pullRequest));
8912
9418
  return { state: "contacted", strategy, push, pull };
8913
9419
  };
8914
9420
  return Object.freeze({
@@ -8961,11 +9467,11 @@ function selectCommits(rows, collected) {
8961
9467
  return { pending, alreadyCollected };
8962
9468
  }
8963
9469
  function readPlanStubs(plansDir) {
8964
- return existsSync5(plansDir) ? planStubsFromFileNames(readdirSync6(plansDir)) : [];
9470
+ return existsSync6(plansDir) ? planStubsFromFileNames(readdirSync6(plansDir)) : [];
8965
9471
  }
8966
- async function collectSessionRow(candidate, planStubs) {
9472
+ async function collectSessionRow(candidate, planStubs, home = homedir3()) {
8967
9473
  const enqueue = await findFirstEnqueue(readLines(candidate.path));
8968
- const stats = await readSessionLog(candidate.path);
9474
+ const stats = await readSessionLog(candidate.path, home);
8969
9475
  const attribution = attributeSession(stats, enqueue.content, planStubs);
8970
9476
  return {
8971
9477
  ...stats,
@@ -9003,7 +9509,7 @@ async function collectSessionHalf(context) {
9003
9509
  let failed2 = 0;
9004
9510
  for (const candidate of selection.pending) {
9005
9511
  try {
9006
- rows.push(await collectSessionRow(candidate, planStubs));
9512
+ rows.push(await collectSessionRow(candidate, planStubs, context.home));
9007
9513
  read.push(candidate);
9008
9514
  context.note(`sessions: read ${candidate.sessionId}`);
9009
9515
  } catch (error) {
@@ -9073,6 +9579,7 @@ async function collectEffort(options) {
9073
9579
  const { worktreeDir, ...sources } = await resolveSources(options, log);
9074
9580
  const context = {
9075
9581
  repoRoot,
9582
+ home: options.home,
9076
9583
  logDirs: logDirsOf(options, worktreeDir),
9077
9584
  ...sources,
9078
9585
  sinceEpochMs: options.sinceEpochMs ?? null,
@@ -9128,14 +9635,14 @@ async function collect2(args, repoRoot) {
9128
9635
  try {
9129
9636
  result = await collectEffort({
9130
9637
  repoRoot,
9131
- home: homedir2(),
9638
+ home: homedir3(),
9132
9639
  sinceEpochMs: parsed.sinceEpochMs,
9133
9640
  collectSessions: parsed.collectSessions,
9134
9641
  collectCommits: parsed.collectCommits,
9135
9642
  skills: parsed.collectHeldSkills ? "held" : "appended",
9136
9643
  verbose: parsed.verbose
9137
9644
  });
9138
- resolved = await loadConfig({ root: repoRoot, home: homedir2() }, {}, () => {});
9645
+ resolved = await loadConfig({ root: repoRoot, home: homedir3() }, {}, () => {});
9139
9646
  } catch (error) {
9140
9647
  if (!(error instanceof ConfigError))
9141
9648
  throw error;
@@ -9145,11 +9652,11 @@ async function collect2(args, repoRoot) {
9145
9652
  activeOutput().info(line);
9146
9653
  }
9147
9654
  const warn = (message) => activeOutput().warn(message);
9148
- await createHubContact({ root: repoRoot, home: homedir2(), resolved, warn }).pushThenPull();
9655
+ await createHubContact({ root: repoRoot, home: homedir3(), resolved, warn }).pushThenPull();
9149
9656
  }
9150
9657
  // packages/rafa/src/core/loop/session-readings.ts
9151
9658
  import { execFileSync as execFileSync2 } from "child_process";
9152
- import { join as join23, relative as relative7 } from "path";
9659
+ import { join as join24, relative as relative7 } from "path";
9153
9660
  var STOP_WAIT_MS = 30000;
9154
9661
  var STOP_POLL_MS = 200;
9155
9662
  function gitBranch(root) {
@@ -9671,7 +10178,7 @@ function tasksFrom(facts, fromIndex) {
9671
10178
  function failingNames(planStub, planCi) {
9672
10179
  if (planStub === null)
9673
10180
  return [];
9674
- const names = new Set(planCi.filter((row) => row.planStub === planStub).flatMap(({ failing }) => failing));
10181
+ const names = new Set(planCi.filter(({ row }) => row.planStub === planStub).flatMap(({ row }) => row.failing));
9675
10182
  return [...names].map((text) => ({ source: "plan-ci", sessionId: null, taskLine: null, field: "failing", text }));
9676
10183
  }
9677
10184
  function findRecurrences(strings, facts, fromIndex, planCi) {
@@ -9686,10 +10193,10 @@ function findRecurrences(strings, facts, fromIndex, planCi) {
9686
10193
  }
9687
10194
 
9688
10195
  // packages/rafa-effort/src/effort/skill-facts.ts
9689
- import { existsSync as existsSync8 } from "fs";
10196
+ import { existsSync as existsSync9 } from "fs";
9690
10197
 
9691
10198
  // packages/rafa/src/effort/store/plan-ci.ts
9692
- import { existsSync as existsSync6, readdirSync as readdirSync7 } from "fs";
10199
+ import { existsSync as existsSync7, readdirSync as readdirSync7 } from "fs";
9693
10200
 
9694
10201
  // packages/rafa/src/effort/store/check-rows.ts
9695
10202
  function verdictOf2(rows) {
@@ -9723,17 +10230,25 @@ function rowOf3(stored) {
9723
10230
  readAt: stored.read_at
9724
10231
  };
9725
10232
  }
9726
- function readPlanCi(repoRoot, planStub) {
10233
+ function readPlanCiFacts(repoRoot, planStub) {
9727
10234
  const path2 = sqliteStorePath(repoRoot);
9728
- if (!existsSync6(path2))
10235
+ if (!existsSync7(path2))
9729
10236
  return [];
9730
- const rows = withSqliteStore(path2, "read", false, (db) => planStub === undefined ? db.query(`${SELECT_COLUMNS} ORDER BY seq`).all() : db.query(`${SELECT_COLUMNS} WHERE plan_stub = ? ORDER BY seq`).all(planStub));
9731
- return rows.map(rowOf3);
10237
+ return withSqliteStore(path2, "read", false, (db) => {
10238
+ const stored = db.query(SELECT_COLUMNS).all();
10239
+ const byKey = new Map(stored.map((row) => [readingKey("plan_ci", { pr: row.pr, head_sha: row.head_sha, read_at: row.read_at }), row]));
10240
+ return readRepositoryFacts(db, "plan_ci").flatMap((fact) => {
10241
+ const canonical = byKey.get(fact.canonical.key);
10242
+ if (canonical === undefined || planStub !== undefined && canonical.plan_stub !== planStub)
10243
+ return [];
10244
+ return [{ row: rowOf3(canonical), sightings: fact.sightings, origins: fact.origins, lastSighting: fact.lastSighting }];
10245
+ });
10246
+ });
9732
10247
  }
9733
10248
 
9734
10249
  // packages/rafa/src/effort/store/reports.ts
9735
10250
  import { randomUUID as randomUUID2 } from "crypto";
9736
- import { existsSync as existsSync7 } from "fs";
10251
+ import { existsSync as existsSync8 } from "fs";
9737
10252
  var ROWS_PER_WRITE = 1;
9738
10253
  var INSERT_REPORT = `
9739
10254
  INSERT INTO task_reports (
@@ -9795,7 +10310,7 @@ var SELECT_TALLIES = `
9795
10310
  `;
9796
10311
  function readTaskReportTallies(repoRoot) {
9797
10312
  const path2 = sqliteStorePath(repoRoot);
9798
- if (!existsSync7(path2))
10313
+ if (!existsSync8(path2))
9799
10314
  return [];
9800
10315
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_TALLIES).all());
9801
10316
  return rows.map((row) => ({
@@ -9820,7 +10335,7 @@ function parseSkillsUsed(sessionId, json) {
9820
10335
  }
9821
10336
  function readReportedSkills(repoRoot) {
9822
10337
  const path2 = sqliteStorePath(repoRoot);
9823
- if (!existsSync7(path2))
10338
+ if (!existsSync8(path2))
9824
10339
  return [];
9825
10340
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_REPORTED_SKILLS).all());
9826
10341
  return rows.map((row) => ({
@@ -9909,7 +10424,7 @@ function orderedReports(reports, plans) {
9909
10424
  return order.flatMap((plan) => reports.filter(({ planStub }) => planStub === plan));
9910
10425
  }
9911
10426
  function readSkillFacts(repoRoot, plans) {
9912
- if (!existsSync8(sqliteStorePath(repoRoot)))
10427
+ if (!existsSync9(sqliteStorePath(repoRoot)))
9913
10428
  return [];
9914
10429
  const reports = orderedReports(readReportedSkills(repoRoot), plans);
9915
10430
  if (reports.length === 0)
@@ -9917,8 +10432,8 @@ function readSkillFacts(repoRoot, plans) {
9917
10432
  const rows = readSessionRows(sqliteStorePath(repoRoot));
9918
10433
  const invoked = invocationsBySession(readSkillInvocations(repoRoot));
9919
10434
  const planCi = new Map;
9920
- for (const row of readPlanCi(repoRoot))
9921
- planCi.set(row.planStub, [...planCi.get(row.planStub) ?? [], row]);
10435
+ for (const fact of readPlanCiFacts(repoRoot))
10436
+ planCi.set(fact.row.planStub, [...planCi.get(fact.row.planStub) ?? [], fact]);
9922
10437
  return reports.map((report) => {
9923
10438
  const offer = rows.offers.get(report.sessionId);
9924
10439
  return {
@@ -10113,8 +10628,14 @@ function armOf(resolver, facts, match, failureStrings, artifacts) {
10113
10628
  m2: m2Of(known)
10114
10629
  };
10115
10630
  }
10116
- function latestReading(readings) {
10117
- return readings.reduce((latest, reading) => latest === null || reading.readAt >= latest.readAt ? reading : latest, null);
10631
+ function isCurrentOver(fact, current) {
10632
+ if (fact.lastSighting !== current.lastSighting)
10633
+ return fact.lastSighting > current.lastSighting;
10634
+ return fact.row.verdict === "red" || current.row.verdict !== "red";
10635
+ }
10636
+ function currentReading(facts) {
10637
+ const current = facts.reduce((picked, fact) => picked === null || isCurrentOver(fact, picked) ? fact : picked, null);
10638
+ return current?.row ?? null;
10118
10639
  }
10119
10640
  function skillsReportOf(facts, failureStrings, artifacts) {
10120
10641
  const plans = [...groupBy(facts, ({ planStub }) => planStub)].map(([planStub, planFacts]) => {
@@ -10123,7 +10644,7 @@ function skillsReportOf(facts, failureStrings, artifacts) {
10123
10644
  return {
10124
10645
  planStub,
10125
10646
  sessions: planFacts.length,
10126
- planCi: latestReading(planFacts[0]?.planCi ?? []),
10647
+ planCi: currentReading(planFacts[0]?.planCi ?? []),
10127
10648
  resolvers: arms.map(([resolver, armFacts]) => armOf(resolver, armFacts, match, failureStrings, artifacts))
10128
10649
  };
10129
10650
  });
@@ -10148,10 +10669,10 @@ async function readSkillsReport(options) {
10148
10669
  }
10149
10670
 
10150
10671
  // packages/rafa-effort/src/effort/report-trend-read.ts
10151
- import { homedir as homedir4 } from "os";
10672
+ import { homedir as homedir5 } from "os";
10152
10673
 
10153
10674
  // packages/rafa/src/effort/store/dispatches.ts
10154
- import { existsSync as existsSync9 } from "fs";
10675
+ import { existsSync as existsSync10 } from "fs";
10155
10676
  var ROWS_PER_WRITE2 = 1;
10156
10677
  var TEXT_KEYS = ["agent", "model", "effort"];
10157
10678
  var INSERT_DISPATCH = `
@@ -10273,7 +10794,7 @@ var SELECT_BUDGETS = `
10273
10794
  `;
10274
10795
  function readSessionBudgets(repoRoot) {
10275
10796
  const path2 = sqliteStorePath(repoRoot);
10276
- if (!existsSync9(path2))
10797
+ if (!existsSync10(path2))
10277
10798
  return [];
10278
10799
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_BUDGETS).all());
10279
10800
  return rows.map((row) => ({
@@ -10291,17 +10812,17 @@ var SELECT_AGENTS = `
10291
10812
  `;
10292
10813
  function readSessionAgents(repoRoot) {
10293
10814
  const path2 = sqliteStorePath(repoRoot);
10294
- if (!existsSync9(path2))
10815
+ if (!existsSync10(path2))
10295
10816
  return [];
10296
10817
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_AGENTS).all());
10297
10818
  return rows.map((row) => ({ sessionId: row.session_id, agent: row.agent }));
10298
10819
  }
10299
10820
 
10300
10821
  // packages/rafa-effort/src/effort/report.ts
10301
- import { homedir as homedir3 } from "os";
10822
+ import { homedir as homedir4 } from "os";
10302
10823
 
10303
10824
  // packages/rafa/src/effort/store/preflight.ts
10304
- import { existsSync as existsSync10 } from "fs";
10825
+ import { existsSync as existsSync11 } from "fs";
10305
10826
  var TIERS = {
10306
10827
  required: true,
10307
10828
  optional: true
@@ -10416,7 +10937,7 @@ function haltedCheckOf(row) {
10416
10937
  }
10417
10938
  function readPreflightHalts(repoRoot) {
10418
10939
  const path2 = sqliteStorePath(repoRoot);
10419
- if (!existsSync10(path2))
10940
+ if (!existsSync11(path2))
10420
10941
  return [];
10421
10942
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_HALTED).all());
10422
10943
  const halts = new Map;
@@ -10596,7 +11117,7 @@ function budgetedSessions(rows, budgets) {
10596
11117
  }
10597
11118
 
10598
11119
  // packages/rafa-effort/src/effort/report-doc-bugs.ts
10599
- import { existsSync as existsSync11 } from "fs";
11120
+ import { existsSync as existsSync12 } from "fs";
10600
11121
 
10601
11122
  // packages/rafa/src/triage/doc-only.ts
10602
11123
  var FILE_EXTENSIONS2 = [
@@ -10656,25 +11177,25 @@ var SELECT_FILED_BUGS = `
10656
11177
  FROM out_of_scope_bugs
10657
11178
  WHERE scope = 'rafa'
10658
11179
  `;
10659
- function bugText(bug) {
11180
+ function bugText2(bug) {
10660
11181
  return bug.artifact === null ? bug.what : `${bug.what}
10661
11182
  ${bug.artifact}`;
10662
11183
  }
10663
11184
  function countDocOnlyBugs(bugs) {
10664
11185
  return {
10665
11186
  bugs: bugs.length,
10666
- docOnly: bugs.filter((bug) => namesOnlyDocs(bugText(bug))).length
11187
+ docOnly: bugs.filter((bug) => namesOnlyDocs(bugText2(bug))).length
10667
11188
  };
10668
11189
  }
10669
11190
  function readDocOnlyBugs(repoRoot) {
10670
11191
  const path2 = sqliteStorePath(repoRoot);
10671
- if (!existsSync11(path2))
11192
+ if (!existsSync12(path2))
10672
11193
  return countDocOnlyBugs([]);
10673
11194
  return countDocOnlyBugs(withSqliteStore(path2, "read", false, (db) => db.query(SELECT_FILED_BUGS).all()));
10674
11195
  }
10675
11196
 
10676
11197
  // packages/rafa-effort/src/effort/report-kinds.ts
10677
- import { existsSync as existsSync12 } from "fs";
11198
+ import { existsSync as existsSync13 } from "fs";
10678
11199
  var SELECT_ROUTED_ENTRIES = `
10679
11200
  SELECT plan_stub AS planStub, kind, route
10680
11201
  FROM bug_routes
@@ -10707,7 +11228,7 @@ function countBugKinds(rows) {
10707
11228
  }
10708
11229
  function readBugKinds(repoRoot) {
10709
11230
  const path2 = sqliteStorePath(repoRoot);
10710
- if (!existsSync12(path2))
11231
+ if (!existsSync13(path2))
10711
11232
  return { plans: [], problem: null };
10712
11233
  try {
10713
11234
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_ROUTED_ENTRIES).all());
@@ -11016,7 +11537,7 @@ function refuse2(problems) {
11016
11537
  async function writeSkillsReport(plans, json, repoRoot) {
11017
11538
  let built;
11018
11539
  try {
11019
- built = await readSkillsReport({ repoRoot, home: homedir3(), plans });
11540
+ built = await readSkillsReport({ repoRoot, home: homedir4(), plans });
11020
11541
  } catch (error) {
11021
11542
  if (!(error instanceof ConfigError))
11022
11543
  throw error;
@@ -11038,7 +11559,7 @@ async function report(args, repoRoot) {
11038
11559
  const parsed = parseReportArgs(args);
11039
11560
  if (parsed.errors.length > 0)
11040
11561
  refuse2(parsed.errors);
11041
- await pullBeforeRead({ roots: { root: repoRoot, home: homedir3() }, warn: (line) => activeOutput().warn(line) });
11562
+ await pullBeforeRead({ roots: { root: repoRoot, home: homedir4() }, warn: (line) => activeOutput().warn(line) });
11042
11563
  if (parsed.skills) {
11043
11564
  await writeSkillsReport(parsed.plans, parsed.json, repoRoot);
11044
11565
  return;
@@ -11051,7 +11572,7 @@ async function report(args, repoRoot) {
11051
11572
  try {
11052
11573
  built = await buildReport({
11053
11574
  repoRoot,
11054
- home: homedir3(),
11575
+ home: homedir4(),
11055
11576
  kinds: parsed.kinds,
11056
11577
  entrypoints: parsed.entrypoints
11057
11578
  });
@@ -11423,7 +11944,7 @@ async function readTrendReport({ repoRoot, home, options }) {
11423
11944
  async function writeTrendReport(options, json, repoRoot) {
11424
11945
  let built;
11425
11946
  try {
11426
- built = await readTrendReport({ repoRoot, home: homedir4(), options });
11947
+ built = await readTrendReport({ repoRoot, home: homedir5(), options });
11427
11948
  } catch (error) {
11428
11949
  if (!(error instanceof ConfigError))
11429
11950
  throw error;
@@ -11479,8 +12000,8 @@ async function readDoctorEffortSync(input, seams = {}) {
11479
12000
  }
11480
12001
  }
11481
12002
  // packages/rafa-effort/src/effort/sync/file.ts
11482
- import { existsSync as existsSync13 } from "fs";
11483
- import { join as join24, resolve as resolve8 } from "path";
12003
+ import { existsSync as existsSync14 } from "fs";
12004
+ import { join as join25, resolve as resolve8 } from "path";
11484
12005
  var REFUSAL2 = "effort sync (file)";
11485
12006
  var NOTHING_COPIED = "Nothing was copied.";
11486
12007
 
@@ -11496,7 +12017,7 @@ function refuseUncarriable(backend, source) {
11496
12017
  if (backend === "ndjson") {
11497
12018
  throw new FileSyncRefusal(`${REFUSAL2}: this project keeps its sessions and commits as NDJSON (store: ndjson), and the file carried` + ` is effort.sqlite, which would hold none of them. ${NOTHING_COPIED} Next safe step: ${MOVE_TO_SQLITE}`);
11498
12019
  }
11499
- if (!existsSync13(join24(source, SQLITE_STORE_FILE_NAME))) {
12020
+ if (!existsSync14(join25(source, SQLITE_STORE_FILE_NAME))) {
11500
12021
  throw new FileSyncRefusal(`${REFUSAL2}: no ${SQLITE_STORE_FILE_NAME} in ${source}. ${NOTHING_COPIED}`);
11501
12022
  }
11502
12023
  }
@@ -11514,11 +12035,11 @@ function createFileSync(options) {
11514
12035
  const source = storeDir();
11515
12036
  refuseUncarriable(backend, source);
11516
12037
  const copied = copyEffortStore({ source, target });
11517
- return Object.freeze({ status: "pushed", path: join24(copied.directory, SQLITE_STORE_FILE_NAME) });
12038
+ return Object.freeze({ status: "pushed", path: join25(copied.directory, SQLITE_STORE_FILE_NAME) });
11518
12039
  };
11519
12040
  const pull = async ({ from, dryRun, sessionId = null }) => {
11520
12041
  const otherPath = resolve8(repoRoot, requirePath("from", from));
11521
- const path2 = join24(storeDir(), SQLITE_STORE_FILE_NAME);
12042
+ const path2 = join25(storeDir(), SQLITE_STORE_FILE_NAME);
11522
12043
  const stamp2 = fileStamp(now());
11523
12044
  const merge2 = mergeStore({ ...mergeSeams(options), path: path2, otherPath, backend, dryRun, stamp: stamp2, now, sessionId });
11524
12045
  return Object.freeze({ status: "pulled", merge: merge2 });
@@ -11594,8 +12115,8 @@ function createJsonOutput({
11594
12115
  }
11595
12116
 
11596
12117
  // src/adapters/planner/claude.ts
11597
- import { existsSync as existsSync14 } from "fs";
11598
- import { mkdir as mkdir3, readFile as readFile3 } from "fs/promises";
12118
+ import { existsSync as existsSync15 } from "fs";
12119
+ import { mkdir as mkdir3, readFile as readFile4 } from "fs/promises";
11599
12120
  import { posix as posix2, resolve as resolve9 } from "path";
11600
12121
  var FAILURE_EXIT_CODE = 1;
11601
12122
  function planFilePath(planDir, fileName) {
@@ -11618,11 +12139,11 @@ function createClaudePlanner(options) {
11618
12139
  const create = async ({ specPath, stub }) => {
11619
12140
  const planPath = planFilePath(planDir, `PLAN-${stub}.md`);
11620
12141
  const prerequisitesPath = planFilePath(planDir, `PREREQUISITES-${stub}.md`);
11621
- const isWritten = (path2) => existsSync14(resolve9(root, path2));
12142
+ const isWritten = (path2) => existsSync15(resolve9(root, path2));
11622
12143
  if (isWritten(planPath)) {
11623
12144
  throw new ClaudePlannerError(`${planPath} already exists`, FAILURE_EXIT_CODE);
11624
12145
  }
11625
- const specContent = await readFile3(resolve9(root, specPath), "utf8");
12146
+ const specContent = await readFile4(resolve9(root, specPath), "utf8");
11626
12147
  const absolutePlanDir = resolve9(root, planDir);
11627
12148
  await mkdir3(absolutePlanDir, { recursive: true });
11628
12149
  const prompt = buildPrompt(specContent, stub, absolutePlanDir);
@@ -11709,7 +12230,7 @@ var CORE_ADAPTERS = [
11709
12230
  portVersion: PORT_VERSIONS.learning,
11710
12231
  create: ({
11711
12232
  repoRoot,
11712
- home = homedir5(),
12233
+ home = homedir6(),
11713
12234
  learningBlessMinConfidence = registeredBlessMinConfidence()
11714
12235
  }) => createLocalLearning({
11715
12236
  instinctsDir: localInstinctsDir(repoRoot),
@@ -11786,8 +12307,8 @@ function resolveBaseBranch(git, configured) {
11786
12307
  return readRemoteHead(git) ?? DEFAULT_BASE_BRANCH;
11787
12308
  }
11788
12309
  // packages/rafa-release/src/release/status-readings.ts
11789
- import { existsSync as existsSync15, readFileSync as readFileSync16 } from "fs";
11790
- import { join as join25 } from "path";
12310
+ import { existsSync as existsSync16, readFileSync as readFileSync16 } from "fs";
12311
+ import { join as join26 } from "path";
11791
12312
 
11792
12313
  // packages/rafa-release/src/release/version.ts
11793
12314
  var RELEASE_REMOTE = "origin";
@@ -11988,14 +12509,14 @@ function newestRootRelease(git) {
11988
12509
  return reading.latest?.version ?? null;
11989
12510
  }
11990
12511
  function readUntagged(root, configured, tags) {
11991
- const resolved = join25(root, configured);
12512
+ const resolved = join26(root, configured);
11992
12513
  const text = textOf(resolved);
11993
12514
  if (text === null) {
11994
12515
  return {
11995
12516
  path: configured,
11996
12517
  released: [],
11997
12518
  versions: [],
11998
- missing: !existsSync15(resolved),
12519
+ missing: !existsSync16(resolved),
11999
12520
  problem: `the changelog could not be read at ${resolved}`
12000
12521
  };
12001
12522
  }
@@ -13315,13 +13836,13 @@ function isRegularFile(full) {
13315
13836
  return false;
13316
13837
  }
13317
13838
  }
13318
- function readFile4(repoRoot, path2) {
13839
+ function readFile5(repoRoot, path2) {
13319
13840
  const resolved = resolve10(repoRoot, path2);
13320
13841
  return { path: path2, resolved, present: isRegularFile(resolved) };
13321
13842
  }
13322
13843
  function resolveReleaseEnabled(settings, repoRoot) {
13323
- const versionFile = readFile4(repoRoot, settings.releaseVersionFile);
13324
- const changelog = readFile4(repoRoot, settings.releaseChangelog);
13844
+ const versionFile = readFile5(repoRoot, settings.releaseVersionFile);
13845
+ const changelog = readFile5(repoRoot, settings.releaseChangelog);
13325
13846
  if (settings.releaseEnabled === RELEASE_AUTO) {
13326
13847
  return {
13327
13848
  enabled: versionFile.present && changelog.present,
@@ -13334,7 +13855,7 @@ function resolveReleaseEnabled(settings, repoRoot) {
13334
13855
  }
13335
13856
  // packages/rafa/src/effort/store/changes.ts
13336
13857
  import { randomUUID as randomUUID3 } from "crypto";
13337
- import { existsSync as existsSync16 } from "fs";
13858
+ import { existsSync as existsSync17 } from "fs";
13338
13859
  var INSERT_CHANGE = `
13339
13860
  INSERT INTO changes (
13340
13861
  id, session_id, plan_stub, task_line,
@@ -13414,7 +13935,7 @@ var SELECT_PLAN_CHANGES = `
13414
13935
  `;
13415
13936
  function readPlanChanges(repoRoot, planStub) {
13416
13937
  const path2 = sqliteStorePath(repoRoot);
13417
- if (!existsSync16(path2))
13938
+ if (!existsSync17(path2))
13418
13939
  return [];
13419
13940
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_PLAN_CHANGES).all(planStub));
13420
13941
  return rows.map((row) => ({
@@ -13446,7 +13967,7 @@ function mergeGuardSettings(config) {
13446
13967
  }
13447
13968
  // packages/rafa-release/src/release/prepare.ts
13448
13969
  import { mkdirSync as mkdirSync3, readFileSync as readFileSync17, writeFileSync as writeFileSync5 } from "fs";
13449
- import { dirname as dirname11, join as join26, posix as posix4 } from "path";
13970
+ import { dirname as dirname11, join as join27, posix as posix4 } from "path";
13450
13971
  var NO_FRAGMENT = "no release fragment";
13451
13972
  var WHITESPACE3 = /\s+/g;
13452
13973
  function levelFields(reading) {
@@ -13539,7 +14060,7 @@ function prepareRelease(input) {
13539
14060
  const fragment = { plan: input.plan, title, level, package: null, notes: lines.notes };
13540
14061
  const name = allocateFragmentName(input.plan, read.base.waiting.map((waiting) => nameOf2(waiting.path)));
13541
14062
  const path2 = posix4.join(input.settings.releaseFragments.replace(/\\/g, "/"), name);
13542
- const resolved = join26(input.repoRoot, path2);
14063
+ const resolved = join27(input.repoRoot, path2);
13543
14064
  const before = textOf2(resolved);
13544
14065
  const after = serializeFragment(fragment);
13545
14066
  const problems = lines.problem === null ? read.problems : [...read.problems, lines.problem];
@@ -13693,23 +14214,15 @@ var DEFAULT_RELEASE_PATHS = Object.freeze({
13693
14214
  });
13694
14215
  var MS_PER_DAY2 = 24 * 60 * 60 * 1000;
13695
14216
  // packages/rafa-pr/src/cleanup/worktrees.ts
13696
- import { join as join28, sep as sep2 } from "path";
14217
+ import { join as join29, sep as sep2 } from "path";
13697
14218
 
13698
14219
  // packages/rafa/src/start/worktree-dir.ts
13699
- import { join as join27, resolve as resolve11 } from "path";
13700
- var WORKTREES_SUBDIR = join27(".rafa", "worktrees");
14220
+ import { join as join28, resolve as resolve11 } from "path";
14221
+ var WORKTREES_SUBDIR = join28(".rafa", "worktrees");
13701
14222
  function worktreeDirAt(projectRoot, worktreeDir) {
13702
14223
  return resolve11(projectRoot, worktreeDir);
13703
14224
  }
13704
14225
 
13705
- // packages/rafa/src/utils/shell.ts
13706
- var PLAIN_WORD = /^[A-Za-z0-9._:/-]+$/;
13707
- var QUOTE = "'";
13708
- var QUOTED_QUOTE = "'\\''";
13709
- function shellQuote(word) {
13710
- return PLAIN_WORD.test(word) ? word : QUOTE + word.split(QUOTE).join(QUOTED_QUOTE) + QUOTE;
13711
- }
13712
-
13713
14226
  // packages/rafa-pr/src/pr/checks.ts
13714
14227
  var PASSING_STATES = new Set(["SUCCESS", "SKIPPED", "NEUTRAL"]);
13715
14228
  var FAILING_STATES = new Set([
@@ -13839,7 +14352,7 @@ function parseWorktrees(stdout) {
13839
14352
  }
13840
14353
 
13841
14354
  // packages/rafa-pr/src/cleanup/worktrees.ts
13842
- var CLAUDE_WORKTREES_SUBDIR = join28(".claude", "worktrees");
14355
+ var CLAUDE_WORKTREES_SUBDIR = join29(".claude", "worktrees");
13843
14356
  var WORKTREE_LIST = Object.freeze(["worktree", "list", "--porcelain"]);
13844
14357
  var GIT_DIR = Object.freeze(["rev-parse", "--absolute-git-dir"]);
13845
14358
  var WORKTREE_STATUS = Object.freeze([
@@ -13848,7 +14361,7 @@ var WORKTREE_STATUS = Object.freeze([
13848
14361
  "--porcelain=v1",
13849
14362
  "--untracked-files=all"
13850
14363
  ]);
13851
- var ADMIN_FILES = Object.freeze(["HEAD", join28("logs", "HEAD"), "index"]);
14364
+ var ADMIN_FILES = Object.freeze(["HEAD", join29("logs", "HEAD"), "index"]);
13852
14365
  var MS_PER_DAY3 = 24 * 60 * 60 * 1000;
13853
14366
  var LIVE_STATES = new Set(["running", "paused"]);
13854
14367
  // packages/rafa-pr/src/commands/pr/declarations.ts
@@ -14820,11 +15333,11 @@ var DEFAULT_PR_SEAMS = Object.freeze({});
14820
15333
  // packages/rafa-pr/src/commands/pr/open-pull.ts
14821
15334
  var USAGE = PR_USAGE.open;
14822
15335
  // packages/rafa-pr/src/docs/task-reading.ts
14823
- import { homedir as homedir6 } from "os";
15336
+ import { homedir as homedir7 } from "os";
14824
15337
 
14825
15338
  // packages/rafa/src/effort/store/stale-docs.ts
14826
15339
  import { randomUUID as randomUUID4 } from "crypto";
14827
- import { existsSync as existsSync17 } from "fs";
15340
+ import { existsSync as existsSync18 } from "fs";
14828
15341
  var STALE_DOC_KINDS = ["sighting", "unsettled"];
14829
15342
  var INSERT_STALE_DOC = `
14830
15343
  INSERT INTO stale_docs (
@@ -14909,7 +15422,7 @@ var SELECT_PLAN_STALE_DOCS = `
14909
15422
  `;
14910
15423
  function readStaleDocsForPlan(repoRoot, planStub) {
14911
15424
  const path2 = sqliteStorePath(repoRoot);
14912
- if (!existsSync17(path2))
15425
+ if (!existsSync18(path2))
14913
15426
  return [];
14914
15427
  const rows = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_PLAN_STALE_DOCS).all(planStub));
14915
15428
  return rows.map((row) => ({
@@ -15055,7 +15568,7 @@ function fileLines(input) {
15055
15568
  const more = rest > 0 ? [`- ...and ${rest} more.`] : [];
15056
15569
  return [`The plan's commits touched these files since it left \`${base2}\`:`, ...listed2, ...more];
15057
15570
  }
15058
- function renderDocTaskSection(input, repoRoot, home = homedir6()) {
15571
+ function renderDocTaskSection(input, repoRoot, home = homedir7()) {
15059
15572
  const redact = localPathRedactor(repoRoot, home);
15060
15573
  const lines = [DOC_TASK_HEADING, DOC_TASK_SENTENCE, ...sightingLines(input), ...fileLines(input)];
15061
15574
  return redact(lines.join(`
@@ -15063,7 +15576,7 @@ function renderDocTaskSection(input, repoRoot, home = homedir6()) {
15063
15576
  }
15064
15577
  // packages/rafa-pr/src/plan/risk.ts
15065
15578
  import { readFileSync as readFileSync19 } from "fs";
15066
- import { isAbsolute as isAbsolute5, join as join29, relative as relative8 } from "path";
15579
+ import { isAbsolute as isAbsolute5, join as join30, relative as relative8 } from "path";
15067
15580
 
15068
15581
  // packages/rafa/src/plan/risk/secrets.ts
15069
15582
  var SECRET_NAME_SHAPES = [
@@ -15174,8 +15687,8 @@ async function viewRepo(gh, target) {
15174
15687
  }
15175
15688
  return {
15176
15689
  ok: true,
15177
- name: stringField(parsed, "nameWithOwner"),
15178
- visibility: stringField(parsed, "visibility")?.toLowerCase() ?? null
15690
+ name: stringField2(parsed, "nameWithOwner"),
15691
+ visibility: stringField2(parsed, "visibility")?.toLowerCase() ?? null
15179
15692
  };
15180
15693
  }
15181
15694
  function parseJsonObject(text) {
@@ -15186,7 +15699,7 @@ function parseJsonObject(text) {
15186
15699
  return null;
15187
15700
  }
15188
15701
  }
15189
- function stringField(object, key) {
15702
+ function stringField2(object, key) {
15190
15703
  const value = object[key];
15191
15704
  return typeof value === "string" && value !== "" ? value : null;
15192
15705
  }
@@ -15255,7 +15768,7 @@ function toolsFinding(task, plan, seams) {
15255
15768
  return null;
15256
15769
  }
15257
15770
  function displayPath(path2, seams) {
15258
- const absolute = isAbsolute5(path2) ? path2 : join29(seams.repoRoot, path2);
15771
+ const absolute = isAbsolute5(path2) ? path2 : join30(seams.repoRoot, path2);
15259
15772
  const within = (root) => {
15260
15773
  const step = relative8(root, absolute);
15261
15774
  return step === "" || step.startsWith("..") || isAbsolute5(step) ? null : step;
@@ -15280,7 +15793,7 @@ function readText5(path2) {
15280
15793
  function findSkillFile(name, seams) {
15281
15794
  const tiers = resolveSkillTiers({ home: seams.home, projectRoot: seams.repoRoot, entry: seams.entry });
15282
15795
  for (const { dir } of tiers) {
15283
- const path2 = join29(dir, name, "SKILL.md");
15796
+ const path2 = join30(dir, name, "SKILL.md");
15284
15797
  if (readText5(path2) !== null)
15285
15798
  return path2;
15286
15799
  }
@@ -15547,13 +16060,13 @@ async function retargetPullRequest(pull, base2, seams) {
15547
16060
  return { kind: "retargeted", from, to: base2 };
15548
16061
  }
15549
16062
  // packages/rafa-pr/src/triage/base-run.ts
15550
- import { existsSync as existsSync19, mkdtempSync, readFileSync as readFileSync21, rmSync as rmSync3, symlinkSync } from "fs";
16063
+ import { existsSync as existsSync20, mkdtempSync, readFileSync as readFileSync21, rmSync as rmSync3, symlinkSync } from "fs";
15551
16064
  import { tmpdir } from "os";
15552
- import { isAbsolute as isAbsolute7, join as join31, normalize, relative as relative9, sep as sep3 } from "path";
16065
+ import { isAbsolute as isAbsolute7, join as join32, normalize, relative as relative9, sep as sep3 } from "path";
15553
16066
 
15554
16067
  // packages/rafa/src/suite/run.ts
15555
- import { existsSync as existsSync18, mkdirSync as mkdirSync4, readFileSync as readFileSync20, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
15556
- import { basename as basename5, dirname as dirname12, extname, isAbsolute as isAbsolute6, join as join30 } from "path";
16068
+ import { existsSync as existsSync19, mkdirSync as mkdirSync4, readFileSync as readFileSync20, rmSync as rmSync2, writeFileSync as writeFileSync7 } from "fs";
16069
+ import { basename as basename5, dirname as dirname12, extname, isAbsolute as isAbsolute6, join as join31 } from "path";
15557
16070
 
15558
16071
  // packages/rafa/src/suite/unhandled.ts
15559
16072
  var UNHANDLED_HEADING = "# Unhandled error between tests";
@@ -15765,7 +16278,25 @@ var OUTPUT_SUFFIX = ".output.txt";
15765
16278
  function outputFileFor(junitFile) {
15766
16279
  const name = basename5(junitFile);
15767
16280
  const stem = name.endsWith(JUNIT_SUFFIX) ? name.slice(0, -JUNIT_SUFFIX.length) : name.slice(0, name.length - extname(name).length);
15768
- return join30(dirname12(junitFile), `${stem}${OUTPUT_SUFFIX}`);
16281
+ return join31(dirname12(junitFile), `${stem}${OUTPUT_SUFFIX}`);
16282
+ }
16283
+ var RED_OUTPUT_SUFFIX = ".red.output.txt";
16284
+ function redOutputFileFor(junitFile, sha) {
16285
+ const outputFile = outputFileFor(junitFile);
16286
+ return `${outputFile.slice(0, -OUTPUT_SUFFIX.length)}.${sha}${RED_OUTPUT_SUFFIX}`;
16287
+ }
16288
+ function readSuiteHead(cwd) {
16289
+ const proc = Bun.spawnSync(["git", "rev-parse", "HEAD"], { cwd, stdin: "ignore", stdout: "pipe", stderr: "ignore" });
16290
+ if (proc.exitCode !== 0)
16291
+ return null;
16292
+ const sha = proc.stdout.toString().trim();
16293
+ return sha === "" ? null : sha;
16294
+ }
16295
+ function keepRedOutput(options, text) {
16296
+ const sha = (options.readHead ?? readSuiteHead)(options.cwd);
16297
+ if (sha === null)
16298
+ return;
16299
+ writeFileSync7(redOutputFileFor(options.junitFile, sha), text);
15769
16300
  }
15770
16301
  function suiteEnv(base2) {
15771
16302
  return Object.fromEntries(Object.entries(base2).filter(([key]) => !SUITE_ENV_REMOVED.includes(key)));
@@ -15892,7 +16423,7 @@ function walkJunit(xml) {
15892
16423
  return walk;
15893
16424
  }
15894
16425
  function readJunit(path2) {
15895
- if (!existsSync18(path2))
16426
+ if (!existsSync19(path2))
15896
16427
  return { junit: "missing", failures: [], files: [], cases: [] };
15897
16428
  let text;
15898
16429
  try {
@@ -15928,14 +16459,18 @@ async function runSuite(options) {
15928
16459
  const { exitCode, stderr, timedOut } = await spawn(command, { cwd: options.cwd, env });
15929
16460
  const { junit, failures: named, files, cases } = readJunit(options.junitFile);
15930
16461
  const failedCases = parseFailedCases(stderr, failingFilesOf(named));
15931
- writeFileSync7(outputFile, suiteOutputText(stderr, failedCases));
16462
+ const outputText = suiteOutputText(stderr, failedCases);
16463
+ writeFileSync7(outputFile, outputText);
15932
16464
  const { summary, errors } = readSummary2(stderr);
15933
16465
  const failures = withErrorLines(named, failedCases);
15934
16466
  const unhandled = parseUnhandled(stderr);
15935
16467
  const outputTail = readOutputTail(stderr);
15936
16468
  const deadline = timedOut === undefined ? {} : { timedOut };
15937
16469
  const result = { command, exitCode, summary, failures, errors, junit, unhandled, outputTail, fileOrder: [files], cases, ...deadline };
15938
- return readNoTestFiles(stderr) ? { ...result, noTestFiles: true } : result;
16470
+ const noTestFiles = readNoTestFiles(stderr);
16471
+ if (exitCode !== 0 && !noTestFiles)
16472
+ keepRedOutput(options, outputText);
16473
+ return noTestFiles ? { ...result, noTestFiles: true } : result;
15939
16474
  }
15940
16475
 
15941
16476
  // packages/rafa-pr/src/triage/base-run.ts
@@ -15975,13 +16510,13 @@ async function runInTree(tree, file, junitFile, commit, options) {
15975
16510
  }
15976
16511
  async function checkOutAndRun(tree, file, junitFile, commit, options) {
15977
16512
  const short = shortCommit(commit);
15978
- const modules = join31(options.checkout, NODE_MODULES);
15979
- if (!existsSync19(modules))
16513
+ const modules = join32(options.checkout, NODE_MODULES);
16514
+ if (!existsSync20(modules))
15980
16515
  return failedRun(`The run checkout holds no ${NODE_MODULES} to link into the worktree at ${short}.`);
15981
- if (!existsSync19(join31(tree, file)))
16516
+ if (!existsSync20(join32(tree, file)))
15982
16517
  return failedRun(`${file} does not exist at ${short}.`);
15983
16518
  try {
15984
- symlinkSync(modules, join31(tree, NODE_MODULES), "dir");
16519
+ symlinkSync(modules, join32(tree, NODE_MODULES), "dir");
15985
16520
  } catch (error) {
15986
16521
  return failedRun(`Could not link ${NODE_MODULES} into the worktree at ${short}: ${messageOf(error)}`);
15987
16522
  }
@@ -15999,18 +16534,18 @@ async function runFileAt(commit, file, options) {
15999
16534
  const git = options.git ?? createGitRunner(options.checkout);
16000
16535
  let scratch;
16001
16536
  try {
16002
- scratch = mkdtempSync(join31(options.tempRoot ?? tmpdir(), SCRATCH_PREFIX));
16537
+ scratch = mkdtempSync(join32(options.tempRoot ?? tmpdir(), SCRATCH_PREFIX));
16003
16538
  } catch (error) {
16004
16539
  return failedRun(`Could not make a temporary folder for the worktree: ${messageOf(error)}`);
16005
16540
  }
16006
- const tree = join31(scratch, "worktree");
16541
+ const tree = join32(scratch, "worktree");
16007
16542
  let added = false;
16008
16543
  try {
16009
16544
  const add = git(["worktree", "add", "--detach", "--quiet", tree, commit]);
16010
16545
  if (!add.ok)
16011
16546
  return failedRun(`Could not check out ${shortCommit(commit)} in a temporary worktree: ${gitSaid(add) || "git said nothing"}`);
16012
16547
  added = true;
16013
- return await checkOutAndRun(tree, file, join31(scratch, "base.junit.xml"), commit, options);
16548
+ return await checkOutAndRun(tree, file, join32(scratch, "base.junit.xml"), commit, options);
16014
16549
  } catch (error) {
16015
16550
  return failedRun(`Could not run ${file} at ${shortCommit(commit)}: ${messageOf(error)}`);
16016
16551
  } finally {
@@ -16122,6 +16657,9 @@ function testFailureOf(bug) {
16122
16657
  evidence: evidenceOf(null, artifactLines)
16123
16658
  };
16124
16659
  }
16660
+ function failedCaseNamesIn(capture) {
16661
+ return linesOf3(capture).map((line) => FAIL_LINE.exec(line)?.[1]).filter((name) => name !== undefined);
16662
+ }
16125
16663
 
16126
16664
  // packages/rafa/src/triage/bug-key.ts
16127
16665
  var KEY_SEPARATOR = ": ";
@@ -16142,17 +16680,17 @@ function strippedText(text) {
16142
16680
  const taken = text.replace(COMMIT_HASH, "").replace(FOLDER_PREFIX, "").replace(NUMBER, "");
16143
16681
  return oneLine7(taken);
16144
16682
  }
16145
- function keyText(text) {
16683
+ function keyText2(text) {
16146
16684
  const stripped = strippedText(text);
16147
16685
  return stripped.length > 0 ? stripped : oneLine7(text);
16148
16686
  }
16149
16687
  function testFailureKeyOf(failure2) {
16150
16688
  const test = failure2.file === null ? oneLine7(failure2.name) : `${basename6(failure2.file)}${CASE_SEPARATOR}${oneLine7(failure2.name)}`;
16151
- return failure2.evidence === null ? test : `${test}${KEY_SEPARATOR}${keyText(failure2.evidence)}`;
16689
+ return failure2.evidence === null ? test : `${test}${KEY_SEPARATOR}${keyText2(failure2.evidence)}`;
16152
16690
  }
16153
16691
  function bugKeyOf(trackerPath, artifact, what = null) {
16154
16692
  const failure2 = testFailureOf({ what, artifact });
16155
- return failure2 === null ? `${basename6(trackerPath)}${KEY_SEPARATOR}${keyText(artifact)}` : testFailureKeyOf(failure2);
16693
+ return failure2 === null ? `${basename6(trackerPath)}${KEY_SEPARATOR}${keyText2(artifact)}` : testFailureKeyOf(failure2);
16156
16694
  }
16157
16695
  function legacyBugKeyOf(trackerPath, artifact) {
16158
16696
  return `${basename6(trackerPath)}${KEY_SEPARATOR}${oneLine7(artifact)}`;
@@ -16171,7 +16709,7 @@ function sameFailure(failure2, baseline) {
16171
16709
  const message = baseline.message ?? null;
16172
16710
  if (!sameTest || !hasText(message))
16173
16711
  return sameTest;
16174
- return evidence !== null && keyText(evidence).includes(keyText(message));
16712
+ return evidence !== null && keyText2(evidence).includes(keyText2(message));
16175
16713
  }
16176
16714
  function inheritedFailureOf(bug, failures) {
16177
16715
  const failure2 = testFailureOf(bug);
@@ -16390,7 +16928,11 @@ function issueText(opening, values, redact) {
16390
16928
  `) + `
16391
16929
  `;
16392
16930
  }
16931
+ // packages/rafa-pr/src/triage/kind-route.ts
16932
+ import { readFileSync as readFileSync24 } from "fs";
16933
+
16393
16934
  // packages/rafa-pr/src/triage/leftover-repair.ts
16935
+ import { createHash as createHash4 } from "crypto";
16394
16936
  import { readFileSync as readFileSync22 } from "fs";
16395
16937
 
16396
16938
  // packages/rafa/src/utils/tracker.ts
@@ -16547,12 +17089,37 @@ var LEFTOVER_AGENTS = Object.freeze({
16547
17089
  });
16548
17090
  var LEFTOVER_MARKER = "<!-- leftover -->";
16549
17091
  var LEFTOVER_REPAIR = /^Repair the own-(?:fallout|gap) leftover: .*\s<!-- leftover -->$/;
17092
+ var KEY_HASH_LENGTH = 12;
17093
+ var KEYED_MARKER = /\s<!-- leftover((?: (?:key|symbol)=\S+)+) --> <!-- leftover -->$/;
17094
+ var MARKER_PART = / (key|symbol)=(\S+)/g;
16550
17095
  var KIND_SENTENCE = Object.freeze({
16551
17096
  "own-fallout": "An earlier task of this plan broke this, and the triage read it as the plan's own fallout",
16552
17097
  "own-gap": "This plan built this and left it unfinished, in files the plan's commits touched"
16553
17098
  });
17099
+ function leftoverKeyHash(key) {
17100
+ return createHash4("sha256").update(key).digest("hex").slice(0, KEY_HASH_LENGTH);
17101
+ }
17102
+ function textOrNull(text) {
17103
+ return typeof text === "string" && text.trim().length > 0 ? text : null;
17104
+ }
17105
+ function leftoverMarkerPartsOf(entry) {
17106
+ const key = textOrNull(entry.key);
17107
+ const symbol = textOrNull(entry.symbol);
17108
+ return {
17109
+ key: key === null ? null : leftoverKeyHash(key),
17110
+ symbol: symbol === null ? null : encodeURIComponent(symbol.trim())
17111
+ };
17112
+ }
17113
+ function markersOf(entry) {
17114
+ const parts = leftoverMarkerPartsOf(entry);
17115
+ const written = [
17116
+ ...parts.key === null ? [] : [`key=${parts.key}`],
17117
+ ...parts.symbol === null ? [] : [`symbol=${parts.symbol}`]
17118
+ ];
17119
+ return written.length === 0 ? LEFTOVER_MARKER : `<!-- leftover ${written.join(" ")} --> ${LEFTOVER_MARKER}`;
17120
+ }
16554
17121
  function leftoverSentence(entry) {
16555
- return `Repair the ${entry.kind} leftover: ${escapeBlockerText(entry.what.trim())} ${LEFTOVER_MARKER}`;
17122
+ return `Repair the ${entry.kind} leftover: ${escapeBlockerText(entry.what.trim())} ${markersOf(entry)}`;
16556
17123
  }
16557
17124
  function leftoverBlocker(entry) {
16558
17125
  const artifact = entry.artifact === null || entry.artifact.trim().length === 0 ? "" : ` The artifact that showed it: ${entry.artifact.trim()}`;
@@ -16568,6 +17135,16 @@ function leftoverRepairTask(entry) {
16568
17135
  function isLeftoverRepairTask(text) {
16569
17136
  return LEFTOVER_REPAIR.test(text.trim());
16570
17137
  }
17138
+ function leftoverMarkerPartsIn(text) {
17139
+ const sentence = text.trim();
17140
+ if (!isLeftoverRepairTask(sentence))
17141
+ return null;
17142
+ const found = KEYED_MARKER.exec(sentence)?.[1];
17143
+ if (found === undefined)
17144
+ return null;
17145
+ const parts = new Map([...found.matchAll(MARKER_PART)].map((part) => [part[1], part[2] ?? null]));
17146
+ return { key: parts.get("key") ?? null, symbol: parts.get("symbol") ?? null };
17147
+ }
16571
17148
  function countIn(trackerContent) {
16572
17149
  return listTrackerTasks(trackerContent).filter((task) => isLeftoverRepairTask(parseTaskDeclaration(task.task).text)).length;
16573
17150
  }
@@ -16576,6 +17153,9 @@ function leftoverCap(retries) {
16576
17153
  }
16577
17154
  function insertLeftoverRepair(trackerPath, entry, retries) {
16578
17155
  const content = readFileSync22(trackerPath, "utf8");
17156
+ const joined = joinOf(content, entry);
17157
+ if (joined !== null)
17158
+ return joined;
16579
17159
  const cap = leftoverCap(retries);
16580
17160
  const count = countIn(content);
16581
17161
  if (count >= cap)
@@ -16583,12 +17163,146 @@ function insertLeftoverRepair(trackerPath, entry, retries) {
16583
17163
  const firstOpen = listTrackerTasks(content).find((task) => task.status !== "done")?.lineNum ?? null;
16584
17164
  return { inserted: true, line: insertTrackerTask(trackerPath, leftoverRepairTask(entry), firstOpen) };
16585
17165
  }
17166
+ function matchOf(held, wanted) {
17167
+ if (wanted.key !== null && held.key === wanted.key)
17168
+ return "key";
17169
+ if (wanted.symbol !== null && held.symbol === wanted.symbol)
17170
+ return "symbol";
17171
+ return null;
17172
+ }
17173
+ function joinOf(trackerContent, entry) {
17174
+ const wanted = leftoverMarkerPartsOf(entry);
17175
+ if (wanted.key === null && wanted.symbol === null)
17176
+ return null;
17177
+ for (const task of listTrackerTasks(trackerContent)) {
17178
+ if (task.status === "done")
17179
+ continue;
17180
+ const held = leftoverMarkerPartsIn(parseTaskDeclaration(task.task).text);
17181
+ const by = held === null ? null : matchOf(held, wanted);
17182
+ if (by !== null)
17183
+ return { inserted: false, joined: true, line: task.lineNum, by };
17184
+ }
17185
+ return null;
17186
+ }
17187
+
17188
+ // packages/rafa-pr/src/triage/own-check.ts
17189
+ import { basename as basename8, extname as extname2, isAbsolute as isAbsolute8 } from "path";
17190
+
17191
+ // packages/rafa-pr/src/triage/runner-evidence.ts
17192
+ import { readdirSync as readdirSync8, readFileSync as readFileSync23 } from "fs";
17193
+ import { join as join33 } from "path";
17194
+ var SUITE_DIR = "suite";
17195
+ var MIN_SHOWN_COMMIT = 7;
17196
+ var FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
17197
+ var STEP_REPAIR = /^Repair the red (task|stage|pre-wrap-up) step at commit ([0-9a-f]+)$/;
17198
+ function namesIn(dir, directories) {
17199
+ try {
17200
+ return readdirSync8(dir, { withFileTypes: true }).filter((entry) => directories ? entry.isDirectory() : entry.isFile()).map((entry) => entry.name).sort();
17201
+ } catch (error) {
17202
+ if (error.code === "ENOENT")
17203
+ return null;
17204
+ return `the folder ${dir} could not be read: ${messageOf(error)}`;
17205
+ }
17206
+ }
17207
+ function captureNameOf(name) {
17208
+ if (!name.endsWith(RED_OUTPUT_SUFFIX))
17209
+ return null;
17210
+ const rest = name.slice(0, -RED_OUTPUT_SUFFIX.length);
17211
+ const dot = rest.lastIndexOf(".");
17212
+ if (dot <= 0)
17213
+ return null;
17214
+ const sha = rest.slice(dot + 1);
17215
+ return FULL_SHA.test(sha) ? { step: rest.slice(0, dot), sha } : null;
17216
+ }
17217
+ function wantedShas(at) {
17218
+ const all = [...at.head === null ? [] : [at.head], ...at.commits ?? []];
17219
+ return new Set(all.map((sha) => sha.trim().toLowerCase()));
17220
+ }
17221
+ function capturesIn(suite, wanted) {
17222
+ const names = namesIn(suite, false);
17223
+ if (names === null)
17224
+ return { captures: [], problems: [] };
17225
+ if (typeof names === "string")
17226
+ return { captures: [], problems: [names] };
17227
+ const captures = [];
17228
+ const problems = [];
17229
+ for (const name of names) {
17230
+ const found = captureNameOf(name);
17231
+ if (found === null || !wanted.has(found.sha))
17232
+ continue;
17233
+ const file = join33(suite, name);
17234
+ try {
17235
+ captures.push({ file, ...found, cases: failedCaseNamesIn(readFileSync23(file, "utf8")) });
17236
+ } catch (error) {
17237
+ problems.push(`the kept capture ${file} could not be read: ${messageOf(error)}`);
17238
+ }
17239
+ }
17240
+ return { captures, problems };
17241
+ }
17242
+ function readKeptCaptures(repoRoot, at) {
17243
+ const wanted = wantedShas(at);
17244
+ if (wanted.size === 0)
17245
+ return { captures: [], problems: [] };
17246
+ const root = runsDir(repoRoot);
17247
+ const sessions = namesIn(root, true);
17248
+ if (sessions === null)
17249
+ return { captures: [], problems: [] };
17250
+ if (typeof sessions === "string")
17251
+ return { captures: [], problems: [sessions] };
17252
+ const read = sessions.map((session) => capturesIn(join33(root, session, SUITE_DIR), wanted));
17253
+ return {
17254
+ captures: read.flatMap((one) => one.captures),
17255
+ problems: read.flatMap((one) => one.problems)
17256
+ };
17257
+ }
17258
+ function captureHolding(captures, name) {
17259
+ return captures.find((capture) => capture.cases.includes(name)) ?? null;
17260
+ }
17261
+ function stepRepairOf(task, sha) {
17262
+ const text = parseTaskDeclaration(task.task).text.trim();
17263
+ const found = STEP_REPAIR.exec(text);
17264
+ if (found === null)
17265
+ return null;
17266
+ const shown2 = found[2];
17267
+ if (shown2.length < MIN_SHOWN_COMMIT || !sha.startsWith(shown2))
17268
+ return null;
17269
+ return { line: task.lineNum, text, kind: found[1], shown: shown2 };
17270
+ }
17271
+ function stepRepairFor(trackerContent, sha) {
17272
+ const commit = sha.trim().toLowerCase();
17273
+ const found = listTrackerTasks(trackerContent).map((task) => stepRepairOf(task, commit)).filter((repair) => repair !== null);
17274
+ return found.at(-1) ?? null;
17275
+ }
17276
+
17277
+ // packages/rafa-pr/src/triage/symbols.ts
17278
+ var MIN_SYMBOL_LENGTH = 6;
17279
+ var ISSUE_REF = /#\d+\b/g;
17280
+ var SYMBOL_SHAPES = [
17281
+ /`([^`\n]+)`/g,
17282
+ /(?<!\p{L})'([^'\n]+)'/gu,
17283
+ /(?<!\p{L})"([^"\n]+)"/gu,
17284
+ /\(([^()\n]+)\)/g,
17285
+ /\b([a-z][a-z0-9]*(?:[A-Z][a-z0-9]*)+)\b/g,
17286
+ /\b([A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)+)\b/g,
17287
+ /\b([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\b/g
17288
+ ];
17289
+ function foundBy(shape, text) {
17290
+ return [...text.matchAll(shape)].map((match) => ({
17291
+ symbol: (match[1] ?? "").trim(),
17292
+ index: match.index
17293
+ }));
17294
+ }
17295
+ function symbolsOf(entry) {
17296
+ const text = `${entry.what ?? ""}
17297
+ ${entry.artifact ?? ""}`.replace(ISSUE_REF, " ");
17298
+ const found = SYMBOL_SHAPES.flatMap((shape) => foundBy(shape, text)).filter(({ symbol }) => symbol.length >= MIN_SYMBOL_LENGTH).sort((a, b) => a.index - b.index);
17299
+ return [...new Set(found.map(({ symbol }) => symbol))];
17300
+ }
16586
17301
 
16587
17302
  // packages/rafa-pr/src/triage/own-check.ts
16588
- import { basename as basename8, isAbsolute as isAbsolute8 } from "path";
16589
17303
  var CHECKED_KINDS = ["bug", "own-fallout", "own-gap"];
16590
17304
  function answer2(kind, row, reason) {
16591
- return { kind, inherited: false, row, reason };
17305
+ return { kind, inherited: false, row, reason, symbol: null, capture: null };
16592
17306
  }
16593
17307
  function namedTestOf(entry) {
16594
17308
  const failure2 = testFailureOf(entry);
@@ -16615,25 +17329,86 @@ function checkTest(name, readings) {
16615
17329
  kind: "bug",
16616
17330
  inherited: true,
16617
17331
  row: "red-on-both",
16618
- reason: `The case ${name} is red on the plan's base and its head, so the plan inherited it.`
17332
+ reason: `The case ${name} is red on the plan's base and its head, so the plan inherited it.`,
17333
+ symbol: null,
17334
+ capture: null
16619
17335
  };
16620
17336
  }
16621
17337
  return answer2("own-fallout", "fallout", `The case ${name} is green on the plan's base and red on its head.`);
16622
17338
  }
16623
- function withoutDotSlash(path2) {
16624
- return path2.replace(/^(?:\.\/)+/, "");
17339
+ var SHOWN_COMMIT = 12;
17340
+ function checkCaptured(tested, name, captures) {
17341
+ if (tested.row === "red-on-both")
17342
+ return tested;
17343
+ const capture = captureHolding(captures, name);
17344
+ if (capture === null)
17345
+ return tested;
17346
+ if (tested.row === "fallout")
17347
+ return { ...tested, capture };
17348
+ const shown2 = capture.sha.slice(0, SHOWN_COMMIT);
17349
+ return {
17350
+ ...answer2("own-fallout", "step-capture", `The case ${name} is red in the ${capture.step} step's capture kept at commit ${shown2}, so it reads as own-fallout.`),
17351
+ capture
17352
+ };
16625
17353
  }
16626
- function isPlanFile(path2, files) {
16627
- const named = withoutDotSlash(path2);
17354
+ var RELATIVE_PREFIX = /^(?:\.\.?\/)+/;
17355
+ var HAS_EXTENSION = /\.[^./]+$/;
17356
+ var SOURCE_EXTENSIONS = new Map([
17357
+ [".js", ".ts"],
17358
+ [".mjs", ".mts"],
17359
+ [".jsx", ".tsx"]
17360
+ ]);
17361
+ function namesFile(path2) {
17362
+ return HAS_EXTENSION.test(path2.split("/").at(-1) ?? "");
17363
+ }
17364
+ function spellingsOf(path2) {
17365
+ const emitted = extname2(path2);
17366
+ const source = SOURCE_EXTENSIONS.get(emitted);
17367
+ return source === undefined ? [path2] : [path2, `${path2.slice(0, -emitted.length)}${source}`];
17368
+ }
17369
+ function isPlanSpelling(named, relative10, files) {
16628
17370
  if (files.includes(named))
16629
17371
  return true;
17372
+ if (relative10)
17373
+ return files.some((file) => file.endsWith(`/${named}`));
16630
17374
  if (isAbsolute8(named))
16631
17375
  return files.some((file) => named.endsWith(`/${file}`));
16632
17376
  return !named.includes("/") && files.some((file) => basename8(file) === named);
16633
17377
  }
17378
+ function isPlanFile(path2, files) {
17379
+ const relative10 = RELATIVE_PREFIX.test(path2);
17380
+ const named = path2.replace(RELATIVE_PREFIX, "");
17381
+ return spellingsOf(named).some((spelling) => isPlanSpelling(spelling, relative10, files));
17382
+ }
17383
+ var IDENTIFIER_CHAR = /[\p{L}\p{N}_$]/u;
17384
+ var REGEXP_SYNTAX = /[.*+?^${}()|[\]\\/]/g;
17385
+ function symbolPattern(symbol) {
17386
+ const before = IDENTIFIER_CHAR.test(symbol.at(0) ?? "") ? "(?<![\\p{L}\\p{N}_$])" : "";
17387
+ const after = IDENTIFIER_CHAR.test(symbol.at(-1) ?? "") ? "(?![\\p{L}\\p{N}_$])" : "";
17388
+ return new RegExp(`${before}${symbol.replace(REGEXP_SYNTAX, "\\$&")}${after}`, "u");
17389
+ }
17390
+ function addedSymbolOf(entry, added) {
17391
+ return symbolsOf(entry).find((symbol) => {
17392
+ const pattern = symbolPattern(symbol);
17393
+ return added.some((line) => pattern.test(line));
17394
+ }) ?? null;
17395
+ }
17396
+ function checkOutside(entry, outside, planFiles, text) {
17397
+ const outsideAnswer = answer2("bug", "file-outside-plan", `${outside} is not one of the plan's files, so it reads as a bug.`);
17398
+ if (planFiles.added === null || testFilesIn(text).length > 0)
17399
+ return outsideAnswer;
17400
+ const symbol = addedSymbolOf(entry, planFiles.added);
17401
+ if (symbol === null)
17402
+ return outsideAnswer;
17403
+ return {
17404
+ ...answer2("own-gap", "plan-symbol", `${outside} is not one of the plan's files, but the plan's commits added ${symbol}, so it reads as own-gap.`),
17405
+ symbol
17406
+ };
17407
+ }
16634
17408
  function checkFiles(entry, planFiles) {
16635
- const paths = pathsNamedIn(`${entry.what ?? ""}
16636
- ${entry.artifact ?? ""}`);
17409
+ const text = `${entry.what ?? ""}
17410
+ ${entry.artifact ?? ""}`;
17411
+ const paths = pathsNamedIn(text).filter(namesFile);
16637
17412
  if (paths.length === 0) {
16638
17413
  return answer2(entry.kind, "nothing-named", "The entry names no test case and no path, so it is taken as said.");
16639
17414
  }
@@ -16641,9 +17416,8 @@ ${entry.artifact ?? ""}`);
16641
17416
  return answer2("bug", "files-unread", `The plan's files were not read, so it reads as a bug. ${planFiles.problem}`);
16642
17417
  }
16643
17418
  const outside = paths.find((path2) => !isPlanFile(path2, planFiles.files));
16644
- if (outside !== undefined) {
16645
- return answer2("bug", "file-outside-plan", `${outside} is not one of the plan's files, so it reads as a bug.`);
16646
- }
17419
+ if (outside !== undefined)
17420
+ return checkOutside(entry, outside, planFiles, text);
16647
17421
  return answer2("own-gap", "plan-files", "Every path the entry names is one of the plan's files.");
16648
17422
  }
16649
17423
  function checkKind2(input) {
@@ -16654,7 +17428,8 @@ function checkKind2(input) {
16654
17428
  const failure2 = testFailureOf(entry);
16655
17429
  if (failure2 === null)
16656
17430
  return checkFiles(entry, input.planFiles);
16657
- return checkTest(failure2.name, failure2.file === null ? null : input.readings);
17431
+ const tested = checkTest(failure2.name, failure2.file === null ? null : input.readings);
17432
+ return checkCaptured(tested, failure2.name, input.captures ?? []);
16658
17433
  }
16659
17434
 
16660
17435
  // packages/rafa-pr/src/triage/kind-route.ts
@@ -16719,21 +17494,47 @@ function routeDocs(entry, context) {
16719
17494
  });
16720
17495
  }
16721
17496
  }
16722
- function routeLeftover(entry, kind, trackerPath, retries) {
16723
- const artifact = artifactOf(entry.bug);
17497
+ function stepRepairOf2(capture, trackerPath) {
17498
+ if (capture === null)
17499
+ return null;
17500
+ let content;
16724
17501
  try {
16725
- const inserted = insertLeftoverRepair(trackerPath, {
16726
- kind,
16727
- what: entry.redact(entry.what),
16728
- artifact: artifact === null ? null : entry.redact(artifact)
16729
- }, retries);
16730
- return inserted.inserted ? settledRow(entry, "public", "repair", kind, { repairLine: inserted.line }) : settledRow(entry, "public", "follow-up", kind);
17502
+ content = readFileSync24(trackerPath, "utf8");
17503
+ } catch {
17504
+ return null;
17505
+ }
17506
+ return stepRepairFor(content, capture.sha);
17507
+ }
17508
+ function routeLeftover(entry, check, trackerPath, retries) {
17509
+ const { kind } = check;
17510
+ const joined = stepRepairOf2(check.capture, trackerPath);
17511
+ if (joined !== null)
17512
+ return settledRow(entry, "public", "repair", kind, { repairLine: joined.line, joined: true });
17513
+ try {
17514
+ return leftoverRow(entry, kind, insertLeftoverRepair(trackerPath, leftoverEntryOf(entry, check, trackerPath), retries));
16731
17515
  } catch (error) {
16732
17516
  return settledRow(entry, "public", "follow-up", kind, {
16733
17517
  problem: entry.redact(`out_of_scope_bugs[${entry.index}]: the repair task was not inserted, so it is a follow-up: ${messageOf(error)}`)
16734
17518
  });
16735
17519
  }
16736
17520
  }
17521
+ function leftoverEntryOf(entry, check, trackerPath) {
17522
+ const reported = artifactOf(entry.bug);
17523
+ const artifact = reported === null ? null : entry.redact(reported);
17524
+ const what = entry.redact(entry.what);
17525
+ return {
17526
+ kind: check.kind,
17527
+ what,
17528
+ artifact,
17529
+ key: artifact === null ? null : bugKeyOf(trackerPath, artifact, what),
17530
+ symbol: check.symbol === null ? null : entry.redact(check.symbol)
17531
+ };
17532
+ }
17533
+ function leftoverRow(entry, kind, done) {
17534
+ if (done.inserted)
17535
+ return settledRow(entry, "public", "repair", kind, { repairLine: done.line });
17536
+ return "joined" in done ? settledRow(entry, "public", "repair", kind, { repairLine: done.line, joined: true }) : settledRow(entry, "public", "follow-up", kind);
17537
+ }
16737
17538
  function routeChecked(entry, check, context, options) {
16738
17539
  switch (check.kind) {
16739
17540
  case "bug":
@@ -16748,7 +17549,7 @@ function routeChecked(entry, check, context, options) {
16748
17549
  return settledRow(entry, "public", "pr-body", "convention");
16749
17550
  case "own-fallout":
16750
17551
  case "own-gap":
16751
- return routeLeftover(entry, check.kind, context.trackerPath, options.retries);
17552
+ return routeLeftover(entry, { ...check, kind: check.kind }, context.trackerPath, options.retries);
16752
17553
  }
16753
17554
  }
16754
17555
  async function routeByKind(entry, context) {
@@ -16757,11 +17558,22 @@ async function routeByKind(entry, context) {
16757
17558
  return KINDS_OFF;
16758
17559
  if (entry.bug.security !== false)
16759
17560
  return { settled: false, kind: entry.bug.kind, inherited: false };
16760
- return routeChecked(entry, await checkedKindOf(entry.bug, options), context, options);
17561
+ return routeChecked(entry, await checkedKindOf(entry.bug, options, context.repoRoot), context, options);
17562
+ }
17563
+ var NO_CAPTURES = Object.freeze({ captures: [], problems: [] });
17564
+ function capturesOf(bug, options, repoRoot) {
17565
+ if (repoRoot === undefined || !CHECKED_KINDS.includes(bug.kind) || testFailureOf(bug) === null)
17566
+ return NO_CAPTURES;
17567
+ return readKeptCaptures(repoRoot, {
17568
+ head: options.head,
17569
+ commits: options.planFiles.ok ? options.planFiles.commits : null
17570
+ });
16761
17571
  }
16762
- async function checkedKindOf(bug, options) {
17572
+ async function checkedKindOf(bug, options, repoRoot) {
16763
17573
  const readings = await readingsOf(bug, options);
16764
- return checkKind2({ entry: bug, readings, planFiles: options.planFiles });
17574
+ const kept = capturesOf(bug, options, repoRoot);
17575
+ const check = checkKind2({ entry: bug, readings, planFiles: options.planFiles, captures: kept.captures });
17576
+ return kept.problems.length === 0 ? check : { ...check, reason: `${check.reason} Kept captures skipped: ${kept.problems.join("; ")}.` };
16765
17577
  }
16766
17578
  // packages/rafa-pr/src/triage/plan-commits.ts
16767
17579
  var REMOTE3 = "origin";
@@ -16783,6 +17595,33 @@ function readPlanBase(git, base2) {
16783
17595
  problem: said === "" ? `HEAD shares no history with ${remoteBase}.` : saying(`Could not read the merge base of HEAD and ${remoteBase}`, said)
16784
17596
  };
16785
17597
  }
17598
+ function addedLinesOf(patch) {
17599
+ const added = [];
17600
+ let inHunk = false;
17601
+ for (const line of patch.split(`
17602
+ `)) {
17603
+ if (line.startsWith("diff --git "))
17604
+ inHunk = false;
17605
+ else if (line.startsWith("@@"))
17606
+ inHunk = true;
17607
+ else if (inHunk && line.startsWith("+"))
17608
+ added.push(line.slice(1));
17609
+ }
17610
+ return added;
17611
+ }
17612
+ function readAdded(git, planBase) {
17613
+ const read = git(["diff", "-U0", "--no-color", planBase, "HEAD", "--"]);
17614
+ return read.ok ? { added: addedLinesOf(read.stdout), addedProblem: null } : { added: null, addedProblem: saying(`Could not read the lines added between ${planBase} and HEAD`, gitSaid(read)) };
17615
+ }
17616
+ function readCommits(git, planBase) {
17617
+ const read = git(["rev-list", `${planBase}..HEAD`]);
17618
+ if (!read.ok) {
17619
+ return { commits: null, commitsProblem: saying(`Could not list the commits between ${planBase} and HEAD`, gitSaid(read)) };
17620
+ }
17621
+ const commits = read.stdout.split(`
17622
+ `).filter((sha) => sha !== "");
17623
+ return { commits, commitsProblem: null };
17624
+ }
16786
17625
  function readPlanFiles(git, planBase) {
16787
17626
  if (planBase.trim() === "")
16788
17627
  return { ok: false, problem: "No plan base was given to read the plan's files from." };
@@ -16791,7 +17630,7 @@ function readPlanFiles(git, planBase) {
16791
17630
  return { ok: false, problem: saying(`Could not list the files changed between ${planBase} and HEAD`, gitSaid(read)) };
16792
17631
  }
16793
17632
  const files = read.stdout.split("\x00").filter((path2) => path2 !== "");
16794
- return { ok: true, files };
17633
+ return { ok: true, files, ...readAdded(git, planBase), ...readCommits(git, planBase) };
16795
17634
  }
16796
17635
  // packages/rafa-pr/src/triage/similarity.ts
16797
17636
  import { basename as basename9 } from "path";
@@ -16900,8 +17739,8 @@ function rankedCandidates(report2, record, openBugs, weights) {
16900
17739
  return [...ranked].sort((a, b) => b.score - a.score);
16901
17740
  }
16902
17741
  // packages/rafa-pr/src/triage/triage.ts
16903
- import { homedir as homedir7 } from "os";
16904
- import { join as join33 } from "path";
17742
+ import { homedir as homedir8 } from "os";
17743
+ import { join as join35 } from "path";
16905
17744
 
16906
17745
  // packages/rafa/src/effort/store/machine-fault.ts
16907
17746
  var BUILD_FAILURE = /\b(?:abort(?:ed|s)?|broke|broken|crash(?:ed|es)?|error|errors|fail(?:ed|ing|s|ure|ures)?|unusable)\b/iu;
@@ -16967,7 +17806,7 @@ function machineFaultSentence(fault) {
16967
17806
 
16968
17807
  // packages/rafa/src/effort/store/tracker-refs.ts
16969
17808
  import { randomUUID as randomUUID5 } from "crypto";
16970
- import { existsSync as existsSync20 } from "fs";
17809
+ import { existsSync as existsSync21 } from "fs";
16971
17810
  var SELECT_HELD2 = `
16972
17811
  SELECT seq, tracker_ref FROM findings
16973
17812
  WHERE session_id = ? AND artifact = ?
@@ -17006,7 +17845,7 @@ function nonBlankText(value) {
17006
17845
  return `is ${describeValue3(value)}, not a string`;
17007
17846
  return value.trim().length === 0 ? "is blank" : null;
17008
17847
  }
17009
- function textOrNull(value) {
17848
+ function textOrNull2(value) {
17010
17849
  return value === null || typeof value === "string" ? null : `is ${describeValue3(value)}, not a string or null`;
17011
17850
  }
17012
17851
  function optionalText3(value) {
@@ -17019,7 +17858,7 @@ var REF_FIELDS = [
17019
17858
  ["opt", safeInteger],
17020
17859
  ["kind", nonBlankText],
17021
17860
  ["externalId", nonBlankText],
17022
- ["url", textOrNull],
17861
+ ["url", textOrNull2],
17023
17862
  ["module", optionalText3],
17024
17863
  ["repo", optionalText3]
17025
17864
  ];
@@ -17116,7 +17955,7 @@ function writeTrackerRef(repoRoot, write, seams = {}) {
17116
17955
  wanted.json,
17117
17956
  collectedAt
17118
17957
  ];
17119
- const [action, stored] = withSqliteStore(path2, "write", !existsSync20(path2), (db) => {
17958
+ const [action, stored] = withSqliteStore(path2, "write", !existsSync21(path2), (db) => {
17120
17959
  const place = db.transaction(() => placeRef(db, path2, write, wanted, superseded, insertValues));
17121
17960
  return place.immediate();
17122
17961
  });
@@ -17125,7 +17964,7 @@ function writeTrackerRef(repoRoot, write, seams = {}) {
17125
17964
  function readTrackerRef(repoRoot, artifact) {
17126
17965
  checkArtifact2("read", artifact);
17127
17966
  const path2 = sqliteStorePath(repoRoot);
17128
- if (!existsSync20(path2))
17967
+ if (!existsSync21(path2))
17129
17968
  return null;
17130
17969
  const newest = withSqliteStore(path2, "read", false, (db) => db.query(SELECT_NEWEST).get(artifact));
17131
17970
  return newest === null ? null : heldRefOf(path2, newest.seq, newest.tracker_ref).ref;
@@ -17135,22 +17974,22 @@ function readTrackerRef(repoRoot, artifact) {
17135
17974
  import { relative as relative11, resolve as resolve14, sep as sep4 } from "path";
17136
17975
 
17137
17976
  // packages/rafa/src/project/package-of.ts
17138
- import { existsSync as existsSync21, readFileSync as readFileSync23 } from "fs";
17139
- import { dirname as dirname13, isAbsolute as isAbsolute9, join as join32, relative as relative10, resolve as resolve13 } from "path";
17977
+ import { existsSync as existsSync22, readFileSync as readFileSync25 } from "fs";
17978
+ import { dirname as dirname13, isAbsolute as isAbsolute9, join as join34, relative as relative10, resolve as resolve13 } from "path";
17140
17979
  var DISK_PACKAGE_FILE_SYSTEM = Object.freeze({
17141
- exists: (path2) => existsSync21(path2),
17142
- readFile: (path2) => readFileSync23(path2, "utf8")
17980
+ exists: (path2) => existsSync22(path2),
17981
+ readFile: (path2) => readFileSync25(path2, "utf8")
17143
17982
  });
17144
17983
  var PACKAGE_MANIFESTS = Object.freeze(["package.json"]);
17145
17984
  function isInside2(root, path2) {
17146
17985
  const steps = relative10(root, path2);
17147
17986
  return steps === "" || !steps.startsWith("..") && !isAbsolute9(steps);
17148
17987
  }
17149
- function textOrNull2(value) {
17988
+ function textOrNull3(value) {
17150
17989
  return typeof value === "string" && value.trim() !== "" ? value : null;
17151
17990
  }
17152
17991
  function ownerAt(dir, root, fs2) {
17153
- const file = PACKAGE_MANIFESTS.map((name) => join32(dir, name)).find((path2) => fs2.exists(path2));
17992
+ const file = PACKAGE_MANIFESTS.map((name) => join34(dir, name)).find((path2) => fs2.exists(path2));
17154
17993
  if (file === undefined)
17155
17994
  return null;
17156
17995
  try {
@@ -17158,8 +17997,8 @@ function ownerAt(dir, root, fs2) {
17158
17997
  if (typeof manifest !== "object" || manifest === null)
17159
17998
  return null;
17160
17999
  const { name, version } = manifest;
17161
- const named = textOrNull2(name);
17162
- return named === null ? null : { name: named, version: textOrNull2(version), dir: relative10(root, dir) || "." };
18000
+ const named = textOrNull3(name);
18001
+ return named === null ? null : { name: named, version: textOrNull3(version), dir: relative10(root, dir) || "." };
17163
18002
  } catch {
17164
18003
  return null;
17165
18004
  }
@@ -17412,10 +18251,10 @@ function triageStaleDocs(staleDocs, redact) {
17412
18251
  }
17413
18252
 
17414
18253
  // packages/rafa-pr/src/triage/triage.ts
17415
- var PRIVATE_TRIAGE_DIR = join33(".rafa", "triage", "private");
18254
+ var PRIVATE_TRIAGE_DIR = join35(".rafa", "triage", "private");
17416
18255
  var BLOCKER_SEPARATOR = "; ";
17417
18256
  function privateTriageDir(repoRoot) {
17418
- return join33(repoRoot, PRIVATE_TRIAGE_DIR);
18257
+ return join35(repoRoot, PRIVATE_TRIAGE_DIR);
17419
18258
  }
17420
18259
  function createPrivateTriageTracker(repoRoot, options = {}) {
17421
18260
  return createLocalTracker({
@@ -17533,13 +18372,13 @@ function resultOf(run, action, fields = {}) {
17533
18372
  ...fields
17534
18373
  };
17535
18374
  }
17536
- async function settle(run, action, ref2, foundBy, supersedes) {
18375
+ async function settle(run, action, ref2, foundBy2, supersedes) {
17537
18376
  const { store } = run.route;
17538
18377
  const { key } = run.filing;
17539
18378
  if (store === null || key === null)
17540
- return resultOf(run, action, { ref: ref2, foundBy });
18379
+ return resultOf(run, action, { ref: ref2, foundBy: foundBy2 });
17541
18380
  const stored = await step(run, "storing the reference", () => store(key, ref2, supersedes));
17542
- return stored.ok ? resultOf(run, action, { ref: ref2, foundBy, stored: stored.value }) : resultOf(run, action, { ref: ref2, foundBy, problem: stored.problem });
18381
+ return stored.ok ? resultOf(run, action, { ref: ref2, foundBy: foundBy2, stored: stored.value }) : resultOf(run, action, { ref: ref2, foundBy: foundBy2, problem: stored.problem });
17543
18382
  }
17544
18383
  async function fileNew(run, extras = {}) {
17545
18384
  const { filing } = run;
@@ -17547,11 +18386,11 @@ async function fileNew(run, extras = {}) {
17547
18386
  const created = await step(run, `the ${run.route.channel} tracker create`, () => run.route.tracker.create(draft));
17548
18387
  return created.ok ? settle(run, "filed", created.value, null, extras.supersedes) : resultOf(run, "failed", { problem: created.problem });
17549
18388
  }
17550
- async function commentOn(run, ref2, foundBy, action = "commented", comment = run.filing.comment) {
18389
+ async function commentOn(run, ref2, foundBy2, action = "commented", comment = run.filing.comment) {
17551
18390
  const commented = await step(run, `the ${run.route.channel} tracker comment`, () => run.route.tracker.comment(ref2, comment));
17552
18391
  if (!commented.ok)
17553
- return resultOf(run, "failed", { ref: ref2, foundBy, problem: commented.problem });
17554
- return foundBy === "store" ? resultOf(run, action, { ref: ref2, foundBy }) : settle(run, action, ref2, foundBy);
18392
+ return resultOf(run, "failed", { ref: ref2, foundBy: foundBy2, problem: commented.problem });
18393
+ return foundBy2 === "store" ? resultOf(run, action, { ref: ref2, foundBy: foundBy2 }) : settle(run, action, ref2, foundBy2);
17555
18394
  }
17556
18395
  async function lookUp2(run, key, searchText) {
17557
18396
  const { route, filing } = run;
@@ -17576,13 +18415,13 @@ async function lookUp2(run, key, searchText) {
17576
18415
  };
17577
18416
  }
17578
18417
  var COMPLETED_ISSUE_STATES = ["done", "released"];
17579
- async function answerRecurrence(run, { ref: ref2, foundBy }) {
18418
+ async function answerRecurrence(run, { ref: ref2, foundBy: foundBy2 }) {
17580
18419
  if (!run.route.readsState)
17581
- return commentOn(run, ref2, foundBy);
18420
+ return commentOn(run, ref2, foundBy2);
17582
18421
  const issue4 = await step(run, `the ${run.route.channel} tracker get`, () => run.route.tracker.get(ref2));
17583
18422
  if (!issue4.ok)
17584
- return resultOf(run, "failed", { ref: ref2, foundBy, problem: issue4.problem });
17585
- return COMPLETED_ISSUE_STATES.includes(issue4.value.state) ? fileNew(run, { supersedes: ref2 }) : commentOn(run, ref2, foundBy);
18423
+ return resultOf(run, "failed", { ref: ref2, foundBy: foundBy2, problem: issue4.problem });
18424
+ return COMPLETED_ISSUE_STATES.includes(issue4.value.state) ? fileNew(run, { supersedes: ref2 }) : commentOn(run, ref2, foundBy2);
17586
18425
  }
17587
18426
  async function commentOnNearest(run, nearest, threshold) {
17588
18427
  const opening = similarCommentOpening(nearest.score, threshold);
@@ -17623,13 +18462,13 @@ async function triageInherited(run, commented) {
17623
18462
  return resultOf(run, "failed", { problem: found.problem });
17624
18463
  if (found.value === null)
17625
18464
  return resultOf(run, "inherited");
17626
- const { ref: ref2, foundBy } = found.value;
18465
+ const { ref: ref2, foundBy: foundBy2 } = found.value;
17627
18466
  const issue4 = await step(run, `the ${run.route.channel} tracker get`, () => run.route.tracker.get(ref2));
17628
18467
  if (!issue4.ok)
17629
- return resultOf(run, "failed", { ref: ref2, foundBy, problem: issue4.problem });
18468
+ return resultOf(run, "failed", { ref: ref2, foundBy: foundBy2, problem: issue4.problem });
17630
18469
  if (!isOpenIssueState(issue4.value.state))
17631
18470
  return resultOf(run, "inherited");
17632
- const result = await commentOn(run, ref2, foundBy, "inherited");
18471
+ const result = await commentOn(run, ref2, foundBy2, "inherited");
17633
18472
  if (result.action === "inherited")
17634
18473
  commented.add(key);
17635
18474
  return result;
@@ -17661,7 +18500,7 @@ async function triageReport(options) {
17661
18500
  checkPrivateTracker(options.tracker, privateTracker);
17662
18501
  const blocker = triageBlockers(options);
17663
18502
  const checkout = options.checkout ?? repoRoot;
17664
- const local = localPathRedactor([checkout, repoRoot], options.home ?? homedir7());
18503
+ const local = localPathRedactor([checkout, repoRoot], options.home ?? homedir8());
17665
18504
  const redact = (text) => redactSecrets(local(text), options.secrets);
17666
18505
  const verifyRefs = options.verifyRefs ?? createArtifactRefsVerifier(checkout, options.env);
17667
18506
  const routes = {
@@ -17717,7 +18556,7 @@ async function triageReport(options) {
17717
18556
  return { blocker, bugs, staleDocs: triageStaleDocs(options.report.staleDocs, redact) };
17718
18557
  }
17719
18558
  // packages/rafa-run/src/claims/device.ts
17720
- import { existsSync as existsSync22 } from "fs";
18559
+ import { existsSync as existsSync23 } from "fs";
17721
18560
  var NO_CLAIMANT = "no claim can name this device";
17722
18561
  function ndjsonReason() {
17723
18562
  return "this project's effort store is NDJSON (store: ndjson), which records no store id," + ` so ${NO_CLAIMANT}. Next safe step: ${MOVE_TO_SQLITE}`;
@@ -17732,7 +18571,7 @@ function readDeviceStoreId(repoRoot, config) {
17732
18571
  if (config.store === "ndjson")
17733
18572
  return { ok: false, cause: "ndjson", reason: ndjsonReason() };
17734
18573
  const path2 = sqliteStorePath(repoRoot);
17735
- if (!existsSync22(path2))
18574
+ if (!existsSync23(path2))
17736
18575
  return { ok: false, cause: "absent", reason: absentReason(path2) };
17737
18576
  const ids = withSqliteStore(path2, "read", false, (db) => {
17738
18577
  const meta = readStoreMeta(db);
@@ -18122,10 +18961,10 @@ var REMOTE_BRANCH_FORMAT = [
18122
18961
 
18123
18962
  // packages/rafa-run/src/start/loop-events.ts
18124
18963
  import { appendFileSync, mkdirSync as mkdirSync5 } from "fs";
18125
- import { join as join34 } from "path";
18964
+ import { join as join36 } from "path";
18126
18965
 
18127
18966
  // packages/rafa-run/src/start/suite-blocker.ts
18128
- import { readFileSync as readFileSync24, writeFileSync as writeFileSync8 } from "fs";
18967
+ import { readFileSync as readFileSync26, writeFileSync as writeFileSync8 } from "fs";
18129
18968
 
18130
18969
  // packages/rafa-run/src/start/suite-outside-case.ts
18131
18970
  import { constants } from "os";
@@ -18371,7 +19210,7 @@ function blockRepairAgain(trackerPath, content, line, blocker) {
18371
19210
  return writeTrackerBlocker(trackerPath, line, blocker) ? { line, inserted: false } : null;
18372
19211
  }
18373
19212
  function writeRepairTask(trackerPath, blocker, site) {
18374
- const content = readFileSync24(trackerPath, "utf8");
19213
+ const content = readFileSync26(trackerPath, "utf8");
18375
19214
  const { tasks } = parsePlan(content);
18376
19215
  const existing = existingRepairOf(tasks, site);
18377
19216
  if (existing !== null)
@@ -18443,7 +19282,7 @@ function eventsFilePath(root, sessionId) {
18443
19282
  if (!isSessionId(sessionId)) {
18444
19283
  throw new Error(`events file: unusable session id ${JSON.stringify(sessionId)}`);
18445
19284
  }
18446
- return join34(runsDir(root), `${sessionId}${EVENTS_EXTENSION}`);
19285
+ return join36(runsDir(root), `${sessionId}${EVENTS_EXTENSION}`);
18447
19286
  }
18448
19287
  function bindEventsFile(root, sessionId, warn2 = (line) => {
18449
19288
  process.stderr.write(line);
@@ -18494,7 +19333,7 @@ function injectionPlace(trackerContent, taskInfo) {
18494
19333
  }
18495
19334
  async function taskTokens(checkout, sessionId, home) {
18496
19335
  try {
18497
- const { usage } = await readSessionLog(join34(sessionLogDir(checkout, home), `${sessionId}.jsonl`));
19336
+ const { usage } = await readSessionLog(join36(sessionLogDir(checkout, home), `${sessionId}.jsonl`));
18498
19337
  return usage.inputTokens + usage.cacheCreationInputTokens + usage.outputTokens;
18499
19338
  } catch {
18500
19339
  return null;
@@ -18747,7 +19586,7 @@ var USAGE2 = "rafa switch <n | -> [--no-rehome]";
18747
19586
  var SWITCH_REFUSAL_EXIT = 2;
18748
19587
  var BACK = "-";
18749
19588
  var REHOME_FLAG = "rehome";
18750
- var ISSUE_NUMBER3 = /^[1-9]\d*$/u;
19589
+ var ISSUE_NUMBER4 = /^[1-9]\d*$/u;
18751
19590
  function refusal3(message) {
18752
19591
  return new CommandExit(SWITCH_REFUSAL_EXIT, `\u274C ${message}`);
18753
19592
  }
@@ -18762,7 +19601,7 @@ function readSwitchTarget(args) {
18762
19601
  throw lineRefusal(`Expected one target, got ${String(args.length)}: ${args.join(" ")}`, USAGE2);
18763
19602
  if (word === BACK)
18764
19603
  return { kind: "back" };
18765
- if (!ISSUE_NUMBER3.test(word)) {
19604
+ if (!ISSUE_NUMBER4.test(word)) {
18766
19605
  throw lineRefusal(`"${word}" is no issue number, which is a whole number from 1, nor - for the previous place`, USAGE2);
18767
19606
  }
18768
19607
  return { kind: "number", number: Number(word) };
@@ -19037,7 +19876,7 @@ function refuseArgumentAliases(args) {
19037
19876
  }
19038
19877
  }
19039
19878
  }
19040
- function spellingsOf(flags) {
19879
+ function spellingsOf2(flags) {
19041
19880
  const owners = new Map;
19042
19881
  const claim = (spelling, name) => {
19043
19882
  const owner = owners.get(spelling);
@@ -19091,7 +19930,7 @@ function readLine2(argv, record) {
19091
19930
  function parseArgs(argv, spec = {}) {
19092
19931
  const { args = [], flags: flagSpecs = [] } = spec;
19093
19932
  refuseArgumentAliases(args);
19094
- const spellings = spellingsOf(flagSpecs);
19933
+ const spellings = spellingsOf2(flagSpecs);
19095
19934
  const flags = {};
19096
19935
  const positional = readLine2(argv, (spelling, value) => {
19097
19936
  flags[spellings.get(spelling) ?? spelling] = value;
@@ -19113,21 +19952,21 @@ function parseArgs(argv, spec = {}) {
19113
19952
  import { rmSync as rmSync5 } from "fs";
19114
19953
 
19115
19954
  // packages/rafa-run/src/plan/list.ts
19116
- import { existsSync as existsSync23, readdirSync as readdirSync8, readFileSync as readFileSync25 } from "fs";
19117
- import { join as join35 } from "path";
19955
+ import { existsSync as existsSync24, readdirSync as readdirSync9, readFileSync as readFileSync27 } from "fs";
19956
+ import { join as join37 } from "path";
19118
19957
  function listing(dir, stub) {
19119
- const plan = join35(dir, planFileName(stub, false));
19120
- const trackerPath = join35(dir, planFileName(stub, true));
19958
+ const plan = join37(dir, planFileName(stub, false));
19959
+ const trackerPath = join37(dir, planFileName(stub, true));
19121
19960
  const tracker = isFile(trackerPath) ? trackerPath : null;
19122
- const planModel = parsePlan(readFileSync25(plan, "utf8"));
19123
- const counted4 = tracker === null ? planModel : parsePlan(readFileSync25(tracker, "utf8"));
19961
+ const planModel = parsePlan(readFileSync27(plan, "utf8"));
19962
+ const counted4 = tracker === null ? planModel : parsePlan(readFileSync27(tracker, "utf8"));
19124
19963
  return { stub, plan, tracker, tasks: countTasks(counted4.tasks), issues: planModel.issues.length };
19125
19964
  }
19126
19965
  function listPlans(plans) {
19127
19966
  const dir = plans.path;
19128
- if (!existsSync23(dir))
19967
+ if (!existsSync24(dir))
19129
19968
  return { dir, plans: [] };
19130
- const stubs = readdirSync8(dir).filter((name) => isFile(join35(dir, name))).map((name) => stubOfPlanFile(name)).filter((stub) => stub !== null).sort((a, b) => a.localeCompare(b));
19969
+ const stubs = readdirSync9(dir).filter((name) => isFile(join37(dir, name))).map((name) => stubOfPlanFile(name)).filter((stub) => stub !== null).sort((a, b) => a.localeCompare(b));
19131
19970
  return { dir, plans: stubs.map((stub) => listing(dir, stub)) };
19132
19971
  }
19133
19972
 
@@ -19276,6 +20115,22 @@ function hasStartedBranch(sources, remote, refs, stub, note) {
19276
20115
  return messages === null || !claimsOnly(messages);
19277
20116
  });
19278
20117
  }
20118
+ async function readMergedHeads(sources, note) {
20119
+ try {
20120
+ const merged = await sources.pulls.listMerged();
20121
+ return new Set(merged.map((pull) => pull.headRefName));
20122
+ } catch (error) {
20123
+ const said = messageOf(error).replace(/\s+/g, " ").trim();
20124
+ note(`the merged pull requests could not be read from the provider, so a plan whose branch merged from another clone may be offered again: ${said}`);
20125
+ return new Set;
20126
+ }
20127
+ }
20128
+ function firstUnmerged(sources, plans, first, merged, unstarted) {
20129
+ const isMerged = (plan) => merged.has(branchNameFor(plan.stub, sources.branchTemplate));
20130
+ if (!isMerged(first))
20131
+ return first;
20132
+ return plans.slice(plans.indexOf(first) + 1).find((plan) => !isMerged(plan) && unstarted(plan)) ?? null;
20133
+ }
19279
20134
  function openWorld(sources) {
19280
20135
  let problems = [];
19281
20136
  const note = (problem) => {
@@ -19292,6 +20147,9 @@ function openWorld(sources) {
19292
20147
  return reading;
19293
20148
  });
19294
20149
  const checkout = once(() => readCheckout(sources, note));
20150
+ const unstarted = (plan) => !hasRun(runs(), plan.stub) && !hasStartedBranch(sources, remote, refs(), plan.stub, note);
20151
+ const unstartedPlan = once(() => plans().find(unstarted) ?? null);
20152
+ const mergedHeads = once(() => readMergedHeads(sources, note));
19295
20153
  return {
19296
20154
  sources,
19297
20155
  remote,
@@ -19302,7 +20160,13 @@ function openWorld(sources) {
19302
20160
  tracked: once(() => readTracked(sources, note)),
19303
20161
  checkout,
19304
20162
  branchPlan: once(() => readBranchPlan(branch(), plans(), sources.branchTemplate)),
19305
- unstartedPlan: once(() => plans().find((plan) => !hasRun(runs(), plan.stub) && !hasStartedBranch(sources, remote, refs(), plan.stub, note)) ?? null),
20163
+ unstartedPlan,
20164
+ unmergedPlan: once(async () => {
20165
+ const first = unstartedPlan();
20166
+ if (first === null)
20167
+ return null;
20168
+ return firstUnmerged(sources, plans(), first, await mergedHeads(), unstarted);
20169
+ }),
19306
20170
  openPull: once(() => readOpenPull(sources, branch(), note)),
19307
20171
  roadmap,
19308
20172
  picked: once(async () => {
@@ -20116,10 +20980,10 @@ async function readPrGreen(world) {
20116
20980
  pullRequest: open.summary.number
20117
20981
  };
20118
20982
  }
20119
- function readPlanUnstarted(world) {
20983
+ async function readPlanUnstarted(world) {
20120
20984
  if (!onBase(world))
20121
20985
  return null;
20122
- const plan = world.unstartedPlan();
20986
+ const plan = await world.unmergedPlan();
20123
20987
  if (plan === null)
20124
20988
  return null;
20125
20989
  return {
@@ -20453,11 +21317,11 @@ function storeRuleLine(file, problem) {
20453
21317
  return `${file}:${String(problem.line)}: ${problem.kind}: ${problem.text}`;
20454
21318
  }
20455
21319
  // packages/rafa-run/src/preflight/first-dispatch.ts
20456
- import { readFileSync as readFileSync26 } from "fs";
21320
+ import { readFileSync as readFileSync28 } from "fs";
20457
21321
  var TICKED_TASK = /^- \[[xX]\] (.+)/;
20458
21322
  function readIfReadable(path3) {
20459
21323
  try {
20460
- return readFileSync26(path3, "utf8");
21324
+ return readFileSync28(path3, "utf8");
20461
21325
  } catch {
20462
21326
  return null;
20463
21327
  }
@@ -20483,14 +21347,14 @@ function isFirstDispatch(planPath) {
20483
21347
  return tracker === null || !hasTickedTask(tracker);
20484
21348
  }
20485
21349
  // packages/rafa/src/project/bin-path.ts
20486
- import { delimiter as delimiter2, isAbsolute as isAbsolute10, join as join36, resolve as resolve15 } from "path";
20487
- var RAFA_BIN_DIR = join36(SCOPE_DIR, "bin");
20488
- var BUN_BIN_DIR = join36(".bun", "bin");
21350
+ import { delimiter as delimiter2, isAbsolute as isAbsolute10, join as join38, resolve as resolve15 } from "path";
21351
+ var RAFA_BIN_DIR = join38(SCOPE_DIR, "bin");
21352
+ var BUN_BIN_DIR = join38(".bun", "bin");
20489
21353
 
20490
21354
  // packages/rafa-run/src/start/runtime.ts
20491
- import { existsSync as existsSync24, readdirSync as readdirSync9, realpathSync as realpathSync2, statSync as statSync8 } from "fs";
20492
- import { homedir as homedir8 } from "os";
20493
- import { isAbsolute as isAbsolute11, join as join37, relative as relative13, resolve as resolve16, sep as sep5 } from "path";
21355
+ import { existsSync as existsSync25, readdirSync as readdirSync10, realpathSync as realpathSync2, statSync as statSync8 } from "fs";
21356
+ import { homedir as homedir9 } from "os";
21357
+ import { isAbsolute as isAbsolute11, join as join39, relative as relative13, resolve as resolve16, sep as sep5 } from "path";
20494
21358
 
20495
21359
  // packages/rafa-run/src/start/session.ts
20496
21360
  import { randomUUID as randomUUID6 } from "crypto";
@@ -20736,7 +21600,7 @@ function resolveRuntime(value, places) {
20736
21600
  throw refusal4([`\u274C Refusing to start: \`--runtime\` names no runtime. Spell it ${SPELLING}.`]);
20737
21601
  }
20738
21602
  const isVersion = VERSION_SHAPE2.test(value);
20739
- const named = isVersion ? join37(places.home, RUNTIME_SUBDIR, value, RUNTIME_ENTRY) : resolve16(places.cwd, value);
21603
+ const named = isVersion ? join39(places.home, RUNTIME_SUBDIR, value, RUNTIME_ENTRY) : resolve16(places.cwd, value);
20740
21604
  refuseInsideSource(value, named, places);
20741
21605
  const entry = entryOf2(value, named, isVersion, places.home);
20742
21606
  const real = realpathSync2(entry);
@@ -20747,7 +21611,7 @@ function entryOf2(value, named, isVersion, home) {
20747
21611
  if (isVersion) {
20748
21612
  if (isFile4(named))
20749
21613
  return named;
20750
- const root = join37(home, RUNTIME_SUBDIR);
21614
+ const root = join39(home, RUNTIME_SUBDIR);
20751
21615
  const installed = installedVersions(root);
20752
21616
  throw refusal4([
20753
21617
  `\u274C Refusing to start: \`--runtime=${value}\` names no installed runtime: ${named} is no file.`,
@@ -20756,7 +21620,7 @@ function entryOf2(value, named, isVersion, home) {
20756
21620
  }
20757
21621
  if (isFile4(named))
20758
21622
  return named;
20759
- const inside = join37(named, RUNTIME_ENTRY);
21623
+ const inside = join39(named, RUNTIME_ENTRY);
20760
21624
  if (isDirectory(named) && isFile4(inside))
20761
21625
  return inside;
20762
21626
  throw refusal4([
@@ -20774,8 +21638,8 @@ function refuseInsideSource(value, path3, places) {
20774
21638
  ]);
20775
21639
  }
20776
21640
  function sourceDirs({ cwd, root }) {
20777
- const dirs = [join37(cwd, SOURCE_DIR), join37(root, SOURCE_DIR)];
20778
- const real = dirs.filter((dir) => existsSync24(dir)).map((dir) => realpathSync2(dir));
21641
+ const dirs = [join39(cwd, SOURCE_DIR), join39(root, SOURCE_DIR)];
21642
+ const real = dirs.filter((dir) => existsSync25(dir)).map((dir) => realpathSync2(dir));
20779
21643
  return [...new Set([...dirs, ...real])];
20780
21644
  }
20781
21645
  function isInside3(path3, dir) {
@@ -20784,7 +21648,7 @@ function isInside3(path3, dir) {
20784
21648
  }
20785
21649
  function installedVersions(root) {
20786
21650
  try {
20787
- return readdirSync9(root).filter((name) => isFile4(join37(root, name, RUNTIME_ENTRY))).sort((a, b) => a.localeCompare(b));
21651
+ return readdirSync10(root).filter((name) => isFile4(join39(root, name, RUNTIME_ENTRY))).sort((a, b) => a.localeCompare(b));
20788
21652
  } catch {
20789
21653
  return [];
20790
21654
  }
@@ -20812,7 +21676,7 @@ async function runFromSelectedRuntime(seams) {
20812
21676
  if (value === undefined)
20813
21677
  return false;
20814
21678
  const cwd = seams.cwd ?? process.cwd();
20815
- const entry = resolveRuntime(value, { cwd, root: seams.root, home: seams.home ?? homedir8() });
21679
+ const entry = resolveRuntime(value, { cwd, root: seams.root, home: seams.home ?? homedir9() });
20816
21680
  if (realOrResolved(seams.currentEntry ?? Bun.main) === entry)
20817
21681
  return false;
20818
21682
  const mode = activeOutputMode();
@@ -20944,12 +21808,12 @@ function markBudgetExit(options) {
20944
21808
  activeOutput().error(" Raise its budget= or split it, then run again to retry.");
20945
21809
  }
20946
21810
  // packages/rafa-run/src/start/checkout-guard.ts
20947
- import { existsSync as existsSync25, realpathSync as realpathSync3 } from "fs";
21811
+ import { existsSync as existsSync26, realpathSync as realpathSync3 } from "fs";
20948
21812
  var CHECKOUT_MOVED = "checkout moved";
20949
21813
  var INDENT = " ";
20950
21814
  var SHORT_COMMIT2 = 12;
20951
21815
  function realDirOf(path3) {
20952
- if (!existsSync25(path3))
21816
+ if (!existsSync26(path3))
20953
21817
  return null;
20954
21818
  try {
20955
21819
  return realpathSync3(path3);
@@ -21123,7 +21987,7 @@ function haltIfWrapUpMoved(options, seams = {}) {
21123
21987
  }
21124
21988
  // packages/rafa/src/project/roots.ts
21125
21989
  import { spawnSync as spawnSync2 } from "child_process";
21126
- import { accessSync, constants as constants2, readFileSync as readFileSync27, statSync as statSync9 } from "fs";
21990
+ import { accessSync, constants as constants2, readFileSync as readFileSync29, statSync as statSync9 } from "fs";
21127
21991
  var REFUSED_ROOTS = Object.freeze([
21128
21992
  { path: "/", why: "is the filesystem root" },
21129
21993
  { path: "/var", why: "holds system state" },
@@ -21141,7 +22005,7 @@ var MONOREPO_MARKER_FILES = Object.freeze([
21141
22005
  ]);
21142
22006
  var DISK_ROOTS_FILE_SYSTEM = Object.freeze({
21143
22007
  ...DISK_FILE_SYSTEM,
21144
- readFile: (path3) => readFileSync27(path3, "utf8"),
22008
+ readFile: (path3) => readFileSync29(path3, "utf8"),
21145
22009
  isDirectory: (path3) => statSync9(path3).isDirectory(),
21146
22010
  assertWritable: (path3) => accessSync(path3, constants2.W_OK)
21147
22011
  });
@@ -21414,8 +22278,8 @@ function parseDecision(output) {
21414
22278
  }
21415
22279
 
21416
22280
  // packages/rafa-run/src/start/decision-prompt.ts
21417
- import { existsSync as existsSync26, readFileSync as readFileSync28 } from "fs";
21418
- import { dirname as dirname14, join as join38, resolve as resolve17 } from "path";
22281
+ import { existsSync as existsSync27, readFileSync as readFileSync30 } from "fs";
22282
+ import { dirname as dirname14, join as join40, resolve as resolve17 } from "path";
21419
22283
  import { fileURLToPath as fileURLToPath4 } from "url";
21420
22284
  var MODULE_DIR4 = dirname14(fileURLToPath4(import.meta.url));
21421
22285
  var DECISION_PROMPT_FILE = "continue-decision-prompt.md";
@@ -21439,21 +22303,21 @@ function chooseRetrySections(template, retriesLeft) {
21439
22303
  var NO_HOLDS = "(no reason was recorded)";
21440
22304
  var NO_OPEN_TASKS = "(no open task is left)";
21441
22305
  function bundledCandidates(file, moduleDir = MODULE_DIR4) {
21442
- return [join38(moduleDir, file), join38(moduleDir, "..", "..", "..", "..", "src", file)];
22306
+ return [join40(moduleDir, file), join40(moduleDir, "..", "..", "..", "..", "src", file)];
21443
22307
  }
21444
22308
  function readBundledFile(file, moduleDir = MODULE_DIR4) {
21445
22309
  const candidates = bundledCandidates(file, moduleDir);
21446
- const found = candidates.find((candidate) => existsSync26(candidate));
22310
+ const found = candidates.find((candidate) => existsSync27(candidate));
21447
22311
  if (found === undefined) {
21448
22312
  throw new Error(`loop continue: ${file} is missing: no file at ${candidates.join(" or ")}`);
21449
22313
  }
21450
- return readFileSync28(found, "utf8");
22314
+ return readFileSync30(found, "utf8");
21451
22315
  }
21452
22316
  function readProjectFile(path3) {
21453
- if (!existsSync26(path3))
22317
+ if (!existsSync27(path3))
21454
22318
  return { text: null };
21455
22319
  try {
21456
- return { text: readFileSync28(path3, "utf8") };
22320
+ return { text: readFileSync30(path3, "utf8") };
21457
22321
  } catch (error) {
21458
22322
  const message = error instanceof Error ? error.message : String(error);
21459
22323
  return { refusal: `loop.continue.criteria cannot be read at ${path3}: ${message}` };
@@ -21641,7 +22505,7 @@ class LoopEnd extends CommandExit {
21641
22505
  }
21642
22506
  }
21643
22507
  // packages/rafa-run/src/start/continue-run.ts
21644
- import { existsSync as existsSync27, readFileSync as readFileSync29 } from "fs";
22508
+ import { existsSync as existsSync28, readFileSync as readFileSync31 } from "fs";
21645
22509
 
21646
22510
  // packages/rafa-run/src/start/decision-session.ts
21647
22511
  import { randomUUID as randomUUID7 } from "crypto";
@@ -21834,7 +22698,7 @@ function whenOf(stop) {
21834
22698
  function openingList(seed, trackerPath) {
21835
22699
  if (seed.length === 0)
21836
22700
  return seed;
21837
- const kept = existsSync27(trackerPath) ? seedFrom(seed, readFileSync29(trackerPath, "utf8")) : [];
22701
+ const kept = existsSync28(trackerPath) ? seedFrom(seed, readFileSync31(trackerPath, "utf8")) : [];
21838
22702
  const back = seed.length - kept.length;
21839
22703
  if (back > 0) {
21840
22704
  activeOutput().info(`\u21A9\uFE0F ${back} task(s) the last --continue run passed over no longer read [BLOCKED], so this run takes them again.`);
@@ -21862,7 +22726,7 @@ function createRunDecisions(options) {
21862
22726
  const mode = options.mode ?? activeOutputMode;
21863
22727
  let directive = options.continueArgs.directive;
21864
22728
  let firstPass = true;
21865
- const readTracker = () => readFileSync29(trackerPath, "utf8");
22729
+ const readTracker = () => readFileSync31(trackerPath, "utf8");
21866
22730
  let list = openingList(options.seed, trackerPath);
21867
22731
  const deferred = new Set;
21868
22732
  const passedOver = new Set;
@@ -22131,7 +22995,7 @@ import { randomUUID as randomUUID11 } from "crypto";
22131
22995
 
22132
22996
  // packages/rafa/src/effort/store/absences.ts
22133
22997
  import { randomUUID as randomUUID8 } from "crypto";
22134
- import { existsSync as existsSync28 } from "fs";
22998
+ import { existsSync as existsSync29 } from "fs";
22135
22999
  var ABSENCE_REASONS = {
22136
23000
  "no-block": true,
22137
23001
  "unclosed-block": true,
@@ -22191,7 +23055,7 @@ function writeReportAbsence(repoRoot, write, seams = {}) {
22191
23055
  write.outcome,
22192
23056
  collectedAt
22193
23057
  ];
22194
- const appended2 = withSqliteStore(path3, "write", !existsSync28(path3), (db) => db.query(INSERT_ABSENCE).run(...values).changes);
23058
+ const appended2 = withSqliteStore(path3, "write", !existsSync29(path3), (db) => db.query(INSERT_ABSENCE).run(...values).changes);
22195
23059
  return { path: path3, appended: appended2, skipped: 1 - appended2 };
22196
23060
  }
22197
23061
 
@@ -22356,8 +23220,8 @@ function describeTaskReportRecord(record) {
22356
23220
  }
22357
23221
 
22358
23222
  // packages/rafa/src/utils/progress.ts
22359
- import { existsSync as existsSync29, writeFileSync as writeFileSync9 } from "fs";
22360
- import { join as join39 } from "path";
23223
+ import { existsSync as existsSync30, writeFileSync as writeFileSync9 } from "fs";
23224
+ import { join as join41 } from "path";
22361
23225
  var PROGRESS_FILE_NAME = "progress.txt";
22362
23226
  var PROGRESS_CAP_BYTES = 16000;
22363
23227
  var LISTED_FIELDS = [
@@ -22399,7 +23263,7 @@ var ESCAPED_CODE_POINTS = new Set([
22399
23263
  8233
22400
23264
  ]);
22401
23265
  function progressFilePath(repoRoot) {
22402
- return join39(repoRoot, PROGRESS_FILE_NAME);
23266
+ return join41(repoRoot, PROGRESS_FILE_NAME);
22403
23267
  }
22404
23268
  function escapeValue(value) {
22405
23269
  let escaped = "";
@@ -22460,7 +23324,7 @@ function renderProgressText(findings, capBytes = PROGRESS_CAP_BYTES) {
22460
23324
  }
22461
23325
  function readProgressFindings(repoRoot, planStub) {
22462
23326
  const path3 = sqliteStorePath(repoRoot);
22463
- if (!existsSync29(path3))
23327
+ if (!existsSync30(path3))
22464
23328
  return [];
22465
23329
  const rows = withSqliteStore(path3, "read", false, (db) => {
22466
23330
  const query = db.query(SELECT_FINDINGS2);
@@ -22581,17 +23445,17 @@ function renderInheritedSection(failures) {
22581
23445
 
22582
23446
  // packages/rafa-run/src/start/preflight.ts
22583
23447
  import { randomUUID as randomUUID10 } from "crypto";
22584
- import { existsSync as existsSync31, readFileSync as readFileSync30 } from "fs";
22585
- import { homedir as homedir9 } from "os";
22586
- import { basename as basename10, join as join40 } from "path";
23448
+ import { existsSync as existsSync32, readFileSync as readFileSync32 } from "fs";
23449
+ import { homedir as homedir10 } from "os";
23450
+ import { basename as basename10, join as join42 } from "path";
22587
23451
 
22588
23452
  // packages/rafa/src/effort/store/schema-report.ts
22589
- import { existsSync as existsSync30 } from "fs";
23453
+ import { existsSync as existsSync31 } from "fs";
22590
23454
  import { Database } from "bun:sqlite";
22591
23455
  var NO_NEXT_STEP = "none";
22592
23456
  function readSchemaReport(path3, options = {}) {
22593
23457
  guardTestProcess(path3);
22594
- if (!existsSync30(path3))
23458
+ if (!existsSync31(path3))
22595
23459
  return absentReport(path3);
22596
23460
  const catalogue = sqliteCatalogue(options.migrations ?? SQLITE_MIGRATIONS);
22597
23461
  const store = readReadOnly(path3);
@@ -22904,13 +23768,13 @@ async function markInDevelopment(claim, board, firstDispatch) {
22904
23768
  }
22905
23769
 
22906
23770
  // packages/rafa-run/src/start/preflight-drift.ts
22907
- import { readdirSync as readdirSync10 } from "fs";
23771
+ import { readdirSync as readdirSync11 } from "fs";
22908
23772
  var DRIFT_EVERY = 2;
22909
23773
  var RECORD_EXTENSION3 = ".json";
22910
23774
  function countRunRecords(root) {
22911
23775
  let names;
22912
23776
  try {
22913
- names = readdirSync10(runsDir(root));
23777
+ names = readdirSync11(runsDir(root));
22914
23778
  } catch (error) {
22915
23779
  if (errorCode(error) === "ENOENT")
22916
23780
  return 0;
@@ -22981,11 +23845,11 @@ function knownMissingNotice(lines) {
22981
23845
  }
22982
23846
  function agentSourcePath(planPath) {
22983
23847
  const tracker = trackerPathFor(planPath);
22984
- return existsSync31(tracker) ? tracker : planPath;
23848
+ return existsSync32(tracker) ? tracker : planPath;
22985
23849
  }
22986
23850
  function readIfReadable2(path3) {
22987
23851
  try {
22988
- return readFileSync30(path3, "utf8");
23852
+ return readFileSync32(path3, "utf8");
22989
23853
  } catch {
22990
23854
  return null;
22991
23855
  }
@@ -23013,7 +23877,7 @@ function refuseUnresolvableAgents(options) {
23013
23877
  };
23014
23878
  const roots = {
23015
23879
  repoRoot: options.repoRoot,
23016
- home: agents.home ?? homedir9(),
23880
+ home: agents.home ?? homedir10(),
23017
23881
  ...agents.entry === undefined ? {} : { entry: agents.entry }
23018
23882
  };
23019
23883
  const roster = resolveAgentRoster(roots, settings);
@@ -23137,7 +24001,7 @@ function announceReminders(planPath, reminders) {
23137
24001
  function announceUnknownMigrations(repoRoot) {
23138
24002
  const output = activeOutput();
23139
24003
  try {
23140
- const report2 = readSchemaReport(join40(effortStoreDir(repoRoot), SQLITE_STORE_FILE_NAME));
24004
+ const report2 = readSchemaReport(join42(effortStoreDir(repoRoot), SQLITE_STORE_FILE_NAME));
23141
24005
  for (const migration of unknownAdditive(report2))
23142
24006
  output.warn(unknownAdditiveWarning(migration));
23143
24007
  } catch (error) {
@@ -23209,9 +24073,9 @@ async function runStartPreflight(options) {
23209
24073
  }
23210
24074
 
23211
24075
  // packages/rafa-run/src/start/type-step.ts
23212
- import { closeSync as closeSync2, existsSync as existsSync32, mkdtempSync as mkdtempSync2, openSync as openSync2, readSync as readSync2, realpathSync as realpathSync4, rmSync as rmSync6, symlinkSync as symlinkSync2, writeFileSync as writeFileSync10 } from "fs";
24076
+ import { closeSync as closeSync2, existsSync as existsSync33, mkdtempSync as mkdtempSync2, openSync as openSync2, readSync as readSync2, realpathSync as realpathSync4, rmSync as rmSync6, symlinkSync as symlinkSync2, writeFileSync as writeFileSync10 } from "fs";
23213
24077
  import { tmpdir as tmpdir2 } from "os";
23214
- import { basename as basename11, dirname as dirname15, join as join41, relative as relative14, resolve as resolve18, sep as sep6 } from "path";
24078
+ import { basename as basename11, dirname as dirname15, join as join43, relative as relative14, resolve as resolve18, sep as sep6 } from "path";
23215
24079
  var TEST_FILE_SUFFIX = ".test.ts";
23216
24080
  var TSC_FLAGS = ["--noEmit", "--pretty", "false"];
23217
24081
  var CANNOT_START_CODES = [126, 127];
@@ -23285,8 +24149,8 @@ function findNodeModules(checkout, git) {
23285
24149
  const stop = walkStop(git);
23286
24150
  const top = stop !== null && isUnder(start, stop) ? stop : start;
23287
24151
  for (let dir = start;; dir = dirname15(dir)) {
23288
- const modules = join41(dir, NODE_MODULES2);
23289
- if (existsSync32(join41(modules, ...TSC_BIN)))
24152
+ const modules = join43(dir, NODE_MODULES2);
24153
+ if (existsSync33(join43(modules, ...TSC_BIN)))
23290
24154
  return modules;
23291
24155
  if (dir === top || dirname15(dir) === dir)
23292
24156
  return null;
@@ -23295,9 +24159,9 @@ function findNodeModules(checkout, git) {
23295
24159
  function scratchTsconfigFields(tree, files, modules) {
23296
24160
  const root = resolve18(tree);
23297
24161
  return {
23298
- extends: join41(root, "tsconfig.json"),
23299
- compilerOptions: { typeRoots: [join41(resolve18(modules), "@types")] },
23300
- files: files.map((file) => join41(root, file)),
24162
+ extends: join43(root, "tsconfig.json"),
24163
+ compilerOptions: { typeRoots: [join43(resolve18(modules), "@types")] },
24164
+ files: files.map((file) => join43(root, file)),
23301
24165
  include: []
23302
24166
  };
23303
24167
  }
@@ -23306,13 +24170,13 @@ function scratchTsconfig(tree, files, modules) {
23306
24170
  `;
23307
24171
  }
23308
24172
  function tscArgv(modules, scratch) {
23309
- return [join41(modules, ...TSC_BIN), "-p", scratch, ...TSC_FLAGS];
24173
+ return [join43(modules, ...TSC_BIN), "-p", scratch, ...TSC_FLAGS];
23310
24174
  }
23311
24175
  function modulesFor(checkout, git) {
23312
- return findNodeModules(checkout, git) ?? join41(resolve18(checkout), NODE_MODULES2);
24176
+ return findNodeModules(checkout, git) ?? join43(resolve18(checkout), NODE_MODULES2);
23313
24177
  }
23314
24178
  function readTypeCheckRecipe(checkout, git) {
23315
- if (!existsSync32(join41(checkout, "tsconfig.json")))
24179
+ if (!existsSync33(join43(checkout, "tsconfig.json")))
23316
24180
  return null;
23317
24181
  const modules = findNodeModules(checkout, git);
23318
24182
  return modules === null ? null : { checkout, modules };
@@ -23407,8 +24271,8 @@ ${run.stderr}`.split(`
23407
24271
  `).map((line) => line.trim()).find((line) => line !== "");
23408
24272
  }
23409
24273
  async function checkTree(input, modules, tree, files) {
23410
- const scratchDir = mkdtempSync2(join41(tmpdir2(), "rafa-type-step-"));
23411
- const scratch = join41(scratchDir, SCRATCH_NAME);
24274
+ const scratchDir = mkdtempSync2(join43(tmpdir2(), "rafa-type-step-"));
24275
+ const scratch = join43(scratchDir, SCRATCH_NAME);
23412
24276
  try {
23413
24277
  writeFileSync10(scratch, scratchTsconfig(tree, files, modules), "utf8");
23414
24278
  let run;
@@ -23435,21 +24299,21 @@ async function checkTree(input, modules, tree, files) {
23435
24299
  }
23436
24300
  }
23437
24301
  async function inBaseTree(input, label, modules, check) {
23438
- const parent = mkdtempSync2(join41(tmpdir2(), "rafa-type-base-"));
23439
- const tree = join41(parent, "tree");
24302
+ const parent = mkdtempSync2(join43(tmpdir2(), "rafa-type-base-"));
24303
+ const tree = join43(parent, "tree");
23440
24304
  try {
23441
24305
  const added = input.git(["worktree", "add", "--detach", tree, input.base]);
23442
24306
  if (!added.ok) {
23443
24307
  activeOutput().warn(`\u26A0\uFE0F The ${label} could not check out ${input.base} (${gitSaid(added) || "nothing said"}); it reads no error as new.`);
23444
24308
  return null;
23445
24309
  }
23446
- if (existsSync32(modules) && !existsSync32(join41(tree, NODE_MODULES2)))
23447
- symlinkSync2(modules, join41(tree, NODE_MODULES2));
23448
- if (!existsSync32(join41(tree, "tsconfig.json")))
24310
+ if (existsSync33(modules) && !existsSync33(join43(tree, NODE_MODULES2)))
24311
+ symlinkSync2(modules, join43(tree, NODE_MODULES2));
24312
+ if (!existsSync33(join43(tree, "tsconfig.json")))
23449
24313
  return { kind: "read", errors: [] };
23450
24314
  return await check(tree);
23451
24315
  } finally {
23452
- if (existsSync32(tree)) {
24316
+ if (existsSync33(tree)) {
23453
24317
  const removed = input.git(["worktree", "remove", "--force", tree]);
23454
24318
  if (!removed.ok)
23455
24319
  activeOutput().warn(`\u26A0\uFE0F The ${label} could not remove its worktree ${tree} (${gitSaid(removed) || "nothing said"}).`);
@@ -23481,13 +24345,13 @@ function interrupted(label) {
23481
24345
  return INTERRUPTED2;
23482
24346
  }
23483
24347
  function cannotStart(label, modules, run) {
23484
- const tsc = join41(modules, ...TSC_BIN);
24348
+ const tsc = join43(modules, ...TSC_BIN);
23485
24349
  const blocker = cannotStartBlockerText(label, tsc, run.run, run.said, scriptInterpreter(tsc));
23486
24350
  activeOutput().warn(`\u26A0\uFE0F ${blocker}`);
23487
24351
  return { ran: false, red: false, interrupted: false, cannotStart: true, blocker };
23488
24352
  }
23489
24353
  function filesToCheck(input, label) {
23490
- if (!existsSync32(join41(input.checkout, "tsconfig.json"))) {
24354
+ if (!existsSync33(join43(input.checkout, "tsconfig.json"))) {
23491
24355
  activeOutput().info(`\uD83D\uDD0E ${label}: no tsconfig.json at the checkout root; nothing to type-check.`);
23492
24356
  return null;
23493
24357
  }
@@ -23827,14 +24691,14 @@ async function holdWhilePaused(options) {
23827
24691
  }
23828
24692
  }
23829
24693
  // packages/rafa-run/src/start/plan-path.ts
23830
- import { existsSync as existsSync33 } from "fs";
24694
+ import { existsSync as existsSync34 } from "fs";
23831
24695
  import { resolve as resolve19 } from "path";
23832
24696
  var DEFAULT_PLAN_FILE = "PLAN.md";
23833
24697
  function resolvePlanPath(repoRoot, planDir, planArg) {
23834
24698
  if (planArg)
23835
24699
  return resolve19(repoRoot, planArg);
23836
24700
  const inPlanDir = resolve19(repoRoot, planDir, DEFAULT_PLAN_FILE);
23837
- return existsSync33(inPlanDir) ? inPlanDir : resolve19(repoRoot, DEFAULT_PLAN_FILE);
24701
+ return existsSync34(inPlanDir) ? inPlanDir : resolve19(repoRoot, DEFAULT_PLAN_FILE);
23838
24702
  }
23839
24703
  // packages/rafa/src/pr/ci-poll.ts
23840
24704
  var CI_POLL_INTERVAL_MS = 20000;
@@ -24221,13 +25085,13 @@ async function handleRedChecks(io, branch, prNumber, rows) {
24221
25085
  return "next";
24222
25086
  }
24223
25087
  // packages/rafa-run/src/start/risk-total.ts
24224
- import { readFileSync as readFileSync31 } from "fs";
25088
+ import { readFileSync as readFileSync33 } from "fs";
24225
25089
  function spawningRunners(root) {
24226
25090
  return { git: createGitRunner(root), gh: createGhRunner({ cwd: root }) };
24227
25091
  }
24228
25092
  async function readRiskTotalLine(input, seams = {}) {
24229
25093
  const makeRunners = seams.runners ?? spawningRunners;
24230
- const report2 = await assessPlanRisk({ path: input.planPath, text: readFileSync31(input.planPath, "utf8") }, {
25094
+ const report2 = await assessPlanRisk({ path: input.planPath, text: readFileSync33(input.planPath, "utf8") }, {
24231
25095
  repoRoot: input.repoRoot,
24232
25096
  home: input.home,
24233
25097
  settingSources: input.config.settingSources,
@@ -24374,20 +25238,41 @@ function refuseWorktreeWhileTracking(args, config) {
24374
25238
  async function resolveRunBranch(request, seams = DEFAULT_BRANCH_SEAMS) {
24375
25239
  const { args, base: base2, standing } = request;
24376
25240
  const noBranch = standing === "no-branch";
24377
- if (!noBranch && !DEFAULT_BRANCHES.includes(base2))
25241
+ const onBase2 = DEFAULT_BRANCHES.includes(base2) || base2 === request.runBase;
25242
+ if (!noBranch && !onBase2)
24378
25243
  return base2;
25244
+ const createBranch = args.includes(CREATE_BRANCH_FLAG);
24379
25245
  const outcome = await offerRunBranch({
24380
25246
  repoRoot: request.checkout,
24381
25247
  planStub: request.planStub,
24382
25248
  base: base2,
24383
25249
  standing,
24384
25250
  anyBranch: args.includes(ANY_BRANCH_FLAG),
24385
- createBranch: args.includes(CREATE_BRANCH_FLAG),
25251
+ createBranch,
24386
25252
  branchTemplate: request.branchTemplate
24387
25253
  }, seams);
24388
25254
  if (outcome.kind === "moved")
24389
25255
  return outcome.branch;
24390
- return noBranch ? null : base2;
25256
+ if (noBranch)
25257
+ return null;
25258
+ if (createBranch)
25259
+ refuseStillOnBase(request.planStub, base2, request.branchTemplate);
25260
+ return base2;
25261
+ }
25262
+ function refuseStillOnBase(planStub, base2, branchTemplate) {
25263
+ const way = planStub === null || planStub.trim() === "" ? [
25264
+ `
25265
+ \u274C Refusing ${CREATE_BRANCH_FLAG}: this plan's file names no stub, so no branch was made`,
25266
+ ` and the run is still on \`${base2}\`, the base.`,
25267
+ ...branchOffer(null, base2, branchTemplate)
25268
+ ] : [
25269
+ `
25270
+ \u274C Refusing ${CREATE_BRANCH_FLAG} for \`${planStub}\`: the run is still on \`${base2}\`, the base.`,
25271
+ ` ${ANY_BRANCH_FLAG} stood the offer aside, so ${branchNameFor(planStub, branchTemplate)} was not made.`,
25272
+ ` Drop ${ANY_BRANCH_FLAG} to make it and run there, or ${CREATE_BRANCH_FLAG} to run on \`${base2}\`.`
25273
+ ];
25274
+ throw new CommandExit(1, [...way, NOTHING_DISPATCHED].join(`
25275
+ `));
24391
25276
  }
24392
25277
  function branchOffer(planStub, base2, branchTemplate) {
24393
25278
  if (planStub === null) {
@@ -24554,7 +25439,7 @@ async function runWorktreeSetup(request, seams = {}) {
24554
25439
 
24555
25440
  // packages/rafa-run/src/start/worktree.ts
24556
25441
  import { realpathSync as realpathSync5 } from "fs";
24557
- import { join as join42, resolve as resolve20 } from "path";
25442
+ import { join as join44, resolve as resolve20 } from "path";
24558
25443
 
24559
25444
  // packages/rafa-run/src/start/claim-catch-up.ts
24560
25445
  var OWN_COMMIT_FORMAT = "--format=%H%x09%P%x09%s";
@@ -24658,7 +25543,7 @@ var INDENT4 = " ";
24658
25543
  var UNTOUCHED = `${INDENT4}The main checkout's branch and working tree were not touched.`;
24659
25544
  var DEFAULT_WORKTREE_SEAMS = Object.freeze({});
24660
25545
  function worktreePathFor(projectRoot, worktreeDir, stub) {
24661
- return join42(worktreeDirAt(projectRoot, worktreeDir), stub);
25546
+ return join44(worktreeDirAt(projectRoot, worktreeDir), stub);
24662
25547
  }
24663
25548
  function addStep(route, plan, path3) {
24664
25549
  const label = `add the worktree for ${plan.branch} at ${path3}`;
@@ -24922,13 +25807,15 @@ async function settleRunCheckout(request, seams = {}) {
24922
25807
  const startedOn = (seams.checkedOutBranch ?? readCheckedOutBranch)(started.checkout);
24923
25808
  const runBase = () => (seams.base ?? readBase2)(projectRoot, request.prBase);
24924
25809
  if (!args.includes(AS_WORKTREE_FLAG)) {
24925
- const stands = startedOn === null ? { base: runBase(), standing: "no-branch" } : { base: startedOn };
25810
+ const base3 = runBase();
25811
+ const stands = startedOn === null ? { base: base3, standing: "no-branch" } : { base: startedOn };
24926
25812
  const branch = await (seams.offer ?? resolveRunBranch)({
24927
25813
  checkout: started.checkout,
24928
25814
  planStub,
24929
25815
  ...stands,
24930
25816
  args,
24931
- branchTemplate: request.branchTemplate
25817
+ branchTemplate: request.branchTemplate,
25818
+ runBase: base3
24932
25819
  });
24933
25820
  return Object.freeze({ projectRoot, checkout: started.checkout, branch });
24934
25821
  }
@@ -24961,17 +25848,17 @@ function haltBeforeSession(options, seams = {}) {
24961
25848
  return moved;
24962
25849
  }
24963
25850
  // packages/rafa-run/src/start/stale-docs.ts
24964
- import { existsSync as existsSync34, readFileSync as readFileSync32 } from "fs";
24965
- import { homedir as homedir10 } from "os";
25851
+ import { existsSync as existsSync35, readFileSync as readFileSync34 } from "fs";
25852
+ import { homedir as homedir11 } from "os";
24966
25853
  import { resolve as resolvePath } from "path";
24967
25854
  var LINE_PREFIX = "Stale docs: ";
24968
25855
  var INDENT5 = " ";
24969
25856
  function localVersion(checkout, versionFile) {
24970
25857
  const path3 = resolvePath(checkout, versionFile);
24971
- if (!existsSync34(path3))
25858
+ if (!existsSync35(path3))
24972
25859
  return null;
24973
25860
  try {
24974
- return readManifestVersion(readFileSync32(path3, "utf8"));
25861
+ return readManifestVersion(readFileSync34(path3, "utf8"));
24975
25862
  } catch {
24976
25863
  return null;
24977
25864
  }
@@ -25028,7 +25915,7 @@ function resultLine(result, text) {
25028
25915
  }
25029
25916
  var PLAN_TITLE = /^# Plan:[ \t]*(.*?)[ \t]*\r?$/m;
25030
25917
  function readDocUpdatePlan(planPath) {
25031
- const markdown = readFileSync32(planPath, "utf8");
25918
+ const markdown = readFileSync34(planPath, "utf8");
25032
25919
  if (PLAN_TITLE.exec(markdown)?.[1] !== DOC_UPDATE_TITLE)
25033
25920
  return null;
25034
25921
  return { issue: parsePlan(markdown).header.issue };
@@ -25052,7 +25939,7 @@ function refName(ref3) {
25052
25939
  }
25053
25940
  function createStartStaleDocs(options) {
25054
25941
  const secrets = namedSecrets(options.config, options.env ?? process.env);
25055
- const local = localPathRedactor([options.repoRoot, options.checkout], options.home ?? homedir10());
25942
+ const local = localPathRedactor([options.repoRoot, options.checkout], options.home ?? homedir11());
25056
25943
  const redact = (text) => local(redactSecrets(text, secrets));
25057
25944
  const kept = new Map;
25058
25945
  let version = null;
@@ -25256,13 +26143,13 @@ function announceRunStepOnly(items) {
25256
26143
  activeOutput().warn(` ${line}`);
25257
26144
  }
25258
26145
  // packages/rafa-run/src/start/suite-step.ts
25259
- import { readFileSync as readFileSync38 } from "fs";
26146
+ import { readFileSync as readFileSync40 } from "fs";
25260
26147
  import { constants as constants3 } from "os";
25261
- import { basename as basename14, join as join48 } from "path";
26148
+ import { basename as basename14, join as join50 } from "path";
25262
26149
 
25263
26150
  // packages/rafa-run/src/suite/baseline.ts
25264
- import { existsSync as existsSync35, mkdirSync as mkdirSync6, readFileSync as readFileSync33, renameSync as renameSync2, writeFileSync as writeFileSync11 } from "fs";
25265
- import { basename as basename12, dirname as dirname16, join as join43 } from "path";
26151
+ import { existsSync as existsSync36, mkdirSync as mkdirSync6, readFileSync as readFileSync35, renameSync as renameSync2, writeFileSync as writeFileSync11 } from "fs";
26152
+ import { basename as basename12, dirname as dirname16, join as join45 } from "path";
25266
26153
  var BASELINE_VERSION = 1;
25267
26154
  var BASELINE_FILE_PREFIX = "SUITE_BASELINE";
25268
26155
  var PLAN_FILE_NAME2 = /^PLAN(?:_TRACKER)?(-.+)?\.md$/;
@@ -25272,7 +26159,7 @@ function baselinePathFor(trackerPath) {
25272
26159
  if (match === null) {
25273
26160
  throw new RangeError(`baselinePathFor: ${trackerPath} is not a PLAN or PLAN_TRACKER file`);
25274
26161
  }
25275
- return join43(dirname16(trackerPath), `${BASELINE_FILE_PREFIX}${match[1] ?? ""}.json`);
26162
+ return join45(dirname16(trackerPath), `${BASELINE_FILE_PREFIX}${match[1] ?? ""}.json`);
25276
26163
  }
25277
26164
  function copyFailure(failure2) {
25278
26165
  return failure2.message === undefined ? { file: failure2.file, name: failure2.name } : { file: failure2.file, name: failure2.name, message: failure2.message };
@@ -25337,11 +26224,11 @@ function asBaseline(parsed) {
25337
26224
  return { state: "read", baseline: parsed };
25338
26225
  }
25339
26226
  function readBaseline(path3) {
25340
- if (!existsSync35(path3))
26227
+ if (!existsSync36(path3))
25341
26228
  return { state: "missing" };
25342
26229
  let text;
25343
26230
  try {
25344
- text = readFileSync33(path3, "utf8");
26231
+ text = readFileSync35(path3, "utf8");
25345
26232
  } catch (error) {
25346
26233
  const reason = error instanceof Error ? error.message : String(error);
25347
26234
  return { state: "unreadable", reason };
@@ -25364,12 +26251,12 @@ function splitFailures(failures, baseline) {
25364
26251
  }
25365
26252
 
25366
26253
  // packages/rafa-run/src/suite/owns.ts
25367
- var ISSUE_NUMBER4 = /^#?(\d+)$/u;
26254
+ var ISSUE_NUMBER5 = /^#?(\d+)$/u;
25368
26255
  function none(reason, detail) {
25369
26256
  return Object.freeze({ owns: null, reason, detail });
25370
26257
  }
25371
26258
  function issueNumberOf(issue4) {
25372
- const digits = ISSUE_NUMBER4.exec(issue4?.trim() ?? "")?.[1];
26259
+ const digits = ISSUE_NUMBER5.exec(issue4?.trim() ?? "")?.[1];
25373
26260
  if (digits === undefined)
25374
26261
  return null;
25375
26262
  const number = Number(digits);
@@ -25436,8 +26323,8 @@ async function readPlanOwns(options) {
25436
26323
  }
25437
26324
 
25438
26325
  // packages/rafa-run/src/suite/scope.ts
25439
- import { existsSync as existsSync36, readdirSync as readdirSync11, readFileSync as readFileSync34 } from "fs";
25440
- import { isAbsolute as isAbsolute13, join as join44, relative as relative15, sep as sep7 } from "path";
26326
+ import { existsSync as existsSync37, readdirSync as readdirSync12, readFileSync as readFileSync36 } from "fs";
26327
+ import { isAbsolute as isAbsolute13, join as join46, relative as relative15, sep as sep7 } from "path";
25441
26328
  var BUNFIG_FILE = "bunfig.toml";
25442
26329
  var TEST_FILE_NAME = /[._](?:test|spec)\.(?:tsx?|jsx?|[cm][jt]s)$/;
25443
26330
  var DEPENDENCY_FOLDER = "node_modules";
@@ -25468,11 +26355,11 @@ function preloadFilesOf(text, root) {
25468
26355
  return paths.filter((path3) => path3 !== null);
25469
26356
  }
25470
26357
  function readPreloadFiles(root) {
25471
- const path3 = join44(root, BUNFIG_FILE);
25472
- if (!existsSync36(path3))
26358
+ const path3 = join46(root, BUNFIG_FILE);
26359
+ if (!existsSync37(path3))
25473
26360
  return { state: "missing", files: [] };
25474
26361
  try {
25475
- return { state: "read", files: preloadFilesOf(readFileSync34(path3, "utf8"), root) };
26362
+ return { state: "read", files: preloadFilesOf(readFileSync36(path3, "utf8"), root) };
25476
26363
  } catch (error) {
25477
26364
  const reason = error instanceof Error ? error.message : String(error);
25478
26365
  return { state: "unreadable", files: [], reason };
@@ -25481,7 +26368,7 @@ function readPreloadFiles(root) {
25481
26368
  function listTestFiles(root) {
25482
26369
  const found = [];
25483
26370
  const walk = (folder) => {
25484
- for (const entry of readdirSync11(join44(root, folder), { withFileTypes: true })) {
26371
+ for (const entry of readdirSync12(join46(root, folder), { withFileTypes: true })) {
25485
26372
  const path3 = folder === "" ? entry.name : `${folder}/${entry.name}`;
25486
26373
  if (entry.isDirectory() && !entry.name.startsWith(".") && entry.name !== DEPENDENCY_FOLDER)
25487
26374
  walk(path3);
@@ -25494,8 +26381,8 @@ function listTestFiles(root) {
25494
26381
  }
25495
26382
 
25496
26383
  // packages/rafa-run/src/start/lint-step.ts
25497
- import { existsSync as existsSync37 } from "fs";
25498
- import { join as join45, relative as relative16 } from "path";
26384
+ import { existsSync as existsSync38 } from "fs";
26385
+ import { join as join47, relative as relative16 } from "path";
25499
26386
  var LINT_COMMAND = ["bunx", "eslint", "--no-warn-ignored"];
25500
26387
  var LINT_REPORT_FLAGS = ["--format", "json"];
25501
26388
  var ESLINT_CONFIG_FILES = [
@@ -25524,7 +26411,7 @@ async function runEslint(options) {
25524
26411
  return { exitCode, stdout, stderr };
25525
26412
  }
25526
26413
  function hasEslintConfig(checkout) {
25527
- return ESLINT_CONFIG_FILES.some((name) => existsSync37(join45(checkout, name)));
26414
+ return ESLINT_CONFIG_FILES.some((name) => existsSync38(join47(checkout, name)));
25528
26415
  }
25529
26416
  function readLintFiles(git, base2) {
25530
26417
  const result = git(["diff", "--name-only", "-z", "--no-renames", "--diff-filter=d", base2, "HEAD"]);
@@ -25628,11 +26515,11 @@ async function runLintStep(input) {
25628
26515
  }
25629
26516
 
25630
26517
  // packages/rafa-run/src/start/suite-retake-alone.ts
25631
- import { join as join46, relative as relative17 } from "path";
26518
+ import { join as join48, relative as relative17 } from "path";
25632
26519
  var RETAKE_ALONE_MAX_FILES = 20;
25633
26520
  var STEP_ONLY_BEFORE = 5;
25634
26521
  function aloneJunitFileFor(repoRoot, sessionId, kind, nth) {
25635
- return join46(runsDir(repoRoot), sessionId, "suite", `${kind}-alone-${nth}.junit.xml`);
26522
+ return join48(runsDir(repoRoot), sessionId, "suite", `${kind}-alone-${nth}.junit.xml`);
25636
26523
  }
25637
26524
  function placeOf(file, orders) {
25638
26525
  for (const [run, order] of orders.entries()) {
@@ -25756,14 +26643,14 @@ function announceStepOnly(context, settling) {
25756
26643
  }
25757
26644
 
25758
26645
  // packages/rafa-run/src/start/suite-stage-ledger.ts
25759
- import { existsSync as existsSync38, mkdirSync as mkdirSync7, readFileSync as readFileSync35, renameSync as renameSync3, writeFileSync as writeFileSync12 } from "fs";
25760
- import { basename as basename13, dirname as dirname17, join as join47 } from "path";
26646
+ import { existsSync as existsSync39, mkdirSync as mkdirSync7, readFileSync as readFileSync37, renameSync as renameSync3, writeFileSync as writeFileSync12 } from "fs";
26647
+ import { basename as basename13, dirname as dirname17, join as join49 } from "path";
25761
26648
  var STAGE_LEDGER_PREFIX = "SUITE_STAGES";
25762
26649
  var STAGE_LEDGER_VERSION = 1;
25763
26650
  function stageLedgerPathFor(trackerPath) {
25764
26651
  const baselinePath = baselinePathFor(trackerPath);
25765
26652
  const name = basename13(baselinePath).replace(BASELINE_FILE_PREFIX, STAGE_LEDGER_PREFIX);
25766
- return join47(dirname17(baselinePath), name);
26653
+ return join49(dirname17(baselinePath), name);
25767
26654
  }
25768
26655
  function isLedgerEntry(value) {
25769
26656
  if (typeof value !== "object" || value === null)
@@ -25787,11 +26674,11 @@ function parseLedger(text) {
25787
26674
  return stages;
25788
26675
  }
25789
26676
  function readStageLedger(path3) {
25790
- if (!existsSync38(path3))
26677
+ if (!existsSync39(path3))
25791
26678
  return [];
25792
26679
  let parsed;
25793
26680
  try {
25794
- parsed = parseLedger(readFileSync35(path3, "utf8"));
26681
+ parsed = parseLedger(readFileSync37(path3, "utf8"));
25795
26682
  } catch (error) {
25796
26683
  parsed = messageOf(error);
25797
26684
  }
@@ -25837,7 +26724,7 @@ function dueStages(trackerContent, ledger) {
25837
26724
  }
25838
26725
 
25839
26726
  // packages/rafa-run/src/start/suite-stage-step.ts
25840
- import { readFileSync as readFileSync36 } from "fs";
26727
+ import { readFileSync as readFileSync38 } from "fs";
25841
26728
 
25842
26729
  // packages/rafa-run/src/suite/checks.ts
25843
26730
  var NO_CHECK = Object.freeze({ kind: "none", reason: "no-check" });
@@ -26085,7 +26972,7 @@ async function runStageStep(context, stage2, baseline) {
26085
26972
  }
26086
26973
  async function runDueStageSteps(context, baseline) {
26087
26974
  const ledger = readStageLedger(stageLedgerPathFor(context.trackerPath));
26088
- const due = dueStages(readFileSync36(context.trackerPath, "utf8"), ledger);
26975
+ const due = dueStages(readFileSync38(context.trackerPath, "utf8"), ledger);
26089
26976
  const outcomes = [];
26090
26977
  for (const stage2 of due) {
26091
26978
  const outcome = await runStageStep(context, stage2, baseline);
@@ -26097,7 +26984,7 @@ async function runDueStageSteps(context, baseline) {
26097
26984
  }
26098
26985
 
26099
26986
  // packages/rafa-run/src/start/sweep-timing.ts
26100
- import { existsSync as existsSync39, readFileSync as readFileSync37 } from "fs";
26987
+ import { existsSync as existsSync40, readFileSync as readFileSync39 } from "fs";
26101
26988
  var SLOW_SWEEP_SECONDS = 10;
26102
26989
  var SUITE_TAG = /<(\/?)testsuite\b([^>]*?)(\/?)>/g;
26103
26990
  function fileTimeOf(attributes) {
@@ -26137,10 +27024,10 @@ function slowSweepLine(slow) {
26137
27024
  return `\uD83D\uDC22 ${slow.length} tests.alwaysRun file(s) took over ${SLOW_SWEEP_SECONDS}s in the task step: ${named}.`;
26138
27025
  }
26139
27026
  function readFileTimes(path3) {
26140
- if (!existsSync39(path3))
27027
+ if (!existsSync40(path3))
26141
27028
  return [];
26142
27029
  try {
26143
- return parseJunitFileTimes(readFileSync37(path3, "utf8")) ?? [];
27030
+ return parseJunitFileTimes(readFileSync39(path3, "utf8")) ?? [];
26144
27031
  } catch {
26145
27032
  return [];
26146
27033
  }
@@ -26305,10 +27192,10 @@ function seamsOf(context) {
26305
27192
  };
26306
27193
  }
26307
27194
  function junitFileFor(repoRoot, sessionId, kind) {
26308
- return join48(runsDir(repoRoot), sessionId, "suite", `${kind}.junit.xml`);
27195
+ return join50(runsDir(repoRoot), sessionId, "suite", `${kind}.junit.xml`);
26309
27196
  }
26310
27197
  function alwaysRunJunitFileFor(repoRoot, sessionId, kind = "task") {
26311
- return join48(runsDir(repoRoot), sessionId, "suite", `${kind}-always-run.junit.xml`);
27198
+ return join50(runsDir(repoRoot), sessionId, "suite", `${kind}-always-run.junit.xml`);
26312
27199
  }
26313
27200
  function readHead(git) {
26314
27201
  const result = git(["rev-parse", "--verify", "HEAD^{commit}"]);
@@ -26480,7 +27367,7 @@ async function ensureBaseline(context) {
26480
27367
  activeOutput().warn(`\u26A0\uFE0F Could not write ${basename14(path3)} (${messageOf(error)}); the next run records the baseline again.`);
26481
27368
  }
26482
27369
  const outcome = settleStep(context, seams, settling);
26483
- const covered = completeStages(readFileSync38(context.trackerPath, "utf8"));
27370
+ const covered = completeStages(readFileSync40(context.trackerPath, "utf8"));
26484
27371
  addToLedger(context.trackerPath, covered.map((stage2) => ({ ...stage2, commit, via: "baseline" })));
26485
27372
  return { baseline, step: outcome.step, interrupted: false, halted: false };
26486
27373
  }
@@ -26686,7 +27573,7 @@ function createRunSuiteSteps(options) {
26686
27573
  return { beforeSession, afterTask, stoppedOnSignal: () => signalled, lastPreWrapUp: () => lastPreWrapUp };
26687
27574
  }
26688
27575
  // packages/rafa-run/src/start/triage.ts
26689
- import { homedir as homedir11 } from "os";
27576
+ import { homedir as homedir12 } from "os";
26690
27577
 
26691
27578
  // packages/rafa/src/ports/unresolved-tracker.ts
26692
27579
  function unresolvedTracker(kind, reason) {
@@ -26705,7 +27592,7 @@ function unresolvedTracker(kind, reason) {
26705
27592
 
26706
27593
  // packages/rafa/src/effort/store/bug-routes.ts
26707
27594
  import { randomUUID as randomUUID12 } from "crypto";
26708
- import { existsSync as existsSync40 } from "fs";
27595
+ import { existsSync as existsSync41 } from "fs";
26709
27596
  var BUG_ROUTES = [
26710
27597
  "filed",
26711
27598
  "private",
@@ -26807,7 +27694,7 @@ var SELECT_PLAN_BUG_ROUTES = `
26807
27694
  `;
26808
27695
  function readBugRoutesForPlan(repoRoot, planStub) {
26809
27696
  const path3 = sqliteStorePath(repoRoot);
26810
- if (!existsSync40(path3))
27697
+ if (!existsSync41(path3))
26811
27698
  return [];
26812
27699
  const rows = withSqliteStore(path3, "read", false, (db) => db.query(SELECT_PLAN_BUG_ROUTES).all(planStub));
26813
27700
  return rows.map((row) => ({
@@ -26966,10 +27853,16 @@ function inheritedNote(bug, name, where, failure2) {
26966
27853
  const comment = bug.ref === null ? "" : `, and ${issueName2(bug.ref)} on ${where}, found by ${foundByText(bug)}, was commented on`;
26967
27854
  return `${name}: inherited: ${test}; nothing was filed${comment}.`;
26968
27855
  }
27856
+ function repairText(bug) {
27857
+ if (bug.joined === true) {
27858
+ return bug.repairLine === undefined ? "it joined a repair task already in the tracker" : `it joined the repair task at tracker line ${bug.repairLine + 1}, already in the tracker`;
27859
+ }
27860
+ return bug.repairLine === undefined ? "a repair task was added above the next plan task" : `a repair task was added at tracker line ${bug.repairLine + 1}, above the next plan task`;
27861
+ }
26969
27862
  function settledText(bug) {
26970
27863
  switch (bug.action) {
26971
27864
  case "repair":
26972
- return bug.repairLine === undefined ? "a repair task was added above the next plan task" : `a repair task was added at tracker line ${bug.repairLine + 1}, above the next plan task`;
27865
+ return repairText(bug);
26973
27866
  case "follow-up":
26974
27867
  return bug.problem === null ? "held for this plan's follow-up issue, past its cap on repair tasks" : "held for this plan's follow-up issue";
26975
27868
  case "pr-body":
@@ -27077,7 +27970,7 @@ function createStartTriage(options) {
27077
27970
  const secrets = namedSecrets(options.config, env);
27078
27971
  const redact = (text) => redactSecrets(text, secrets);
27079
27972
  const checkout = options.checkout ?? options.repoRoot;
27080
- const local = localPathRedactor([checkout, options.repoRoot], homedir11());
27973
+ const local = localPathRedactor([checkout, options.repoRoot], homedir12());
27081
27974
  const git = options.git ?? createGitRunner(checkout);
27082
27975
  const bugRules = bugRulesOf(options.config);
27083
27976
  const triage = options.triageReport ?? triageReport;
@@ -27166,7 +28059,7 @@ function createStartTriage(options) {
27166
28059
  };
27167
28060
  }
27168
28061
  // packages/rafa-run/src/start/convention-body.ts
27169
- import { homedir as homedir12 } from "os";
28062
+ import { homedir as homedir13 } from "os";
27170
28063
 
27171
28064
  // packages/rafa-run/src/start/release-body.ts
27172
28065
  var RELEASE_BODY_SEAMS = {
@@ -27325,7 +28218,7 @@ async function writeLines(input, seams, redact) {
27325
28218
  }
27326
28219
  async function writeConventionLines(input, seams = {}) {
27327
28220
  const secrets = namedSecrets(input.settings, seams.env ?? process.env);
27328
- const local = localPathRedactor([input.repoRoot, input.checkout], seams.home ?? homedir12());
28221
+ const local = localPathRedactor([input.repoRoot, input.checkout], seams.home ?? homedir13());
27329
28222
  const redact = (text) => local(redactSecrets(text, secrets));
27330
28223
  try {
27331
28224
  return await writeLines(input, seams, redact);
@@ -27337,7 +28230,7 @@ async function writeConventionLines(input, seams = {}) {
27337
28230
  }
27338
28231
 
27339
28232
  // packages/rafa-run/src/start/follow-ups.ts
27340
- import { homedir as homedir13 } from "os";
28233
+ import { homedir as homedir14 } from "os";
27341
28234
  var LINE_PREFIX4 = "Follow-ups: ";
27342
28235
  var INDENT8 = " ";
27343
28236
  var FOLLOW_UPS_OPENING = "What this plan broke or left unfinished in its own work, " + "past its cap on repair tasks. Each line names the kind the loop read and what was reported.";
@@ -27479,7 +28372,7 @@ async function fileLines2(input, seams, redact) {
27479
28372
  }
27480
28373
  async function fileFollowUps(input, seams = {}) {
27481
28374
  const secrets = namedSecrets(input.settings, seams.env ?? process.env);
27482
- const local = localPathRedactor([input.repoRoot, input.checkout], seams.home ?? homedir13());
28375
+ const local = localPathRedactor([input.repoRoot, input.checkout], seams.home ?? homedir14());
27483
28376
  const redact = (text) => local(redactSecrets(text, secrets));
27484
28377
  let result;
27485
28378
  try {
@@ -27734,7 +28627,7 @@ async function finishRelease(input, seams = {}) {
27734
28627
  }
27735
28628
 
27736
28629
  // packages/rafa-run/src/start/runner-pr.ts
27737
- import { readFileSync as readFileSync39 } from "fs";
28630
+ import { readFileSync as readFileSync41 } from "fs";
27738
28631
  import path3 from "path";
27739
28632
  var RELEASE_NOTES_HEADING = "## Release notes";
27740
28633
  var UNFINISHED_WRAP_UP_LINE = "> \u26A0\uFE0F The wrap-up did not finish: no wrap-up session opened this pull request, so the loop opened it. Check that the base is merged in, the release notes were rewritten and the lessons were promoted before merging.";
@@ -27767,7 +28660,7 @@ function fragmentNotesIn(checkout, fragment) {
27767
28660
  return [];
27768
28661
  let text;
27769
28662
  try {
27770
- text = readFileSync39(path3.resolve(checkout, fragment), "utf8");
28663
+ text = readFileSync41(path3.resolve(checkout, fragment), "utf8");
27771
28664
  } catch {
27772
28665
  return [];
27773
28666
  }
@@ -27976,14 +28869,41 @@ function unpromotedLine(check, head) {
27976
28869
  const named = check.unpromoted.map((lesson) => unpromotedPhrase(lesson, head)).join("; ");
27977
28870
  return `Lessons listed for promotion that this pull request does not carry: ${named}.`;
27978
28871
  }
28872
+ function refusedLine(member, named, path4, error) {
28873
+ const who = member.id === named.id ? `\`${member.id}\`` : `\`${member.id}\` (same action as \`${named.id}\`)`;
28874
+ return `${who} is in ${path4}, but its promoted_to could not be recorded: ${messageOf(error)}`;
28875
+ }
28876
+ function groupMates(lesson, blessed) {
28877
+ const group = sameActionGroups(blessed).find((each) => each.action_hash === lesson.action_hash);
28878
+ return (group?.members ?? []).filter((member) => member.id !== lesson.id);
28879
+ }
28880
+ async function blessedOrProblem(learning) {
28881
+ try {
28882
+ return { blessed: (await learning.pullBlessed()).instincts, problem: null };
28883
+ } catch (error) {
28884
+ return { blessed: [], problem: messageOf(error) };
28885
+ }
28886
+ }
27979
28887
  async function recordPromotions(learning, promoted) {
27980
28888
  const problems = [];
28889
+ if (promoted.length === 0)
28890
+ return problems;
28891
+ const { blessed, problem } = await blessedOrProblem(learning);
28892
+ const pushed = new Set;
27981
28893
  for (const { lesson, path: path4 } of promoted) {
27982
- const sourceId = lesson.sources?.[0] ?? lesson.id;
27983
- try {
27984
- await learning.push({ source_id: sourceId, instincts: [{ ...lesson, promoted_to: path4 }] });
27985
- } catch (error) {
27986
- problems.push(`\`${lesson.id}\` is in ${path4}, but its promoted_to could not be recorded: ${messageOf(error)}`);
28894
+ if (problem !== null) {
28895
+ problems.push(`\`${lesson.id}\` is in ${path4}, but the rest of its same-action group was not recorded, as the blessed set could not be read: ${problem}`);
28896
+ }
28897
+ for (const member of [lesson, ...groupMates(lesson, blessed)]) {
28898
+ if (pushed.has(member.id))
28899
+ continue;
28900
+ pushed.add(member.id);
28901
+ const sourceId = member.sources?.[0] ?? member.id;
28902
+ try {
28903
+ await learning.push({ source_id: sourceId, instincts: [{ ...member, promoted_to: path4 }] });
28904
+ } catch (error) {
28905
+ problems.push(refusedLine(member, lesson, path4, error));
28906
+ }
27987
28907
  }
27988
28908
  }
27989
28909
  return problems;
@@ -28429,11 +29349,11 @@ async function openByRunner(seams, branch, retriesSpent) {
28429
29349
  activeOutput().warn(line);
28430
29350
  return { kind: "delivered", pull: attempt2.pull, by: "runner", retriesSpent };
28431
29351
  }
28432
- var ISSUE_NUMBER5 = /^#?(\d+)$/;
29352
+ var ISSUE_NUMBER6 = /^#?(\d+)$/;
28433
29353
  var RAFA_ID = /(?:^|\/)rafa-(\d+)(?:-|$)/;
28434
29354
  function planIssueNumber(planContent, planStub, branch) {
28435
29355
  const declared = parsePlan(planContent).header.issue?.trim() ?? "";
28436
- const spelled = ISSUE_NUMBER5.exec(declared)?.[1] ?? RAFA_ID.exec(planStub ?? "")?.[1] ?? RAFA_ID.exec(branch)?.[1];
29356
+ const spelled = ISSUE_NUMBER6.exec(declared)?.[1] ?? RAFA_ID.exec(planStub ?? "")?.[1] ?? RAFA_ID.exec(branch)?.[1];
28437
29357
  return spelled === undefined ? null : Number(spelled);
28438
29358
  }
28439
29359
  function runnerPrInputFor(source) {
@@ -28520,13 +29440,13 @@ function registerCoreServices() {
28520
29440
  }
28521
29441
  // src/plan.ts
28522
29442
  import fs5 from "fs";
28523
- import { homedir as homedir15 } from "os";
29443
+ import { homedir as homedir16 } from "os";
28524
29444
  import path7 from "path";
28525
29445
  import { fileURLToPath as fileURLToPath5 } from "url";
28526
29446
 
28527
29447
  // src/commands/plan/bundled-check.ts
28528
- import { readdirSync as readdirSync12, readFileSync as readFileSync40, realpathSync as realpathSync6, statSync as statSync10, writeFileSync as writeFileSync13 } from "fs";
28529
- import { basename as basename15, isAbsolute as isAbsolute15, join as join49, relative as relative19, resolve as resolve21, sep as sep8 } from "path";
29448
+ import { readdirSync as readdirSync13, readFileSync as readFileSync42, realpathSync as realpathSync6, statSync as statSync10, writeFileSync as writeFileSync13 } from "fs";
29449
+ import { basename as basename15, isAbsolute as isAbsolute15, join as join51, relative as relative19, resolve as resolve21, sep as sep8 } from "path";
28530
29450
  var SOURCE_DIR2 = "src";
28531
29451
  var CODE_SPAN6 = /`([^`]+)`/gu;
28532
29452
  var PATH_LIKE = /^\S+$/u;
@@ -28551,11 +29471,11 @@ function bundledAgents(root) {
28551
29471
  function bundledSkills(root) {
28552
29472
  if (root === null)
28553
29473
  return [];
28554
- return readdirSync12(root).filter((name) => isFilePath(join49(root, name, SKILL_FILE2))).sort((a, b) => a.localeCompare(b));
29474
+ return readdirSync13(root).filter((name) => isFilePath(join51(root, name, SKILL_FILE2))).sort((a, b) => a.localeCompare(b));
28555
29475
  }
28556
29476
  function readBundle(repoRoot) {
28557
- const agentsRoot = realPathOrNull(join49(repoRoot, SOURCE_DIR2, BUNDLED_AGENTS_DIR));
28558
- const skillsRoot = realPathOrNull(join49(repoRoot, SOURCE_DIR2, BUNDLED_SKILLS_DIR));
29477
+ const agentsRoot = realPathOrNull(join51(repoRoot, SOURCE_DIR2, BUNDLED_AGENTS_DIR));
29478
+ const skillsRoot = realPathOrNull(join51(repoRoot, SOURCE_DIR2, BUNDLED_SKILLS_DIR));
28559
29479
  return { agentsRoot, skillsRoot, agents: bundledAgents(agentsRoot), skills: bundledSkills(skillsRoot) };
28560
29480
  }
28561
29481
  function skillHolding(bundle, realPath2) {
@@ -28622,7 +29542,7 @@ function tierPinItem(edit, planFileName2) {
28622
29542
  }
28623
29543
  function readOrNull(path4) {
28624
29544
  try {
28625
- return readFileSync40(path4, "utf8");
29545
+ return readFileSync42(path4, "utf8");
28626
29546
  } catch (error) {
28627
29547
  const isAbsent = typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
28628
29548
  if (isAbsent)
@@ -28675,7 +29595,7 @@ function notePlanBundledEdits(repoRoot, generated, output = activeOutput()) {
28675
29595
  const planFile = resolve21(repoRoot, generated.planPath);
28676
29596
  if (!isFile(planFile))
28677
29597
  return generated;
28678
- const edits = findBundledEdits(readFileSync40(planFile, "utf8"), { repoRoot });
29598
+ const edits = findBundledEdits(readFileSync42(planFile, "utf8"), { repoRoot });
28679
29599
  if (edits.length === 0)
28680
29600
  return generated;
28681
29601
  const file = generated.prerequisitesPath ?? prerequisitesPathForPlan(generated.planPath);
@@ -28894,7 +29814,7 @@ function createPlanBlockedOffer(seams = DEFAULT_BLOCKED_SEAMS) {
28894
29814
 
28895
29815
  // src/commands/plan/ready-offer.ts
28896
29816
  var runIssueReadyLazily = async (options) => {
28897
- const { runIssueReady: run } = await import("./ready-kac4ty0p.js");
29817
+ const { runIssueReady: run } = await import("./ready-9e1pyxdh.js");
28898
29818
  return run(options);
28899
29819
  };
28900
29820
  var DEFAULT_OFFER_SEAMS = Object.freeze({});
@@ -29006,10 +29926,10 @@ async function resolveCreateSpec(options, seams = DEFAULT_ROUTE_SEAMS) {
29006
29926
  }
29007
29927
 
29008
29928
  // src/commands/plan/store-check.ts
29009
- import { mkdirSync as mkdirSync8, readFileSync as readFileSync41, renameSync as renameSync4 } from "fs";
29929
+ import { mkdirSync as mkdirSync8, readFileSync as readFileSync43, renameSync as renameSync4 } from "fs";
29010
29930
  import { basename as basename16, dirname as dirname18, resolve as resolve22 } from "path";
29011
29931
  function readFileOrNull(path6) {
29012
- return path6 !== null && isFile(path6) ? readFileSync41(path6, "utf8") : null;
29932
+ return path6 !== null && isFile(path6) ? readFileSync43(path6, "utf8") : null;
29013
29933
  }
29014
29934
  function checkStoreRules(file, markdown) {
29015
29935
  const prerequisitesPath = prerequisitesPathForPlan(file);
@@ -29036,7 +29956,7 @@ function enforceStoreRules(repoRoot, generated, output = activeOutput()) {
29036
29956
  const planFile = resolve22(repoRoot, generated.planPath);
29037
29957
  if (!isFile(planFile))
29038
29958
  return;
29039
- const problems = checkStoreRules(planFile, readFileSync41(planFile, "utf8"));
29959
+ const problems = checkStoreRules(planFile, readFileSync43(planFile, "utf8"));
29040
29960
  if (problems.length === 0)
29041
29961
  return;
29042
29962
  const prerequisites = generated.prerequisitesPath ?? prerequisitesPathForPlan(generated.planPath);
@@ -29112,16 +30032,16 @@ function stretchRulesReader(env, repoRoot) {
29112
30032
  }
29113
30033
 
29114
30034
  // src/notices/run.ts
29115
- import { homedir as homedir14 } from "os";
30035
+ import { homedir as homedir15 } from "os";
29116
30036
 
29117
30037
  // src/notices/notices.ts
29118
- import { mkdirSync as mkdirSync9, readFileSync as readFileSync42, writeFileSync as writeFileSync14 } from "fs";
29119
- import { dirname as dirname19, join as join50 } from "path";
30038
+ import { mkdirSync as mkdirSync9, readFileSync as readFileSync44, writeFileSync as writeFileSync14 } from "fs";
30039
+ import { dirname as dirname19, join as join52 } from "path";
29120
30040
  var NOTICE_IDS = Object.freeze(["alpha", "danger"]);
29121
30041
  var FEEDBACK_URL = "https://github.com/open-tomato/rafa/issues/new/choose";
29122
30042
  var ROADMAP_URL = "https://github.com/open-tomato/rafa/issues/31";
29123
30043
  function noticesPath(home) {
29124
- return join50(home, ".rafa", "notices.json");
30044
+ return join52(home, ".rafa", "notices.json");
29125
30045
  }
29126
30046
  function isNoticeId(value) {
29127
30047
  return typeof value === "string" && NOTICE_IDS.includes(value);
@@ -29129,7 +30049,7 @@ function isNoticeId(value) {
29129
30049
  function readDismissed(home) {
29130
30050
  let raw;
29131
30051
  try {
29132
- raw = readFileSync42(noticesPath(home), "utf8");
30052
+ raw = readFileSync44(noticesPath(home), "utf8");
29133
30053
  } catch {
29134
30054
  return [];
29135
30055
  }
@@ -29227,7 +30147,7 @@ async function offerNotices(request, seams) {
29227
30147
  // src/notices/run.ts
29228
30148
  var NOTICES_CANCELLED = "\uD83D\uDED1 Cancelled at the notice: nothing was started.";
29229
30149
  async function requireNoticesAnswered(settingSources) {
29230
- const outcome = await offerNotices({ home: homedir14(), version: RAFA_VERSION, settingSources }, {
30150
+ const outcome = await offerNotices({ home: homedir15(), version: RAFA_VERSION, settingSources }, {
29231
30151
  isTerminal: () => process.stdin.isTTY === true,
29232
30152
  openPrompter: () => createLinePrompter(process.stdin, process.stderr),
29233
30153
  warn: (line) => {
@@ -29416,7 +30336,7 @@ async function resolvePlanConfig(repoRoot, home) {
29416
30336
  }
29417
30337
  }
29418
30338
  async function plan(args, repoRoot, roster, registry = CORE_ADAPTER_REGISTRY) {
29419
- const home = homedir15();
30339
+ const home = homedir16();
29420
30340
  const config = await resolvePlanConfig(repoRoot, home);
29421
30341
  const {
29422
30342
  settingSources,
@@ -29508,10 +30428,146 @@ async function plan(args, repoRoot, roster, registry = CORE_ADAPTER_REGISTRY) {
29508
30428
  }
29509
30429
  // src/start.ts
29510
30430
  import fs6 from "fs";
29511
- import { homedir as homedir16 } from "os";
30431
+ import { homedir as homedir17 } from "os";
29512
30432
  import path8 from "path";
29513
30433
  import { fileURLToPath as fileURLToPath6 } from "url";
29514
30434
 
30435
+ // src/learning/plan-stage-links.ts
30436
+ import { readdir as readdir2, readFile as readFile6 } from "fs/promises";
30437
+ import { join as join53 } from "path";
30438
+ var PLAN_FILE = /^PLAN-.+\.md$/;
30439
+ var FENCE_RUN = /^( {0,3})(`{3,}|~{3,})/;
30440
+ var CLOSING_FENCE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
30441
+ function warnPassedOver(message) {
30442
+ activeLogger().child({ module: "learning", action: "plan-stage-links" }).log({ level: "warn", message });
30443
+ }
30444
+ function messageOf11(error) {
30445
+ return error instanceof Error ? error.message : String(error);
30446
+ }
30447
+ function fencedLines(markdown) {
30448
+ const lines = markdown.split(`
30449
+ `).map((line) => line.endsWith("\r") ? line.slice(0, -1) : line);
30450
+ const fenced3 = new Set;
30451
+ let index = 0;
30452
+ while (index < lines.length) {
30453
+ const line = lines[index] ?? "";
30454
+ const match = FENCE_RUN.exec(line);
30455
+ const run = match?.[2];
30456
+ const info = line.slice(match?.[0].length ?? 0);
30457
+ if (run === undefined || run.startsWith("`") && info.includes("`")) {
30458
+ index += 1;
30459
+ continue;
30460
+ }
30461
+ let closing = index + 1;
30462
+ while (closing < lines.length && !closesFence5(lines[closing] ?? "", run))
30463
+ closing += 1;
30464
+ for (let covered = index;covered <= Math.min(closing, lines.length - 1); covered += 1) {
30465
+ fenced3.add(covered);
30466
+ }
30467
+ index = closing + 1;
30468
+ }
30469
+ return fenced3;
30470
+ }
30471
+ function closesFence5(line, opener) {
30472
+ const run = CLOSING_FENCE.exec(line)?.[1];
30473
+ return run !== undefined && run.charAt(0) === opener.charAt(0) && run.length >= opener.length;
30474
+ }
30475
+ function stageLinks(stub, model, fenced3) {
30476
+ return model.stages.map((stage2, index) => ({
30477
+ stub,
30478
+ stage: stage2.name,
30479
+ context: stage2.context,
30480
+ tasks: model.tasks.filter((task) => task.stage === index && !fenced3.has(task.lineNum)).map((task) => task.task)
30481
+ }));
30482
+ }
30483
+ async function readPlanFile(path8, name) {
30484
+ let markdown;
30485
+ try {
30486
+ markdown = await readFile6(path8, "utf8");
30487
+ } catch (error) {
30488
+ return { skipped: `could not be read: ${messageOf11(error)}` };
30489
+ }
30490
+ const model = parsePlan(markdown);
30491
+ const unclosed = model.issues.find((issue4) => issue4.reason === "unclosed-block");
30492
+ if (unclosed !== undefined) {
30493
+ return { skipped: `holds a rafa block never closed, opened at line ${unclosed.line}` };
30494
+ }
30495
+ const stub = model.header.stub ?? planStubFromPath(name);
30496
+ if (stub === null) {
30497
+ return { skipped: "names no stub in its rafa:plan block or its file name" };
30498
+ }
30499
+ return { links: stageLinks(stub, model, fencedLines(markdown)) };
30500
+ }
30501
+ async function planFileNames(plansDir) {
30502
+ try {
30503
+ const names = await readdir2(plansDir);
30504
+ return names.filter((name) => PLAN_FILE.test(name)).sort();
30505
+ } catch (error) {
30506
+ if (error.code === "ENOENT")
30507
+ return [];
30508
+ throw error;
30509
+ }
30510
+ }
30511
+ async function readPlanStageLinks(plansDir, options = {}) {
30512
+ const warn2 = options.warn ?? warnPassedOver;
30513
+ const links = [];
30514
+ for (const name of await planFileNames(plansDir)) {
30515
+ const reading = await readPlanFile(join53(plansDir, name), name);
30516
+ if ("skipped" in reading) {
30517
+ warn2(`Plan file ${name} passed over: it ${reading.skipped}.`);
30518
+ continue;
30519
+ }
30520
+ links.push(...reading.links);
30521
+ }
30522
+ return links;
30523
+ }
30524
+
30525
+ // src/learning/bug-fix-pass.ts
30526
+ var PASS_ADAPTER = "local";
30527
+ var WARNING = "bug-fix pass";
30528
+ var NOTHING = { pushed: 0, skipped: 0, unpaired: 0 };
30529
+ function warnThroughActiveOutput4(message) {
30530
+ activeOutput().warn(message);
30531
+ }
30532
+ async function resolvedConfig(roots) {
30533
+ return (await loadConfig(roots, {}, () => {})).config;
30534
+ }
30535
+ async function pass(roots, seams, warn2) {
30536
+ const config = seams.config ?? await resolvedConfig(roots);
30537
+ if (config.learningAdapter !== PASS_ADAPTER) {
30538
+ throw new Error(`learning.adapter is \`${config.learningAdapter}\`, and the pass pushes through \`${PASS_ADAPTER}\` only`);
30539
+ }
30540
+ const { rows, note } = readBugFixRows(roots.root);
30541
+ if (note !== null)
30542
+ return NOTHING;
30543
+ const links = await readPlanStageLinks(plansDirAt(roots.root, config.planDir).path, { warn: warn2 });
30544
+ const now = (seams.now ?? (() => new Date))();
30545
+ const { pairs, unpaired } = pairBugFixes(rows, links, now);
30546
+ const push = await pushBugFixPairs({
30547
+ instinctsDir: localInstinctsDir(roots.root),
30548
+ home: roots.home,
30549
+ minConfidence: config.learningBlessMinConfidence,
30550
+ warn: warn2
30551
+ }, pairs, now);
30552
+ if (push.problems.length > 0) {
30553
+ warn2([
30554
+ `${WARNING}: ${push.problems.length} of ${pairs.length} pairs were not pushed:`,
30555
+ ...push.problems.map((problem) => ` ${problem}`)
30556
+ ].join(`
30557
+ `));
30558
+ }
30559
+ return { pushed: push.pushed.length, skipped: push.skipped.length, unpaired: unpaired.length };
30560
+ }
30561
+ async function runBugFixPass(roots, seams = {}) {
30562
+ const warn2 = seams.warn ?? warnThroughActiveOutput4;
30563
+ try {
30564
+ return await pass(roots, seams, warn2);
30565
+ } catch (error) {
30566
+ warn2(`${WARNING}: nothing was pushed: ${messageOf(error)}`);
30567
+ return NOTHING;
30568
+ }
30569
+ }
30570
+
29515
30571
  // src/utils/schedule.ts
29516
30572
  function msUntil(startAt, now = new Date) {
29517
30573
  const match = startAt.match(/^(\d{1,2}):(\d{2})$/);
@@ -29552,7 +30608,7 @@ async function start(args, repoRoot) {
29552
30608
  return;
29553
30609
  let runConfig;
29554
30610
  try {
29555
- runConfig = await loadRunConfig({ root: repoRoot, home: homedir16() }, args);
30611
+ runConfig = await loadRunConfig({ root: repoRoot, home: homedir17() }, args);
29556
30612
  } catch (error) {
29557
30613
  if (!(error instanceof ConfigError))
29558
30614
  throw error;
@@ -29589,7 +30645,7 @@ async function start(args, repoRoot) {
29589
30645
  let expected2 = openCheckoutExpectation({ projectRoot: repoRoot, checkout, branch });
29590
30646
  await announceRiskTotal({
29591
30647
  repoRoot,
29592
- home: homedir16(),
30648
+ home: homedir17(),
29593
30649
  planPath,
29594
30650
  config: runConfig.config,
29595
30651
  environment: process.env
@@ -29619,16 +30675,16 @@ async function start(args, repoRoot) {
29619
30675
  tiersRafa: runConfig.config.tiersRafa,
29620
30676
  tiersSkills: runConfig.config.tiersSkills,
29621
30677
  tiersAgents: runConfig.config.tiersAgents,
29622
- home: homedir16()
30678
+ home: homedir17()
29623
30679
  },
29624
- sync: { resolved: runConfig, home: homedir16() },
30680
+ sync: { resolved: runConfig, home: homedir17() },
29625
30681
  claim: createStartPreflightClaim(repoRoot, runConfig.config),
29626
30682
  drift: createStartPreflightDrift(repoRoot, runConfig.config)
29627
30683
  });
29628
- const serving = { root: repoRoot, run: session.id, home: homedir16(), settings: runConfig.config };
30684
+ const serving = { root: repoRoot, run: session.id, home: homedir17(), settings: runConfig.config };
29629
30685
  const learning = {
29630
30686
  kind: runConfig.config.learningAdapter,
29631
- home: homedir16(),
30687
+ home: homedir17(),
29632
30688
  blessMinConfidence: runConfig.config.learningBlessMinConfidence
29633
30689
  };
29634
30690
  const handout = {
@@ -29644,7 +30700,7 @@ async function start(args, repoRoot) {
29644
30700
  };
29645
30701
  const hubContact = createHubContact({
29646
30702
  root: repoRoot,
29647
- home: homedir16(),
30703
+ home: homedir17(),
29648
30704
  resolved: runConfig,
29649
30705
  warn: (message) => activeOutput().warn(message),
29650
30706
  sessionId: session.id
@@ -29756,7 +30812,7 @@ async function start(args, repoRoot) {
29756
30812
  inject: injectMode,
29757
30813
  repoRoot,
29758
30814
  checkout,
29759
- home: homedir16(),
30815
+ home: homedir17(),
29760
30816
  settingSources,
29761
30817
  knownMissing,
29762
30818
  inherited: runStartFailures(trackerPath),
@@ -29780,6 +30836,7 @@ async function start(args, repoRoot) {
29780
30836
  await triageTask({ trackerPath, lineNum: taskInfo.lineNum, planStub, dispatch, outcome });
29781
30837
  await staleDocs.afterTask({ planStub, dispatch, outcome });
29782
30838
  await hubContact.pushThenPull();
30839
+ await runBugFixPass({ root: repoRoot, home: homedir17() }, { config: runConfig.config });
29783
30840
  return stored2;
29784
30841
  };
29785
30842
  if (interrupted2) {
@@ -29917,6 +30974,7 @@ export {
29917
30974
  WireExportRefusal,
29918
30975
  WIRE_VERSION,
29919
30976
  WIRE_FORMAT,
30977
+ WIRE_CONTRACT_VERSION,
29920
30978
  TRUSTED_PERMISSIONS,
29921
30979
  ScopeError,
29922
30980
  SYNC_STRATEGIES,