@gate-forge/cli 0.4.1 → 0.5.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 (88) hide show
  1. package/README.md +37 -11
  2. package/dist/args.js +1 -1
  3. package/dist/args.js.map +1 -1
  4. package/dist/broker.d.ts.map +1 -1
  5. package/dist/broker.js +73 -123
  6. package/dist/broker.js.map +1 -1
  7. package/dist/candidate-tree.d.ts +36 -0
  8. package/dist/candidate-tree.d.ts.map +1 -0
  9. package/dist/candidate-tree.js +321 -0
  10. package/dist/candidate-tree.js.map +1 -0
  11. package/dist/cli.d.ts +8 -2
  12. package/dist/cli.d.ts.map +1 -1
  13. package/dist/cli.js +17 -3
  14. package/dist/cli.js.map +1 -1
  15. package/dist/commands/adopt.js +2 -2
  16. package/dist/commands/adopt.js.map +1 -1
  17. package/dist/commands/check.d.ts.map +1 -1
  18. package/dist/commands/check.js +10 -3
  19. package/dist/commands/check.js.map +1 -1
  20. package/dist/commands/controller.d.ts +43 -0
  21. package/dist/commands/controller.d.ts.map +1 -0
  22. package/dist/commands/controller.js +110 -0
  23. package/dist/commands/controller.js.map +1 -0
  24. package/dist/commands/enforcement.d.ts.map +1 -1
  25. package/dist/commands/enforcement.js +61 -1
  26. package/dist/commands/enforcement.js.map +1 -1
  27. package/dist/commands/explain.d.ts.map +1 -1
  28. package/dist/commands/explain.js +2 -7
  29. package/dist/commands/explain.js.map +1 -1
  30. package/dist/commands/init.d.ts +6 -2
  31. package/dist/commands/init.d.ts.map +1 -1
  32. package/dist/commands/init.js +407 -60
  33. package/dist/commands/init.js.map +1 -1
  34. package/dist/commands/next.d.ts +15 -0
  35. package/dist/commands/next.d.ts.map +1 -0
  36. package/dist/commands/next.js +337 -0
  37. package/dist/commands/next.js.map +1 -0
  38. package/dist/commands/test-gates.d.ts +18 -0
  39. package/dist/commands/test-gates.d.ts.map +1 -1
  40. package/dist/commands/test-gates.js +157 -5
  41. package/dist/commands/test-gates.js.map +1 -1
  42. package/dist/commands/tests.js +114 -13
  43. package/dist/commands/tests.js.map +1 -1
  44. package/dist/evaluate.d.ts +8 -0
  45. package/dist/evaluate.d.ts.map +1 -1
  46. package/dist/evaluate.js +19 -10
  47. package/dist/evaluate.js.map +1 -1
  48. package/dist/execution.d.ts +20 -0
  49. package/dist/execution.d.ts.map +1 -1
  50. package/dist/execution.js +14 -2
  51. package/dist/execution.js.map +1 -1
  52. package/dist/input-snapshot.d.ts.map +1 -1
  53. package/dist/input-snapshot.js +4 -0
  54. package/dist/input-snapshot.js.map +1 -1
  55. package/dist/io.d.ts +3 -0
  56. package/dist/io.d.ts.map +1 -1
  57. package/dist/io.js.map +1 -1
  58. package/dist/isolation.d.ts +104 -0
  59. package/dist/isolation.d.ts.map +1 -0
  60. package/dist/isolation.js +353 -0
  61. package/dist/isolation.js.map +1 -0
  62. package/dist/mapping.d.ts +29 -9
  63. package/dist/mapping.d.ts.map +1 -1
  64. package/dist/mapping.js +37 -10
  65. package/dist/mapping.js.map +1 -1
  66. package/dist/pipeline.d.ts +14 -4
  67. package/dist/pipeline.d.ts.map +1 -1
  68. package/dist/pipeline.js +64 -7
  69. package/dist/pipeline.js.map +1 -1
  70. package/dist/podman-bootstrap.d.ts +59 -0
  71. package/dist/podman-bootstrap.d.ts.map +1 -0
  72. package/dist/podman-bootstrap.js +123 -0
  73. package/dist/podman-bootstrap.js.map +1 -0
  74. package/dist/receipts.d.ts +8 -0
  75. package/dist/receipts.d.ts.map +1 -1
  76. package/dist/receipts.js +4 -0
  77. package/dist/receipts.js.map +1 -1
  78. package/dist/repo-scan.d.ts +63 -0
  79. package/dist/repo-scan.d.ts.map +1 -0
  80. package/dist/repo-scan.js +272 -0
  81. package/dist/repo-scan.js.map +1 -0
  82. package/dist/scope.d.ts.map +1 -1
  83. package/dist/scope.js +3 -0
  84. package/dist/scope.js.map +1 -1
  85. package/dist/state.d.ts.map +1 -1
  86. package/dist/state.js +2 -7
  87. package/dist/state.js.map +1 -1
  88. package/package.json +9 -9
@@ -18,20 +18,47 @@
18
18
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
19
19
  import { createInterface } from 'node:readline/promises';
20
20
  import { join } from 'node:path';
21
- import { parse as parseYaml } from 'yaml';
21
+ import { parse as parseYaml, parseDocument } from 'yaml';
22
22
  import { ClassificationPolicySchema, PolicyFileSchema, loadConfig, parseConfig, serializeBaseline, strictCapabilityGaps, } from '@gate-forge/core';
23
23
  import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, PACK_VERSION as PACK_SQLALCHEMY_VERSION, } from '@gate-forge/pack-sqlalchemy';
24
24
  import { PACK_VERSION as PACK_FASTAPI_VERSION } from '@gate-forge/pack-fastapi';
25
25
  import { PACK_VERSION as PACK_HTTP_VERSION } from '@gate-forge/pack-http';
26
26
  import { PACK_VERSION as PACK_TASK_VERSION } from '@gate-forge/pack-task';
27
- import { parseArgs } from '../args.js';
27
+ import { parseArgs, stringFlag } from '../args.js';
28
+ import { ensurePodman } from '../podman-bootstrap.js';
28
29
  import { writeLine } from '../io.js';
29
30
  import { UsageError } from '../errors.js';
31
+ import { languageDefaultPlugins, recommendPlugins, renderScanBlock, scanRepo } from '../repo-scan.js';
32
+ import { rejectUnknownFlags } from './common.js';
30
33
  import { expandIncludePaths } from '../glob.js';
31
34
  import { inferPlanesConfig } from '../planes-inference.js';
32
35
  import { installCommitHook, writeStandaloneGateScript } from '../git-hooks.js';
33
36
  import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation } from './blocking.js';
34
- export const INIT_USAGE = 'usage: gateforge init [--languages <comma,list>] [--blocking] [--pre-commit] [--mode changed|staged] [--ci] [--no-ci] [--strict-e2e] [--planes]';
37
+ export const INIT_USAGE = 'usage: gateforge init [--languages <comma,list>] [--plugins <comma,list>] [--accept-recommended] ' +
38
+ '[--no-scan] [--proof overlay|observe] [--blocking] [--pre-commit] [--mode changed|staged] [--ci] [--no-ci] ' +
39
+ '[--strict-e2e] [--managed] [--planes] [--behavior]';
40
+ /** Template for the complete-behavior owner document (plan §4.1). */
41
+ export const BEHAVIOR_TEMPLATE = `\
42
+ # Complete-behavior owner document (plan §4.1).
43
+ # Presence of this file enables the complete-behavior profile: every
44
+ # discovered endpoint must have an approved declaration (cases or an
45
+ # owner disposition). There is no warnOnly or silent fallback.
46
+ #
47
+ # This scaffold is NOT approval: fill in real cases per endpoint, then
48
+ # run 'gateforge check' — missing declarations block with
49
+ # ENDPOINT_BEHAVIOR_MISSING until you define them.
50
+ schemaVersion: 1
51
+ endpoints: []
52
+ resources: []
53
+ `;
54
+ /** The behavior-setup checklist: the work no scaffold can do. */
55
+ export const BEHAVIOR_CHECKLIST = [
56
+ 'behavior setup is NOT complete: this scaffold only enables the profile',
57
+ 'next: run `gateforge check` — every discovered endpoint is listed as ENDPOINT_BEHAVIOR_MISSING',
58
+ 'next: for each endpoint, declare cases (or an owner disposition) in .gateforge/behavior.yml',
59
+ 'next: map each case to a test with `tests mark --case`, then prove it through the witness',
60
+ 'note: strong HTTP contracts stay blocking until witness-produced case evidence exists',
61
+ ].map((line) => ` ${line}`).join('\n');
35
62
  const BUNDLED_PLUGIN_MODULES = Object.freeze({
36
63
  'gateforge.pack-fastapi': '@gate-forge/pack-fastapi',
37
64
  'gateforge.pack-http': '@gate-forge/pack-http',
@@ -52,9 +79,18 @@ const BUNDLED_PLUGIN_VERSIONS = Object.freeze({
52
79
  'gateforge.pack-sqlalchemy': PACK_SQLALCHEMY_VERSION,
53
80
  'gateforge.pack-task': PACK_TASK_VERSION,
54
81
  });
82
+ /**
83
+ * The bundled plugin ids init may write (the four trusted detector
84
+ * packs). `gateforge.pack-task` carries no semantic verifier, so it is
85
+ * opt-in only via `--plugins` — never recommended, never defaulted.
86
+ */
87
+ const KNOWN_BUNDLED_PLUGIN_IDS = new Set(Object.keys(BUNDLED_PLUGIN_MODULES));
55
88
  /**
56
89
  * Selects the bundled detectors required by the generated coverage and
57
90
  * trusted-entry-point rules for the requested source languages.
91
+ * `gateforge.pack-task` is NEVER included: it has no semantic verifier
92
+ * (every contract grades VERIFIER_UNSUPPORTED), so it is opt-in only
93
+ * via `--plugins`.
58
94
  *
59
95
  * Args:
60
96
  * languages (readonly string[]): Languages selected by `gateforge init`.
@@ -63,20 +99,11 @@ const BUNDLED_PLUGIN_VERSIONS = Object.freeze({
63
99
  * string[]: Deterministically ordered bundled detector ids.
64
100
  */
65
101
  function bundledPluginIds(languages) {
66
- const normalized = new Set(languages.map((language) => language.toLowerCase()));
67
- const ids = ['gateforge.pack-task'];
68
- if (normalized.has('python')) {
69
- ids.unshift('gateforge.pack-sqlalchemy');
70
- ids.unshift('gateforge.pack-fastapi');
71
- }
72
- if (normalized.has('javascript') || normalized.has('typescript')) {
73
- ids.splice(ids.length - 1, 0, 'gateforge.pack-http');
74
- }
75
- return ids;
102
+ return languageDefaultPlugins(languages);
76
103
  }
77
104
  /** Renders the trusted bundled plugin entries for `.gateforge.yml`. */
78
- function pluginsTemplate(languages) {
79
- return bundledPluginIds(languages)
105
+ function pluginsTemplate(pluginIds) {
106
+ return pluginIds
80
107
  .map((id) => ` - id: ${id}\n version: '${BUNDLED_PLUGIN_VERSIONS[id]}'\n transport: in-process\n module: '${BUNDLED_PLUGIN_MODULES[id]}'`)
81
108
  .join('\n');
82
109
  }
@@ -141,27 +168,12 @@ export const POLICIES_TEMPLATE = `\
141
168
  # and are graded on the witness's own engine-side observation.
142
169
  # UI-semantic crud:* contracts intentionally fail closed (no
143
170
  # witness-controlled UI observation channel exists yet) — add them only
144
- # deliberately.
171
+ # deliberately. Endpoint proof stays transport-only and opt-in
172
+ # (TRANSPORT_ONLY_POLICY_EXAMPLE below): 'http:frontend-request-observed'
173
+ # has no independent browser/test observation channel, so it is NEVER a
174
+ # starter requirement.
145
175
  schemaVersion: 1
146
176
  policies:
147
- - id: frontend-consumed-endpoints
148
- # ADR 0004 D8 + plan §8 / D1: only endpoints the frontend actually
149
- # consumes (static join) owe browser-exercise obligations;
150
- # server-only routes never do. NOTE: 'http:frontend-request-observed'
151
- # is BLOCKING with the current observer — no independent
152
- # browser/test observation channel exists yet, so the verifier
153
- # returns missing before examining evidence (test attribution is
154
- # suite-claimed). Keep this requirement to hold the frontend-proof
155
- # bar; or SEPARATELY opt in to the narrower transport-only policy
156
- # (TRANSPORT_ONLY_POLICY_EXAMPLE: 'http:request-observed', proving
157
- # only a witness-observed HTTP exchange) when that smaller guarantee
158
- # suffices. Never auto-migrate policies, baselines, or waivers.
159
- when:
160
- kind: http.endpoint
161
- consumed: true
162
- require:
163
- - http:frontend-request-observed
164
- - http:response-status-ok
165
177
  # Capability-scoped endpoint policies (workflow/validation/...) may be added
166
178
  # ONLY when the owning pack ships an engine-owned state-observing producer;
167
179
  # until then those contracts cannot be honestly evidenced and stay blocking.
@@ -186,24 +198,45 @@ policies:
186
198
  * scope every closed-world proof, trusted categories name the internal
187
199
  * entry points an internality certificate may rely on. Organization
188
200
  * internal rules and declaration syntax go here too.
201
+ *
202
+ * Task-scoped rules (the `linkage.task` coverage rule and the worker
203
+ * entry-point detector binding) are emitted ONLY when `pack-task` is in
204
+ * the selected plugin set: a coverage rule or detector binding naming an
205
+ * unconfigured detector fails every run closed, and task is opt-in
206
+ * (no semantic verifier).
189
207
  */
190
- function classificationPolicyTemplate(languages) {
208
+ function classificationPolicyTemplate(languages, pluginIds) {
209
+ const selected = new Set(pluginIds);
210
+ const taskSelected = selected.has('gateforge.pack-task');
211
+ const httpSelected = selected.has('gateforge.pack-http');
212
+ const sqlalchemySelected = selected.has('gateforge.pack-sqlalchemy');
191
213
  const coverageRules = [];
192
214
  // Capabilities (red-team round 6): a rule grants a capability over its
193
215
  // files. Model/task discovery NEVER grants exposure, and no generated
194
216
  // rule declares `exhaustive: true` — today's detectors are heuristics,
195
217
  // so generated policies keep the internality certificate UNAVAILABLE
196
218
  // until the organization asserts an exhaustive exposure parser itself.
197
- if (languages.includes('typescript') || languages.includes('javascript') || languages.includes('node')) {
219
+ // Every rule names a detector from the SELECTED plugin set: a rule
220
+ // naming an unconfigured detector fails every run closed.
221
+ if (httpSelected &&
222
+ (languages.includes('typescript') || languages.includes('javascript') || languages.includes('node'))) {
198
223
  coverageRules.push(` - capability: exposure.http\n detector: gateforge.pack-http\n appliesTo:\n - '**/*.ts'\n - '**/*.js'\n - '**/*.tsx'\n - '**/*.jsx'\n - '**/*.mjs'\n - '**/*.cjs'`);
199
- coverageRules.push(` - capability: linkage.task\n detector: gateforge.pack-task\n appliesTo:\n - '**/*.ts'\n - '**/*.js'\n - '**/*.tsx'\n - '**/*.jsx'\n - '**/*.mjs'\n - '**/*.cjs'`);
224
+ if (taskSelected) {
225
+ coverageRules.push(` - capability: linkage.task\n detector: gateforge.pack-task\n appliesTo:\n - '**/*.ts'\n - '**/*.js'\n - '**/*.tsx'\n - '**/*.jsx'\n - '**/*.mjs'\n - '**/*.cjs'`);
226
+ }
200
227
  }
201
- if (languages.includes('python')) {
228
+ if (sqlalchemySelected && languages.includes('python')) {
202
229
  // Model discovery is NOT an exposure capability: python exposure stays
203
230
  // uncovered until an exhaustive python exposure detector exists.
204
231
  coverageRules.push(` - capability: models.sqlalchemy\n detector: gateforge.pack-sqlalchemy\n appliesTo:\n - '**/*.py'`);
205
232
  }
206
233
  const coverageBlock = coverageRules.length > 0 ? `coverage:\n${coverageRules.join('\n')}` : 'coverage: []';
234
+ // The worker entry-point category keeps its detector binding only when
235
+ // task is selected; otherwise it is an unbound category (can never
236
+ // certify reachability) rather than a fail-closed dangling reference.
237
+ const workerEntry = taskSelected
238
+ ? ` - category: worker\n patterns: ['**/workers/**', '**/jobs/**']\n # Reachability is only honored from this bundled detector (round 5).\n detector: gateforge.pack-task`
239
+ : ` - category: worker\n patterns: ['**/workers/**', '**/jobs/**']\n # No detector binding: task is opt-in (no semantic verifier), so this\n # category can never certify reachability until pack-task is selected.`;
207
240
  return `\
208
241
  # Repository-wide deterministic classification rules (ADR 0003 D5).
209
242
  # Effective classifications are computed automatically from detector
@@ -218,10 +251,7 @@ scanRoots:
218
251
  # Entry-point categories trusted as internal reachability (an internality
219
252
  # certificate may rely only on these).
220
253
  trustedInternalEntryPoints:
221
- - category: worker
222
- patterns: ['**/workers/**', '**/jobs/**']
223
- # Reachability is only honored from this bundled detector (round 5).
224
- detector: gateforge.pack-task
254
+ ${workerEntry}
225
255
  # Categories WITHOUT a detector binding can never certify: no plugin may
226
256
  # assert their reachability. Bind one when a bundled detector exists.
227
257
  - category: migration
@@ -246,15 +276,15 @@ volatileFields:
246
276
  `;
247
277
  }
248
278
  /** Builds the `.gateforge.yml` document for the requested languages. */
249
- function configTemplate(languages, options = {}) {
250
- const enforcementBlock = options.strictE2E === true
279
+ function configTemplate(languages, pluginIds, options = {}) {
280
+ const enforcementBlock = options.strictE2E === true || options.managed === true
251
281
  ? `# Enforcement modes (plan §3.4/§3.3, ADR 0005): 'standard' = local hook +
252
282
  # mandatory trusted server check (honest about --no-verify); 'managed' =
253
283
  # additionally puts the authoritative commit service outside the agent's
254
284
  # write/process boundary. strictE2E makes waived/baselined in-scope E2E
255
285
  # obligations NOT proof (they block with ENFORCEMENT_UNTRUSTED).
256
286
  enforcement:
257
- mode: standard
287
+ mode: ${options.managed === true ? 'managed' : 'standard'}
258
288
  strictE2E: true
259
289
  `
260
290
  : '';
@@ -281,7 +311,7 @@ ${sourceIncludePatterns(languages).map((pattern) => ` - '${pattern}'`).join
281
311
  # Detector plugins. Bundled detectors are preconfigured for the selected
282
312
  # languages and are loaded from their trusted package entry points.
283
313
  plugins:
284
- ${pluginsTemplate(languages)}
314
+ ${pluginsTemplate(pluginIds)}
285
315
  policies: .gateforge/policies.yml
286
316
  classificationPolicy: .gateforge/classification-policy.yml
287
317
  adapters: .gateforge/adapters
@@ -296,6 +326,39 @@ clock:
296
326
  ${enforcementBlock}\
297
327
  `;
298
328
  }
329
+ /**
330
+ * Upgrades an existing config only when the owner explicitly selects
331
+ * `init --managed`; ordinary init remains strictly non-destructive.
332
+ *
333
+ * Args:
334
+ * configPath (string): absolute path to the existing config.
335
+ *
336
+ * Returns:
337
+ * boolean: whether the file changed.
338
+ *
339
+ * Throws:
340
+ * UsageError: when the existing YAML or resulting config is invalid.
341
+ */
342
+ function upgradeManagedConfig(configPath) {
343
+ const document = parseDocument(readFileSync(configPath, 'utf8'));
344
+ if (document.errors.length > 0) {
345
+ throw new UsageError(`managed initialization cannot update '${configPath}': ${document.errors.map((error) => error.message).join('; ')}`);
346
+ }
347
+ const currentMode = document.getIn(['enforcement', 'mode']);
348
+ const currentStrictE2E = document.getIn(['enforcement', 'strictE2E']);
349
+ if (currentMode === 'managed' && currentStrictE2E === true)
350
+ return false;
351
+ document.setIn(['enforcement', 'mode'], 'managed');
352
+ document.setIn(['enforcement', 'strictE2E'], true);
353
+ try {
354
+ parseConfig(document.toJS(), { file: configPath });
355
+ }
356
+ catch (cause) {
357
+ throw new UsageError(`managed initialization cannot update '${configPath}': ${cause instanceof Error ? cause.message : String(cause)}`);
358
+ }
359
+ writeFileSync(configPath, document.toString(), 'utf8');
360
+ return true;
361
+ }
299
362
  /**
300
363
  * Strict-setup preflight (plan Phase 0 item 4, ADR 0005 D1): when the
301
364
  * requested setup enables strict E2E mode, every contract its policies
@@ -491,6 +554,104 @@ function writeGitlabCiTemplate(io) {
491
554
  writeFileSync(gitlabCi, `${current.endsWith('\n') ? current : current + '\n'}include:\n${local}\n`);
492
555
  writeLine(io.stdout, `updated: ${gitlabCi} (include appended)`);
493
556
  }
557
+ /**
558
+ * The agent skill file init writes at the repo root (only when absent).
559
+ * One loop, one action, no self-approval — the overlay-first contract.
560
+ */
561
+ const GATEFORGE_MD_TEMPLATE = `# GATEFORGE.md — agent loop (written by \`gateforge init\`; safe to edit)
562
+
563
+ You are gated by Gateforge. Work one blocking item at a time.
564
+
565
+ ## The loop
566
+
567
+ 1. If blocked, run \`gateforge next\` (or \`gateforge next --json\` for machines).
568
+ 2. Read the single \`next:\` block: \`cause\`, \`why\`, and exactly one \`do:\` line.
569
+ 3. Do the single \`do:\` line. Stop. Re-run \`gateforge next\`.
570
+
571
+ \`next\` prints ONE action — never a dump. Mapping is intent, not proof.
572
+
573
+ ## Proof lives in the overlay
574
+
575
+ - New proof tests go in \`tests/e2e/gateforge/\` (engine-driven fixture:
576
+ \`evidence.ui.*\` + \`persistence.verify\`).
577
+ - Never rewrite existing \`tests/e2e/**\` journeys into \`evidence.ui\`.
578
+ - Never run \`gateforge tests mark\` as proof — mappings declare intent;
579
+ only witnessed overlay evidence satisfies an obligation.
580
+ - \`tests suggest\` is inspection, not a gate.
581
+
582
+ ## Never self-approve
583
+
584
+ - Never edit \`.gateforge/policies.yml\`, \`coveragePolicy\`, waivers,
585
+ baselines, or plugin lists to make the gate pass. Those are
586
+ owner-controlled; an agent edit never authorizes weaker checks.
587
+ - Coverage dispositions are owner acts. Strict-E2E waivers are not proof.
588
+
589
+ ## Capability gaps
590
+
591
+ - \`VERIFIER_UNSUPPORTED\` means no honest proof channel exists: tell the
592
+ human (remove the contract from \`.gateforge/policies.yml\` or drop the
593
+ pack). Do not invent tests for it.
594
+ - \`http:frontend-request-observed\` has no independent browser channel;
595
+ transport-only \`http:request-observed\` is a separate, weaker opt-in.
596
+ - Observe proof (\`--proof observe\`): existing suite-driven browser tests
597
+ prove persistence via the witness (proxy traffic + independent adapter
598
+ read) once mapped \`--kind observed-e2e\`. Weaker than overlay by
599
+ design — proves "the server stored it", not "the engine typed it".
600
+ `;
601
+ /**
602
+ * The overlay proof-directory README init scaffolds (only when absent):
603
+ * what the overlay is, and where the fixture shape is documented.
604
+ */
605
+ const OVERLAY_README_TEMPLATE = `# tests/e2e/gateforge/ — overlay proof tests
606
+
607
+ Thin engine-driven tests that prove persistence obligations. They use the
608
+ Gateforge Playwright fixture (\`evidence.ui.*\` + \`persistence.verify\`)
609
+ with a surface map — they do NOT rewrite existing journeys.
610
+
611
+ - New proof tests go here: \`tests/e2e/gateforge/<resource>.<op>.spec.js\`.
612
+ - Do not rewrite existing \`tests/e2e/**\` journeys into \`evidence.ui\`.
613
+ - Do not use \`gateforge tests mark\` as proof: mappings are intent, not proof.
614
+ - Fixture shape: \`example/e2e/accounts-crud-journey.spec.js\` in the
615
+ gateforge monorepo and the \`@gate-forge/pack-playwright\` README.
616
+ `;
617
+ /**
618
+ * The Observe proof checklist init prints (never writes) for
619
+ * `--proof observe`: the per-repo wiring no scaffold can do. Each step
620
+ * is owner/agent work; the gate stays blocking until all three hold.
621
+ */
622
+ const OBSERVE_CHECKLIST = `observe proof checklist (existing suite through the witness — no new tests):
623
+ 1. Point the Playwright config baseURL at the witness session proxy
624
+ (GATEFORGE_APP_BASE_URL) so browser traffic is attributable to its test.
625
+ 2. Give each .gateforge/adapters/<name>.mjs an \`observe\` binding
626
+ ({create/read/update/delete: {method, path}}, {id} on id-bearing
627
+ routes) plus list() for before-snapshots.
628
+ 3. Map existing tests with \`gateforge tests mark --kind observed-e2e\`
629
+ (suite-driven browser tests only — fixture tests stay overlay).
630
+ 4. Run \`gateforge test-gates --changed\`, then \`gateforge check --require-e2e\`.
631
+ Honest scope: proves persistence (the server stored what the proxied
632
+ request sent), not "the engine typed the form".`;
633
+ /**
634
+ * Asks (TTY only) whether init should write the recommended setup.
635
+ * Flags win: `--accept-recommended` forces yes, `--plugins` (an explicit
636
+ * choice) skips the prompt, and non-interactive runs default to yes —
637
+ * writing the recommended set with a tip, never hanging on a prompt.
638
+ */
639
+ async function resolveRecommended(io, options) {
640
+ if (options['accept-recommended'] === true)
641
+ return true;
642
+ if (!process.stdin.isTTY) {
643
+ writeLine(io.stdout, 'tip: re-run with --plugins <comma,list> to change detectors');
644
+ return true;
645
+ }
646
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
647
+ try {
648
+ const answer = (await rl.question('Enable recommended setup? [Y/n] ')).trim().toLowerCase();
649
+ return answer === '' || answer === 'y' || answer === 'yes';
650
+ }
651
+ finally {
652
+ rl.close();
653
+ }
654
+ }
494
655
  /**
495
656
  * Asks (TTY only) whether gateforge should be a blocking gate. Flags win:
496
657
  * --blocking forces yes, --no-blocking forces no, and non-interactive
@@ -604,29 +765,136 @@ export async function initCommand(io, argv) {
604
765
  writeLine(io.stdout, INIT_USAGE);
605
766
  return 0;
606
767
  }
768
+ rejectUnknownFlags(options, [
769
+ 'languages',
770
+ 'plugins',
771
+ 'accept-recommended',
772
+ 'no-scan',
773
+ 'proof',
774
+ 'blocking',
775
+ 'no-blocking',
776
+ 'pre-commit',
777
+ 'no-pre-commit',
778
+ 'mode',
779
+ 'ci',
780
+ 'no-ci',
781
+ 'strict-e2e',
782
+ 'managed',
783
+ 'planes',
784
+ 'no-planes',
785
+ 'behavior',
786
+ 'help',
787
+ ], INIT_USAGE);
788
+ // --proof validation BEFORE any writes: the selected proof path
789
+ // (overlay default, observe reuses the existing suite).
790
+ const proofValue = options['proof'];
791
+ if (proofValue !== undefined) {
792
+ if (typeof proofValue !== 'string' || Array.isArray(proofValue)) {
793
+ throw new UsageError(`flag '--proof' may only be given once`);
794
+ }
795
+ if (proofValue !== 'overlay' && proofValue !== 'observe') {
796
+ throw new UsageError(`flag '--proof' must be 'overlay' or 'observe' (got '${proofValue}')`);
797
+ }
798
+ }
799
+ const proofMode = proofValue === 'observe' ? 'observe' : 'overlay';
800
+ // --plugins validation BEFORE any writes: explicit ids must be known.
801
+ const pluginsValue = options['plugins'];
802
+ if (pluginsValue !== undefined && (typeof pluginsValue === 'boolean' || Array.isArray(pluginsValue))) {
803
+ throw new UsageError(`flag '--plugins' may only be given once`);
804
+ }
805
+ let explicitPlugins = null;
806
+ if (typeof pluginsValue === 'string') {
807
+ const seen = new Set();
808
+ explicitPlugins = [];
809
+ for (const raw of pluginsValue.split(',')) {
810
+ const id = raw.trim();
811
+ if (id.length === 0)
812
+ continue;
813
+ if (!KNOWN_BUNDLED_PLUGIN_IDS.has(id)) {
814
+ throw new UsageError(`unknown plugin '${id}' (known bundled ids: ${[...KNOWN_BUNDLED_PLUGIN_IDS].sort().join(', ')})`);
815
+ }
816
+ if (!seen.has(id)) {
817
+ seen.add(id);
818
+ explicitPlugins.push(id);
819
+ }
820
+ }
821
+ }
607
822
  const languagesValue = options['languages'];
608
823
  if (typeof languagesValue === 'boolean' || Array.isArray(languagesValue)) {
609
824
  throw new UsageError(`flag '--languages' may only be given once`);
610
825
  }
611
- const languages = (languagesValue ?? 'python')
612
- .split(',')
613
- .map((language) => language.trim().toLowerCase())
614
- .filter((language) => language.length > 0);
615
- if (languages.length === 0) {
826
+ const explicitLanguages = languagesValue === undefined
827
+ ? null
828
+ : languagesValue
829
+ .split(',')
830
+ .map((language) => language.trim().toLowerCase())
831
+ .filter((language) => language.length > 0);
832
+ if (explicitLanguages !== null && explicitLanguages.length === 0) {
616
833
  throw new UsageError(`flag '--languages' requires at least one language`);
617
834
  }
618
- const strictE2E = options['strict-e2e'] === true;
835
+ const managed = options['managed'] === true;
836
+ if (typeof options['managed'] !== 'boolean' && options['managed'] !== undefined) {
837
+ throw new UsageError(`flag '--managed' must be a boolean flag`);
838
+ }
839
+ if (managed && options['no-blocking'] === true) {
840
+ throw new UsageError(`flag '--managed' requires the existing blocking initialization wiring`);
841
+ }
842
+ const strictE2E = options['strict-e2e'] === true || managed;
619
843
  if (typeof options['strict-e2e'] !== 'boolean' && options['strict-e2e'] !== undefined) {
620
844
  throw new UsageError(`flag '--strict-e2e' must be a boolean flag`);
621
845
  }
846
+ // Managed bootstrap happens before any project file is written. The
847
+ // existing init command remains local unless the owner explicitly selects
848
+ // --managed.
849
+ const podman = managed
850
+ ? await ensurePodman({
851
+ env: io.env,
852
+ runner: io.hostCommandRunner,
853
+ confirmSystemUpgrade: async (question) => {
854
+ if (!process.stdin.isTTY)
855
+ return false;
856
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
857
+ try {
858
+ const answer = (await rl.question(question)).trim().toLowerCase();
859
+ return answer === 'y' || answer === 'yes';
860
+ }
861
+ finally {
862
+ rl.close();
863
+ }
864
+ },
865
+ })
866
+ : null;
867
+ if (podman !== null) {
868
+ writeLine(io.stdout, `managed runtime ready: ${podman.version}${podman.installedNow ? ` (installed with ${podman.packageManager})` : ''}; rootless=true`);
869
+ }
622
870
  // Strict-setup preflight (plan Phase 0 item 4): BEFORE anything is
623
- // written — a strict setup demanding an unavailable proof channel (the
624
- // starter policies require browser observation no pack provides yet)
625
- // stays visibly incomplete instead of shipping a false green.
871
+ // written — a strict setup demanding an unavailable proof channel
872
+ // stays visibly incomplete instead of shipping a false green. The
873
+ // starter policy is persistence-only (available), so this passes for
874
+ // the recommended install.
626
875
  if (strictE2E) {
627
876
  preflightStrictSetup(POLICIES_TEMPLATE);
628
877
  }
878
+ // Scan + recommend + choose (Phase 1 item 1): heuristics inform the
879
+ // install; nothing extra is silently enabled. --no-scan skips the
880
+ // filesystem walk and falls back to the language-derived set.
881
+ const noScan = options['no-scan'] === true;
882
+ const scan = noScan || explicitLanguages !== null
883
+ ? {
884
+ languages: explicitLanguages ?? ['python'],
885
+ signals: noScan ? [] : scanRepo(io.cwd).signals,
886
+ }
887
+ : scanRepo(io.cwd);
888
+ const recommended = explicitPlugins ?? recommendPlugins(scan);
889
+ writeLine(io.stdout, renderScanBlock(scan, recommended, proofMode));
890
+ // Flags win: an explicit --plugins choice skips the prompt entirely.
891
+ if (explicitPlugins === null && !(await resolveRecommended(io, options))) {
892
+ writeLine(io.stdout, 'skipped by user choice; re-run with --accept-recommended to write the recommended setup');
893
+ return 0;
894
+ }
629
895
  const cwd = io.cwd;
896
+ const languages = scan.languages;
897
+ const pluginIds = recommended;
630
898
  const gateforgeDir = join(cwd, '.gateforge');
631
899
  const targets = [
632
900
  {
@@ -636,8 +904,8 @@ export async function initCommand(io, argv) {
636
904
  // Self-check the template against the pinned schema before
637
905
  // writing anything (a broken template must fail here, not in
638
906
  // every later command).
639
- parseConfig(parseYaml(configTemplate(languages, { strictE2E })), { file: '.gateforge.yml' });
640
- writeFileSync(join(cwd, '.gateforge.yml'), configTemplate(languages, { strictE2E }), 'utf8');
907
+ parseConfig(parseYaml(configTemplate(languages, pluginIds, { strictE2E, managed })), { file: '.gateforge.yml' });
908
+ writeFileSync(join(cwd, '.gateforge.yml'), configTemplate(languages, pluginIds, { strictE2E, managed }), 'utf8');
641
909
  },
642
910
  },
643
911
  {
@@ -649,7 +917,7 @@ export async function initCommand(io, argv) {
649
917
  path: join(gateforgeDir, 'classification-policy.yml'),
650
918
  label: 'classification policy',
651
919
  write: () => {
652
- const policyText = classificationPolicyTemplate(languages);
920
+ const policyText = classificationPolicyTemplate(languages, pluginIds);
653
921
  // Self-check against the pinned policy schema (same contract as
654
922
  // the config template).
655
923
  ClassificationPolicySchema.parse(parseYaml(policyText));
@@ -661,18 +929,92 @@ export async function initCommand(io, argv) {
661
929
  label: 'baseline (empty)',
662
930
  write: () => writeFileSync(join(gateforgeDir, 'baselines', 'obligations.json'), serializeBaseline({ schemaVersion: 1, fingerprints: [] }), 'utf8'),
663
931
  },
932
+ {
933
+ path: join(cwd, 'GATEFORGE.md'),
934
+ label: 'agent skill file',
935
+ write: () => writeFileSync(join(cwd, 'GATEFORGE.md'), GATEFORGE_MD_TEMPLATE, 'utf8'),
936
+ },
937
+ // Overlay proof README (overlay proof only): the observe path reuses
938
+ // the existing suite, so no overlay directory is scaffolded for it.
939
+ ...(proofMode === 'overlay'
940
+ ? [
941
+ {
942
+ path: join(cwd, 'tests', 'e2e', 'gateforge', 'README.md'),
943
+ label: 'overlay proof README',
944
+ write: () => {
945
+ mkdirSync(join(cwd, 'tests', 'e2e', 'gateforge'), { recursive: true });
946
+ writeFileSync(join(cwd, 'tests', 'e2e', 'gateforge', 'README.md'), OVERLAY_README_TEMPLATE, 'utf8');
947
+ },
948
+ },
949
+ ]
950
+ : []),
664
951
  ];
665
952
  mkdirSync(join(gateforgeDir, 'adapters'), { recursive: true });
666
953
  mkdirSync(join(gateforgeDir, 'waivers'), { recursive: true });
667
954
  mkdirSync(join(gateforgeDir, 'baselines'), { recursive: true });
955
+ // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
956
+ // .gateforge/behavior.yml (scaffold only — never real approval) and
957
+ // wires `behaviorPolicy` into a NEW .gateforge.yml; an existing config
958
+ // is left untouched with an instruction to add the key manually.
959
+ // `--no-behavior` skips; default (flag absent) skips.
960
+ const behaviorFlag = options['behavior'] === true;
961
+ const noBehavior = options['no-behavior'] === true;
962
+ const wantBehavior = behaviorFlag && !noBehavior;
963
+ if (wantBehavior) {
964
+ const behaviorPath = join(gateforgeDir, 'behavior.yml');
965
+ if (existsSync(behaviorPath)) {
966
+ writeLine(io.stdout, `exists, leaving untouched: ${behaviorPath}`);
967
+ }
968
+ else {
969
+ targets.push({
970
+ path: behaviorPath,
971
+ label: 'complete-behavior document (SCAFFOLD — not approval)',
972
+ write: () => writeFileSync(behaviorPath, BEHAVIOR_TEMPLATE, 'utf8'),
973
+ });
974
+ }
975
+ if (!existsSync(join(cwd, '.gateforge.yml'))) {
976
+ targets.push({
977
+ path: join(cwd, '.gateforge.yml'),
978
+ label: 'config (with behaviorPolicy)',
979
+ write: () => {
980
+ const text = configTemplate(languages, pluginIds, { strictE2E, managed });
981
+ const withBehavior = text.replace(/^policies:/m, 'behaviorPolicy: .gateforge/behavior.yml\npolicies:');
982
+ parseConfig(parseYaml(withBehavior), { file: '.gateforge.yml' });
983
+ writeFileSync(join(cwd, '.gateforge.yml'), withBehavior, 'utf8');
984
+ },
985
+ });
986
+ }
987
+ else {
988
+ writeLine(io.stdout, 'note: existing .gateforge.yml left untouched — add `behaviorPolicy: .gateforge/behavior.yml` to enable the profile');
989
+ }
990
+ }
668
991
  for (const target of targets) {
669
992
  if (existsSync(target.path)) {
670
- writeLine(io.stdout, `exists, leaving untouched: ${target.path}`);
993
+ if (managed && target.path === join(cwd, '.gateforge.yml')) {
994
+ const updated = upgradeManagedConfig(target.path);
995
+ writeLine(io.stdout, updated
996
+ ? `updated: ${target.path} (managed enforcement)`
997
+ : `exists, leaving untouched: ${target.path}`);
998
+ }
999
+ else {
1000
+ writeLine(io.stdout, `exists, leaving untouched: ${target.path}`);
1001
+ }
671
1002
  continue;
672
1003
  }
673
1004
  target.write();
674
1005
  writeLine(io.stdout, `created: ${target.path}`);
675
1006
  }
1007
+ // Observe proof checklist (observe proof only): the work no scaffold
1008
+ // can do — proxy wiring, adapter bindings, and kind declarations.
1009
+ if (proofMode === 'observe') {
1010
+ writeLine(io.stdout, OBSERVE_CHECKLIST);
1011
+ }
1012
+ // Behavior checklist (behavior setup only): honest "not ready" — the
1013
+ // scaffold enables the profile but every endpoint blocks until the
1014
+ // owner declares cases and they are proven through the witness.
1015
+ if (wantBehavior) {
1016
+ writeLine(io.stdout, BEHAVIOR_CHECKLIST);
1017
+ }
676
1018
  // Plane-config proposal (flags win; TTY prompt fills the gap;
677
1019
  // non-interactive defaults to scaffold-only, like every granular step):
678
1020
  // --planes / --no-planes
@@ -685,6 +1027,11 @@ export async function initCommand(io, argv) {
685
1027
  await proposePlanesConfig(cwd, io);
686
1028
  }
687
1029
  }
1030
+ // Behavior-profile setup (plan 2026-09-19 §4.11): `--behavior` scaffolds
1031
+ // .gateforge/behavior.yml (scaffold only — never real approval) and
1032
+ // wires `behaviorPolicy` into a NEW .gateforge.yml; an existing config
1033
+ // is left untouched with an instruction to add the key manually.
1034
+ // `--no-behavior` skips; default (flag absent) skips.
688
1035
  // Enforcement wiring is granular (flags win; TTY prompts fill the gaps;
689
1036
  // non-interactive runs default to scaffold-only so tests and CI never
690
1037
  // hang on a prompt):
@@ -701,7 +1048,7 @@ export async function initCommand(io, argv) {
701
1048
  throw new UsageError(`flag '--mode' must be 'changed' or 'staged'`);
702
1049
  }
703
1050
  }
704
- const blocking = await resolveBlocking(io, options);
1051
+ const blocking = managed || (await resolveBlocking(io, options));
705
1052
  const preCommit = options['pre-commit'] === true || blocking;
706
1053
  const ci = options['ci'] === true || blocking;
707
1054
  const mode = typeof modeValue === 'string'