@gate-forge/cli 0.8.0 → 0.9.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 (122) hide show
  1. package/README.md +78 -1143
  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 +7 -0
  20. package/dist/commands/adopt.d.ts.map +1 -1
  21. package/dist/commands/adopt.js +35 -1
  22. package/dist/commands/adopt.js.map +1 -1
  23. package/dist/commands/blocking.d.ts +25 -1
  24. package/dist/commands/blocking.d.ts.map +1 -1
  25. package/dist/commands/blocking.js +64 -5
  26. package/dist/commands/blocking.js.map +1 -1
  27. package/dist/commands/check.d.ts.map +1 -1
  28. package/dist/commands/check.js +60 -2
  29. package/dist/commands/check.js.map +1 -1
  30. package/dist/commands/classify.d.ts +1 -1
  31. package/dist/commands/classify.d.ts.map +1 -1
  32. package/dist/commands/classify.js +63 -18
  33. package/dist/commands/classify.js.map +1 -1
  34. package/dist/commands/enforcement.d.ts.map +1 -1
  35. package/dist/commands/enforcement.js +81 -4
  36. package/dist/commands/enforcement.js.map +1 -1
  37. package/dist/commands/explain.d.ts +1 -1
  38. package/dist/commands/explain.d.ts.map +1 -1
  39. package/dist/commands/explain.js +162 -3
  40. package/dist/commands/explain.js.map +1 -1
  41. package/dist/commands/init-presets.d.ts +7 -0
  42. package/dist/commands/init-presets.d.ts.map +1 -1
  43. package/dist/commands/init-presets.js +10 -1
  44. package/dist/commands/init-presets.js.map +1 -1
  45. package/dist/commands/init.d.ts.map +1 -1
  46. package/dist/commands/init.js +386 -39
  47. package/dist/commands/init.js.map +1 -1
  48. package/dist/commands/next.d.ts.map +1 -1
  49. package/dist/commands/next.js +103 -5
  50. package/dist/commands/next.js.map +1 -1
  51. package/dist/commands/test-gates.js +1 -1
  52. package/dist/commands/tests.d.ts.map +1 -1
  53. package/dist/commands/tests.js +39 -7
  54. package/dist/commands/tests.js.map +1 -1
  55. package/dist/docs-exclusions.d.ts.map +1 -1
  56. package/dist/docs-exclusions.js +18 -3
  57. package/dist/docs-exclusions.js.map +1 -1
  58. package/dist/endpoint-compiler.d.ts.map +1 -1
  59. package/dist/endpoint-compiler.js +49 -1
  60. package/dist/endpoint-compiler.js.map +1 -1
  61. package/dist/evaluate.d.ts +16 -1
  62. package/dist/evaluate.d.ts.map +1 -1
  63. package/dist/evaluate.js +12 -2
  64. package/dist/evaluate.js.map +1 -1
  65. package/dist/gateforge-owned.d.ts +78 -0
  66. package/dist/gateforge-owned.d.ts.map +1 -0
  67. package/dist/gateforge-owned.js +254 -0
  68. package/dist/gateforge-owned.js.map +1 -0
  69. package/dist/git-hooks.d.ts +18 -0
  70. package/dist/git-hooks.d.ts.map +1 -1
  71. package/dist/git-hooks.js +21 -1
  72. package/dist/git-hooks.js.map +1 -1
  73. package/dist/git-ignored.d.ts +27 -0
  74. package/dist/git-ignored.d.ts.map +1 -0
  75. package/dist/git-ignored.js +102 -0
  76. package/dist/git-ignored.js.map +1 -0
  77. package/dist/glob.d.ts +33 -14
  78. package/dist/glob.d.ts.map +1 -1
  79. package/dist/glob.js +96 -5
  80. package/dist/glob.js.map +1 -1
  81. package/dist/index.d.ts +4 -1
  82. package/dist/index.d.ts.map +1 -1
  83. package/dist/index.js +2 -1
  84. package/dist/index.js.map +1 -1
  85. package/dist/io.d.ts +18 -5
  86. package/dist/io.d.ts.map +1 -1
  87. package/dist/io.js +5 -4
  88. package/dist/io.js.map +1 -1
  89. package/dist/pipeline.d.ts +16 -1
  90. package/dist/pipeline.d.ts.map +1 -1
  91. package/dist/pipeline.js +23 -3
  92. package/dist/pipeline.js.map +1 -1
  93. package/dist/planes-inference.d.ts +12 -5
  94. package/dist/planes-inference.d.ts.map +1 -1
  95. package/dist/planes-inference.js +13 -15
  96. package/dist/planes-inference.js.map +1 -1
  97. package/dist/repo-scan.d.ts +7 -0
  98. package/dist/repo-scan.d.ts.map +1 -1
  99. package/dist/repo-scan.js +109 -8
  100. package/dist/repo-scan.js.map +1 -1
  101. package/dist/route-plane-proposals.d.ts +100 -0
  102. package/dist/route-plane-proposals.d.ts.map +1 -0
  103. package/dist/route-plane-proposals.js +213 -0
  104. package/dist/route-plane-proposals.js.map +1 -0
  105. package/dist/scope.d.ts +20 -0
  106. package/dist/scope.d.ts.map +1 -1
  107. package/dist/scope.js +26 -5
  108. package/dist/scope.js.map +1 -1
  109. package/dist/singleton-guidance.d.ts +15 -6
  110. package/dist/singleton-guidance.d.ts.map +1 -1
  111. package/dist/singleton-guidance.js +30 -10
  112. package/dist/singleton-guidance.js.map +1 -1
  113. package/dist/unmatched-routes.d.ts +60 -0
  114. package/dist/unmatched-routes.d.ts.map +1 -0
  115. package/dist/unmatched-routes.js +131 -0
  116. package/dist/unmatched-routes.js.map +1 -0
  117. package/guides/CONNECT-YOUR-PROJECT.md +78 -20
  118. package/guides/QUICKSTART.md +55 -10
  119. package/guides/REFERENCE.md +1710 -0
  120. package/guides/TEST-ENVIRONMENT.md +8 -5
  121. package/guides/UPGRADE-0.8-to-0.9.md +104 -0
  122. package/package.json +10 -10
@@ -18,10 +18,11 @@
18
18
  import { existsSync, mkdirSync, readFileSync, renameSync, unlinkSync, writeFileSync } from 'node:fs';
19
19
  import { randomUUID } from 'node:crypto';
20
20
  import { createInterface } from 'node:readline/promises';
21
- import { join } from 'node:path';
21
+ import { isAbsolute, join } from 'node:path';
22
22
  import { parse as parseYaml, parseDocument, isSeq as isYamlSeq, isMap as isYamlMap } from 'yaml';
23
23
  import { ClassificationPolicySchema, PolicyFileSchema, loadConfig, parseConfig, serializeBaseline, strictCapabilityGaps, } from '@gate-forge/core';
24
24
  import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, PACK_VERSION as PACK_SQLALCHEMY_VERSION, } from '@gate-forge/pack-sqlalchemy';
25
+ import { collectRoutePlaneFacts, proposeRouteFolderPlanes, } from '../route-plane-proposals.js';
25
26
  import { PACK_VERSION as PACK_FASTAPI_VERSION } from '@gate-forge/pack-fastapi';
26
27
  import { PACK_VERSION as PACK_HTTP_VERSION } from '@gate-forge/pack-http';
27
28
  import { PACK_VERSION as PACK_TASK_VERSION } from '@gate-forge/pack-task';
@@ -31,21 +32,23 @@ import { recordInitPath, writeLine } from '../io.js';
31
32
  import { UsageError } from '../errors.js';
32
33
  import { languageDefaultPlugins, recommendPlugins, renderScanBlock, scanRepo } from '../repo-scan.js';
33
34
  import { rejectUnknownFlags } from './common.js';
34
- import { expandIncludePaths } from '../glob.js';
35
+ import { expandScanPaths } from '../glob.js';
36
+ import { gitIgnoredPaths } from '../git-ignored.js';
35
37
  import { inferPlanesConfig } from '../planes-inference.js';
36
38
  import { hasGateforgeMarker, installCommitHook, installPrePushHook, writeStandaloneGateScript } from '../git-hooks.js';
37
- import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, writeServerProtectionInstructions, } from './blocking.js';
39
+ import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation, detectCiProvider, writeGitlabCiTemplate as writeSharedGitlabCiTemplate, writeServerProtectionInstructions, } from './blocking.js';
38
40
  import { trustedPolicyDigestForConfig } from '../execution.js';
39
41
  import { DOCS_EXCLUSIONS_GUARANTEE, DOCS_EXCLUSIONS_PATH, loadDocsExclusions, renderDocsExclusions, validateRequestedDocsFolders, } from '../docs-exclusions.js';
40
42
  import { CACHE_EXCLUSIONS_GUARANTEE, CACHE_EXCLUSIONS_PATH, loadCacheExclusions, renderCacheExclusions, validateRequestedCacheFiles, } from '../cache-exclusions.js';
43
+ import { DEFAULT_STATE_DIR } from '../state.js';
41
44
  import { CHOOSE_ANOTHER_GOAL_ADVICE, INIT_PRESETS, isInitPresetName, parseGoalAnswer, renderGoalQuestion, renderPresetTable, renderPresetSummary, } from './init-presets.js';
42
45
  import { BEHAVIOR_NAMESPACES, behaviorPackEvidence, behaviorSkeletonExamples, detectBehaviorPacks, parseBehaviorPacks, } from '../behavior-setup.js';
43
46
  export const INIT_USAGE = '[--preset light|normal|strict] [--explain-presets] [--no-scan] [--proof overlay|observe] ' +
44
47
  '[--blocking] [--no-blocking] [--pre-commit] [--no-pre-commit] [--mode changed|staged] ' +
45
48
  '[--witnessed staged|full] [--ci] [--no-ci] ' +
46
- '[--docs-exclude <folder,...> [--confirm-doc-exclusions]] [--cache-exclude <file,...> ' +
49
+ '[--docs-exclude <folder,...> [--docs-exclude-file <path>] [--confirm-doc-exclusions]] [--cache-exclude <file,...> ' +
47
50
  '[--confirm-cache-exclusions]] [--strict-e2e] [--planes] [--no-planes] ' +
48
- '[--behavior] [--no-behavior] [--behavior-packs <pack,...>]';
51
+ '[--behavior] [--no-behavior] [--behavior-packs <pack,...>] [--unmatched-routes block|warn]';
49
52
  /** Template for the complete-behavior owner document (plan §4.1). */
50
53
  export const BEHAVIOR_TEMPLATE = `\
51
54
  # Complete-behavior owner document.
@@ -395,6 +398,18 @@ runner: ${options.runner}
395
398
  const historyBlock = options.historyRetentionDays === undefined
396
399
  ? ''
397
400
  : `history:\n retentionDays: ${String(options.historyRetentionDays)}\n`;
401
+ // The owner-owned unmatched-route grading. Only written when the owner
402
+ // answered (the terminal question, the flag, or the non-interactive
403
+ // `warn`); an existing config that said nothing keeps saying nothing,
404
+ // and the `check`/`next` banner keeps asking.
405
+ const endpointsBlock = options.unmatchedRoutes === undefined
406
+ ? ''
407
+ : `# Routes whose name matches no discovered resource (ENDPOINT_RESOURCE_CANDIDATE_UNMATCHED).
408
+ # 'warn' reports them as advisories with a banner; 'block' makes them
409
+ # blocking entries like any other finding. Absent means 'warn'.
410
+ endpoints:
411
+ unmatchedRoutes: ${options.unmatchedRoutes}
412
+ `;
398
413
  return `\
399
414
  # gateforge project configuration (schemaVersion 1)
400
415
  schemaVersion: 1
@@ -415,6 +430,15 @@ ${sourceIncludePatterns(languages).map((pattern) => ` - '${pattern}'`).join
415
430
  - '**/.mypy_cache/**'
416
431
  - '**/dist/**'
417
432
  - '**/build/**'
433
+ # Hidden dot-folders (agent tooling like .claude/ or .cursor/,
434
+ # editor/tool caches, leftover merge or working folders) hold
435
+ # tooling and debris, never application code. The rule is generic
436
+ # -- it keys on the dot prefix at any depth -- so any hidden folder
437
+ # is skipped, whatever it is called. .gateforge is the ONE
438
+ # exception and is deliberately NOT matched here: Gateforge's own
439
+ # configuration stays in scope.
440
+ - '**/.(!(gateforge))/**'
441
+ - '.!(gateforge)/**'
418
442
  # Detector plugins. Bundled detectors are preconfigured for the selected
419
443
  # languages and are loaded from their trusted package entry points.
420
444
  plugins:
@@ -430,7 +454,7 @@ witness:
430
454
  maxDurationSeconds: 5
431
455
  clock:
432
456
  mode: system
433
- ${runnerBlock}${historyBlock}${strictnessBlock}${enforcementBlock}\
457
+ ${endpointsBlock}${runnerBlock}${historyBlock}${strictnessBlock}${enforcementBlock}\
434
458
  `;
435
459
  }
436
460
  /**
@@ -550,6 +574,23 @@ const OBSERVE_CHECKLIST = `observe proof checklist (existing suite through the w
550
574
  4. Run \`gateforge test-gates --changed\`, then \`gateforge check --require-e2e\`.
551
575
  Honest scope: proves persistence (the server stored what the proxied
552
576
  request sent), not "the engine typed the form".`;
577
+ /**
578
+ * The adoption block init prints on the FIRST init of a repository that
579
+ * already has code. Such a repository is not green on day one: the very
580
+ * next commit sees everything discovery found as existing debt. Without
581
+ * this block the owner meets that as a wall of findings with no name
582
+ * for the sanctioned way through it — `gateforge adopt` — which is why
583
+ * the command had to be discovered from a source file instead of from
584
+ * `init`.
585
+ *
586
+ * Everything here is exactly what `adopt` does: the recorded set, its
587
+ * shrink-only standing, and the one case where an adopted E2E
588
+ * obligation still blocks.
589
+ */
590
+ const ADOPT_ADVICE = `this repository already had code, so \`gateforge check\` reports what discovery finds today, and today\'s findings block the first commit:
591
+ gateforge adopt — records today\'s blocking findings as forgiven debt, in a baseline plus a dated, count-annotated receipt, then wires the blocking gate.
592
+ 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.
593
+ with strictE2E enabled, an adopted E2E obligation still blocks with ENFORCEMENT_UNTRUSTED as soon as a change touches it — baselined is not proof.`;
553
594
  /**
554
595
  * Asks (TTY only) whether init should write the recommended setup.
555
596
  * Flags win: `--accept-recommended` forces yes, `--plugins` (an explicit
@@ -686,6 +727,63 @@ async function resolveHistoryRetention(io) {
686
727
  rl.close();
687
728
  }
688
729
  }
730
+ /**
731
+ * Resolves how a NEW repository grades unmatched by-id routes (0.9.0,
732
+ * owner decision D7).
733
+ *
734
+ * Flags win, then the terminal question, then `warn`. A non-interactive
735
+ * run (an agent, a CI job, a test) writes `warn` and prints the exact
736
+ * setting to choose `block` — it never blocks a repository the owner
737
+ * never asked to gate on. A repository that ALREADY has a
738
+ * `.gateforge.yml` is left untouched: an existing config that has said
739
+ * nothing keeps saying nothing, and the banner keeps asking.
740
+ *
741
+ * Args:
742
+ * io: process context (prompt + informational output).
743
+ * options: parsed init flags.
744
+ * configExisted: whether `.gateforge.yml` was already present.
745
+ *
746
+ * Returns:
747
+ * Promise<{ mode: 'block' | 'warn' | undefined; note: string | undefined }>:
748
+ * the answer to write (`undefined` writes no key) and the non-interactive
749
+ * line to print.
750
+ */
751
+ async function resolveUnmatchedRoutes(io, options, configExisted) {
752
+ const flagValue = stringFlag(options, 'unmatched-routes');
753
+ if (flagValue !== undefined) {
754
+ const mode = flagValue.trim().toLowerCase();
755
+ if (mode !== 'block' && mode !== 'warn') {
756
+ throw new UsageError("init: --unmatched-routes must be 'block' or 'warn'");
757
+ }
758
+ return { mode, note: undefined };
759
+ }
760
+ if (configExisted)
761
+ return { mode: undefined, note: undefined };
762
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
763
+ return {
764
+ mode: 'warn',
765
+ note: "note: routes whose name matches no table will be REPORTED, not blocking. " +
766
+ "set 'endpoints:\n unmatchedRoutes: block' in .gateforge.yml (or re-run with --unmatched-routes block) to block on them",
767
+ };
768
+ }
769
+ // The question is printed by the command (like the goal question), so it
770
+ // is in the run's own output and survives a non-interactive transcript;
771
+ // the readline prompt only takes the answer.
772
+ writeLine(io.stdout, 'Routes whose name matches no table: block commits, or warn only? [block/warn] (default warn)');
773
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
774
+ try {
775
+ const answer = (await rl.question(' ')).trim().toLowerCase();
776
+ if (answer === '')
777
+ return { mode: 'warn', note: undefined };
778
+ if (answer !== 'block' && answer !== 'warn') {
779
+ throw new UsageError("init: unmatched-route grading must be 'block' or 'warn'");
780
+ }
781
+ return { mode: answer, note: undefined };
782
+ }
783
+ finally {
784
+ rl.close();
785
+ }
786
+ }
689
787
  /**
690
788
  * Resolves which behavior packs' cases `init` enables (plan 2026-09-30
691
789
  * Phase 4). Flags win, then the terminal question, then nothing.
@@ -771,28 +869,67 @@ async function resolvePlanes(io, options) {
771
869
  rl.close();
772
870
  }
773
871
  }
872
+ /**
873
+ * Reads an owner-supplied folder list file: ONE folder per line, blank
874
+ * lines and `#` comments ignored. The comma list stays supported; this
875
+ * is the same declaration in a form that survives a long repository
876
+ * (typing or pasting dozens of folder names into one prompt wraps
877
+ * unreadably, and `paste -sd,` is not discoverable).
878
+ *
879
+ * Args:
880
+ * cwd: absolute repository root the relative path resolves against.
881
+ * filePath: the value given to `--docs-exclude-file`.
882
+ *
883
+ * Returns:
884
+ * string[]: the folders named by the file, in file order.
885
+ *
886
+ * Throws:
887
+ * UsageError: the file is missing or unreadable (never guessed at).
888
+ */
889
+ function readFolderListFile(cwd, filePath) {
890
+ const absolute = isAbsolute(filePath) ? filePath : join(cwd, filePath);
891
+ let text;
892
+ try {
893
+ text = readFileSync(absolute, 'utf8');
894
+ }
895
+ catch (error) {
896
+ throw new UsageError(`init: cannot read --docs-exclude-file '${filePath}': ${error instanceof Error ? error.message : String(error)}`);
897
+ }
898
+ return text
899
+ .split('\n')
900
+ .map((line) => line.split('#')[0]?.trim() ?? '')
901
+ .filter((line) => line.length > 0);
902
+ }
774
903
  /** Resolves the init owner's explicit documentation-folder declaration. */
775
904
  async function resolveDocsExclusionsForInit(io, options, config) {
776
905
  const current = loadDocsExclusions(io.cwd, config);
777
906
  const requestedValue = stringFlag(options, 'docs-exclude');
907
+ const fileValue = stringFlag(options, 'docs-exclude-file');
778
908
  const confirmUpdate = options['confirm-doc-exclusions'] === true;
779
909
  if (typeof options['confirm-doc-exclusions'] !== 'boolean' && options['confirm-doc-exclusions'] !== undefined) {
780
910
  throw new UsageError("init: '--confirm-doc-exclusions' must be a boolean flag");
781
911
  }
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);
912
+ if (requestedValue !== undefined || fileValue !== undefined) {
913
+ // Both flags are the SAME declaration in two spellings, so they
914
+ // combine into one ordered, deduplicated list instead of one
915
+ // silently winning over the other.
916
+ const declared = [
917
+ ...(requestedValue === undefined || requestedValue.trim() === ''
918
+ ? []
919
+ : requestedValue.split(',').map((folder) => folder.trim()).filter((folder) => folder.length > 0)),
920
+ ...(fileValue === undefined ? [] : readFolderListFile(io.cwd, fileValue)),
921
+ ];
922
+ const requested = [...new Set(declared)];
786
923
  if (current.length > 0 && JSON.stringify(requested) !== JSON.stringify(current) && !confirmUpdate) {
787
924
  throw new UsageError(`init: changing ${DOCS_EXCLUSIONS_PATH} needs explicit owner review; repeat with --confirm-doc-exclusions`);
788
925
  }
789
926
  if (current.length === 0 && requested.length === 0 && confirmUpdate) {
790
927
  throw new UsageError('init: --confirm-doc-exclusions requires a non-empty --docs-exclude update');
791
928
  }
792
- return { folders: requested, changed: JSON.stringify(requested) !== JSON.stringify(current) };
929
+ return { folders: validateRequestedDocsFolders(io.cwd, requested, config), changed: JSON.stringify(requested) !== JSON.stringify(current) };
793
930
  }
794
931
  if (confirmUpdate) {
795
- throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude');
932
+ throw new UsageError('init: --confirm-doc-exclusions requires --docs-exclude or --docs-exclude-file');
796
933
  }
797
934
  if (current.length > 0)
798
935
  return { folders: current, changed: false };
@@ -800,7 +937,8 @@ async function resolveDocsExclusionsForInit(io, options, config) {
800
937
  const rl = createInterface({ input: process.stdin, output: process.stdout });
801
938
  try {
802
939
  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): ');
940
+ 'Gateforge cannot prove that app/tests do not read these files. Folders (comma-separated; for a long list ' +
941
+ 'write them one per line to a file and pass --docs-exclude-file <path>): ');
804
942
  const raw = answer.trim();
805
943
  const folders = raw.length === 0
806
944
  ? []
@@ -811,7 +949,7 @@ async function resolveDocsExclusionsForInit(io, options, config) {
811
949
  rl.close();
812
950
  }
813
951
  }
814
- writeLine(io.stdout, 'tip: non-interactive init keeps full evidence identity; use --docs-exclude <folder,...> to opt in');
952
+ 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
953
  return { folders: [], changed: false };
816
954
  }
817
955
  /**
@@ -854,15 +992,92 @@ function resolveCacheExclusionsForInit(io, options, config) {
854
992
  }
855
993
  return { files: requested, changed };
856
994
  }
995
+ /**
996
+ * Asks the owner ONE plane question per ROUTE folder that still has
997
+ * unresolved endpoints (owner decision D1: ask, never infer).
998
+ *
999
+ * The linked model's plane is shown as a HINT and is never applied: an
1000
+ * `accounts` route can serve master data, so the owner answers for the
1001
+ * ROUTES. `proposeRouteFolderPlaneRules` already withholds the hint when
1002
+ * the linked models disagree or are themselves unresolved, so a hint
1003
+ * here always means "these routes serve a model whose plane IS this".
1004
+ *
1005
+ * A non-interactive run proposes nothing and writes nothing: it prints
1006
+ * the folders and the runnable `gateforge classify plane` shape for each,
1007
+ * with the plane and the reason LEFT AS PLACEHOLDERS — printing a concrete
1008
+ * plane would be inferring it for the owner, which is exactly what D1
1009
+ * forbids, and an agent that copies the line would apply a wrong plane to
1010
+ * a folder whose models init inferred as `master`.
1011
+ *
1012
+ * Args:
1013
+ * cwd: absolute repository root.
1014
+ * io: process context.
1015
+ *
1016
+ * Returns:
1017
+ * Promise<PlaneConfigRule[]>: the rules the owner answered for.
1018
+ */
1019
+ async function askRouteFolderPlanes(cwd, io) {
1020
+ let proposals;
1021
+ try {
1022
+ proposals = proposeRouteFolderPlanes(await collectRoutePlaneFacts(cwd));
1023
+ }
1024
+ catch (cause) {
1025
+ writeLine(io.stdout, `warning: route plane discovery failed (${cause instanceof Error ? cause.message : String(cause)}); ` +
1026
+ 'answer the route folders with `gateforge classify plane <folder> <tenant|master|global> --reason "<why>" --confirm` — init continues');
1027
+ return [];
1028
+ }
1029
+ if (proposals.length === 0)
1030
+ return [];
1031
+ const planes = new Set(['tenant', 'master', 'global']);
1032
+ const answers = [];
1033
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
1034
+ writeLine(io.stdout, `route folders with no answered plane (${proposals.length}) — one owner answer each, ` +
1035
+ 'never inferred from the linked model:');
1036
+ for (const proposal of proposals) {
1037
+ writeLine(io.stdout, ` ${proposal.folder} (${proposal.routeCount} route(s)` +
1038
+ `${proposal.hintPlane === null ? '' : `, linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane} — a hint only`})`);
1039
+ writeLine(io.stdout, ` gateforge classify plane ${proposal.folder} <tenant|master|global> --reason '<why the ROUTES in this folder serve that data>' --confirm`);
1040
+ }
1041
+ return answers;
1042
+ }
1043
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1044
+ try {
1045
+ writeLine(io.stdout, 'route folders whose plane is still unanswered — one answer per folder, asked because ' +
1046
+ 'a route linked to a model can still serve different data:');
1047
+ for (const proposal of proposals) {
1048
+ const hint = proposal.hintPlane === null
1049
+ ? ''
1050
+ : ` — hint only: the linked model(s) ${proposal.linkedModels.join(', ')} answer to ${proposal.hintPlane}; ` +
1051
+ 'a route can serve other data, so this is your answer to make';
1052
+ const answer = (await rl.question(`plane for '${proposal.folder}' (${proposal.routeCount} route(s)) — tenant/master/global, blank to skip${hint}: `))
1053
+ .trim()
1054
+ .toLowerCase();
1055
+ if (!planes.has(answer)) {
1056
+ if (answer !== '')
1057
+ writeLine(io.stdout, ` skipped '${proposal.folder}': '${answer}' is not a plane`);
1058
+ continue;
1059
+ }
1060
+ answers.push({
1061
+ match: `${proposal.folder}/**`,
1062
+ plane: answer,
1063
+ reason: `answered for the route folder '${proposal.folder}' during gateforge init; review before relying on this`,
1064
+ });
1065
+ }
1066
+ }
1067
+ finally {
1068
+ rl.close();
1069
+ }
1070
+ return answers;
1071
+ }
857
1072
  /**
858
1073
  * 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.
1074
+ * planes proposal from the discovered table directories, adds the owner's
1075
+ * answered ROUTE-folder rules, self-checks the draft against the runtime's
1076
+ * strict parser, and writes `.gateforge/planes.json` — only when absent
1077
+ * (never overwrites a reviewed document). Inference failure is surfaced as a
1078
+ * visible warning, never silently skipped, but does not abort the scaffold.
864
1079
  */
865
- async function proposePlanesConfig(cwd, io) {
1080
+ async function proposePlanesConfig(cwd, io, routeRules = []) {
866
1081
  const planesPath = join(cwd, PLANES_CONFIG_PATH);
867
1082
  if (existsSync(planesPath)) {
868
1083
  writeLine(io.stdout, `exists, leaving untouched: ${planesPath}`);
@@ -872,7 +1087,10 @@ async function proposePlanesConfig(cwd, io) {
872
1087
  try {
873
1088
  const config = loadConfig(join(cwd, '.gateforge.yml'));
874
1089
  const expandErrors = [];
875
- const paths = expandIncludePaths(config.project.paths.include, config.project.paths.exclude, cwd, expandErrors);
1090
+ // The same DETECTOR-INPUT scope the pipeline scans: a gitignored
1091
+ // tree (a built report bundle, a local cache) holds no table the
1092
+ // planes proposal should infer from.
1093
+ const paths = expandScanPaths(config.project.paths.include, config.project.paths.exclude, cwd, gitIgnoredPaths(cwd), expandErrors);
876
1094
  // The planes config plays no role in inference (only table SOURCE
877
1095
  // paths matter), so the detector runs with the default no-mapping
878
1096
  // rule — immune to whatever a previous run wrote.
@@ -896,7 +1114,11 @@ async function proposePlanesConfig(cwd, io) {
896
1114
  // assumes while the file is absent. Writing it anyway is what makes
897
1115
  // `gateforge init --planes` the runnable prerequisite the
898
1116
  // `gateforge next` guidance prints for an unresolved route.
899
- const serialized = `${JSON.stringify(inference.config ?? { rules: [] }, null, 2)}\n`;
1117
+ // The owner's ROUTE-folder answers join the inferred model rules in the
1118
+ // one file init writes: both are reviewed proposals, and splitting them
1119
+ // across two writes would make the second overwrite the first.
1120
+ const combined = [...(inference.config?.rules ?? []), ...routeRules];
1121
+ const serialized = `${JSON.stringify(combined.length === 0 ? { rules: [] } : { rules: combined }, null, 2)}\n`;
900
1122
  // Self-check the draft against the runtime's strict reader contract
901
1123
  // BEFORE writing (a broken proposal must fail here, not at the next run).
902
1124
  parsePlanesConfigText(serialized, planesPath);
@@ -906,7 +1128,78 @@ async function proposePlanesConfig(cwd, io) {
906
1128
  'the file declares no plane, so every table still blocks until you add a reviewed rule)');
907
1129
  return;
908
1130
  }
909
- writeLine(io.stdout, `created: ${planesPath} (${inference.config.rules.length} rule(s) inferred from model directories — review the reasons before the next gateforge run)`);
1131
+ writeLine(io.stdout, `created: ${planesPath} (${combined.length} rule(s) — ${inference.config?.rules.length ?? 0} inferred from model directories, ` +
1132
+ `${routeRules.length} answered for route folders — review the reasons before the next gateforge run)`);
1133
+ }
1134
+ /**
1135
+ * The engine-owned state directories that must never be committed.
1136
+ *
1137
+ * `.gateforge/test-gates/` holds everything a supervised run caches and
1138
+ * seals: the test catalog, plugin caches, receipts, records, spool and
1139
+ * history. The engine writes it on every `check`/`test-gates`/`next`,
1140
+ * so after `init` the very next `git add -A` staged it — and then the
1141
+ * gate, quite correctly, reported the engine's own cache as unmapped
1142
+ * product changes. Nothing else under `.gateforge/` is engine state:
1143
+ * policies, adapters, waivers, baselines, hooks and the CI template are
1144
+ * owner-reviewed files that MUST be committed.
1145
+ */
1146
+ const ENGINE_STATE_IGNORE_ENTRIES = [`${DEFAULT_STATE_DIR}/`];
1147
+ /**
1148
+ * Whether a `.gitignore` already covers one engine-state entry.
1149
+ *
1150
+ * Comparison is line-wise and tolerant of the forms a human writes
1151
+ * (leading `/`, a trailing `/`, surrounding spaces, a comment) so a
1152
+ * repeated `init` never appends the same rule twice.
1153
+ *
1154
+ * Args:
1155
+ * text: the current `.gitignore` contents (empty when absent).
1156
+ * entry: the repo-relative directory to ignore.
1157
+ *
1158
+ * Returns:
1159
+ * boolean: true when the file already ignores that path.
1160
+ */
1161
+ function ignoresEngineState(text, entry) {
1162
+ const wanted = entry.replace(/\/+$/, '');
1163
+ return text.split('\n').some((line) => {
1164
+ const trimmed = line.trim().replace(/^\/+|\/+$/g, '');
1165
+ return trimmed === wanted || trimmed === `${wanted}/**`;
1166
+ });
1167
+ }
1168
+ /**
1169
+ * Adds the engine-owned state directories to the repository's
1170
+ * `.gitignore`, creating the file when absent and appending when
1171
+ * present. The owner's own lines are preserved byte for byte and a
1172
+ * second run reports "already ignored" instead of appending again.
1173
+ *
1174
+ * Args:
1175
+ * io: process context.
1176
+ * cwd: absolute repository root.
1177
+ *
1178
+ * Returns:
1179
+ * void.
1180
+ */
1181
+ function ignoreEngineState(io, cwd) {
1182
+ const path = join(cwd, '.gitignore');
1183
+ const existed = existsSync(path);
1184
+ const existing = existed ? readFileSync(path, 'utf8') : '';
1185
+ const missing = ENGINE_STATE_IGNORE_ENTRIES.filter((entry) => !ignoresEngineState(existing, entry));
1186
+ if (missing.length === 0) {
1187
+ if (existed) {
1188
+ recordInitPath(io, cwd, path, 'preserved');
1189
+ writeLine(io.stdout, `exists, leaving untouched: ${path} (gateforge engine state already ignored)`);
1190
+ }
1191
+ return;
1192
+ }
1193
+ const block = [
1194
+ '# Gateforge engine state — never committed (regenerated by every run).',
1195
+ ...missing,
1196
+ '',
1197
+ ].join('\n');
1198
+ const prefix = existing.length === 0 || existing.endsWith('\n') ? existing : `${existing}\n`;
1199
+ writeFileSync(path, `${prefix}${block}`, 'utf8');
1200
+ recordInitPath(io, cwd, path, existed ? 'modified' : 'created');
1201
+ writeLine(io.stdout, `${existed ? 'updated' : 'created'}: ${path} (gateforge engine state ignored: ${missing.join(', ')} — ` +
1202
+ 'without this, `git add -A` stages the run cache and the gate blocks on its own files)');
910
1203
  }
911
1204
  /**
912
1205
  * Runs `gateforge init` in the io cwd.
@@ -922,7 +1215,7 @@ export async function initCommand(io, argv) {
922
1215
  // The ledger every writer below fills: the closing summary names only
923
1216
  // what THIS run created or kept, so it can never offer to delete the
924
1217
  // owner's pre-existing config, baselines, waivers, hooks or CI file.
925
- io.initPaths ??= { created: [], preserved: [] };
1218
+ io.initPaths ??= { created: [], modified: [], preserved: [] };
926
1219
  const { options } = parseArgs(argv);
927
1220
  if (options['help'] === true) {
928
1221
  writeLine(io.stdout, INIT_USAGE);
@@ -948,9 +1241,11 @@ export async function initCommand(io, argv) {
948
1241
  'planes',
949
1242
  'no-planes',
950
1243
  'behavior',
1244
+ 'unmatched-routes',
951
1245
  'no-behavior',
952
1246
  'behavior-packs',
953
1247
  'docs-exclude',
1248
+ 'docs-exclude-file',
954
1249
  'confirm-doc-exclusions',
955
1250
  'cache-exclude',
956
1251
  'confirm-cache-exclusions',
@@ -1044,15 +1339,18 @@ export async function initCommand(io, argv) {
1044
1339
  preflightStrictSetup(POLICIES_TEMPLATE);
1045
1340
  }
1046
1341
  // 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.
1342
+ // install; nothing extra is silently enabled. `--no-scan` skips the
1343
+ // filesystem walk and falls back to the language-derived set (and
1344
+ // claims nothing about how much code is there); `--languages` skips
1345
+ // only the language DERIVATION — the signals and the number of files
1346
+ // the walk really saw are still true.
1049
1347
  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);
1348
+ const walked = noScan ? null : scanRepo(io.cwd);
1349
+ const scan = walked === null
1350
+ ? { languages: explicitLanguages ?? ['python'], signals: [], reasons: undefined, files: 0 }
1351
+ : explicitLanguages === null
1352
+ ? walked
1353
+ : { ...walked, languages: explicitLanguages };
1056
1354
  // Which runner the scan saw. The `runner:` key is owner-owned, so it
1057
1355
  // is written ONLY when exactly one non-Playwright runner was detected:
1058
1356
  // Playwright stays the frozen default, and an ambiguous repository
@@ -1073,10 +1371,23 @@ export async function initCommand(io, argv) {
1073
1371
  return 0;
1074
1372
  }
1075
1373
  const cwd = io.cwd;
1374
+ // Which CI provider this repository ALREADY used, captured BEFORE any
1375
+ // CI file is written by this run: a repository that shows no provider
1376
+ // at all gets both sets of instructions, and after wiring
1377
+ // `.gitlab-ci.yml` always exists — the question would then be answered
1378
+ // by us rather than read from the repository.
1379
+ const ciProviderBeforeWiring = detectCiProvider(cwd);
1076
1380
  // Whether `.gateforge.yml` was already there BEFORE this run: the
1077
1381
  // preset summary must tell the truth about what changed.
1078
1382
  const existedConfigAtStart = existsSync(join(io.cwd, '.gateforge.yml'));
1079
1383
  const historyRetentionDays = existsSync(join(cwd, '.gateforge.yml')) ? undefined : await resolveHistoryRetention(io);
1384
+ // How a NEW repository grades unmatched by-id routes (0.9.0, owner
1385
+ // decision D7). Asked once, in a terminal; `warn` and the exact key to
1386
+ // choose `block` on a non-interactive run; an existing config is left
1387
+ // alone and keeps the `check`/`next` banner asking.
1388
+ const unmatchedRoutes = await resolveUnmatchedRoutes(io, options, existedConfigAtStart);
1389
+ if (unmatchedRoutes.note !== undefined)
1390
+ writeLine(io.stdout, unmatchedRoutes.note);
1080
1391
  const languages = scan.languages;
1081
1392
  const pluginIds = recommended;
1082
1393
  const configOptions = {
@@ -1091,6 +1402,8 @@ export async function initCommand(io, argv) {
1091
1402
  strictnessMode: goal?.settings.strictnessMode,
1092
1403
  // The scanned runner, when it is unambiguous and not Playwright.
1093
1404
  runner: detectedRunner,
1405
+ // The owner's answer for unmatched by-id routes; undefined writes no key.
1406
+ unmatchedRoutes: unmatchedRoutes.mode,
1094
1407
  };
1095
1408
  const generatedDraftConfig = () => parseConfig(parseYaml(configTemplate(languages, pluginIds, configOptions)), { file: '.gateforge.yml' });
1096
1409
  let draftConfig;
@@ -1170,10 +1483,27 @@ export async function initCommand(io, argv) {
1170
1483
  ]
1171
1484
  : []),
1172
1485
  ];
1486
+ /**
1487
+ * Queues one scaffold file, keyed by path. Two steps of the same run
1488
+ * can want the SAME file with different content (the config and the
1489
+ * config-with-behaviorPolicy); pushing both made the second entry
1490
+ * report "exists, leaving untouched" about a file the same run had
1491
+ * just created, and silently dropped the richer content. The later
1492
+ * entry wins, in the later entry's position, so exactly one line per
1493
+ * file is ever printed and the fullest content is what lands.
1494
+ */
1495
+ const pushTarget = (target) => {
1496
+ const existing = targets.findIndex((candidate) => candidate.path === target.path);
1497
+ if (existing === -1) {
1498
+ targets.push(target);
1499
+ return;
1500
+ }
1501
+ targets[existing] = target;
1502
+ };
1173
1503
  if (docsExclusionChoice.changed) {
1174
1504
  const exclusionPath = join(cwd, ...DOCS_EXCLUSIONS_PATH.split('/'));
1175
1505
  const exclusionText = renderDocsExclusions(docsExclusionChoice.folders);
1176
- targets.push({
1506
+ pushTarget({
1177
1507
  path: exclusionPath,
1178
1508
  label: 'owner-declared documentation exclusions',
1179
1509
  write: () => {
@@ -1193,7 +1523,7 @@ export async function initCommand(io, argv) {
1193
1523
  if (cacheExclusionChoice.changed) {
1194
1524
  const exclusionPath = join(cwd, ...CACHE_EXCLUSIONS_PATH.split('/'));
1195
1525
  const exclusionText = renderCacheExclusions(cacheExclusionChoice.files);
1196
- targets.push({
1526
+ pushTarget({
1197
1527
  path: exclusionPath,
1198
1528
  label: 'owner-declared Python bytecode exclusions',
1199
1529
  write: () => {
@@ -1274,14 +1604,14 @@ export async function initCommand(io, argv) {
1274
1604
  }
1275
1605
  }
1276
1606
  else {
1277
- targets.push({
1607
+ pushTarget({
1278
1608
  path: behaviorPath,
1279
1609
  label: 'complete-behavior document (SCAFFOLD — not approval)',
1280
1610
  write: () => writeFileSync(behaviorPath, template, 'utf8'),
1281
1611
  });
1282
1612
  }
1283
1613
  if (!existsSync(join(cwd, '.gateforge.yml'))) {
1284
- targets.push({
1614
+ pushTarget({
1285
1615
  path: join(cwd, '.gateforge.yml'),
1286
1616
  label: 'config (with behaviorPolicy)',
1287
1617
  write: () => {
@@ -1316,7 +1646,7 @@ export async function initCommand(io, argv) {
1316
1646
  const added = loadConfig(configPath).plugins
1317
1647
  .map((plugin) => plugin.id)
1318
1648
  .filter((id) => explicitPlugins.includes(id));
1319
- recordInitPath(io, cwd, configPath, 'preserved');
1649
+ recordInitPath(io, cwd, configPath, 'modified');
1320
1650
  writeLine(io.stdout, `updated: ${configPath} (added detector(s): ${added.join(', ')} — every other key left as it was)`);
1321
1651
  }
1322
1652
  }
@@ -1325,6 +1655,7 @@ export async function initCommand(io, argv) {
1325
1655
  if ((target.label === 'owner-declared documentation exclusions' && docsExclusionChoice.changed) ||
1326
1656
  (target.label === 'owner-declared Python bytecode exclusions' && cacheExclusionChoice.changed)) {
1327
1657
  target.write();
1658
+ recordInitPath(io, cwd, target.path, 'modified');
1328
1659
  writeLine(io.stdout, `updated: ${target.path}`);
1329
1660
  continue;
1330
1661
  }
@@ -1336,6 +1667,10 @@ export async function initCommand(io, argv) {
1336
1667
  recordInitPath(io, cwd, target.path, 'created');
1337
1668
  writeLine(io.stdout, `created: ${target.path}`);
1338
1669
  }
1670
+ // Engine-owned state is never a product change: without this the
1671
+ // first `git add -A` stages the run cache the gate just wrote, and the
1672
+ // gate then blocks on its own files.
1673
+ ignoreEngineState(io, cwd);
1339
1674
  // Observe proof checklist (observe proof only): the work no scaffold
1340
1675
  // can do — proxy wiring, adapter bindings, and kind declarations.
1341
1676
  if (proofMode === 'observe') {
@@ -1379,7 +1714,11 @@ export async function initCommand(io, argv) {
1379
1714
  const planesRequested = options['planes'] === true;
1380
1715
  if (planesRequested || languages.includes('python')) {
1381
1716
  if (await resolvePlanes(io, options)) {
1382
- await proposePlanesConfig(cwd, io);
1717
+ // The route folders are asked in the SAME flow, right before the
1718
+ // model folders are written, so both sets of answers land in one
1719
+ // reviewed `.gateforge/planes.json`.
1720
+ const routeRules = await askRouteFolderPlanes(cwd, io);
1721
+ await proposePlanesConfig(cwd, io, routeRules);
1383
1722
  }
1384
1723
  }
1385
1724
  // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
@@ -1516,7 +1855,7 @@ export async function initCommand(io, argv) {
1516
1855
  }
1517
1856
  writeLine(io.stdout, `${pushHook.status}: ${pushHook.detail}`);
1518
1857
  }
1519
- writeServerProtectionInstructions(io);
1858
+ writeServerProtectionInstructions(io, ciProviderBeforeWiring);
1520
1859
  }
1521
1860
  // A preset can ask for the CI job without a local hook (`normal`):
1522
1861
  // the server check is then the only place the gate runs, which is a
@@ -1531,12 +1870,20 @@ export async function initCommand(io, argv) {
1531
1870
  configExisted: existedConfigAtStart,
1532
1871
  autoChosen: goal.autoChosen === true,
1533
1872
  created: [...(ledger?.created ?? [])],
1873
+ modified: [...(ledger?.modified ?? [])],
1534
1874
  repoHasCommitHook: existsSync(join(cwd, '.git/hooks/pre-commit')),
1535
1875
  repoHasCi: existsSync(join(cwd, '.gitlab-ci.yml')) || existsSync(join(cwd, '.github/workflows/gateforge.yml')),
1536
1876
  })) {
1537
1877
  writeLine(io.stdout, line);
1538
1878
  }
1539
1879
  }
1880
+ // A repository that already had code before this run gets the
1881
+ // adoption path named HERE, where the owner is deciding what the
1882
+ // gate will do to them. `init` on a fresh project has no debt and
1883
+ // must not talk about adopting one.
1884
+ if (!existedConfigAtStart && scan.files > 0) {
1885
+ writeLine(io.stdout, ADOPT_ADVICE);
1886
+ }
1540
1887
  writeLine(io.stdout, 'skeleton ready: .gateforge/adapters, .gateforge/waivers, .gateforge/baselines');
1541
1888
  const alembicOptIn = renderAlembicOptIn(cwd);
1542
1889
  if (alembicOptIn !== null)