yadflow 4.7.0 → 4.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 (96) hide show
  1. package/CHANGELOG.md +116 -0
  2. package/README.md +43 -4
  3. package/bin/commands.mjs +5 -1
  4. package/bin/yad.mjs +169 -22
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +388 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/build.mjs +1 -1
  10. package/cli/ci-check.mjs +492 -0
  11. package/cli/docs.mjs +1 -1
  12. package/cli/doctor.mjs +148 -7
  13. package/cli/epic-state.mjs +3 -3
  14. package/cli/errors.mjs +1 -0
  15. package/cli/guide.mjs +549 -0
  16. package/cli/hook.mjs +32 -3
  17. package/cli/lib.mjs +46 -0
  18. package/cli/lifecycle/defaults/2.json +124 -0
  19. package/cli/lifecycle/lifecycle.schema.json +5 -2
  20. package/cli/lifecycle.mjs +16 -3
  21. package/cli/machine.mjs +141 -0
  22. package/cli/manifest.mjs +75 -0
  23. package/cli/marked-block.mjs +48 -0
  24. package/cli/members.mjs +19 -5
  25. package/cli/migrate.mjs +17 -19
  26. package/cli/next.mjs +1 -1
  27. package/cli/openpr.mjs +46 -6
  28. package/cli/plan.mjs +326 -22
  29. package/cli/preview.mjs +253 -0
  30. package/cli/protection.mjs +50 -0
  31. package/cli/reconcile.mjs +187 -26
  32. package/cli/repo.mjs +64 -3
  33. package/cli/report.mjs +62 -14
  34. package/cli/review.mjs +4 -0
  35. package/cli/setup.mjs +244 -25
  36. package/cli/signing.mjs +377 -0
  37. package/cli/story-frames.mjs +296 -0
  38. package/cli/test-agents-file.mjs +993 -0
  39. package/cli/test-ci-check.mjs +616 -0
  40. package/cli/test-guide.mjs +1267 -0
  41. package/cli/test-machine.mjs +140 -0
  42. package/cli/test-node.mjs +129 -0
  43. package/cli/test-preview.mjs +511 -0
  44. package/cli/test-setup-agent.mjs +352 -0
  45. package/cli/test-signing.mjs +524 -0
  46. package/cli/test-story-frames.mjs +339 -0
  47. package/cli/toolbox.mjs +35 -1
  48. package/cli/update-commit.mjs +313 -11
  49. package/cli/workspace.mjs +37 -12
  50. package/package.json +6 -4
  51. package/skills/sdlc/config.yaml +4 -4
  52. package/skills/sdlc/module-help.csv +1 -0
  53. package/skills/yad-change/SKILL.md +3 -2
  54. package/skills/yad-checks/SKILL.md +29 -9
  55. package/skills/yad-checks/references/check-gates.md +9 -4
  56. package/skills/yad-checks/templates/checks/package-manager.sh +1 -1
  57. package/skills/yad-checks/templates/github/yad-checks.yml +1 -1
  58. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +1 -1
  59. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +1 -1
  60. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +1 -1
  61. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +1 -1
  62. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +1 -1
  63. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  64. package/skills/yad-commit/SKILL.md +4 -3
  65. package/skills/yad-connect-design/SKILL.md +7 -4
  66. package/skills/yad-connect-design/references/design-context.md +23 -0
  67. package/skills/yad-connect-design/references/design-registry.md +3 -3
  68. package/skills/yad-connect-repos/SKILL.md +13 -3
  69. package/skills/yad-connect-repos/references/code-context.md +2 -1
  70. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  71. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  72. package/skills/yad-engineer-review/SKILL.md +25 -7
  73. package/skills/yad-engineer-review/references/ship-and-record.md +7 -4
  74. package/skills/yad-epic/SKILL.md +2 -1
  75. package/skills/yad-epic/references/state-schema.md +7 -1
  76. package/skills/yad-guide/SKILL.md +192 -0
  77. package/skills/yad-implement/SKILL.md +14 -0
  78. package/skills/yad-open-pr/SKILL.md +5 -2
  79. package/skills/yad-pair-review/SKILL.md +19 -5
  80. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -0
  81. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -0
  82. package/skills/yad-product-bridge/SKILL.md +32 -13
  83. package/skills/yad-product-bridge/references/bridge.md +6 -3
  84. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  85. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +1 -1
  86. package/skills/yad-report/SKILL.md +15 -0
  87. package/skills/yad-review-companion/SKILL.md +9 -4
  88. package/skills/yad-review-gate/SKILL.md +13 -9
  89. package/skills/yad-review-gate/references/gating.md +1 -1
  90. package/skills/yad-run/SKILL.md +10 -6
  91. package/skills/yad-run/references/run-loop.md +2 -1
  92. package/skills/yad-spec/SKILL.md +21 -0
  93. package/skills/yad-stories/SKILL.md +22 -0
  94. package/skills/yad-stories/references/story-schema.md +1 -0
  95. package/skills/yad-sync-repos/SKILL.md +2 -1
  96. package/skills/yad-ui/SKILL.md +7 -2
package/cli/setup.mjs CHANGED
@@ -5,18 +5,20 @@ import os from 'node:os';
5
5
  import {
6
6
  c, log, step, guide, ok, info, warn, hand, fail, ask, askYesNo, run, runLauncher, has,
7
7
  exists, readJSON, readJSONStrict, writeJSON,
8
- writeProductConfig, forTerminal,
8
+ writeProductConfig, forTerminal, inJSON,
9
9
  } from './lib.mjs';
10
+ import { err } from './errors.mjs';
10
11
  import { VERSION, IDE_TARGETS, IDE_AGENTS, DEFAULT_IDE_TARGETS, PROJECT_FILES, DESIGN_TOOLS, DESIGN_PRIMARY, TESTING_TOOLS, TESTING_PRIMARY, LEARNING_TOOLS, LEARNING_PRIMARY , productConfigPath } from './manifest.mjs';
11
12
  import {
12
- moduleActions, repoActions, productActions, hookActions, captureHookActions, legacyHookScriptActions, gitHookActions, gitHookState, gitHookAdvice,
13
+ moduleActions, repoActions, productActions, hookActions, agentFileActions, agentGuardActions, allowListActions, captureHookActions, legacyHookScriptActions, gitHookActions, gitHookState, gitHookAdvice,
13
14
  legacyModuleActions, removedModuleActions, legacyRepoActions, legacyProductActions, withoutKeptRenames,
14
- safeIdeTargetsFor, detectedIdeTargetStateFor, recordManagedWrites,
15
+ safeIdeTargetsFor, detectedIdeTargetStateFor, recordManagedWrites, canonicalIdeTargets,
15
16
  } from './plan.mjs';
16
17
  import { modeFields, modeOf } from './mode.mjs';
17
18
  import { recordActor } from './skip.mjs';
18
19
  import { loadSkillBindings, stepSkills } from './epic-state.mjs';
19
20
  import { offerToolbox, REPOMIX_VERSION } from './toolbox.mjs';
21
+ import { readAllowList } from './agent-rules.mjs';
20
22
 
21
23
  // Parse a comma/space separated list into a clean, deduped array of trimmed tokens.
22
24
  export function parseList(s) {
@@ -254,6 +256,9 @@ export function setupModeFields(root, cur, solo, opts = {}) {
254
256
  function applyActions(actions, { force = false } = {}) {
255
257
  let changed = 0;
256
258
  for (const a of actions) {
259
+ // An action that cannot write (a settings file that does not parse, rules-block markers yad cannot trust)
260
+ // said why when it was planned, and `--overwrite-local` would not help it.
261
+ if (a.writesNothing) continue;
257
262
  // A managed file the team edited is left alone here too — setup re-runs with force:true, so
258
263
  // without this the wizard would be a second silent-clobber path for the same edits (#164).
259
264
  if (a.status === 'modified') {
@@ -269,6 +274,165 @@ function applyActions(actions, { force = false } = {}) {
269
274
  return changed;
270
275
  }
271
276
 
277
+ // ---- E159: every setup question as data, so an AI agent can ask them in chat ---------------------------
278
+ //
279
+ // `setupQuestions` lists the questions THIS run would ask, in the order `runSetup` asks them, each with the
280
+ // flag that answers it and whether that flag was given. It only reads (the disk and the flags) and follows
281
+ // the same branches `runSetup` takes, so a question appears only where the run would really ask it. Under
282
+ // `--json` (without SDLC_NONINTERACTIVE, which takes every default) `runSetup` refuses with the unanswered
283
+ // ones BEFORE it writes anything (`assertSetupAnswered`), and `yad guide --json` shows the same list.
284
+ const has_ = (v) => v !== undefined && v !== null;
285
+ const toolsGiven = (opts) => has_(opts.design) || has_(opts.testing) || has_(opts.learning);
286
+ // The tools step runs: `--tools`, or any one tool named. `--no-tools` turns it off; unanswered, it is asked.
287
+ const toolsOn = (opts) => opts.tools === true || toolsGiven(opts);
288
+ // The code repos this run would end with: the registered ones, those `--add-repo` adds, and those `yad init`
289
+ // found that `--connect` picks.
290
+ // A monorepo connects one repo per step, as `runSetup` does (it stops after the first).
291
+ function reposAfter(root, opts) {
292
+ const out = registeredRepos(root).map((r) => ({ name: r.name, rpath: r.path }));
293
+ const mono = isMonorepo(root, opts);
294
+ const fresh = newlyFound(root, opts).filter((d) => connects(opts.connect, d.name) !== false);
295
+ out.push(...(mono ? fresh.slice(0, 1) : fresh));
296
+ const added = (opts.addRepo || []).map(parseAddRepo).filter((r) => !out.some((o) => o.name === r.name));
297
+ out.push(...(mono ? added.slice(0, 1) : added).map((r) => ({ name: r.name, rpath: r.rpath })));
298
+ return out;
299
+ }
300
+ const registeredRepos = (root) => (readJSON(path.join(root, PROJECT_FILES.reposRegistry), { repos: [] }) || { repos: [] }).repos || [];
301
+ // The repos `yad init` found that are not registered yet: the ones `runSetup` asks about.
302
+ const newlyFound = (root, opts) => {
303
+ const known = new Set(registeredRepos(root).map((r) => r.name));
304
+ return (opts.discovered || []).filter((d) => !known.has(d.name));
305
+ };
306
+ const isMonorepo = (root, opts) => (opts.monorepo ? true : opts.separate ? false : readJSON(productConfigPath(root), null)?.profile?.repo_layout === 'monorepo');
307
+ // `--connect all|none|<name,name>` for one repo: true, false, or undefined when not answered.
308
+ function connects(connect, name) {
309
+ if (!has_(connect)) return undefined;
310
+ if (connect === 'all') return true;
311
+ if (connect === 'none') return false;
312
+ return parseList(connect).includes(name);
313
+ }
314
+ // `--add-repo <name>=<path>[,<platform>[,<branch>]]`.
315
+ export function parseAddRepo(spec) {
316
+ const m = /^([^=]+)=([^,]+)(?:,([^,]*))?(?:,([^,]*))?$/.exec(String(spec));
317
+ if (!m) throw setupFlagError(`--add-repo ${spec}: expected <name>=<path>[,<platform>[,<branch>]]`);
318
+ return { name: m[1].trim(), rpath: m[2].trim(), platform: (m[3] || '').trim().toLowerCase() || null, default_branch: (m[4] || '').trim() || null };
319
+ }
320
+ const setupFlagError = (message) => Object.assign(new Error(message), { hint: '`yad --help` lists the setup flags and their values' });
321
+
322
+ // The AI tools to install the skills for: setup's question, and `yad join`'s only one.
323
+ export function ideTargetsQuestion(root, opts = {}) {
324
+ const detected = exists(root) ? detectedIdeTargetStateFor(root).targets : [];
325
+ return { id: 'ide-targets', text: 'Which AI tools to install the skills for?', choices: IDE_TARGETS.map((t) => `${t} (${(IDE_AGENTS[t] || []).join(', ')})`), default: (detected.length ? detected : DEFAULT_IDE_TARGETS).join(','), flag: '--ide-targets <a,b>', given: has_(opts.ideTargets) };
326
+ }
327
+
328
+ export function setupQuestions(root, opts = {}) {
329
+ const productConfig = readJSON(productConfigPath(root), null);
330
+ const prev = productConfig?.profile || {};
331
+ const qs = [];
332
+ const add = (q) => qs.push(q);
333
+ const modeCarried = typeof productConfig?.solo === 'boolean' || productConfig?.review_gate?.solo === true;
334
+ if (!modeCarried) {
335
+ const known = prev.team_size ?? (productConfig ? 2 : 1);
336
+ add({ id: 'mode', text: 'Solo or team? For a team, how many people?', choices: ['solo', 'team <n>'], default: known > 1 ? `team ${Math.max(2, known)}` : 'solo', flag: '--solo | --team <n>', given: !!opts.solo || has_(opts.team) });
337
+ }
338
+ if (!prev.codebase) add({ id: 'codebase', text: 'Greenfield (new code) or brownfield (existing code)?', choices: ['greenfield', 'brownfield'], default: 'greenfield', flag: '--greenfield | --brownfield', given: !!(opts.greenfield || opts.brownfield) });
339
+ if (!prev.repo_layout) add({ id: 'layout', text: 'Monorepo (one repo) or separate repos?', choices: ['monorepo', 'separate'], default: 'monorepo', flag: '--monorepo | --separate', given: !!(opts.monorepo || opts.separate) });
340
+ add({ id: 'tools', text: 'Configure the design, testing and learning tools now (else connect them later)?', choices: ['yes', 'no'], default: 'no', flag: '--tools | --no-tools', given: opts.tools === true || opts.noTools === true || toolsGiven(opts) });
341
+ if (!exists(path.join(root, '.git'))) add({ id: 'git-init', text: 'This folder is not a git repo. Run `git init` here?', choices: ['yes', 'no'], default: 'yes', flag: '--git-init | --no-git-init', given: has_(opts.gitInit) });
342
+ add(ideTargetsQuestion(root, opts));
343
+ const productExists = exists(productConfigPath(root));
344
+ const toolFile = (f) => exists(path.join(root, f));
345
+ const anyToolFile = toolsOn(opts) && [PROJECT_FILES.designConfig, PROJECT_FILES.testingConfig, PROJECT_FILES.learningConfig].some(toolFile);
346
+ if (productExists || anyToolFile) add({ id: 'reconfigure', text: 'Settings from an earlier setup are here. Change them (platform, default branch, tools)?', choices: ['yes', 'no'], default: 'no', flag: '--reconfigure | --no-reconfigure', given: has_(opts.reconfigure) });
347
+ if (!productExists || opts.reconfigure === true) {
348
+ const remote = run('git', ['remote', 'get-url', 'origin'], { cwd: root });
349
+ const platformDefault = detectPlatform(remote.ok ? remote.stdout : '') || 'none';
350
+ add({ id: 'platform', text: 'Where does the Product live: GitHub, GitLab, or nowhere yet (a local gate)?', choices: ['github', 'gitlab', 'none'], default: platformDefault, flag: '--platform <github|gitlab|none>', given: has_(opts.platform) });
351
+ // Asked only for a platform. With the platform not answered yet it is listed too, so both are asked at
352
+ // once, but it is required only once the answer is github or gitlab.
353
+ if (!has_(opts.platform) || opts.platform !== 'none') add({ id: 'default-branch', text: 'The Product\'s default branch? (only for GitHub or GitLab)', choices: [], default: 'main', flag: '--default-branch <name>', given: has_(opts.defaultBranch), ...(has_(opts.platform) ? {} : { optional: true }) });
354
+ }
355
+ if (toolsOn(opts)) {
356
+ const tool = (id, file, tools, primary) => {
357
+ if (toolFile(file) && opts.reconfigure !== true) return;
358
+ add({ id, text: `Which ${id} tool?`, choices: [...tools, 'none'], default: primary, flag: `--${id} <${[...tools, 'none'].join('|')}>`, given: has_(opts[id]) });
359
+ };
360
+ tool('design', PROJECT_FILES.designConfig, DESIGN_TOOLS, DESIGN_PRIMARY);
361
+ tool('testing', PROJECT_FILES.testingConfig, TESTING_TOOLS, TESTING_PRIMARY);
362
+ tool('learning', PROJECT_FILES.learningConfig, LEARNING_TOOLS, LEARNING_PRIMARY);
363
+ }
364
+ const found = newlyFound(root, opts).map((d) => d.name);
365
+ add({
366
+ id: 'repos',
367
+ text: found.length ? `Connect and wire the repos found beside the Product (${found.join(', ')}), and any other code repo?` : 'Connect a code repo (its name, path, platform and default branch)?',
368
+ choices: found.length ? ['all', 'none', found.join(',')] : ['none', '<name>=<path>[,<platform>[,<branch>]]'],
369
+ default: found.length ? 'all' : 'none',
370
+ flag: found.length ? '--connect <all|none|name,name> [--add-repo <name>=<path>[,<platform>[,<branch>]]]' : '--add-repo <name>=<path>[,<platform>[,<branch>]] | --connect none',
371
+ // Repos found beside the Product are asked one by one unless `--connect` answers them: `--add-repo` alone
372
+ // does not.
373
+ given: has_(opts.connect) || (!found.length && (opts.addRepo || []).length > 0),
374
+ });
375
+ const noCr = reposAfter(root, opts).filter((r) => !exists(path.join(path.resolve(root, r.rpath), '.coderabbit.yaml'))).map((r) => r.name);
376
+ if (noCr.length) add({ id: 'coderabbit', text: `Wire CodeRabbit (an advisory AI review of each PR/MR) in: ${noCr.join(', ')}?`, choices: ['all', 'none', noCr.join(',')], default: 'none', flag: '--coderabbit <all|none|name,name>', given: has_(opts.coderabbit) });
377
+ return qs;
378
+ }
379
+
380
+ // The setup flags' values, checked before anything is written: a bad value is refused, never guessed at.
381
+ export function checkSetupFlags(root, opts = {}) {
382
+ if (opts.tools === true && opts.noTools === true) throw setupFlagError('--tools and --no-tools say opposite things — pick one');
383
+ if (opts.noTools === true && toolsGiven(opts)) throw setupFlagError('--no-tools and a tool flag (--design, --testing, --learning) say opposite things — pick one');
384
+ if (opts.solo && has_(opts.team)) throw setupFlagError('--solo and --team say opposite things — pick one');
385
+ if (has_(opts.team) && !/^[1-9]\d*$/.test(String(opts.team))) throw setupFlagError(`--team ${opts.team}: expected how many people, a whole number from 1`);
386
+ if (has_(opts.ideTargets)) {
387
+ try { canonicalIdeTargets(opts.ideTargets); } catch (e) { throw setupFlagError(`--ide-targets: ${e.message}`); }
388
+ }
389
+ if (has_(opts.platform) && !['github', 'gitlab', 'none'].includes(opts.platform)) throw setupFlagError(`--platform ${opts.platform}: expected github, gitlab or none`);
390
+ const branchOk = (b) => /^[A-Za-z0-9._/-]+$/.test(b) && !b.startsWith('-') && !b.includes('..');
391
+ if (has_(opts.defaultBranch) && !branchOk(opts.defaultBranch)) throw setupFlagError(`--default-branch ${opts.defaultBranch}: not a plain branch name`);
392
+ for (const [id, tools] of [['design', DESIGN_TOOLS], ['testing', TESTING_TOOLS], ['learning', LEARNING_TOOLS]]) {
393
+ if (has_(opts[id]) && ![...tools, 'none'].includes(opts[id])) throw setupFlagError(`--${id} ${opts[id]}: expected one of ${[...tools, 'none'].join(', ')}`);
394
+ }
395
+ const found = (opts.discovered || []).map((d) => d.name);
396
+ if (has_(opts.connect) && !['all', 'none'].includes(opts.connect)) {
397
+ const unknown = parseList(opts.connect).filter((n) => !found.includes(n));
398
+ if (unknown.length) throw setupFlagError(`--connect: no repo named ${unknown.join(', ')} was found beside the Product${found.length ? ` (found: ${found.join(', ')})` : ''}`);
399
+ }
400
+ const names = new Set();
401
+ for (const spec of opts.addRepo || []) {
402
+ const r = parseAddRepo(spec);
403
+ if (!/^[A-Za-z0-9._-]+$/.test(r.name)) throw setupFlagError(`--add-repo ${spec}: a repo name is letters, digits, ".", "_" or "-"`);
404
+ if (names.has(r.name) || found.includes(r.name)) throw setupFlagError(`--add-repo ${spec}: ${r.name} is named twice`);
405
+ names.add(r.name);
406
+ if (throughGitDir(root, r.rpath)) throw setupFlagError(`--add-repo ${spec}: ${r.rpath} runs through a .git folder — not a code repo`);
407
+ if (!insideWorkspace(root, r.rpath)) throw setupFlagError(`--add-repo ${spec}: ${r.rpath} resolves outside the workspace (the Product's parent folder)`);
408
+ if (r.platform && !['github', 'gitlab'].includes(r.platform)) throw setupFlagError(`--add-repo ${spec}: platform ${r.platform} — expected github or gitlab`);
409
+ if (r.default_branch && !branchOk(r.default_branch)) throw setupFlagError(`--add-repo ${spec}: ${r.default_branch} is not a plain branch name`);
410
+ // What `registerRepo` refuses, refused here first: a skipped repo would change which one a monorepo connects.
411
+ if (gitHead(path.resolve(root, r.rpath)) === null) throw setupFlagError(`--add-repo ${spec}: ${r.rpath} is not a git repository`);
412
+ }
413
+ if (has_(opts.coderabbit) && !['all', 'none'].includes(opts.coderabbit)) {
414
+ // Only a repo this run ends with, and in a monorepo only the one it connects.
415
+ const known = reposAfter(root, opts).map((r) => r.name);
416
+ const unknown = parseList(opts.coderabbit).filter((n) => !known.includes(n));
417
+ if (unknown.length) throw setupFlagError(`--coderabbit: no connected repo named ${unknown.join(', ')}`);
418
+ }
419
+ }
420
+
421
+ // Under --json, every question this run would ask needs its flag: refused with the unanswered ones, before
422
+ // anything is written. SDLC_NONINTERACTIVE takes every default instead, as it always has.
423
+ export function assertSetupAnswered(root, opts = {}) {
424
+ checkSetupFlags(root, opts);
425
+ if (!inJSON() || process.env.SDLC_NONINTERACTIVE) return;
426
+ const open = setupQuestions(root, opts).filter((q) => !q.given);
427
+ const missing = open.filter((q) => !q.optional);
428
+ if (!missing.length) return;
429
+ const e = err('YAD-CLI-001', `setup needs ${missing.length} answer(s) before it can run: ${missing.map((q) => q.id).join(', ')}`,
430
+ 'ask the person each question in `questions`, then run it again with those flags (or SDLC_NONINTERACTIVE=1 to take every default)');
431
+ // Every open question, the optional ones too (a default branch, asked with the platform), so they are asked at once.
432
+ e.questions = open.map(({ given: _given, ...q }) => q);
433
+ throw e;
434
+ }
435
+
272
436
  // Step 0 — resolve the setup profile that branches the rest of the wizard. Flags pre-answer each
273
437
  // question (CI/scripts); an existing hub.json carries prior answers forward (idempotent re-run);
274
438
  // otherwise we prompt with a default. Pure of side effects — it only reads. Returns
@@ -308,8 +472,8 @@ export async function resolveProfile(root, opts = {}) {
308
472
  else repo_layout = (await ask('Monorepo (one repo) or separate repos?', 'monorepo')).toLowerCase().startsWith('s') ? 'separate' : 'monorepo';
309
473
 
310
474
  // 4. Configure the optional tools now, or defer (records them as none, connect later).
311
- const configureTools = opts.tools === true ? true
312
- : process.env.SDLC_NONINTERACTIVE ? false
475
+ const configureTools = toolsOn(opts) ? true
476
+ : opts.noTools === true || process.env.SDLC_NONINTERACTIVE ? false
313
477
  : await askYesNo('Configure design/testing/learning tools now? (else connect them later)', false);
314
478
 
315
479
  return { solo, team_size, codebase, repo_layout, configureTools };
@@ -320,6 +484,9 @@ export async function resolveProfile(root, opts = {}) {
320
484
  export async function runSetup(root, opts = {}) {
321
485
  log(c.bold(`\nSDLC Workflow setup ${c.dim('v' + VERSION)}`));
322
486
  log(c.dim(`target: ${root}`));
487
+ // E159: a bad flag value, or (under --json) an unanswered question, is refused here — before anything is written.
488
+ assertSetupAnswered(root, opts);
489
+ const notes = [];
323
490
 
324
491
  // 0. Profile interview — branch the wizard to the user's situation (solo/team, code, repo layout).
325
492
  const { solo, team_size, codebase, repo_layout, configureTools } = await resolveProfile(root, opts);
@@ -339,7 +506,7 @@ export async function runSetup(root, opts = {}) {
339
506
  // Preflight
340
507
  S('Preflight');
341
508
  if (!exists(path.join(root, '.git'))) {
342
- if (await askYesNo('Not a git repo. Run `git init` here?', true)) {
509
+ if (opts.gitInit ?? await askYesNo('Not a git repo. Run `git init` here?', true)) {
343
510
  run('git', ['init'], { cwd: root });
344
511
  ok('git initialized');
345
512
  } else warn('continuing without git — the Product platform will not be detected');
@@ -369,7 +536,12 @@ export async function runSetup(root, opts = {}) {
369
536
  // so touching the home dir requires an interactive yes — never auto-fire it in SDLC_NONINTERACTIVE
370
537
  // (scripted/CI) mode, where the prompt would otherwise return its default. Silent when there is
371
538
  // nothing to migrate.
372
- const globalLegacy = process.env.SDLC_NONINTERACTIVE ? [] : legacyModuleActions(os.homedir(), ['.claude']);
539
+ // Under --json (an agent's run, E159) the person's home folder is not the agent's to tidy: left, and said.
540
+ const homeAsk = !process.env.SDLC_NONINTERACTIVE && !inJSON();
541
+ if (!process.env.SDLC_NONINTERACTIVE && inJSON() && (legacyModuleActions(os.homedir(), ['.claude']).length || removedModuleActions(os.homedir(), ['.claude']).length)) {
542
+ notes.push('old yad skills are in your global ~/.claude/skills — run `yad setup` in a terminal to migrate or delete them');
543
+ }
544
+ const globalLegacy = homeAsk ? legacyModuleActions(os.homedir(), ['.claude']) : [];
373
545
  if (globalLegacy.length) {
374
546
  if (await askYesNo(`Found ${globalLegacy.length} legacy sdlc-* skill(s) in your global ~/.claude/skills (pre-2.0 install). Migrate them to yad-*?`, true)) {
375
547
  applyActions(globalLegacy, { force: true });
@@ -381,7 +553,7 @@ export async function runSetup(root, opts = {}) {
381
553
 
382
554
  // Same opt-in pass for skills removed in a later release (REMOVED_SKILLS) that linger in the
383
555
  // global ~/.claude/skills — purge them so a global install also drops the dead command.
384
- const globalRemoved = process.env.SDLC_NONINTERACTIVE ? [] : removedModuleActions(os.homedir(), ['.claude']);
556
+ const globalRemoved = homeAsk ? removedModuleActions(os.homedir(), ['.claude']) : [];
385
557
  if (globalRemoved.length) {
386
558
  if (await askYesNo(`Found ${globalRemoved.length} removed skill(s) in your global ~/.claude/skills. Delete them?`, true)) {
387
559
  applyActions(globalRemoved, { force: true });
@@ -405,18 +577,18 @@ export async function runSetup(root, opts = {}) {
405
577
  'It also reports how many people it would like: 3 on a contract review, 2 where auth or payments is touched, 1 elsewhere. That extra number is advisory for now.',
406
578
  ]);
407
579
  const productPath = productConfigPath(root);
408
- if (exists(productPath) && !(await askYesNo(`${path.relative(root, productPath)} exists — reconfigure?`, false))) {
580
+ if (exists(productPath) && !(opts.reconfigure ?? await askYesNo(`${path.relative(root, productPath)} exists — reconfigure?`, false))) {
409
581
  info(`keeping the existing ${path.relative(root, productPath)}`);
410
582
  } else {
411
583
  const remote = run('git', ['remote', 'get-url', 'origin'], { cwd: root });
412
584
  if (!remote.ok && exists(path.join(root, '.git'))) info('no origin remote — platform detection skipped');
413
585
  let platform = detectPlatform(remote.ok ? remote.stdout : '');
414
- platform = (await ask('Product platform (github/gitlab/none)', platform || 'none')).toLowerCase();
586
+ platform = (opts.platform ?? await ask('Product platform (github/gitlab/none)', platform || 'none')).toLowerCase();
415
587
  if (!['github', 'gitlab', 'none'].includes(platform)) {
416
588
  warn(`unknown platform '${platform}' — using none (local gate)`);
417
589
  platform = 'none';
418
590
  }
419
- const default_branch = platform === 'none' ? 'main' : await ask('Product default branch', 'main');
591
+ const default_branch = platform === 'none' ? 'main' : opts.defaultBranch ?? await ask('Product default branch', 'main');
420
592
  // `ledger` is the canonical switch (shape 2): "verified" = CI writes the ledger, "local" = this
421
593
  // machine does. The two booleans below say the same thing in the older spelling and are written
422
594
  // ALONGSIDE it, not instead of it — add before you remove (rule 3). They are what a check gate
@@ -478,15 +650,16 @@ export async function runSetup(root, opts = {}) {
478
650
  'Where yad-ui materializes real screens. figma (confirm the MCP later) or none for markdown-only.',
479
651
  'Skipping is safe — the UI step degrades to ui-design.md.',
480
652
  ]);
481
- if (exists(designPath) && !(await askYesNo('design.json exists — reconfigure?', false))) {
653
+ if (exists(designPath) && !(opts.reconfigure ?? await askYesNo('design.json exists — reconfigure?', false))) {
482
654
  info('keeping existing .sdlc/design.json');
483
655
  } else {
484
- let tool = (await ask(`Design tool (${DESIGN_TOOLS.join('/')}/none)`, DESIGN_PRIMARY)).toLowerCase();
656
+ let tool = (opts.design ?? await ask(`Design tool (${DESIGN_TOOLS.join('/')}/none)`, DESIGN_PRIMARY)).toLowerCase();
485
657
  if (![...DESIGN_TOOLS, 'none'].includes(tool)) {
486
658
  warn(`unknown design tool '${tool}' — using ${DESIGN_PRIMARY}`);
487
659
  tool = DESIGN_PRIMARY;
488
660
  }
489
- const project_url = tool === 'none' ? null : (await ask(' project/file URL (blank to set later)', '')) || null;
661
+ // A tool named by flag takes its URL by flag too (blank when not given): no prompt.
662
+ const project_url = tool === 'none' ? null : (has_(opts.design) ? opts.designUrl : await ask(' project/file URL (blank to set later)', '')) || null;
490
663
  registerDesign(root, { tool, project_url, today: opts.today ?? null });
491
664
  ok(tool === 'none'
492
665
  ? `wrote ${PROJECT_FILES.designConfig} (markdown-only)`
@@ -502,15 +675,15 @@ export async function runSetup(root, opts = {}) {
502
675
  `Where yad-test-cases generates automation. ${TESTING_TOOLS.join('/')}, or none for artifacts-only.`,
503
676
  'Skipping is safe — test-cases authors test-cases.md only.',
504
677
  ]);
505
- if (exists(testingPath) && !(await askYesNo('testing.json exists — reconfigure?', false))) {
678
+ if (exists(testingPath) && !(opts.reconfigure ?? await askYesNo('testing.json exists — reconfigure?', false))) {
506
679
  info('keeping existing .sdlc/testing.json');
507
680
  } else {
508
- let tool = (await ask(`Testing tool (${TESTING_TOOLS.join('/')}/none)`, TESTING_PRIMARY)).toLowerCase();
681
+ let tool = (opts.testing ?? await ask(`Testing tool (${TESTING_TOOLS.join('/')}/none)`, TESTING_PRIMARY)).toLowerCase();
509
682
  if (![...TESTING_TOOLS, 'none'].includes(tool)) {
510
683
  warn(`unknown testing tool '${tool}' — using ${TESTING_PRIMARY}`);
511
684
  tool = TESTING_PRIMARY;
512
685
  }
513
- const project_url = tool === 'none' ? null : (await ask(' project/config reference (blank to set later)', '')) || null;
686
+ const project_url = tool === 'none' ? null : (has_(opts.testing) ? opts.testingUrl : await ask(' project/config reference (blank to set later)', '')) || null;
514
687
  registerTesting(root, { tool, project_url, today: opts.today ?? null });
515
688
  ok(tool === 'none'
516
689
  ? `wrote ${PROJECT_FILES.testingConfig} (artifacts-only)`
@@ -523,10 +696,10 @@ export async function runSetup(root, opts = {}) {
523
696
  'Lets any team member invoke yad-learn to be tutored in-context. deeptutor (a CLI), or none.',
524
697
  'Skipping is safe — yad-learn tutors via the harness model (harness-native).',
525
698
  ]);
526
- if (exists(learningPath) && !(await askYesNo('learning.json exists — reconfigure?', false))) {
699
+ if (exists(learningPath) && !(opts.reconfigure ?? await askYesNo('learning.json exists — reconfigure?', false))) {
527
700
  info('keeping existing .sdlc/learning.json');
528
701
  } else {
529
- let tool = (await ask(`Learning tool (${LEARNING_TOOLS.join('/')}/none)`, LEARNING_PRIMARY)).toLowerCase();
702
+ let tool = (opts.learning ?? await ask(`Learning tool (${LEARNING_TOOLS.join('/')}/none)`, LEARNING_PRIMARY)).toLowerCase();
530
703
  if (![...LEARNING_TOOLS, 'none'].includes(tool)) {
531
704
  warn(`unknown learning tool '${tool}' — using ${LEARNING_PRIMARY}`);
532
705
  tool = LEARNING_PRIMARY;
@@ -572,7 +745,7 @@ export async function runSetup(root, opts = {}) {
572
745
  const default_branch = detectDefaultBranch(repoRoot);
573
746
  // "Connect" means what it means in the loop below: register it, and the wiring step then writes the
574
747
  // CI gates and the PR template into it. Said here, because init asks for every repo at once.
575
- if (!(await askYesNo(`Connect and wire ${d.name} (${d.rpath}, ${platform}, default branch ${default_branch}) — writes its CI gates + PR template?`, true))) continue;
748
+ if (!(connects(opts.connect, d.name) ?? await askYesNo(`Connect and wire ${d.name} (${d.rpath}, ${platform}, default branch ${default_branch}) — writes its CI gates + PR template?`, true))) continue;
576
749
  const repo = registerRepo(root, registry, { name: d.name, rpath: d.rpath, platform, default_branch, today: opts.today ?? null, pack: !greenfield });
577
750
  if (!repo) continue;
578
751
  known.add(d.name);
@@ -581,7 +754,22 @@ export async function runSetup(root, opts = {}) {
581
754
  else packRepo(root, repo);
582
755
  if (mono) { info('monorepo — one repo connected'); break; }
583
756
  }
584
- if (await askYesNo(`Connect a code repo? ${c.dim(`(${registry.repos.length} already registered)`)}`, registry.repos.length === 0)) {
757
+ // E159: repos named by flag (`--add-repo`, checked before anything was written), and no question when the
758
+ // repos were answered by flag (`--connect` or `--add-repo`).
759
+ for (const r of (opts.addRepo || []).map(parseAddRepo)) {
760
+ if (known.has(r.name)) { warn(`${r.name} already registered — skipping`); continue; }
761
+ const detected = run('git', ['remote', 'get-url', 'origin'], { cwd: path.resolve(root, r.rpath) });
762
+ const platform = r.platform || detectPlatform(detected.ok ? detected.stdout : '') || 'github';
763
+ const repo = registerRepo(root, registry, { name: r.name, rpath: r.rpath, platform, default_branch: r.default_branch || 'main', today: opts.today ?? null, pack: !greenfield });
764
+ if (!repo) continue;
765
+ known.add(r.name);
766
+ ok(`registered ${r.name}`);
767
+ if (greenfield) info(`${r.name}: greenfield — skipped repomix pack (run \`yad repo refresh ${r.name}\` once it has code)`);
768
+ else packRepo(root, repo);
769
+ if (mono) { info('monorepo — one repo connected'); break; }
770
+ }
771
+ const reposAnswered = has_(opts.connect) || (opts.addRepo || []).length > 0;
772
+ if (!reposAnswered && await askYesNo(`Connect a code repo? ${c.dim(`(${registry.repos.length} already registered)`)}`, registry.repos.length === 0)) {
585
773
  for (;;) {
586
774
  const name = await ask(' repo name (blank to finish)', '');
587
775
  if (!name) break;
@@ -610,12 +798,23 @@ export async function runSetup(root, opts = {}) {
610
798
  // Every managed file this step writes is recorded (sha per repo root) so a LATER `yad update` can
611
799
  // tell a stale copy from one the team edited, instead of silently rewriting both (#164).
612
800
  const wired = [];
801
+ // E158 (#353): the read-only yad commands Claude Code may run without asking are shown before they are first
802
+ // written — in a code repo (E158b) or the Product — and named again after that. Not when nothing is written.
803
+ let allowListShown = false;
804
+ const showAllowList = (who, actions) => {
805
+ if (!actions.some((a) => a.allowList && a.status !== 'ok' && !a.writesNothing)) return;
806
+ log(` ${c.bold(who)} ${c.dim('(read-only yad commands Claude Code runs without asking, in .claude/settings.json)')}`);
807
+ if (allowListShown) { log(` ${c.dim('the same list as above')}`); return; }
808
+ for (const e of readAllowList()) log(` ${c.dim(e)}`);
809
+ allowListShown = true;
810
+ };
613
811
  for (const repo of registry.repos) {
614
812
  log(` ${c.bold(repo.name)} ${c.dim(`(${repo.platform})`)}`);
615
813
  // Migrate renamed wired CI (marker-owned sdlc-*.yml -> yad-*.yml); a user-authored same-named file is
616
814
  // never touched, and an edited one is kept without its new name beside it (E123, `withoutKeptRenames`).
617
815
  const repoLegacy = legacyRepoActions(root, repo);
618
816
  const repoWiring = withoutKeptRenames([...repoActions(root, repo), ...repoLegacy]).filter((a) => !repoLegacy.includes(a));
817
+ showAllowList(repo.name, repoWiring);
619
818
  applyActions(repoWiring, { force: true });
620
819
  wired.push(...repoWiring);
621
820
  applyActions(repoLegacy, { force: true });
@@ -655,6 +854,26 @@ export async function runSetup(root, opts = {}) {
655
854
  applyActions(captureWiring, { force: true });
656
855
  wired.push(...captureWiring);
657
856
  }
857
+ // E158: the rules block in AGENTS.md (and CLAUDE.md importing it), which an AI agent reads first. The team's
858
+ // own text in these files is kept; only the lines between yad's markers are written.
859
+ const agentFiles = agentFileActions(root, ideTargets);
860
+ log(` ${c.bold('product')} ${c.dim('(AGENTS.md rules for AI agents)')}`);
861
+ applyActions(agentFiles, { force: true });
862
+ // E158: the agent guard — refuses a human-only yad command, a PR/MR approval or merge, skipping the git hooks or
863
+ // a force push before the agent's shell runs it.
864
+ const agentGuard = agentGuardActions(root, ideTargets);
865
+ if (agentGuard.length) {
866
+ log(` ${c.bold('product')} ${c.dim('(agent guard)')}`);
867
+ applyActions(agentGuard, { force: true });
868
+ wired.push(...agentGuard);
869
+ }
870
+ // E158 (#353): the read-only yad commands Claude Code may run without asking — shown before they are written.
871
+ const allowList = allowListActions(root, ideTargets);
872
+ // Shown only when it will be written: a settings file that does not parse writes nothing, and says so.
873
+ if (allowList.some((a) => a.status !== 'ok' && !a.writesNothing)) {
874
+ showAllowList('product', allowList);
875
+ applyActions(allowList);
876
+ }
658
877
  // E113: the shell-script hooks a re-run replaces, once the entries above no longer name them.
659
878
  const retiredHooks = legacyHookScriptActions(root, ideTargets);
660
879
  if (retiredHooks.length) applyActions(retiredHooks, { force: true });
@@ -668,7 +887,7 @@ export async function runSetup(root, opts = {}) {
668
887
  for (const repo of registry.repos) {
669
888
  const cr = path.join(path.resolve(root, repo.path), '.coderabbit.yaml');
670
889
  if (exists(cr)) { info(`${repo.name}: .coderabbit.yaml present`); continue; }
671
- if (await askYesNo(`Wire CodeRabbit (advisory) in ${repo.name}?`, false)) {
890
+ if (connects(opts.coderabbit, repo.name) ?? await askYesNo(`Wire CodeRabbit (advisory) in ${repo.name}?`, false)) {
672
891
  fs.writeFileSync(cr, 'reviews:\n high_level_summary: true\n poem: false\n');
673
892
  ok(`${repo.name}: wrote .coderabbit.yaml`);
674
893
  }
@@ -717,12 +936,12 @@ export async function runSetup(root, opts = {}) {
717
936
  }
718
937
  log('');
719
938
  log(c.dim('Re-run anytime: `yad check` (report) / `yad check --fix` (reconcile).'));
720
- // The --json answer (E1). A --json setup never prompts: every answer comes from a flag, or the run is
721
- // refused (YAD-CLI-001) at the first question it would have asked — which can come after an earlier
722
- // step has written, so a scripted setup passes every flag (or SDLC_NONINTERACTIVE for the defaults).
939
+ // The --json answer (E1). A --json setup never prompts: every answer comes from a flag, or the run was
940
+ // refused (YAD-CLI-001, with `questions`) before anything was written (E159, `assertSetupAnswered`).
723
941
  return {
724
942
  profile: { solo, team_size, codebase, repo_layout }, ideTargets,
725
943
  repos: registry.repos.map((r) => r.name ?? null), next: epicSkill, toolbox,
944
+ ...(notes.length ? { notes } : {}),
726
945
  };
727
946
  }
728
947