@gate-forge/cli 0.4.0 → 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 +426 -62
  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,26 +18,79 @@
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
- import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, } from '@gate-forge/pack-sqlalchemy';
24
- import { parseArgs } from '../args.js';
23
+ import { DEFAULT_PLANES_CONFIG, PLANES_CONFIG_PATH, createSqlalchemyDetector, parsePlanesConfigText, PACK_VERSION as PACK_SQLALCHEMY_VERSION, } from '@gate-forge/pack-sqlalchemy';
24
+ import { PACK_VERSION as PACK_FASTAPI_VERSION } from '@gate-forge/pack-fastapi';
25
+ import { PACK_VERSION as PACK_HTTP_VERSION } from '@gate-forge/pack-http';
26
+ import { PACK_VERSION as PACK_TASK_VERSION } from '@gate-forge/pack-task';
27
+ import { parseArgs, stringFlag } from '../args.js';
28
+ import { ensurePodman } from '../podman-bootstrap.js';
25
29
  import { writeLine } from '../io.js';
26
30
  import { UsageError } from '../errors.js';
31
+ import { languageDefaultPlugins, recommendPlugins, renderScanBlock, scanRepo } from '../repo-scan.js';
32
+ import { rejectUnknownFlags } from './common.js';
27
33
  import { expandIncludePaths } from '../glob.js';
28
34
  import { inferPlanesConfig } from '../planes-inference.js';
29
35
  import { installCommitHook, writeStandaloneGateScript } from '../git-hooks.js';
30
36
  import { appendPreCommitHook, ensureHookScript, engineRootFromInvocation } from './blocking.js';
31
- 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');
32
62
  const BUNDLED_PLUGIN_MODULES = Object.freeze({
33
63
  'gateforge.pack-fastapi': '@gate-forge/pack-fastapi',
34
64
  'gateforge.pack-http': '@gate-forge/pack-http',
35
65
  'gateforge.pack-sqlalchemy': '@gate-forge/pack-sqlalchemy',
36
66
  'gateforge.pack-task': '@gate-forge/pack-task',
37
67
  });
68
+ /**
69
+ * The bundled plugins' detector-identity versions, imported from each
70
+ * pack's own constant — NEVER a hardcoded literal. The GPP/3 handshake
71
+ * pins the plugin entry's version and every classification signal is
72
+ * checked against that pin, so a stale literal in this template made
73
+ * every generated config fail closed the moment a pack's detector
74
+ * identity moved (pack-sqlalchemy 0.2.0 did exactly that).
75
+ */
76
+ const BUNDLED_PLUGIN_VERSIONS = Object.freeze({
77
+ 'gateforge.pack-fastapi': PACK_FASTAPI_VERSION,
78
+ 'gateforge.pack-http': PACK_HTTP_VERSION,
79
+ 'gateforge.pack-sqlalchemy': PACK_SQLALCHEMY_VERSION,
80
+ 'gateforge.pack-task': PACK_TASK_VERSION,
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));
38
88
  /**
39
89
  * Selects the bundled detectors required by the generated coverage and
40
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`.
41
94
  *
42
95
  * Args:
43
96
  * languages (readonly string[]): Languages selected by `gateforge init`.
@@ -46,21 +99,12 @@ const BUNDLED_PLUGIN_MODULES = Object.freeze({
46
99
  * string[]: Deterministically ordered bundled detector ids.
47
100
  */
48
101
  function bundledPluginIds(languages) {
49
- const normalized = new Set(languages.map((language) => language.toLowerCase()));
50
- const ids = ['gateforge.pack-task'];
51
- if (normalized.has('python')) {
52
- ids.unshift('gateforge.pack-sqlalchemy');
53
- ids.unshift('gateforge.pack-fastapi');
54
- }
55
- if (normalized.has('javascript') || normalized.has('typescript')) {
56
- ids.splice(ids.length - 1, 0, 'gateforge.pack-http');
57
- }
58
- return ids;
102
+ return languageDefaultPlugins(languages);
59
103
  }
60
104
  /** Renders the trusted bundled plugin entries for `.gateforge.yml`. */
61
- function pluginsTemplate(languages) {
62
- return bundledPluginIds(languages)
63
- .map((id) => ` - id: ${id}\n version: '0.1.0'\n transport: in-process\n module: '${BUNDLED_PLUGIN_MODULES[id]}'`)
105
+ function pluginsTemplate(pluginIds) {
106
+ return pluginIds
107
+ .map((id) => ` - id: ${id}\n version: '${BUNDLED_PLUGIN_VERSIONS[id]}'\n transport: in-process\n module: '${BUNDLED_PLUGIN_MODULES[id]}'`)
64
108
  .join('\n');
65
109
  }
66
110
  /**
@@ -124,27 +168,12 @@ export const POLICIES_TEMPLATE = `\
124
168
  # and are graded on the witness's own engine-side observation.
125
169
  # UI-semantic crud:* contracts intentionally fail closed (no
126
170
  # witness-controlled UI observation channel exists yet) — add them only
127
- # 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.
128
175
  schemaVersion: 1
129
176
  policies:
130
- - id: frontend-consumed-endpoints
131
- # ADR 0004 D8 + plan §8 / D1: only endpoints the frontend actually
132
- # consumes (static join) owe browser-exercise obligations;
133
- # server-only routes never do. NOTE: 'http:frontend-request-observed'
134
- # is BLOCKING with the current observer — no independent
135
- # browser/test observation channel exists yet, so the verifier
136
- # returns missing before examining evidence (test attribution is
137
- # suite-claimed). Keep this requirement to hold the frontend-proof
138
- # bar; or SEPARATELY opt in to the narrower transport-only policy
139
- # (TRANSPORT_ONLY_POLICY_EXAMPLE: 'http:request-observed', proving
140
- # only a witness-observed HTTP exchange) when that smaller guarantee
141
- # suffices. Never auto-migrate policies, baselines, or waivers.
142
- when:
143
- kind: http.endpoint
144
- consumed: true
145
- require:
146
- - http:frontend-request-observed
147
- - http:response-status-ok
148
177
  # Capability-scoped endpoint policies (workflow/validation/...) may be added
149
178
  # ONLY when the owning pack ships an engine-owned state-observing producer;
150
179
  # until then those contracts cannot be honestly evidenced and stay blocking.
@@ -169,24 +198,45 @@ policies:
169
198
  * scope every closed-world proof, trusted categories name the internal
170
199
  * entry points an internality certificate may rely on. Organization
171
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).
172
207
  */
173
- 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');
174
213
  const coverageRules = [];
175
214
  // Capabilities (red-team round 6): a rule grants a capability over its
176
215
  // files. Model/task discovery NEVER grants exposure, and no generated
177
216
  // rule declares `exhaustive: true` — today's detectors are heuristics,
178
217
  // so generated policies keep the internality certificate UNAVAILABLE
179
218
  // until the organization asserts an exhaustive exposure parser itself.
180
- 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'))) {
181
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'`);
182
- 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
+ }
183
227
  }
184
- if (languages.includes('python')) {
228
+ if (sqlalchemySelected && languages.includes('python')) {
185
229
  // Model discovery is NOT an exposure capability: python exposure stays
186
230
  // uncovered until an exhaustive python exposure detector exists.
187
231
  coverageRules.push(` - capability: models.sqlalchemy\n detector: gateforge.pack-sqlalchemy\n appliesTo:\n - '**/*.py'`);
188
232
  }
189
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.`;
190
240
  return `\
191
241
  # Repository-wide deterministic classification rules (ADR 0003 D5).
192
242
  # Effective classifications are computed automatically from detector
@@ -201,10 +251,7 @@ scanRoots:
201
251
  # Entry-point categories trusted as internal reachability (an internality
202
252
  # certificate may rely only on these).
203
253
  trustedInternalEntryPoints:
204
- - category: worker
205
- patterns: ['**/workers/**', '**/jobs/**']
206
- # Reachability is only honored from this bundled detector (round 5).
207
- detector: gateforge.pack-task
254
+ ${workerEntry}
208
255
  # Categories WITHOUT a detector binding can never certify: no plugin may
209
256
  # assert their reachability. Bind one when a bundled detector exists.
210
257
  - category: migration
@@ -229,15 +276,15 @@ volatileFields:
229
276
  `;
230
277
  }
231
278
  /** Builds the `.gateforge.yml` document for the requested languages. */
232
- function configTemplate(languages, options = {}) {
233
- const enforcementBlock = options.strictE2E === true
279
+ function configTemplate(languages, pluginIds, options = {}) {
280
+ const enforcementBlock = options.strictE2E === true || options.managed === true
234
281
  ? `# Enforcement modes (plan §3.4/§3.3, ADR 0005): 'standard' = local hook +
235
282
  # mandatory trusted server check (honest about --no-verify); 'managed' =
236
283
  # additionally puts the authoritative commit service outside the agent's
237
284
  # write/process boundary. strictE2E makes waived/baselined in-scope E2E
238
285
  # obligations NOT proof (they block with ENFORCEMENT_UNTRUSTED).
239
286
  enforcement:
240
- mode: standard
287
+ mode: ${options.managed === true ? 'managed' : 'standard'}
241
288
  strictE2E: true
242
289
  `
243
290
  : '';
@@ -264,7 +311,7 @@ ${sourceIncludePatterns(languages).map((pattern) => ` - '${pattern}'`).join
264
311
  # Detector plugins. Bundled detectors are preconfigured for the selected
265
312
  # languages and are loaded from their trusted package entry points.
266
313
  plugins:
267
- ${pluginsTemplate(languages)}
314
+ ${pluginsTemplate(pluginIds)}
268
315
  policies: .gateforge/policies.yml
269
316
  classificationPolicy: .gateforge/classification-policy.yml
270
317
  adapters: .gateforge/adapters
@@ -279,6 +326,39 @@ clock:
279
326
  ${enforcementBlock}\
280
327
  `;
281
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
+ }
282
362
  /**
283
363
  * Strict-setup preflight (plan Phase 0 item 4, ADR 0005 D1): when the
284
364
  * requested setup enables strict E2E mode, every contract its policies
@@ -474,6 +554,104 @@ function writeGitlabCiTemplate(io) {
474
554
  writeFileSync(gitlabCi, `${current.endsWith('\n') ? current : current + '\n'}include:\n${local}\n`);
475
555
  writeLine(io.stdout, `updated: ${gitlabCi} (include appended)`);
476
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
+ }
477
655
  /**
478
656
  * Asks (TTY only) whether gateforge should be a blocking gate. Flags win:
479
657
  * --blocking forces yes, --no-blocking forces no, and non-interactive
@@ -587,29 +765,136 @@ export async function initCommand(io, argv) {
587
765
  writeLine(io.stdout, INIT_USAGE);
588
766
  return 0;
589
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
+ }
590
822
  const languagesValue = options['languages'];
591
823
  if (typeof languagesValue === 'boolean' || Array.isArray(languagesValue)) {
592
824
  throw new UsageError(`flag '--languages' may only be given once`);
593
825
  }
594
- const languages = (languagesValue ?? 'python')
595
- .split(',')
596
- .map((language) => language.trim().toLowerCase())
597
- .filter((language) => language.length > 0);
598
- 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) {
599
833
  throw new UsageError(`flag '--languages' requires at least one language`);
600
834
  }
601
- 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;
602
843
  if (typeof options['strict-e2e'] !== 'boolean' && options['strict-e2e'] !== undefined) {
603
844
  throw new UsageError(`flag '--strict-e2e' must be a boolean flag`);
604
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
+ }
605
870
  // Strict-setup preflight (plan Phase 0 item 4): BEFORE anything is
606
- // written — a strict setup demanding an unavailable proof channel (the
607
- // starter policies require browser observation no pack provides yet)
608
- // 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.
609
875
  if (strictE2E) {
610
876
  preflightStrictSetup(POLICIES_TEMPLATE);
611
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
+ }
612
895
  const cwd = io.cwd;
896
+ const languages = scan.languages;
897
+ const pluginIds = recommended;
613
898
  const gateforgeDir = join(cwd, '.gateforge');
614
899
  const targets = [
615
900
  {
@@ -619,8 +904,8 @@ export async function initCommand(io, argv) {
619
904
  // Self-check the template against the pinned schema before
620
905
  // writing anything (a broken template must fail here, not in
621
906
  // every later command).
622
- parseConfig(parseYaml(configTemplate(languages, { strictE2E })), { file: '.gateforge.yml' });
623
- 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');
624
909
  },
625
910
  },
626
911
  {
@@ -632,7 +917,7 @@ export async function initCommand(io, argv) {
632
917
  path: join(gateforgeDir, 'classification-policy.yml'),
633
918
  label: 'classification policy',
634
919
  write: () => {
635
- const policyText = classificationPolicyTemplate(languages);
920
+ const policyText = classificationPolicyTemplate(languages, pluginIds);
636
921
  // Self-check against the pinned policy schema (same contract as
637
922
  // the config template).
638
923
  ClassificationPolicySchema.parse(parseYaml(policyText));
@@ -644,18 +929,92 @@ export async function initCommand(io, argv) {
644
929
  label: 'baseline (empty)',
645
930
  write: () => writeFileSync(join(gateforgeDir, 'baselines', 'obligations.json'), serializeBaseline({ schemaVersion: 1, fingerprints: [] }), 'utf8'),
646
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
+ : []),
647
951
  ];
648
952
  mkdirSync(join(gateforgeDir, 'adapters'), { recursive: true });
649
953
  mkdirSync(join(gateforgeDir, 'waivers'), { recursive: true });
650
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
+ }
651
991
  for (const target of targets) {
652
992
  if (existsSync(target.path)) {
653
- 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
+ }
654
1002
  continue;
655
1003
  }
656
1004
  target.write();
657
1005
  writeLine(io.stdout, `created: ${target.path}`);
658
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
+ }
659
1018
  // Plane-config proposal (flags win; TTY prompt fills the gap;
660
1019
  // non-interactive defaults to scaffold-only, like every granular step):
661
1020
  // --planes / --no-planes
@@ -668,6 +1027,11 @@ export async function initCommand(io, argv) {
668
1027
  await proposePlanesConfig(cwd, io);
669
1028
  }
670
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.
671
1035
  // Enforcement wiring is granular (flags win; TTY prompts fill the gaps;
672
1036
  // non-interactive runs default to scaffold-only so tests and CI never
673
1037
  // hang on a prompt):
@@ -684,7 +1048,7 @@ export async function initCommand(io, argv) {
684
1048
  throw new UsageError(`flag '--mode' must be 'changed' or 'staged'`);
685
1049
  }
686
1050
  }
687
- const blocking = await resolveBlocking(io, options);
1051
+ const blocking = managed || (await resolveBlocking(io, options));
688
1052
  const preCommit = options['pre-commit'] === true || blocking;
689
1053
  const ci = options['ci'] === true || blocking;
690
1054
  const mode = typeof modeValue === 'string'