@gate-forge/cli 0.8.0 → 0.9.1

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 (136) hide show
  1. package/README.md +85 -1145
  2. package/dist/adapter-audit.d.ts +54 -0
  3. package/dist/adapter-audit.d.ts.map +1 -1
  4. package/dist/adapter-audit.js +48 -0
  5. package/dist/adapter-audit.js.map +1 -1
  6. package/dist/adapter-scaffold.d.ts +28 -3
  7. package/dist/adapter-scaffold.d.ts.map +1 -1
  8. package/dist/adapter-scaffold.js +145 -24
  9. package/dist/adapter-scaffold.js.map +1 -1
  10. package/dist/args.d.ts.map +1 -1
  11. package/dist/args.js +2 -0
  12. package/dist/args.js.map +1 -1
  13. package/dist/behavior-setup.d.ts.map +1 -1
  14. package/dist/behavior-setup.js +18 -5
  15. package/dist/behavior-setup.js.map +1 -1
  16. package/dist/commands/adapters.d.ts.map +1 -1
  17. package/dist/commands/adapters.js +73 -2
  18. package/dist/commands/adapters.js.map +1 -1
  19. package/dist/commands/adopt.d.ts +9 -1
  20. package/dist/commands/adopt.d.ts.map +1 -1
  21. package/dist/commands/adopt.js +72 -5
  22. package/dist/commands/adopt.js.map +1 -1
  23. package/dist/commands/blocking.d.ts +45 -2
  24. package/dist/commands/blocking.d.ts.map +1 -1
  25. package/dist/commands/blocking.js +165 -11
  26. package/dist/commands/blocking.js.map +1 -1
  27. package/dist/commands/check.d.ts +34 -0
  28. package/dist/commands/check.d.ts.map +1 -1
  29. package/dist/commands/check.js +152 -8
  30. package/dist/commands/check.js.map +1 -1
  31. package/dist/commands/classify.d.ts +1 -1
  32. package/dist/commands/classify.d.ts.map +1 -1
  33. package/dist/commands/classify.js +63 -18
  34. package/dist/commands/classify.js.map +1 -1
  35. package/dist/commands/enforcement.d.ts.map +1 -1
  36. package/dist/commands/enforcement.js +263 -9
  37. package/dist/commands/enforcement.js.map +1 -1
  38. package/dist/commands/explain.d.ts +1 -1
  39. package/dist/commands/explain.d.ts.map +1 -1
  40. package/dist/commands/explain.js +162 -3
  41. package/dist/commands/explain.js.map +1 -1
  42. package/dist/commands/init-presets.d.ts +7 -0
  43. package/dist/commands/init-presets.d.ts.map +1 -1
  44. package/dist/commands/init-presets.js +10 -1
  45. package/dist/commands/init-presets.js.map +1 -1
  46. package/dist/commands/init.d.ts.map +1 -1
  47. package/dist/commands/init.js +579 -61
  48. package/dist/commands/init.js.map +1 -1
  49. package/dist/commands/next.d.ts.map +1 -1
  50. package/dist/commands/next.js +109 -6
  51. package/dist/commands/next.js.map +1 -1
  52. package/dist/commands/pre-commit.d.ts.map +1 -1
  53. package/dist/commands/pre-commit.js +62 -19
  54. package/dist/commands/pre-commit.js.map +1 -1
  55. package/dist/commands/test-gates.js +1 -1
  56. package/dist/commands/tests.d.ts.map +1 -1
  57. package/dist/commands/tests.js +46 -7
  58. package/dist/commands/tests.js.map +1 -1
  59. package/dist/docs-exclusions.d.ts.map +1 -1
  60. package/dist/docs-exclusions.js +18 -3
  61. package/dist/docs-exclusions.js.map +1 -1
  62. package/dist/endpoint-compiler.d.ts.map +1 -1
  63. package/dist/endpoint-compiler.js +49 -1
  64. package/dist/endpoint-compiler.js.map +1 -1
  65. package/dist/evaluate.d.ts +16 -1
  66. package/dist/evaluate.d.ts.map +1 -1
  67. package/dist/evaluate.js +12 -2
  68. package/dist/evaluate.js.map +1 -1
  69. package/dist/gateforge-owned.d.ts +103 -0
  70. package/dist/gateforge-owned.d.ts.map +1 -0
  71. package/dist/gateforge-owned.js +375 -0
  72. package/dist/gateforge-owned.js.map +1 -0
  73. package/dist/git-hooks.d.ts +18 -0
  74. package/dist/git-hooks.d.ts.map +1 -1
  75. package/dist/git-hooks.js +36 -1
  76. package/dist/git-hooks.js.map +1 -1
  77. package/dist/git-ignored.d.ts +27 -0
  78. package/dist/git-ignored.d.ts.map +1 -0
  79. package/dist/git-ignored.js +102 -0
  80. package/dist/git-ignored.js.map +1 -0
  81. package/dist/glob.d.ts +33 -14
  82. package/dist/glob.d.ts.map +1 -1
  83. package/dist/glob.js +96 -5
  84. package/dist/glob.js.map +1 -1
  85. package/dist/index.d.ts +4 -1
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +2 -1
  88. package/dist/index.js.map +1 -1
  89. package/dist/io.d.ts +18 -5
  90. package/dist/io.d.ts.map +1 -1
  91. package/dist/io.js +5 -4
  92. package/dist/io.js.map +1 -1
  93. package/dist/pipeline.d.ts +16 -1
  94. package/dist/pipeline.d.ts.map +1 -1
  95. package/dist/pipeline.js +23 -3
  96. package/dist/pipeline.js.map +1 -1
  97. package/dist/planes-inference.d.ts +12 -5
  98. package/dist/planes-inference.d.ts.map +1 -1
  99. package/dist/planes-inference.js +13 -15
  100. package/dist/planes-inference.js.map +1 -1
  101. package/dist/providers.d.ts +54 -0
  102. package/dist/providers.d.ts.map +1 -1
  103. package/dist/providers.js +101 -0
  104. package/dist/providers.js.map +1 -1
  105. package/dist/repo-scan.d.ts +7 -0
  106. package/dist/repo-scan.d.ts.map +1 -1
  107. package/dist/repo-scan.js +109 -8
  108. package/dist/repo-scan.js.map +1 -1
  109. package/dist/route-plane-proposals.d.ts +100 -0
  110. package/dist/route-plane-proposals.d.ts.map +1 -0
  111. package/dist/route-plane-proposals.js +213 -0
  112. package/dist/route-plane-proposals.js.map +1 -0
  113. package/dist/scope.d.ts +20 -0
  114. package/dist/scope.d.ts.map +1 -1
  115. package/dist/scope.js +26 -5
  116. package/dist/scope.js.map +1 -1
  117. package/dist/singleton-guidance.d.ts +15 -6
  118. package/dist/singleton-guidance.d.ts.map +1 -1
  119. package/dist/singleton-guidance.js +30 -10
  120. package/dist/singleton-guidance.js.map +1 -1
  121. package/dist/staged-candidate.d.ts.map +1 -1
  122. package/dist/staged-candidate.js +2 -1
  123. package/dist/staged-candidate.js.map +1 -1
  124. package/dist/trusted-policy.d.ts.map +1 -1
  125. package/dist/trusted-policy.js +3 -2
  126. package/dist/trusted-policy.js.map +1 -1
  127. package/dist/unmatched-routes.d.ts +60 -0
  128. package/dist/unmatched-routes.d.ts.map +1 -0
  129. package/dist/unmatched-routes.js +131 -0
  130. package/dist/unmatched-routes.js.map +1 -0
  131. package/guides/CONNECT-YOUR-PROJECT.md +93 -20
  132. package/guides/QUICKSTART.md +81 -16
  133. package/guides/REFERENCE.md +1756 -0
  134. package/guides/TEST-ENVIRONMENT.md +8 -5
  135. package/guides/UPGRADE-0.8-to-0.9.md +112 -0
  136. package/package.json +10 -10
@@ -15,13 +15,15 @@
15
15
  * classification file to fill in. Effective classifications are computed
16
16
  * from detector signals on every run.
17
17
  */
18
+ import { spawnSync } from 'node:child_process';
18
19
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
19
20
  import { randomUUID } from 'node:crypto';
20
21
  import { createInterface } from 'node:readline/promises';
21
- import { join } from 'node:path';
22
+ import { isAbsolute, join } from 'node:path';
22
23
  import { parse as parseYaml, parseDocument, isSeq as isYamlSeq, isMap as isYamlMap } from 'yaml';
23
- import { ClassificationPolicySchema, PolicyFileSchema, loadConfig, parseConfig, serializeBaseline, strictCapabilityGaps, } from '@gate-forge/core';
24
+ import { ClassificationPolicySchema, PolicyFileSchema, loadConfig, parseConfig, resolveStrictnessMode, serializeBaseline, strictCapabilityGaps, } from '@gate-forge/core';
24
25
  import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, PACK_VERSION as PACK_SQLALCHEMY_VERSION, } from '@gate-forge/pack-sqlalchemy';
26
+ import { collectRoutePlaneFacts, proposeRouteFolderPlanes, } from '../route-plane-proposals.js';
25
27
  import { PACK_VERSION as PACK_FASTAPI_VERSION } from '@gate-forge/pack-fastapi';
26
28
  import { PACK_VERSION as PACK_HTTP_VERSION } from '@gate-forge/pack-http';
27
29
  import { PACK_VERSION as PACK_TASK_VERSION } from '@gate-forge/pack-task';
@@ -31,21 +33,23 @@ import { recordInitPath, writeLine } from '../io.js';
31
33
  import { UsageError } from '../errors.js';
32
34
  import { languageDefaultPlugins, recommendPlugins, renderScanBlock, scanRepo } from '../repo-scan.js';
33
35
  import { rejectUnknownFlags } from './common.js';
34
- import { expandIncludePaths } from '../glob.js';
36
+ import { expandScanPaths } from '../glob.js';
37
+ import { gitIgnoredPaths } from '../git-ignored.js';
35
38
  import { inferPlanesConfig } from '../planes-inference.js';
36
39
  import { hasGateforgeMarker, installCommitHook, installPrePushHook, writeStandaloneGateScript } from '../git-hooks.js';
37
- import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, writeServerProtectionInstructions, } from './blocking.js';
40
+ import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, detectCiProvider, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, writeServerProtectionInstructions, } from './blocking.js';
38
41
  import { trustedPolicyDigestForConfig } from '../execution.js';
39
42
  import { DOCS_EXCLUSIONS_GUARANTEE, DOCS_EXCLUSIONS_PATH, loadDocsExclusions, renderDocsExclusions, validateRequestedDocsFolders, } from '../docs-exclusions.js';
40
43
  import { CACHE_EXCLUSIONS_GUARANTEE, CACHE_EXCLUSIONS_PATH, loadCacheExclusions, renderCacheExclusions, validateRequestedCacheFiles, } from '../cache-exclusions.js';
44
+ import { ENGINE_STATE_IGNORE_COMMENT, ENGINE_STATE_IGNORE_ENTRIES, } from '../gateforge-owned.js';
41
45
  import { CHOOSE_ANOTHER_GOAL_ADVICE, INIT_PRESETS, isInitPresetName, parseGoalAnswer, renderGoalQuestion, renderPresetTable, renderPresetSummary, } from './init-presets.js';
42
46
  import { BEHAVIOR_NAMESPACES, behaviorPackEvidence, behaviorSkeletonExamples, detectBehaviorPacks, parseBehaviorPacks, } from '../behavior-setup.js';
43
47
  export const INIT_USAGE = '[--preset light|normal|strict] [--explain-presets] [--no-scan] [--proof overlay|observe] ' +
44
48
  '[--blocking] [--no-blocking] [--pre-commit] [--no-pre-commit] [--mode changed|staged] ' +
45
49
  '[--witnessed staged|full] [--ci] [--no-ci] ' +
46
- '[--docs-exclude <folder,...> [--confirm-doc-exclusions]] [--cache-exclude <file,...> ' +
50
+ '[--docs-exclude <folder,...> [--docs-exclude-file <path>] [--confirm-doc-exclusions]] [--cache-exclude <file,...> ' +
47
51
  '[--confirm-cache-exclusions]] [--strict-e2e] [--planes] [--no-planes] ' +
48
- '[--behavior] [--no-behavior] [--behavior-packs <pack,...>]';
52
+ '[--behavior] [--no-behavior] [--behavior-packs <pack,...>] [--unmatched-routes block|warn]';
49
53
  /** Template for the complete-behavior owner document (plan §4.1). */
50
54
  export const BEHAVIOR_TEMPLATE = `\
51
55
  # Complete-behavior owner document.
@@ -395,6 +399,18 @@ runner: ${options.runner}
395
399
  const historyBlock = options.historyRetentionDays === undefined
396
400
  ? ''
397
401
  : `history:\n retentionDays: ${String(options.historyRetentionDays)}\n`;
402
+ // The owner-owned unmatched-route grading. Only written when the owner
403
+ // answered (the terminal question, the flag, or the non-interactive
404
+ // `warn`); an existing config that said nothing keeps saying nothing,
405
+ // and the `check`/`next` banner keeps asking.
406
+ const endpointsBlock = options.unmatchedRoutes === undefined
407
+ ? ''
408
+ : `# Routes whose name matches no discovered resource (ENDPOINT_RESOURCE_CANDIDATE_UNMATCHED).
409
+ # 'warn' reports them as advisories with a banner; 'block' makes them
410
+ # blocking entries like any other finding. Absent means 'warn'.
411
+ endpoints:
412
+ unmatchedRoutes: ${options.unmatchedRoutes}
413
+ `;
398
414
  return `\
399
415
  # gateforge project configuration (schemaVersion 1)
400
416
  schemaVersion: 1
@@ -415,6 +431,15 @@ ${sourceIncludePatterns(languages).map((pattern) => ` - '${pattern}'`).join
415
431
  - '**/.mypy_cache/**'
416
432
  - '**/dist/**'
417
433
  - '**/build/**'
434
+ # Hidden dot-folders (agent tooling like .claude/ or .cursor/,
435
+ # editor/tool caches, leftover merge or working folders) hold
436
+ # tooling and debris, never application code. The rule is generic
437
+ # -- it keys on the dot prefix at any depth -- so any hidden folder
438
+ # is skipped, whatever it is called. .gateforge is the ONE
439
+ # exception and is deliberately NOT matched here: Gateforge's own
440
+ # configuration stays in scope.
441
+ - '**/.(!(gateforge))/**'
442
+ - '.!(gateforge)/**'
418
443
  # Detector plugins. Bundled detectors are preconfigured for the selected
419
444
  # languages and are loaded from their trusted package entry points.
420
445
  plugins:
@@ -430,7 +455,7 @@ witness:
430
455
  maxDurationSeconds: 5
431
456
  clock:
432
457
  mode: system
433
- ${runnerBlock}${historyBlock}${strictnessBlock}${enforcementBlock}\
458
+ ${endpointsBlock}${runnerBlock}${historyBlock}${strictnessBlock}${enforcementBlock}\
434
459
  `;
435
460
  }
436
461
  /**
@@ -550,6 +575,23 @@ const OBSERVE_CHECKLIST = `observe proof checklist (existing suite through the w
550
575
  4. Run \`gateforge test-gates --changed\`, then \`gateforge check --require-e2e\`.
551
576
  Honest scope: proves persistence (the server stored what the proxied
552
577
  request sent), not "the engine typed the form".`;
578
+ /**
579
+ * The adoption block init prints on the FIRST init of a repository that
580
+ * already has code. Such a repository is not green on day one: the very
581
+ * next commit sees everything discovery found as existing debt. Without
582
+ * this block the owner meets that as a wall of findings with no name
583
+ * for the sanctioned way through it — `gateforge adopt` — which is why
584
+ * the command had to be discovered from a source file instead of from
585
+ * `init`.
586
+ *
587
+ * Everything here is exactly what `adopt` does: the recorded set, its
588
+ * shrink-only standing, and the one case where an adopted E2E
589
+ * obligation still blocks.
590
+ */
591
+ const ADOPT_ADVICE = `this repository already had code, so \`gateforge check\` reports what discovery finds today, and today\'s findings block the first commit:
592
+ gateforge adopt — records today\'s blocking findings as forgiven debt, in a baseline plus a dated, count-annotated receipt, then wires the blocking gate.
593
+ it is shrink-only from here: it never forgives new work. Resolve debt and run \`gateforge baseline update\` to shrink the recorded set; new unproven work keeps blocking.
594
+ with strictE2E enabled, an adopted E2E obligation still blocks with ENFORCEMENT_UNTRUSTED as soon as a change touches it — baselined is not proof.`;
553
595
  /**
554
596
  * Asks (TTY only) whether init should write the recommended setup.
555
597
  * Flags win: `--accept-recommended` forces yes, `--plugins` (an explicit
@@ -572,42 +614,158 @@ async function resolveRecommended(io, options) {
572
614
  rl.close();
573
615
  }
574
616
  }
617
+ /**
618
+ * The wiring flags each preset already implies (R1-1): a flag the
619
+ * preset implies is a no-op — the preset the owner named is the
620
+ * goal that applies. `light` wires nothing, so it implies no flag
621
+ * and no `--no-*` flag can contradict it.
622
+ */
623
+ const PRESET_IMPLIED_FLAGS = {
624
+ light: [],
625
+ normal: ['pre-commit', 'ci'],
626
+ strict: ['blocking', 'pre-commit', 'ci', 'strict-e2e'],
627
+ };
628
+ /** What one wiring flag decides, named in the contradiction error. */
629
+ const PRESET_FLAG_THING = {
630
+ blocking: 'the gate wiring',
631
+ 'pre-commit': 'the pre-commit hook',
632
+ ci: 'the CI job',
633
+ 'strict-e2e': 'strict E2E',
634
+ };
635
+ /**
636
+ * The preset/flag contradiction (R1-1): null when every given flag
637
+ * is consistent with the preset (implied by it, or a `--no-*` for
638
+ * something the preset does not wire — both are no-ops); the
639
+ * conflicting flag otherwise: a positive wiring flag the preset
640
+ * does NOT wire, or a `--no-*` flag for something it DOES wire.
641
+ * Both spellings ask for two different goals at once, so the owner
642
+ * must drop one of them — silently overriding the named preset
643
+ * (the old "is ignored" note) hid the choice instead.
644
+ */
645
+ function presetFlagConflict(preset, options) {
646
+ const implied = PRESET_IMPLIED_FLAGS[preset];
647
+ for (const flag of ['blocking', 'pre-commit', 'ci', 'strict-e2e']) {
648
+ const wired = implied.includes(flag);
649
+ if (options[flag] === true && !wired)
650
+ return flag;
651
+ if (wired && options[`no-${flag}`] === true)
652
+ return `no-${flag}`;
653
+ }
654
+ return null;
655
+ }
656
+ /**
657
+ * The config settings a run REQUESTS that an existing
658
+ * `.gateforge.yml` already owns with a different value
659
+ * (R1-2): a chosen preset's strictness `mode` and
660
+ * `enforcement.strictE2E`, plus the `--strict-e2e` and
661
+ * `--unmatched-routes` flags. init never rewrites an
662
+ * existing config, so a differing request is a usage error
663
+ * the owner resolves by setting the key in the file — one
664
+ * line per differing key, BEFORE anything is written.
665
+ *
666
+ * Absent keys compare as their effective values (`mode`
667
+ * defaults to `strict`, `strictE2E` to false, absent
668
+ * `unmatchedRoutes` grades advisories — `warn`), so a
669
+ * request that matches what the file already does is not a
670
+ * conflict. Only an explicit `--preset` names a request:
671
+ * the non-interactive auto-chosen light goal and a
672
+ * terminal answer to the goal question are default
673
+ * behavior paths, not requests — a headless re-run of
674
+ * `init` on an initialized repository must keep working.
675
+ */
676
+ function requestedConfigConflicts(cwd, options, goal) {
677
+ const conflicts = [];
678
+ if (!existsSync(join(cwd, '.gateforge.yml')))
679
+ return conflicts;
680
+ // An unparseable document is today's path (the draft load
681
+ // below rethrows or falls back); there is no value to
682
+ // compare a request against, so nothing is a conflict.
683
+ let existing;
684
+ try {
685
+ existing = loadConfig(join(cwd, '.gateforge.yml'));
686
+ }
687
+ catch {
688
+ return conflicts;
689
+ }
690
+ const requests = [];
691
+ if (goal !== null && options['preset'] !== undefined) {
692
+ requests.push({
693
+ key: 'mode',
694
+ current: resolveStrictnessMode(existing),
695
+ requested: goal.settings.strictnessMode,
696
+ }, {
697
+ key: 'enforcement.strictE2E',
698
+ current: existing.enforcement?.strictE2E === true ? 'true' : 'false',
699
+ requested: goal.settings.strictE2E ? 'true' : 'false',
700
+ });
701
+ }
702
+ if (options['strict-e2e'] === true) {
703
+ requests.push({
704
+ key: 'enforcement.strictE2E',
705
+ current: existing.enforcement?.strictE2E === true ? 'true' : 'false',
706
+ requested: 'true',
707
+ });
708
+ }
709
+ const unmatchedRoutes = stringFlag(options, 'unmatched-routes');
710
+ if (unmatchedRoutes !== undefined) {
711
+ requests.push({
712
+ key: 'endpoints.unmatchedRoutes',
713
+ current: existing.endpoints?.unmatchedRoutes ?? 'warn',
714
+ requested: unmatchedRoutes.trim().toLowerCase(),
715
+ });
716
+ }
717
+ for (const request of requests) {
718
+ if (request.current !== request.requested)
719
+ conflicts.push(request);
720
+ }
721
+ return conflicts;
722
+ }
575
723
  /**
576
724
  * Resolves the goal `init` should set up. Three paths, in order:
577
725
  *
578
- * 1. `--preset light|normal|strict` — an agent or CI run picks the goal
579
- * explicitly.
580
- * 2. A real terminal — ONE question ("What should Gateforge do for
581
- * you?") with three choices, each explained in one line.
582
- * 3. No terminal and no `--preset` — light only, stated ONCE on the
583
- * line that also names `--preset <light|normal|strict>`. Gateforge
584
- * never guesses normal or strict for someone who is not there:
585
- * guessing strict blocks a team, guessing normal pretends a gate
586
- * nobody asked for.
726
+ * 1. `--preset light|normal|strict` — an agent or CI run picks
727
+ * the goal explicitly. An enforcement flag the preset already
728
+ * implies is a no-op (the preset applies); one that
729
+ * contradicts it throws (R1-1) before any file is written.
730
+ * 2. A real terminal — ONE question ("What should Gateforge do
731
+ * for you?") with three choices, each explained in one line.
732
+ * 3. No terminal and no `--preset` — light only, stated ONCE on
733
+ * the line that also names `--preset <light|normal|strict>`.
734
+ * Gateforge never guesses normal or strict for someone who is
735
+ * not there: guessing strict blocks a team, guessing normal
736
+ * pretends a gate nobody asked for.
587
737
  *
588
- * A run that already carries explicit enforcement flags (`--blocking`,
589
- * `--strict-e2e`, …) has chosen for itself: no preset is applied and the
590
- * generated config keeps today's exact bytes.
738
+ * A run WITHOUT a preset that carries explicit enforcement flags
739
+ * (`--blocking`, `--strict-e2e`, …) has chosen for itself: no
740
+ * preset is applied and the generated config keeps today's
741
+ * exact bytes.
591
742
  *
592
743
  * Args:
593
744
  * io: process context (prompt + informational output).
594
745
  * options: parsed init flags.
595
- * enforcementFlagGiven (boolean): true when an enforcement flag was
596
- * passed and therefore wins over any preset.
746
+ * enforcementFlagGiven (boolean): true when an enforcement flag
747
+ * was passed and therefore wins over any preset.
597
748
  *
598
749
  * Returns:
599
750
  * Promise<{ name: InitPresetName; settings: InitPresetSettings;
600
751
  * autoChosen?: boolean } | null>: the applied goal (with
601
- * `autoChosen` when no human chose it), or null when the run kept
602
- * today's behavior.
752
+ * `autoChosen` when no human chose it), or null when the run
753
+ * kept today's behavior.
754
+ * @throws UsageError (exit 2): a flag contradicts the named
755
+ * preset (R1-1) — nothing is written.
603
756
  */
604
757
  async function resolveGoal(io, options, enforcementFlagGiven, configExisted) {
605
758
  const explicit = options['preset'];
606
759
  if (explicit !== undefined && isInitPresetName(explicit)) {
607
- if (!enforcementFlagGiven)
608
- return { name: explicit, settings: INIT_PRESETS[explicit] };
609
- writeLine(io.stdout, `note: --preset ${explicit} is ignored because an enforcement flag decides the wiring; the preset's meaning: ${INIT_PRESETS[explicit].explanation}`);
610
- return null;
760
+ const conflict = presetFlagConflict(explicit, options);
761
+ if (conflict !== null) {
762
+ throw new UsageError(`--preset ${explicit} already decides ${PRESET_FLAG_THING[conflict.replace(/^no-/, '')]}; ` +
763
+ `--${conflict} contradicts it — drop one of them`);
764
+ }
765
+ // Every given flag is one the preset already implies (or a
766
+ // `--no-*` for something it does not wire): a no-op. The
767
+ // goal the owner named is the one that applies.
768
+ return { name: explicit, settings: INIT_PRESETS[explicit] };
611
769
  }
612
770
  if (enforcementFlagGiven)
613
771
  return null;
@@ -686,6 +844,63 @@ async function resolveHistoryRetention(io) {
686
844
  rl.close();
687
845
  }
688
846
  }
847
+ /**
848
+ * Resolves how a NEW repository grades unmatched by-id routes (0.9.0,
849
+ * owner decision D7).
850
+ *
851
+ * Flags win, then the terminal question, then `warn`. A non-interactive
852
+ * run (an agent, a CI job, a test) writes `warn` and prints the exact
853
+ * setting to choose `block` — it never blocks a repository the owner
854
+ * never asked to gate on. A repository that ALREADY has a
855
+ * `.gateforge.yml` is left untouched: an existing config that has said
856
+ * nothing keeps saying nothing, and the banner keeps asking.
857
+ *
858
+ * Args:
859
+ * io: process context (prompt + informational output).
860
+ * options: parsed init flags.
861
+ * configExisted: whether `.gateforge.yml` was already present.
862
+ *
863
+ * Returns:
864
+ * Promise<{ mode: 'block' | 'warn' | undefined; note: string | undefined }>:
865
+ * the answer to write (`undefined` writes no key) and the non-interactive
866
+ * line to print.
867
+ */
868
+ async function resolveUnmatchedRoutes(io, options, configExisted) {
869
+ const flagValue = stringFlag(options, 'unmatched-routes');
870
+ if (flagValue !== undefined) {
871
+ const mode = flagValue.trim().toLowerCase();
872
+ if (mode !== 'block' && mode !== 'warn') {
873
+ throw new UsageError("init: --unmatched-routes must be 'block' or 'warn'");
874
+ }
875
+ return { mode, note: undefined };
876
+ }
877
+ if (configExisted)
878
+ return { mode: undefined, note: undefined };
879
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
880
+ return {
881
+ mode: 'warn',
882
+ note: "note: routes whose name matches no table will be REPORTED, not blocking. " +
883
+ "set 'endpoints:\n unmatchedRoutes: block' in .gateforge.yml (or re-run with --unmatched-routes block) to block on them",
884
+ };
885
+ }
886
+ // The question is printed by the command (like the goal question), so it
887
+ // is in the run's own output and survives a non-interactive transcript;
888
+ // the readline prompt only takes the answer.
889
+ writeLine(io.stdout, 'Routes whose name matches no table: block commits, or warn only? [block/warn] (default warn)');
890
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
891
+ try {
892
+ const answer = (await rl.question(' ')).trim().toLowerCase();
893
+ if (answer === '')
894
+ return { mode: 'warn', note: undefined };
895
+ if (answer !== 'block' && answer !== 'warn') {
896
+ throw new UsageError("init: unmatched-route grading must be 'block' or 'warn'");
897
+ }
898
+ return { mode: answer, note: undefined };
899
+ }
900
+ finally {
901
+ rl.close();
902
+ }
903
+ }
689
904
  /**
690
905
  * Resolves which behavior packs' cases `init` enables (plan 2026-09-30
691
906
  * Phase 4). Flags win, then the terminal question, then nothing.
@@ -771,28 +986,67 @@ async function resolvePlanes(io, options) {
771
986
  rl.close();
772
987
  }
773
988
  }
989
+ /**
990
+ * Reads an owner-supplied folder list file: ONE folder per line, blank
991
+ * lines and `#` comments ignored. The comma list stays supported; this
992
+ * is the same declaration in a form that survives a long repository
993
+ * (typing or pasting dozens of folder names into one prompt wraps
994
+ * unreadably, and `paste -sd,` is not discoverable).
995
+ *
996
+ * Args:
997
+ * cwd: absolute repository root the relative path resolves against.
998
+ * filePath: the value given to `--docs-exclude-file`.
999
+ *
1000
+ * Returns:
1001
+ * string[]: the folders named by the file, in file order.
1002
+ *
1003
+ * Throws:
1004
+ * UsageError: the file is missing or unreadable (never guessed at).
1005
+ */
1006
+ function readFolderListFile(cwd, filePath) {
1007
+ const absolute = isAbsolute(filePath) ? filePath : join(cwd, filePath);
1008
+ let text;
1009
+ try {
1010
+ text = readFileSync(absolute, 'utf8');
1011
+ }
1012
+ catch (error) {
1013
+ throw new UsageError(`init: cannot read --docs-exclude-file '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
1014
+ }
1015
+ return text
1016
+ .split('\n')
1017
+ .map((line) => line.split('#')[0]?.trim() ?? '')
1018
+ .filter((line) => line.length > 0);
1019
+ }
774
1020
  /** Resolves the init owner's explicit documentation-folder declaration. */
775
1021
  async function resolveDocsExclusionsForInit(io, options, config) {
776
1022
  const current = loadDocsExclusions(io.cwd, config);
777
1023
  const requestedValue = stringFlag(options, 'docs-exclude');
1024
+ const fileValue = stringFlag(options, 'docs-exclude-file');
778
1025
  const confirmUpdate = options['confirm-doc-exclusions'] === true;
779
1026
  if (typeof options['confirm-doc-exclusions'] !== 'boolean' && options['confirm-doc-exclusions'] !== undefined) {
780
1027
  throw new UsageError("init: '--confirm-doc-exclusions' must be a boolean flag");
781
1028
  }
782
- if (requestedValue !== undefined) {
783
- const requested = requestedValue.trim() === ''
784
- ? []
785
- : validateRequestedDocsFolders(io.cwd, requestedValue.split(',').map((folder) => folder.trim()).filter((folder) => folder.length > 0), config);
1029
+ if (requestedValue !== undefined || fileValue !== undefined) {
1030
+ // Both flags are the SAME declaration in two spellings, so they
1031
+ // combine into one ordered, deduplicated list instead of one
1032
+ // silently winning over the other.
1033
+ const declared = [
1034
+ ...(requestedValue === undefined || requestedValue.trim() === ''
1035
+ ? []
1036
+ : requestedValue.split(',').map((folder) => folder.trim()).filter((folder) => folder.length > 0)),
1037
+ ...(fileValue === undefined ? [] : readFolderListFile(io.cwd, fileValue)),
1038
+ ];
1039
+ const requested = [...new Set(declared)];
786
1040
  if (current.length > 0 && JSON.stringify(requested) !== JSON.stringify(current) && !confirmUpdate) {
787
1041
  throw new UsageError(`init: changing ${DOCS_EXCLUSIONS_PATH} needs explicit owner review; repeat with --confirm-doc-exclusions`);
788
1042
  }
789
1043
  if (current.length === 0 && requested.length === 0 && confirmUpdate) {
790
1044
  throw new UsageError('init: --confirm-doc-exclusions requires a non-empty --docs-exclude update');
791
1045
  }
792
- return { folders: requested, changed: JSON.stringify(requested) !== JSON.stringify(current) };
1046
+ return { folders: validateRequestedDocsFolders(io.cwd, requested, config), changed: JSON.stringify(requested) !== JSON.stringify(current) };
793
1047
  }
794
1048
  if (confirmUpdate) {
795
- throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude');
1049
+ throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude or --docs-exclude-file');
796
1050
  }
797
1051
  if (current.length > 0)
798
1052
  return { folders: current, changed: false };
@@ -800,7 +1054,8 @@ async function resolveDocsExclusionsForInit(io, options, config) {
800
1054
  const rl = createInterface({ input: process.stdin, output: process.stdout });
801
1055
  try {
802
1056
  const answer = await rl.question('Owner assertion: enter documentation-only folders to exclude from evidence identity, or leave blank for none. ' +
803
- 'Gateforge cannot prove that app/tests do not read these files. Folders (comma-separated): ');
1057
+ 'Gateforge cannot prove that app/tests do not read these files. Folders (comma-separated; for a long list ' +
1058
+ 'write them one per line to a file and pass --docs-exclude-file <path>): ');
804
1059
  const raw = answer.trim();
805
1060
  const folders = raw.length === 0
806
1061
  ? []
@@ -811,7 +1066,7 @@ async function resolveDocsExclusionsForInit(io, options, config) {
811
1066
  rl.close();
812
1067
  }
813
1068
  }
814
- writeLine(io.stdout, 'tip: non-interactive init keeps full evidence identity; use --docs-exclude <folder,...> to opt in');
1069
+ writeLine(io.stdout, 'tip: non-interactive init keeps full evidence identity; use --docs-exclude <folder,...> (or --docs-exclude-file <path>, one folder per line) to opt in');
815
1070
  return { folders: [], changed: false };
816
1071
  }
817
1072
  /**
@@ -854,15 +1109,92 @@ function resolveCacheExclusionsForInit(io, options, config) {
854
1109
  }
855
1110
  return { files: requested, changed };
856
1111
  }
1112
+ /**
1113
+ * Asks the owner ONE plane question per ROUTE folder that still has
1114
+ * unresolved endpoints (owner decision D1: ask, never infer).
1115
+ *
1116
+ * The linked model's plane is shown as a HINT and is never applied: an
1117
+ * `accounts` route can serve master data, so the owner answers for the
1118
+ * ROUTES. `proposeRouteFolderPlaneRules` already withholds the hint when
1119
+ * the linked models disagree or are themselves unresolved, so a hint
1120
+ * here always means "these routes serve a model whose plane IS this".
1121
+ *
1122
+ * A non-interactive run proposes nothing and writes nothing: it prints
1123
+ * the folders and the runnable `gateforge classify plane` shape for each,
1124
+ * with the plane and the reason LEFT AS PLACEHOLDERS — printing a concrete
1125
+ * plane would be inferring it for the owner, which is exactly what D1
1126
+ * forbids, and an agent that copies the line would apply a wrong plane to
1127
+ * a folder whose models init inferred as `master`.
1128
+ *
1129
+ * Args:
1130
+ * cwd: absolute repository root.
1131
+ * io: process context.
1132
+ *
1133
+ * Returns:
1134
+ * Promise<PlaneConfigRule[]>: the rules the owner answered for.
1135
+ */
1136
+ async function askRouteFolderPlanes(cwd, io) {
1137
+ let proposals;
1138
+ try {
1139
+ proposals = proposeRouteFolderPlanes(await collectRoutePlaneFacts(cwd));
1140
+ }
1141
+ catch (cause) {
1142
+ writeLine(io.stdout, `warning: route plane discovery failed (${cause instanceof Error ? cause.message : String(cause)}); ` +
1143
+ 'answer the route folders with `gateforge classify plane <folder> <tenant|master|global> --reason "<why>" --confirm` — init continues');
1144
+ return [];
1145
+ }
1146
+ if (proposals.length === 0)
1147
+ return [];
1148
+ const planes = new Set(['tenant', 'master', 'global']);
1149
+ const answers = [];
1150
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
1151
+ writeLine(io.stdout, `route folders with no answered plane (${proposals.length}) — one owner answer each, ` +
1152
+ 'never inferred from the linked model:');
1153
+ for (const proposal of proposals) {
1154
+ writeLine(io.stdout, ` ${proposal.folder} (${proposal.routeCount} route(s)` +
1155
+ `${proposal.hintPlane === null ? '' : `, linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane} — a hint only`})`);
1156
+ writeLine(io.stdout, ` gateforge classify plane ${proposal.folder} <tenant|master|global> --reason '<why the ROUTES in this folder serve that data>' --confirm`);
1157
+ }
1158
+ return answers;
1159
+ }
1160
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1161
+ try {
1162
+ writeLine(io.stdout, 'route folders whose plane is still unanswered — one answer per folder, asked because ' +
1163
+ 'a route linked to a model can still serve different data:');
1164
+ for (const proposal of proposals) {
1165
+ const hint = proposal.hintPlane === null
1166
+ ? ''
1167
+ : ` — hint only: the linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane}; ` +
1168
+ 'a route can serve other data, so this is your answer to make';
1169
+ const answer = (await rl.question(`plane for '${proposal.folder}' (${proposal.routeCount} route(s)) — tenant/master/global, blank to skip${hint}: `))
1170
+ .trim()
1171
+ .toLowerCase();
1172
+ if (!planes.has(answer)) {
1173
+ if (answer !== '')
1174
+ writeLine(io.stdout, ` skipped '${proposal.folder}': '${answer}' is not a plane`);
1175
+ continue;
1176
+ }
1177
+ answers.push({
1178
+ match: `${proposal.folder}/**`,
1179
+ plane: answer,
1180
+ reason: `answered for the route folder '${proposal.folder}' during gateforge init; review before relying on this`,
1181
+ });
1182
+ }
1183
+ }
1184
+ finally {
1185
+ rl.close();
1186
+ }
1187
+ return answers;
1188
+ }
857
1189
  /**
858
1190
  * Runs discovery over the repo's own include/exclude config, infers a
859
- * planes proposal from the discovered table directories, self-checks
860
- * the draft against the runtime's strict parser, and writes
861
- * `.gateforge/planes.json` — only when absent (never overwrites a
862
- * reviewed document). Inference failure is surfaced as a visible
863
- * warning, never silently skipped, but does not abort the scaffold.
1191
+ * planes proposal from the discovered table directories, adds the owner's
1192
+ * answered ROUTE-folder rules, self-checks the draft against the runtime's
1193
+ * strict parser, and writes `.gateforge/planes.json` — only when absent
1194
+ * (never overwrites a reviewed document). Inference failure is surfaced as a
1195
+ * visible warning, never silently skipped, but does not abort the scaffold.
864
1196
  */
865
- async function proposePlanesConfig(cwd, io) {
1197
+ async function proposePlanesConfig(cwd, io, routeRules = []) {
866
1198
  const planesPath = join(cwd, PLANES_CONFIG_PATH);
867
1199
  if (existsSync(planesPath)) {
868
1200
  writeLine(io.stdout, `exists, leaving untouched: ${planesPath}`);
@@ -872,7 +1204,10 @@ async function proposePlanesConfig(cwd, io) {
872
1204
  try {
873
1205
  const config = loadConfig(join(cwd, '.gateforge.yml'));
874
1206
  const expandErrors = [];
875
- const paths = expandIncludePaths(config.project.paths.include, config.project.paths.exclude, cwd, expandErrors);
1207
+ // The same DETECTOR-INPUT scope the pipeline scans: a gitignored
1208
+ // tree (a built report bundle, a local cache) holds no table the
1209
+ // planes proposal should infer from.
1210
+ const paths = expandScanPaths(config.project.paths.include, config.project.paths.exclude, cwd, gitIgnoredPaths(cwd), expandErrors);
876
1211
  // The planes config plays no role in inference (only table SOURCE
877
1212
  // paths matter), so the detector runs with the default no-mapping
878
1213
  // rule — immune to whatever a previous run wrote.
@@ -896,7 +1231,11 @@ async function proposePlanesConfig(cwd, io) {
896
1231
  // assumes while the file is absent. Writing it anyway is what makes
897
1232
  // `gateforge init --planes` the runnable prerequisite the
898
1233
  // `gateforge next` guidance prints for an unresolved route.
899
- const serialized = `${JSON.stringify(inference.config ?? { rules: [] }, null, 2)}\n`;
1234
+ // The owner's ROUTE-folder answers join the inferred model rules in the
1235
+ // one file init writes: both are reviewed proposals, and splitting them
1236
+ // across two writes would make the second overwrite the first.
1237
+ const combined = [...(inference.config?.rules ?? []), ...routeRules];
1238
+ const serialized = `${JSON.stringify(combined.length === 0 ? { rules: [] } : { rules: combined }, null, 2)}\n`;
900
1239
  // Self-check the draft against the runtime's strict reader contract
901
1240
  // BEFORE writing (a broken proposal must fail here, not at the next run).
902
1241
  parsePlanesConfigText(serialized, planesPath);
@@ -906,7 +1245,106 @@ async function proposePlanesConfig(cwd, io) {
906
1245
  'the file declares no plane, so every table still blocks until you add a reviewed rule)');
907
1246
  return;
908
1247
  }
909
- writeLine(io.stdout, `created: ${planesPath} (${inference.config.rules.length} rule(s) inferred from model directories — review the reasons before the next gateforge run)`);
1248
+ writeLine(io.stdout, `created: ${planesPath} (${combined.length} rule(s) — ${inference.config?.rules.length ?? 0} inferred from model directories, ` +
1249
+ `${routeRules.length} answered for route folders — review the reasons before the next gateforge run)`);
1250
+ }
1251
+ /**
1252
+ * Whether a `.gitignore` already covers one engine-state entry.
1253
+ *
1254
+ * Comparison is line-wise and tolerant of the forms a human writes
1255
+ * (leading `/`, a trailing `/`, surrounding spaces, a comment) so a
1256
+ * repeated `init` never appends the same rule twice.
1257
+ *
1258
+ * Args:
1259
+ * text: the current `.gitignore` contents (empty when absent).
1260
+ * entry: the repo-relative directory to ignore.
1261
+ *
1262
+ * Returns:
1263
+ * boolean: true when the file already ignores that path.
1264
+ */
1265
+ function ignoresEngineState(text, entry) {
1266
+ const wanted = entry.replace(/\/+$/, '');
1267
+ return text.split('\n').some((line) => {
1268
+ const trimmed = line.trim().replace(/^\/+|\/+$/g, '');
1269
+ return trimmed === wanted || trimmed === `${wanted}/**`;
1270
+ });
1271
+ }
1272
+ /**
1273
+ * Adds the engine-owned state directories to the repository's
1274
+ * `.gitignore`, creating the file when absent and appending when
1275
+ * present. The owner's own lines are preserved byte for byte and a
1276
+ * second run reports "already ignored" instead of appending again.
1277
+ *
1278
+ * Args:
1279
+ * io: process context.
1280
+ * cwd: absolute repository root.
1281
+ *
1282
+ * Returns:
1283
+ * void.
1284
+ */
1285
+ function ignoreEngineState(io, cwd) {
1286
+ const path = join(cwd, '.gitignore');
1287
+ const existed = existsSync(path);
1288
+ const existing = existed ? readFileSync(path, 'utf8') : '';
1289
+ const missing = ENGINE_STATE_IGNORE_ENTRIES.filter((entry) => !ignoresEngineState(existing, entry));
1290
+ if (missing.length === 0) {
1291
+ if (existed) {
1292
+ recordInitPath(io, cwd, path, 'preserved');
1293
+ writeLine(io.stdout, `exists, leaving untouched: ${path} (gateforge engine state already ignored)`);
1294
+ }
1295
+ return;
1296
+ }
1297
+ const block = [
1298
+ ENGINE_STATE_IGNORE_COMMENT,
1299
+ ...missing,
1300
+ '',
1301
+ ].join('\n');
1302
+ const prefix = existing.length === 0 || existing.endsWith('\n') ? existing : `${existing}\n`;
1303
+ writeFileSync(path, `${prefix}${block}`, 'utf8');
1304
+ recordInitPath(io, cwd, path, existed ? 'modified' : 'created');
1305
+ writeLine(io.stdout, `${existed ? 'updated' : 'created'}: ${path} (gateforge engine state ignored: ${missing.join(', ')} — ` +
1306
+ 'without this, `git add -A` stages the run cache and the gate blocks on its own files)');
1307
+ }
1308
+ /** The dependency files whose uncommitted state the install note names. */
1309
+ const INSTALL_MANIFEST_FILES = [
1310
+ 'package.json',
1311
+ 'package-lock.json',
1312
+ 'npm-shrinkwrap.json',
1313
+ 'pnpm-lock.yaml',
1314
+ 'yarn.lock',
1315
+ 'bun.lockb',
1316
+ 'bun.lock',
1317
+ ];
1318
+ /** The one line an init run prints while the install is uncommitted. */
1319
+ const INSTALL_COMMIT_NOTE = 'note: commit the Gateforge install (package.json and lockfile) on its own BEFORE committing the setup files — a setup commit that also changes dependencies is a product change, and under strictE2E it re-grades the adopted E2E debt as blocking. Commit it now, before the commit gate is wired.';
1320
+ /**
1321
+ * Prints the install-commit note when the install itself (the
1322
+ * dependency change that brought Gateforge into the repository)
1323
+ * is still uncommitted: the setup commit must stay
1324
+ * product-behavior-neutral, so the install belongs in its own
1325
+ * commit BEFORE the setup files are committed.
1326
+ *
1327
+ * Args:
1328
+ * io: process context.
1329
+ *
1330
+ * Returns:
1331
+ * void: a non-repository, a repository without commits, or a
1332
+ * clean install prints nothing; the run always proceeds
1333
+ * exactly as before (never refuses, never changes the exit
1334
+ * code).
1335
+ */
1336
+ function noteUncommittedInstall(io) {
1337
+ const head = spawnSync('git', ['rev-parse', '--verify', '-q', 'HEAD'], {
1338
+ cwd: io.cwd,
1339
+ env: io.env,
1340
+ encoding: 'utf8',
1341
+ });
1342
+ if (head.status !== 0)
1343
+ return;
1344
+ const status = spawnSync('git', ['status', '--porcelain', '--', ...INSTALL_MANIFEST_FILES], { cwd: io.cwd, env: io.env, encoding: 'utf8' });
1345
+ if (status.status !== 0 || (status.stdout ?? '').trim().length === 0)
1346
+ return;
1347
+ writeLine(io.stdout, INSTALL_COMMIT_NOTE);
910
1348
  }
911
1349
  /**
912
1350
  * Runs `gateforge init` in the io cwd.
@@ -922,7 +1360,7 @@ export async function initCommand(io, argv) {
922
1360
  // The ledger every writer below fills: the closing summary names only
923
1361
  // what THIS run created or kept, so it can never offer to delete the
924
1362
  // owner's pre-existing config, baselines, waivers, hooks or CI file.
925
- io.initPaths ??= { created: [], preserved: [] };
1363
+ io.initPaths ??= { created: [], modified: [], preserved: [] };
926
1364
  const { options } = parseArgs(argv);
927
1365
  if (options['help'] === true) {
928
1366
  writeLine(io.stdout, INIT_USAGE);
@@ -948,9 +1386,11 @@ export async function initCommand(io, argv) {
948
1386
  'planes',
949
1387
  'no-planes',
950
1388
  'behavior',
1389
+ 'unmatched-routes',
951
1390
  'no-behavior',
952
1391
  'behavior-packs',
953
1392
  'docs-exclude',
1393
+ 'docs-exclude-file',
954
1394
  'confirm-doc-exclusions',
955
1395
  'cache-exclude',
956
1396
  'confirm-cache-exclusions',
@@ -1020,6 +1460,12 @@ export async function initCommand(io, argv) {
1020
1460
  if (typeof options['strict-e2e'] !== 'boolean' && options['strict-e2e'] !== undefined) {
1021
1461
  throw new UsageError("flag '--strict-e2e' must be a boolean flag");
1022
1462
  }
1463
+ // The install-commit note (0.9.1): the dependency change that
1464
+ // brought Gateforge in belongs in its own commit BEFORE the
1465
+ // setup files — a setup commit that also changes dependencies
1466
+ // is a product change. Printed at the START of the run; never
1467
+ // refuses and never changes the exit code.
1468
+ noteUncommittedInstall(io);
1023
1469
  // Goal resolution (plan Phase 1/2): --preset wins, then the one goal
1024
1470
  // question in a terminal, then light with a loud note. A run that
1025
1471
  // already carries explicit enforcement flags has chosen for itself, so
@@ -1035,6 +1481,21 @@ export async function initCommand(io, argv) {
1035
1481
  options['strict-e2e'] === true;
1036
1482
  const goal = await resolveGoal(io, options, enforcementFlagGiven, existsSync(join(io.cwd, '.gateforge.yml')));
1037
1483
  const strictE2E = goal !== null ? goal.settings.strictE2E : options['strict-e2e'] === true;
1484
+ // An existing config is never rewritten (R1-2): a run that
1485
+ // REQUESTS a setting the file already owns with a different
1486
+ // value — a chosen preset's `mode`/`enforcement.strictE2E`,
1487
+ // or the `--strict-e2e` / `--unmatched-routes` flags — exits
1488
+ // 2 BEFORE anything is written, one line per differing key,
1489
+ // naming the key, both values, and the edit that fixes it.
1490
+ // Same value (or no such request) behaves exactly as today.
1491
+ const configConflicts = requestedConfigConflicts(io.cwd, options, goal);
1492
+ if (configConflicts.length > 0) {
1493
+ throw new UsageError(configConflicts
1494
+ .map((conflict) => `.gateforge.yml exists and has ${conflict.key}: ${conflict.current}; ` +
1495
+ `you asked for ${conflict.requested}. init never rewrites an existing config — ` +
1496
+ `set ${conflict.key}: ${conflict.requested} in .gateforge.yml yourself.`)
1497
+ .join('\n'));
1498
+ }
1038
1499
  // Strict-setup preflight (plan Phase 0 item 4): BEFORE anything is
1039
1500
  // written — a strict setup demanding an unavailable proof channel
1040
1501
  // stays visibly incomplete instead of shipping a false green. The
@@ -1044,15 +1505,18 @@ export async function initCommand(io, argv) {
1044
1505
  preflightStrictSetup(POLICIES_TEMPLATE);
1045
1506
  }
1046
1507
  // Scan + recommend + choose (Phase 1 item 1): heuristics inform the
1047
- // install; nothing extra is silently enabled. --no-scan skips the
1048
- // filesystem walk and falls back to the language-derived set.
1508
+ // install; nothing extra is silently enabled. `--no-scan` skips the
1509
+ // filesystem walk and falls back to the language-derived set (and
1510
+ // claims nothing about how much code is there); `--languages` skips
1511
+ // only the language DERIVATION — the signals and the number of files
1512
+ // the walk really saw are still true.
1049
1513
  const noScan = options['no-scan'] === true;
1050
- const scan = noScan || explicitLanguages !== null
1051
- ? {
1052
- languages: explicitLanguages ?? ['python'],
1053
- signals: noScan ? [] : scanRepo(io.cwd).signals,
1054
- }
1055
- : scanRepo(io.cwd);
1514
+ const walked = noScan ? null : scanRepo(io.cwd);
1515
+ const scan = walked === null
1516
+ ? { languages: explicitLanguages ?? ['python'], signals: [], reasons: undefined, files: 0 }
1517
+ : explicitLanguages === null
1518
+ ? walked
1519
+ : { ...walked, languages: explicitLanguages };
1056
1520
  // Which runner the scan saw. The `runner:` key is owner-owned, so it
1057
1521
  // is written ONLY when exactly one non-Playwright runner was detected:
1058
1522
  // Playwright stays the frozen default, and an ambiguous repository
@@ -1073,10 +1537,23 @@ export async function initCommand(io, argv) {
1073
1537
  return 0;
1074
1538
  }
1075
1539
  const cwd = io.cwd;
1540
+ // Which CI provider this repository ALREADY used, captured BEFORE any
1541
+ // CI file is written by this run: a repository that shows no provider
1542
+ // at all gets both sets of instructions, and after wiring
1543
+ // `.gitlab-ci.yml` always exists — the question would then be answered
1544
+ // by us rather than read from the repository.
1545
+ const ciProviderBeforeWiring = detectCiProvider(cwd);
1076
1546
  // Whether `.gateforge.yml` was already there BEFORE this run: the
1077
1547
  // preset summary must tell the truth about what changed.
1078
1548
  const existedConfigAtStart = existsSync(join(io.cwd, '.gateforge.yml'));
1079
1549
  const historyRetentionDays = existsSync(join(cwd, '.gateforge.yml')) ? undefined : await resolveHistoryRetention(io);
1550
+ // How a NEW repository grades unmatched by-id routes (0.9.0, owner
1551
+ // decision D7). Asked once, in a terminal; `warn` and the exact key to
1552
+ // choose `block` on a non-interactive run; an existing config is left
1553
+ // alone and keeps the `check`/`next` banner asking.
1554
+ const unmatchedRoutes = await resolveUnmatchedRoutes(io, options, existedConfigAtStart);
1555
+ if (unmatchedRoutes.note !== undefined)
1556
+ writeLine(io.stdout, unmatchedRoutes.note);
1080
1557
  const languages = scan.languages;
1081
1558
  const pluginIds = recommended;
1082
1559
  const configOptions = {
@@ -1091,6 +1568,8 @@ export async function initCommand(io, argv) {
1091
1568
  strictnessMode: goal?.settings.strictnessMode,
1092
1569
  // The scanned runner, when it is unambiguous and not Playwright.
1093
1570
  runner: detectedRunner,
1571
+ // The owner's answer for unmatched by-id routes; undefined writes no key.
1572
+ unmatchedRoutes: unmatchedRoutes.mode,
1094
1573
  };
1095
1574
  const generatedDraftConfig = () => parseConfig(parseYaml(configTemplate(languages, pluginIds, configOptions)), { file: '.gateforge.yml' });
1096
1575
  let draftConfig;
@@ -1170,10 +1649,27 @@ export async function initCommand(io, argv) {
1170
1649
  ]
1171
1650
  : []),
1172
1651
  ];
1652
+ /**
1653
+ * Queues one scaffold file, keyed by path. Two steps of the same run
1654
+ * can want the SAME file with different content (the config and the
1655
+ * config-with-behaviorPolicy); pushing both made the second entry
1656
+ * report "exists, leaving untouched" about a file the same run had
1657
+ * just created, and silently dropped the richer content. The later
1658
+ * entry wins, in the later entry's position, so exactly one line per
1659
+ * file is ever printed and the fullest content is what lands.
1660
+ */
1661
+ const pushTarget = (target) => {
1662
+ const existing = targets.findIndex((candidate) => candidate.path === target.path);
1663
+ if (existing === -1) {
1664
+ targets.push(target);
1665
+ return;
1666
+ }
1667
+ targets[existing] = target;
1668
+ };
1173
1669
  if (docsExclusionChoice.changed) {
1174
1670
  const exclusionPath = join(cwd, ...DOCS_EXCLUSIONS_PATH.split('/'));
1175
1671
  const exclusionText = renderDocsExclusions(docsExclusionChoice.folders);
1176
- targets.push({
1672
+ pushTarget({
1177
1673
  path: exclusionPath,
1178
1674
  label: 'owner-declared documentation exclusions',
1179
1675
  write: () => {
@@ -1193,7 +1689,7 @@ export async function initCommand(io, argv) {
1193
1689
  if (cacheExclusionChoice.changed) {
1194
1690
  const exclusionPath = join(cwd, ...CACHE_EXCLUSIONS_PATH.split('/'));
1195
1691
  const exclusionText = renderCacheExclusions(cacheExclusionChoice.files);
1196
- targets.push({
1692
+ pushTarget({
1197
1693
  path: exclusionPath,
1198
1694
  label: 'owner-declared Python bytecode exclusions',
1199
1695
  write: () => {
@@ -1274,14 +1770,14 @@ export async function initCommand(io, argv) {
1274
1770
  }
1275
1771
  }
1276
1772
  else {
1277
- targets.push({
1773
+ pushTarget({
1278
1774
  path: behaviorPath,
1279
1775
  label: 'complete-behavior document (SCAFFOLD — not approval)',
1280
1776
  write: () => writeFileSync(behaviorPath, template, 'utf8'),
1281
1777
  });
1282
1778
  }
1283
1779
  if (!existsSync(join(cwd, '.gateforge.yml'))) {
1284
- targets.push({
1780
+ pushTarget({
1285
1781
  path: join(cwd, '.gateforge.yml'),
1286
1782
  label: 'config (with behaviorPolicy)',
1287
1783
  write: () => {
@@ -1316,7 +1812,7 @@ export async function initCommand(io, argv) {
1316
1812
  const added = loadConfig(configPath).plugins
1317
1813
  .map((plugin) => plugin.id)
1318
1814
  .filter((id) => explicitPlugins.includes(id));
1319
- recordInitPath(io, cwd, configPath, 'preserved');
1815
+ recordInitPath(io, cwd, configPath, 'modified');
1320
1816
  writeLine(io.stdout, `updated: ${configPath} (added detector(s): ${added.join(', ')} — every other key left as it was)`);
1321
1817
  }
1322
1818
  }
@@ -1325,6 +1821,7 @@ export async function initCommand(io, argv) {
1325
1821
  if ((target.label === 'owner-declared documentation exclusions' && docsExclusionChoice.changed) ||
1326
1822
  (target.label === 'owner-declared Python bytecode exclusions' && cacheExclusionChoice.changed)) {
1327
1823
  target.write();
1824
+ recordInitPath(io, cwd, target.path, 'modified');
1328
1825
  writeLine(io.stdout, `updated: ${target.path}`);
1329
1826
  continue;
1330
1827
  }
@@ -1336,6 +1833,10 @@ export async function initCommand(io, argv) {
1336
1833
  recordInitPath(io, cwd, target.path, 'created');
1337
1834
  writeLine(io.stdout, `created: ${target.path}`);
1338
1835
  }
1836
+ // Engine-owned state is never a product change: without this the
1837
+ // first `git add -A` stages the run cache the gate just wrote, and the
1838
+ // gate then blocks on its own files.
1839
+ ignoreEngineState(io, cwd);
1339
1840
  // Observe proof checklist (observe proof only): the work no scaffold
1340
1841
  // can do — proxy wiring, adapter bindings, and kind declarations.
1341
1842
  if (proofMode === 'observe') {
@@ -1379,7 +1880,11 @@ export async function initCommand(io, argv) {
1379
1880
  const planesRequested = options['planes'] === true;
1380
1881
  if (planesRequested || languages.includes('python')) {
1381
1882
  if (await resolvePlanes(io, options)) {
1382
- await proposePlanesConfig(cwd, io);
1883
+ // The route folders are asked in the SAME flow, right before the
1884
+ // model folders are written, so both sets of answers land in one
1885
+ // reviewed `.gateforge/planes.json`.
1886
+ const routeRules = await askRouteFolderPlanes(cwd, io);
1887
+ await proposePlanesConfig(cwd, io, routeRules);
1383
1888
  }
1384
1889
  }
1385
1890
  // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
@@ -1491,7 +1996,12 @@ export async function initCommand(io, argv) {
1491
1996
  writeLine(io.stdout, `verified: ${outcome.detail}`);
1492
1997
  break;
1493
1998
  case 'framework':
1494
- writeLine(io.stdout, `framework-managed pre-commit hook detected: wiring through .pre-commit-config.yaml`);
1999
+ if (outcome.hookPath !== null && !existsSync(outcome.hookPath)) {
2000
+ writeLine(io.stdout, 'pre-commit framework config found: gateforge-check added to .pre-commit-config.yaml — run `pre-commit install` to activate the gate');
2001
+ }
2002
+ else {
2003
+ writeLine(io.stdout, `framework-managed pre-commit hook detected: wiring through .pre-commit-config.yaml`);
2004
+ }
1495
2005
  break;
1496
2006
  case 'conflict':
1497
2007
  case 'incomplete':
@@ -1516,7 +2026,7 @@ export async function initCommand(io, argv) {
1516
2026
  }
1517
2027
  writeLine(io.stdout, `${pushHook.status}: ${pushHook.detail}`);
1518
2028
  }
1519
- writeServerProtectionInstructions(io);
2029
+ writeServerProtectionInstructions(io, ciProviderBeforeWiring);
1520
2030
  }
1521
2031
  // A preset can ask for the CI job without a local hook (`normal`):
1522
2032
  // the server check is then the only place the gate runs, which is a
@@ -1531,12 +2041,20 @@ export async function initCommand(io, argv) {
1531
2041
  configExisted: existedConfigAtStart,
1532
2042
  autoChosen: goal.autoChosen === true,
1533
2043
  created: [...(ledger?.created ?? [])],
2044
+ modified: [...(ledger?.modified ?? [])],
1534
2045
  repoHasCommitHook: existsSync(join(cwd, '.git/hooks/pre-commit')),
1535
2046
  repoHasCi: existsSync(join(cwd, '.gitlab-ci.yml')) || existsSync(join(cwd, '.github/workflows/gateforge.yml')),
1536
2047
  })) {
1537
2048
  writeLine(io.stdout, line);
1538
2049
  }
1539
2050
  }
2051
+ // A repository that already had code before this run gets the
2052
+ // adoption path named HERE, where the owner is deciding what the
2053
+ // gate will do to them. `init` on a fresh project has no debt and
2054
+ // must not talk about adopting one.
2055
+ if (!existedConfigAtStart && scan.files > 0) {
2056
+ writeLine(io.stdout, ADOPT_ADVICE);
2057
+ }
1540
2058
  writeLine(io.stdout, 'skeleton ready: .gateforge/adapters, .gateforge/waivers, .gateforge/baselines');
1541
2059
  const alembicOptIn = renderAlembicOptIn(cwd);
1542
2060
  if (alembicOptIn !== null)