rungate 0.5.0 → 0.7.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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -1,5 +1,8 @@
1
1
  import { appendFileSync, readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
2
- import { dirname, join } from "path";
2
+ import { homedir } from "os";
3
+ import { basename, dirname, join } from "path";
4
+
5
+ import { BRIEF_CONSTRAINTS_SECTION } from "./agents-md-sections.js";
3
6
 
4
7
  /**
5
8
  * The history's record shape (#116).
@@ -464,22 +467,364 @@ export function detectHillClimbNeeds(report: ComplianceReport): HillClimbAction[
464
467
  return actions;
465
468
  }
466
469
 
470
+ /**
471
+ * Where a reinforcement goes, named (#624).
472
+ *
473
+ * The loop used to write the tracked brief at the bottom of the compose loop,
474
+ * as a side effect of having composed it. Nobody chose that: no brief in this
475
+ * repository has ever carried a committed reinforcement, so every rule the
476
+ * loop produced was either discarded by the next `git checkout` or left in a
477
+ * working tree for some later run to trip over.
478
+ *
479
+ * Three answers are defensible, and the point of this binding is that a run
480
+ * says which one it is giving:
481
+ *
482
+ * - `COMMIT` — write the tracked brief in place, for a human to review and
483
+ * commit. This is what the loop did, now chosen rather than fallen into.
484
+ * - `UNTRACKED` — write the reinforced brief outside the brief's own
485
+ * directory, so the proposal survives without dirtying the tree.
486
+ * - `DISCARD` — compose it, report it, write nothing.
487
+ */
488
+ export const HILL_CLIMB_DESTINATIONS = ["COMMIT", "UNTRACKED", "DISCARD"] as const;
489
+
490
+ export type HillClimbDestination = (typeof HILL_CLIMB_DESTINATIONS)[number];
491
+
492
+ /**
493
+ * The destination a caller gets when it does not name one.
494
+ *
495
+ * `COMMIT` is the behaviour every existing caller already had, so this change
496
+ * routes the write without changing where it lands. Which destination the
497
+ * shipped loop should default to is #624's AC-2 and is a separate decision —
498
+ * it has to move `scripts/persist-compliance.ts`'s re-grade step with it,
499
+ * because re-grading a brief that was not written measures the old one.
500
+ */
501
+ export const DEFAULT_HILL_CLIMB_DESTINATION: HillClimbDestination = "COMMIT";
502
+
503
+ /** What a write actually did, so a caller can report it rather than assume. */
504
+ export interface HillClimbWrite {
505
+ destination: HillClimbDestination;
506
+ /** The path written, or `null` when the destination writes nothing. */
507
+ path: string | null;
508
+ }
509
+
510
+ export interface HillClimbWriteOptions {
511
+ destination?: HillClimbDestination;
512
+ /** Where an `UNTRACKED` write lands. Defaults to `~/.rungate/hill-climb`. */
513
+ untrackedDir?: string;
514
+ }
515
+
516
+ export function defaultUntrackedDir(): string {
517
+ return join(homedir(), ".rungate", "hill-climb");
518
+ }
519
+
520
+ /** The path an `UNTRACKED` write uses for a given brief. */
521
+ export function untrackedBriefPath(
522
+ briefPath: string,
523
+ untrackedDir: string = defaultUntrackedDir(),
524
+ ): string {
525
+ return join(untrackedDir, basename(briefPath));
526
+ }
527
+
528
+ /**
529
+ * The one place a reinforced brief is written.
530
+ *
531
+ * Every destination goes through here, so there is one binding to mutate and
532
+ * one answer to "where did that rule go".
533
+ */
534
+ export function writeReinforcedBrief(
535
+ briefPath: string,
536
+ content: string,
537
+ opts: HillClimbWriteOptions = {},
538
+ ): HillClimbWrite {
539
+ const destination = opts.destination ?? DEFAULT_HILL_CLIMB_DESTINATION;
540
+ if (destination === "DISCARD") return { destination, path: null };
541
+
542
+ const path =
543
+ destination === "COMMIT"
544
+ ? briefPath
545
+ : untrackedBriefPath(briefPath, opts.untrackedDir);
546
+ mkdirSync(dirname(path), { recursive: true });
547
+ writeFileSync(path, content);
548
+ return { destination, path };
549
+ }
550
+
551
+ /** The one spelling of the inserted bullet's opening. */
552
+ export const REINFORCEMENT_PREFIX = "- **REINFORCED (auto):** ";
553
+
554
+ const ATX_HEADING = /^#{1,6} /;
555
+
556
+ /**
557
+ * Splice one reinforcement bullet into a brief at `insertIdx`.
558
+ *
559
+ * A list item immediately followed by an ATX heading is not a reliably parsed
560
+ * construct, and a brief is read by agents as context — so the inserted block
561
+ * is separated from a following heading by a blank line. The separator is
562
+ * decided here and nowhere else; it is not a newline smuggled into the prefix,
563
+ * which would move the rule's text off its own bullet and leave the heading
564
+ * exactly where it was.
565
+ */
566
+ export function insertReinforcement(
567
+ content: string,
568
+ insertIdx: number,
569
+ reinforcement: string,
570
+ ): string {
571
+ const before = content.slice(0, insertIdx);
572
+ const rest = content.slice(insertIdx).replace(/^\n+/, "");
573
+ const lead = before.length === 0 || before.endsWith("\n") ? "" : "\n";
574
+ const separator = ATX_HEADING.test(rest) ? "\n\n" : "\n";
575
+ return `${before}${lead}${REINFORCEMENT_PREFIX}${reinforcement}${separator}${rest}`;
576
+ }
577
+
578
+ /**
579
+ * The region a reinforcement goes to whenever the brief has one (#655).
580
+ *
581
+ * It outranks every COMP's own preference, and that ordering is #655's
582
+ * finding rather than a taste: `## Efficiency Rules`, `## Testing Rules` and
583
+ * `## Never Do` are generated from `templates/agent-briefs/`, so a
584
+ * reinforcement written into one of them is destroyed by the next
585
+ * `bunx rungate scaffold .`. `## Project Constraints` is the one region of a
586
+ * brief a re-scaffold carries forward verbatim, so a rule mined from this
587
+ * repo's own compliance history survives there and nowhere else in the file.
588
+ *
589
+ * Read from `BRIEF_CONSTRAINTS_SECTION` rather than spelled here, because a
590
+ * second literal naming that heading is a copy that stops agreeing with the
591
+ * preserver (#621).
592
+ */
593
+ export const HILL_CLIMB_DURABLE_SECTION = BRIEF_CONSTRAINTS_SECTION.label;
594
+
595
+ /**
596
+ * Every heading a reinforcement can be spliced under (#704, #655).
597
+ *
598
+ * The durable region first, then the three generated ones. This is the list
599
+ * the brief is searched for and the order a COMP with no stated preference
600
+ * tries them in. It is exported because every other position that talks
601
+ * about "the headings" — the refusal sentence, the spec, the tests — must
602
+ * name the same set, and a second hand-written copy would be a list that
603
+ * silently stops agreeing with the one the code reads.
604
+ *
605
+ * Preference, not creation. A brief with none of the four still reaches
606
+ * `NO_SECTION`, which is the state #646 made reportable — writing a heading
607
+ * in would make that state unreachable and silently change what every
608
+ * receipt says.
609
+ */
610
+ export const HILL_CLIMB_SECTIONS = [
611
+ HILL_CLIMB_DURABLE_SECTION,
612
+ "## Efficiency Rules",
613
+ "## Testing Rules",
614
+ "## Never Do",
615
+ ] as const;
616
+
617
+ export type HillClimbSection = (typeof HILL_CLIMB_SECTIONS)[number];
618
+
619
+ /**
620
+ * Which heading each COMP's reinforcement belongs under (#704).
621
+ *
622
+ * Before this table the selector was one nested conditional — `## Testing
623
+ * Rules` if the COMP was literally `COMP-2`, otherwise `## Efficiency Rules`,
624
+ * otherwise `## Never Do`. Read as a mapping that is: one id reaches one
625
+ * heading and twelve reach two, so a brief carrying ONLY `## Testing Rules`
626
+ * — which is `marcus.md`, the role that produces most of the traffic —
627
+ * accepts a reinforcement for COMP-2 and drops every other COMP on the floor
628
+ * reporting that the brief had no section. Measured over the recorded history
629
+ * with `scripts/replay-hill-climb-history.ts`: 51 of marcus's 136 detected
630
+ * actions were refused by a brief that was carrying a heading the whole time.
631
+ *
632
+ * The primary is the section the rule is ABOUT, which is also what
633
+ * `lib/transcript-checker.ts` records in each criterion's `source` for the
634
+ * four it names: COMP-2 is `marcus.md § Testing Rules`, COMP-9 is
635
+ * `marcus.md § Efficiency Rules`, COMP-6 and COMP-7 are `marcus.md § Never
636
+ * Do`. The rest are classified the same way — a prohibition under `Never Do`,
637
+ * a tool-economy rule under `Efficiency Rules`, a test-ordering rule under
638
+ * `Testing Rules`.
639
+ *
640
+ * It is a lookup WITHOUT a fallback on purpose. An id nobody classified is a
641
+ * fact about this table, and `resolveHillClimbSection` says so by name rather
642
+ * than letting it arrive at the same refusal a brief with no headings
643
+ * produces — those are different states and only one of them is fixed by
644
+ * editing a brief.
645
+ */
646
+ const COMP_PRIMARY_SECTION: Record<string, HillClimbSection> = {
647
+ "COMP-1": "## Never Do",
648
+ "COMP-2": "## Testing Rules",
649
+ "COMP-3": "## Testing Rules",
650
+ "COMP-4": "## Never Do",
651
+ "COMP-5": "## Never Do",
652
+ "COMP-6": "## Never Do",
653
+ "COMP-7": "## Never Do",
654
+ "COMP-8": "## Never Do",
655
+ "COMP-9": "## Efficiency Rules",
656
+ "COMP-10": "## Efficiency Rules",
657
+ "COMP-11": "## Never Do",
658
+ "COMP-12": "## Efficiency Rules",
659
+ "COMP-13": "## Testing Rules",
660
+ };
661
+
662
+ /**
663
+ * The headings to try for `compId`, most preferred first, or `null` when the
664
+ * id is not classified.
665
+ *
666
+ * Three rules, in this order, and the first is #655's rather than this
667
+ * issue's: DURABILITY BEATS TOPICALITY. A rule spliced into the right
668
+ * section of a brief that the next scaffold run rewrites is a rule that
669
+ * does not exist, so `## Project Constraints` is tried first for every
670
+ * COMP. `COMP_PRIMARY_SECTION` then decides among the generated three, and
671
+ * the remainder follow in `HILL_CLIMB_SECTIONS` order.
672
+ *
673
+ * The tail is DERIVED from `HILL_CLIMB_SECTIONS` rather than written out
674
+ * per id, so a heading added to that list is reachable from every COMP
675
+ * without thirteen edits — and so the table above cannot contain a row that
676
+ * omits one.
677
+ */
678
+ export function hillClimbSectionPreference(compId: string): readonly HillClimbSection[] | null {
679
+ const primary = COMP_PRIMARY_SECTION[compId];
680
+ if (!primary) return null;
681
+ const ranked: HillClimbSection[] = [HILL_CLIMB_DURABLE_SECTION, primary];
682
+ return [...ranked, ...HILL_CLIMB_SECTIONS.filter((s) => !ranked.includes(s))];
683
+ }
684
+
685
+ /**
686
+ * Where in `content` a level-2 heading starts, or -1.
687
+ *
688
+ * Anchored to the start of a line, because `indexOf("## Never Do")` also
689
+ * matches the last eleven characters of `### Never Do` — and the insertion
690
+ * arithmetic below then measures from an index that is not where the heading
691
+ * begins.
692
+ */
693
+ function headingIndex(content: string, heading: HillClimbSection): number {
694
+ if (content.startsWith(heading)) return 0;
695
+ const at = content.indexOf(`\n${heading}`);
696
+ return at === -1 ? -1 : at + 1;
697
+ }
698
+
699
+ /**
700
+ * Where a reinforcement for `compId` goes in `content` (#704).
701
+ *
702
+ * The ONE binding that maps a COMP id to a destination heading, with one call
703
+ * site — `applyHillClimb`. A second place that answered this question would
704
+ * survive any mutation of this one and hold its cases up
705
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
706
+ *
707
+ * Three answers, and the distinction between the last two is the whole point:
708
+ *
709
+ * - `RESOLVED` — the heading, and the index it starts at.
710
+ * - `UNMAPPED_COMP` — the id is not in `COMP_PRIMARY_SECTION`. Nothing about
711
+ * the brief caused this and no edit to a brief fixes it.
712
+ * - `NO_SECTION` — the id is mapped and the brief carries none of the three.
713
+ */
714
+ export type HillClimbSectionResolution =
715
+ | { kind: "RESOLVED"; compId: string; heading: HillClimbSection; index: number }
716
+ | { kind: "UNMAPPED_COMP"; compId: string; reason: string }
717
+ | { kind: "NO_SECTION"; compId: string; reason: string };
718
+
719
+ export function resolveHillClimbSection(
720
+ compId: string,
721
+ content: string,
722
+ ): HillClimbSectionResolution {
723
+ const preference = hillClimbSectionPreference(compId);
724
+ if (!preference) {
725
+ return {
726
+ kind: "UNMAPPED_COMP",
727
+ compId,
728
+ reason: `${compId} has no destination heading declared, so no brief can accept it`,
729
+ };
730
+ }
731
+ for (const heading of preference) {
732
+ const index = headingIndex(content, heading);
733
+ if (index !== -1) return { kind: "RESOLVED", compId, heading, index };
734
+ }
735
+ return {
736
+ kind: "NO_SECTION",
737
+ compId,
738
+ reason: `the brief carries none of ${HILL_CLIMB_SECTIONS.join(", ")}`,
739
+ };
740
+ }
741
+
742
+ /**
743
+ * What `applyHillClimb` decided about an action it did NOT apply (#646).
744
+ *
745
+ * The function decides exactly three things, and it used to report all three
746
+ * as English in one `skipped: string[]`. A caller that wanted the tier it was
747
+ * being told to promote to had to recover it from the middle of a sentence,
748
+ * which is the same defect as an unsourced verdict: the decision was readable
749
+ * and not usable.
750
+ *
751
+ * - `TIER_PROMOTION` — the rule is past the tier-1 threshold, so a brief
752
+ * bullet is the wrong instrument. `tier` and `promotion` are FIELDS here,
753
+ * not substrings of the sentence.
754
+ * - `REINFORCEMENT_PRESENT` — the brief already carries this reinforcement.
755
+ * - `NO_SECTION` — the brief has none of the headings a reinforcement is
756
+ * spliced into.
757
+ * - `UNMAPPED_COMP` — the COMP id has no destination heading declared (#704).
758
+ * Separate from `NO_SECTION` because the two have opposite remedies: one is
759
+ * fixed by editing a brief and the other by editing
760
+ * `COMP_PRIMARY_SECTION`, and a run that reports the first for the second
761
+ * sends whoever reads it to the wrong file.
762
+ *
763
+ * `promotion` is `string | undefined` rather than optional because an action
764
+ * at tier 2 or 3 may carry none, and "the action named no promotion" is a
765
+ * state the outcome has to be able to hold — the sentence rendered it as the
766
+ * word `undefined`, and that is preserved byte for byte.
767
+ */
768
+ export type HillClimbSkipOutcome =
769
+ | { kind: "TIER_PROMOTION"; compId: string; tier: 2 | 3; promotion: string | undefined }
770
+ | { kind: "REINFORCEMENT_PRESENT"; compId: string }
771
+ | { kind: "NO_SECTION"; compId: string }
772
+ | { kind: "UNMAPPED_COMP"; compId: string; reason: string };
773
+
774
+ /**
775
+ * The one binding that turns a skip outcome into the reported line.
776
+ *
777
+ * Every sentence `applyHillClimb` reports is produced here and nowhere else,
778
+ * so there is a single thing to mutate; a second producer elsewhere would
779
+ * hold a case up through any mutation of this one
780
+ * (`.claude/rules/checks-must-be-able-to-fail.md`). The strings are the ones
781
+ * the loop has always printed — `scripts/persist-compliance.ts` logs them as
782
+ * `HILL-CLIMB skipped: …` and that stderr is unchanged.
783
+ */
784
+ export function hillClimbSkipSentence(outcome: HillClimbSkipOutcome): string {
785
+ switch (outcome.kind) {
786
+ case "TIER_PROMOTION":
787
+ return `${outcome.compId}: TIER ${outcome.tier} PROMOTION needed — ${outcome.promotion}`;
788
+ case "REINFORCEMENT_PRESENT":
789
+ return `${outcome.compId}: reinforcement already present in brief`;
790
+ case "NO_SECTION":
791
+ return `${outcome.compId}: no suitable section found in brief`;
792
+ case "UNMAPPED_COMP":
793
+ return `${outcome.compId}: ${outcome.reason}`;
794
+ }
795
+ }
796
+
467
797
  export function applyHillClimb(
468
798
  briefPath: string,
469
- actions: HillClimbAction[]
470
- ): { applied: string[]; skipped: string[] } {
799
+ actions: HillClimbAction[],
800
+ opts: HillClimbWriteOptions = {},
801
+ ): {
802
+ applied: string[];
803
+ skipped: string[];
804
+ /** One entry per action that was not applied, in the order they were decided. */
805
+ skipOutcomes: HillClimbSkipOutcome[];
806
+ write: HillClimbWrite;
807
+ } {
808
+ const destination = opts.destination ?? DEFAULT_HILL_CLIMB_DESTINATION;
809
+ const nothingWritten: HillClimbWrite = { destination, path: null };
810
+
471
811
  if (!existsSync(briefPath) || actions.length === 0)
472
- return { applied: [], skipped: [] };
812
+ return { applied: [], skipped: [], skipOutcomes: [], write: nothingWritten };
473
813
 
474
814
  let content = readFileSync(briefPath, "utf-8");
475
815
  const applied: string[] = [];
476
- const skipped: string[] = [];
816
+ const skipOutcomes: HillClimbSkipOutcome[] = [];
477
817
 
478
818
  for (const action of actions) {
479
819
  if (action.tier >= 2) {
480
- skipped.push(
481
- `${action.compId}: TIER ${action.tier} PROMOTION needed — ${action.promotion}`
482
- );
820
+ skipOutcomes.push({
821
+ kind: "TIER_PROMOTION",
822
+ compId: action.compId,
823
+ // `>=` rather than `!== 1`, so an off-type tier keeps the branch it
824
+ // has always taken; the declared type admits only 1, 2 and 3.
825
+ tier: action.tier as 2 | 3,
826
+ promotion: action.promotion,
827
+ });
483
828
  continue;
484
829
  }
485
830
 
@@ -489,55 +834,42 @@ export function applyHillClimb(
489
834
  const normalizedContent = content.toLowerCase().replace(/[`*"']/g, "");
490
835
 
491
836
  if (normalizedContent.includes(normalizedReinforcement.slice(0, 40))) {
492
- skipped.push(
493
- `${action.compId}: reinforcement already present in brief`
494
- );
837
+ skipOutcomes.push({ kind: "REINFORCEMENT_PRESENT", compId: action.compId });
495
838
  continue;
496
839
  }
497
840
 
498
- const efficiencyIdx = content.indexOf("## Efficiency Rules");
499
- const testingIdx = content.indexOf("## Testing Rules");
500
- const neverIdx = content.indexOf("## Never Do");
501
-
502
- let insertIdx = -1;
503
- let prefix = "\n- ";
504
-
505
- if (
506
- action.compId === "COMP-2" &&
507
- testingIdx !== -1
508
- ) {
509
- const nextSection = content.indexOf("\n## ", testingIdx + 1);
510
- insertIdx = nextSection !== -1 ? nextSection : content.length;
511
- prefix = "\n- **REINFORCED (auto):** ";
512
- } else if (efficiencyIdx !== -1) {
513
- const nextSection = content.indexOf("\n## ", efficiencyIdx + 1);
514
- insertIdx = nextSection !== -1 ? nextSection : content.length;
515
- prefix = "\n- **REINFORCED (auto):** ";
516
- } else if (neverIdx !== -1) {
517
- const nextSection = content.indexOf("\n## ", neverIdx + 1);
518
- insertIdx = nextSection !== -1 ? nextSection : content.length;
519
- prefix = "\n- **REINFORCED (auto):** ";
841
+ // The one call site of the one binding that maps a COMP to a heading
842
+ // (#704). #655's `## Project Constraints` precedence lives inside it,
843
+ // not here: asking the question a second time at the call site would
844
+ // make both copies unmutatable.
845
+ const resolution = resolveHillClimbSection(action.compId, content);
846
+ if (resolution.kind === "UNMAPPED_COMP") {
847
+ skipOutcomes.push(resolution);
848
+ continue;
520
849
  }
521
-
522
- if (insertIdx === -1) {
523
- skipped.push(`${action.compId}: no suitable section found in brief`);
850
+ if (resolution.kind === "NO_SECTION") {
851
+ skipOutcomes.push({ kind: "NO_SECTION", compId: action.compId });
524
852
  continue;
525
853
  }
854
+ const sectionIdx = resolution.index;
526
855
 
527
- content =
528
- content.slice(0, insertIdx) +
529
- `${prefix}${action.reinforcement}` +
530
- content.slice(insertIdx);
856
+ const nextSection = content.indexOf("\n## ", sectionIdx + 1);
857
+ const insertIdx = nextSection !== -1 ? nextSection : content.length;
858
+
859
+ content = insertReinforcement(content, insertIdx, action.reinforcement);
531
860
  applied.push(
532
- `${action.compId}: added reinforcement (${action.consecutiveFails} consecutive fails)`
861
+ `${action.compId}: added reinforcement (${action.consecutiveFails} consecutive fails) → ${destination}`
533
862
  );
534
863
  }
535
864
 
536
- if (applied.length > 0) {
537
- writeFileSync(briefPath, content);
538
- }
865
+ const write =
866
+ applied.length > 0
867
+ ? writeReinforcedBrief(briefPath, content, { ...opts, destination })
868
+ : nothingWritten;
539
869
 
540
- return { applied, skipped };
870
+ // The reported strings are DERIVED from the outcomes, in one expression, so
871
+ // the typed answer and the human-readable one cannot disagree.
872
+ return { applied, skipped: skipOutcomes.map(hillClimbSkipSentence), skipOutcomes, write };
541
873
  }
542
874
 
543
875
  // --- WARN-to-FAIL promotion tracking (SC-515, DEC-012) ---