yadflow 4.6.0 → 4.8.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 (136) hide show
  1. package/CHANGELOG.md +259 -0
  2. package/README.md +46 -4
  3. package/bin/commands.mjs +9 -2
  4. package/bin/yad.mjs +309 -30
  5. package/cli/agent-guard.mjs +511 -0
  6. package/cli/agent-guide.mjs +83 -0
  7. package/cli/agent-rules.mjs +381 -0
  8. package/cli/argv-flags.mjs +7 -0
  9. package/cli/artifact-status.mjs +88 -20
  10. package/cli/build.mjs +1372 -0
  11. package/cli/checkpoint.mjs +2 -2
  12. package/cli/ci-check.mjs +492 -0
  13. package/cli/commit.mjs +1 -0
  14. package/cli/dial.mjs +21 -1
  15. package/cli/docs.mjs +7 -2
  16. package/cli/doctor.mjs +176 -33
  17. package/cli/epic-state.mjs +360 -12
  18. package/cli/errors.mjs +3 -0
  19. package/cli/find-product.mjs +36 -2
  20. package/cli/fold.mjs +9 -5
  21. package/cli/gate-local.mjs +9 -1
  22. package/cli/gate.mjs +364 -22
  23. package/cli/guide.mjs +549 -0
  24. package/cli/history.mjs +22 -2
  25. package/cli/hook.mjs +35 -4
  26. package/cli/index-command.mjs +2 -2
  27. package/cli/ledger.mjs +60 -0
  28. package/cli/lib.mjs +46 -0
  29. package/cli/lifecycle/defaults/2.json +124 -0
  30. package/cli/lifecycle/lifecycle.schema.json +5 -2
  31. package/cli/lifecycle.mjs +16 -3
  32. package/cli/manifest.mjs +75 -0
  33. package/cli/marked-block.mjs +48 -0
  34. package/cli/members.mjs +19 -5
  35. package/cli/migrate.mjs +17 -19
  36. package/cli/next.mjs +35 -12
  37. package/cli/openpr.mjs +81 -5
  38. package/cli/plan.mjs +326 -22
  39. package/cli/platform.mjs +21 -0
  40. package/cli/pr-list.mjs +5 -3
  41. package/cli/product-index.mjs +6 -3
  42. package/cli/product-token.mjs +186 -0
  43. package/cli/productcommit.mjs +33 -0
  44. package/cli/protection.mjs +50 -0
  45. package/cli/recommend.mjs +3 -1
  46. package/cli/reconcile.mjs +187 -26
  47. package/cli/repo-publish.mjs +2 -2
  48. package/cli/report.mjs +62 -14
  49. package/cli/run-checks.mjs +586 -0
  50. package/cli/setup.mjs +244 -25
  51. package/cli/ship-drift.mjs +49 -18
  52. package/cli/signing.mjs +377 -0
  53. package/cli/standup.mjs +1 -1
  54. package/cli/status.mjs +282 -0
  55. package/cli/test-agents-file.mjs +993 -0
  56. package/cli/test-build.mjs +1559 -0
  57. package/cli/test-ci-check.mjs +616 -0
  58. package/cli/test-guide.mjs +1267 -0
  59. package/cli/test-node.mjs +129 -0
  60. package/cli/test-run-checks.mjs +603 -0
  61. package/cli/test-setup-agent.mjs +352 -0
  62. package/cli/test-signing.mjs +524 -0
  63. package/cli/test-worktree.mjs +520 -0
  64. package/cli/thread.mjs +4 -0
  65. package/cli/tidy.mjs +2 -2
  66. package/cli/toolbox.mjs +37 -6
  67. package/cli/update-commit.mjs +313 -11
  68. package/cli/workspace.mjs +38 -10
  69. package/cli/worktree-record.mjs +53 -0
  70. package/cli/worktree.mjs +379 -0
  71. package/package.json +6 -4
  72. package/skills/sdlc/config.yaml +5 -5
  73. package/skills/sdlc/module-help.csv +2 -1
  74. package/skills/yad-backfill/templates/checks/backfill-check.sh +9 -9
  75. package/skills/yad-change/SKILL.md +5 -1
  76. package/skills/yad-checks/SKILL.md +61 -12
  77. package/skills/yad-checks/references/check-gates.md +78 -14
  78. package/skills/yad-checks/templates/checks/build-test-lint.sh +22 -3
  79. package/skills/yad-checks/templates/checks/commit-message.sh +8 -2
  80. package/skills/yad-checks/templates/checks/contract-check.sh +61 -33
  81. package/skills/yad-checks/templates/checks/epic-open.sh +87 -14
  82. package/skills/yad-checks/templates/checks/ledger-guard.sh +3 -3
  83. package/skills/yad-checks/templates/checks/lineage-check.sh +88 -15
  84. package/skills/yad-checks/templates/checks/member-check.mjs +206 -35
  85. package/skills/yad-checks/templates/checks/package-manager.sh +42 -5
  86. package/skills/yad-checks/templates/checks/product-checkout.sh +161 -13
  87. package/skills/yad-checks/templates/checks/reconcile-debt-check.sh +94 -15
  88. package/skills/yad-checks/templates/checks/risk-map-check.sh +2 -2
  89. package/skills/yad-checks/templates/checks/spec-link.sh +63 -4
  90. package/skills/yad-checks/templates/checks/verified-commits.sh +23 -5
  91. package/skills/yad-checks/templates/github/yad-checks.yml +9 -9
  92. package/skills/yad-checks/templates/gitlab/.gitlab-ci.yml +4 -1
  93. package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +5 -5
  94. package/skills/yad-checks/templates/gitlab/yad-product-checks.gitlab-ci.yml +16 -3
  95. package/skills/yad-checks/templates/gitlab/yad-update-guard.gitlab-ci.yml +5 -1
  96. package/skills/yad-checks/templates/gitlab/yad-verified-commits.gitlab-ci.yml +5 -1
  97. package/skills/yad-checks/templates/hooks/agent-guard.mjs +116 -0
  98. package/skills/yad-commit/SKILL.md +8 -5
  99. package/skills/yad-connect-repos/SKILL.md +5 -3
  100. package/skills/yad-connect-repos/references/code-context.md +2 -1
  101. package/skills/yad-connect-repos/references/repos-registry.md +2 -1
  102. package/skills/yad-docs/templates/app/package-lock.json +395 -106
  103. package/skills/yad-docs/templates/app/package.json +2 -2
  104. package/skills/yad-docs-overview/references/pipeline-model.md +2 -2
  105. package/skills/yad-engineer-review/SKILL.md +55 -25
  106. package/skills/yad-engineer-review/references/ship-and-record.md +49 -12
  107. package/skills/yad-epic/SKILL.md +2 -1
  108. package/skills/yad-epic/references/state-schema.md +76 -17
  109. package/skills/yad-guide/SKILL.md +192 -0
  110. package/skills/yad-implement/SKILL.md +75 -13
  111. package/skills/yad-implement/references/implement-conventions.md +8 -1
  112. package/skills/yad-implement/templates/.gitmessage +3 -0
  113. package/skills/yad-open-pr/SKILL.md +21 -0
  114. package/skills/yad-pair-review/SKILL.md +14 -5
  115. package/skills/yad-pr-template/SKILL.md +6 -2
  116. package/skills/yad-pr-template/templates/checks/pr-template.sh +85 -4
  117. package/skills/yad-pr-template/templates/checks/pr-title.sh +1 -1
  118. package/skills/yad-pr-template/templates/github/pull_request_template.md +1 -1
  119. package/skills/yad-pr-template/templates/gitlab/merge_request_templates/Default.md +1 -1
  120. package/skills/yad-product-bridge/SKILL.md +44 -12
  121. package/skills/yad-product-bridge/references/bridge.md +11 -5
  122. package/skills/yad-product-bridge/templates/github/yad-gate-sync.yml +2 -2
  123. package/skills/yad-product-bridge/templates/gitlab/yad-gate-sync.gitlab-ci.yml +9 -4
  124. package/skills/yad-reconcile/SKILL.md +9 -3
  125. package/skills/yad-report/SKILL.md +15 -0
  126. package/skills/yad-review-companion/SKILL.md +5 -3
  127. package/skills/yad-review-gate/SKILL.md +16 -8
  128. package/skills/yad-review-gate/references/gating.md +26 -1
  129. package/skills/yad-run/SKILL.md +61 -33
  130. package/skills/yad-run/references/run-loop.md +44 -22
  131. package/skills/yad-spec/SKILL.md +137 -16
  132. package/skills/yad-spec/references/spec-handoff.md +50 -3
  133. package/skills/yad-status/SKILL.md +7 -0
  134. package/skills/yad-stories/references/story-schema.md +1 -1
  135. package/skills/yad-sync-repos/SKILL.md +2 -1
  136. package/skills/yad-ui/SKILL.md +2 -2
@@ -0,0 +1,186 @@
1
+ // #345 — where a connected code repo's CI gets `YAD_PRODUCT_TOKEN`, the token `checks/product-checkout.sh`
2
+ // clones the Product with before the four Product-reading gates. Without it those gates only defer, so a
3
+ // token that is missing, or set where the PR pipelines never see it, goes quiet. `yad doctor` asks the
4
+ // platform, with the user's own `gh`/`glab` (the E70 reads in cli/protection.mjs, and the same
5
+ // `YAD_PLATFORM_READ=0` off switch), and reports:
6
+ // - whether the code repo has the secret (GitHub: an Actions secret on the repo, or an organisation
7
+ // secret shared with it; GitLab: a CI/CD variable on the project, or on one of its groups);
8
+ // - on GitLab, a variable that MR pipelines never get: `protected` (only protected branches get it) or
9
+ // limited to one environment;
10
+ // - on GitLab, a token set on a GROUP — every project in that group then gets a token that reads the
11
+ // Product (the user's decision, 2026-10-19: that is the "wrong level"), with the other registered
12
+ // repos in that group named;
13
+ // - on a GitLab Product, its own access tokens that can clone it and expire within 30 days. Which of them
14
+ // is the one in a code repo's variable is never known here, and the line says so.
15
+ // NAMES ONLY. A token's value never reaches this machine from GitHub (its API lists secret names), but
16
+ // GitLab's variables API answers with each variable's value: the answer is cut down to key, `protected`
17
+ // and `environment_scope` at the call, and nothing else of it is kept or printed. The token's own expiry
18
+ // is read where the token is — in CI, by product-checkout.sh.
19
+ import { run } from './lib.mjs';
20
+ import { api, loggedIn, whyFailed, repoPathFromGitUrl, shown, PAGE, PLATFORM_NAME } from './protection.mjs';
21
+ import { cliFor, hostFromGitUrl, detectPlatform, plainHost } from './platform.mjs';
22
+
23
+ export const TOKEN_NAME = 'YAD_PRODUCT_TOKEN';
24
+ export const EXPIRY_WARN_DAYS = 30;
25
+
26
+ const enc = (p) => encodeURIComponent(p);
27
+
28
+ // The parts every platform read shares: which CLI, which host, which repo, and whether it may be asked.
29
+ function target({ platform, gitUrl }, { runner, env, authCache }) {
30
+ const rawHost = hostFromGitUrl(gitUrl || '');
31
+ const host = plainHost(rawHost);
32
+ const repo = repoPathFromGitUrl(gitUrl || '');
33
+ const plat = platform || detectPlatform(gitUrl || '') || null;
34
+ const base = { platform: plat, host, repo };
35
+ const unknown = (kind, why) => ({ ...base, known: false, kind, why });
36
+ const cli = cliFor(plat);
37
+ if (!cli) return { fail: unknown('no-platform', 'no platform yad reads (GitHub or GitLab) is set for it') };
38
+ if (env.YAD_PLATFORM_READ === '0') return { fail: unknown('off', 'platform reads are turned off (YAD_PLATFORM_READ=0)') };
39
+ if (rawHost && !host) return { fail: unknown('no-url', 'its git remote URL names a host that is not a plain host name, so yad does not ask about it') };
40
+ if (!host || !repo) return { fail: unknown('no-url', 'no git remote URL yad can read, so it cannot tell which repo to ask about') };
41
+ if (!runner(process.platform === 'win32' ? 'where' : 'which', [cli], {}).ok) return { fail: unknown('no-cli', `${cli} is not installed, so yad cannot ask ${PLATFORM_NAME[plat]}`) };
42
+ if (!loggedIn(runner, cli, host, authCache)) return { fail: unknown('no-login', `${cli} is not logged in for ${host} (or ${host} did not answer)`) };
43
+ return { base, cli, unknown };
44
+ }
45
+
46
+ // GitLab variables, cut down at the call to what may be kept: never the value.
47
+ const gitlabVars = (body) => (Array.isArray(body) ? body : [])
48
+ .filter((v) => v && v.key === TOKEN_NAME)
49
+ .map((v) => ({ protected: v.protected === true, scope: typeof v.environment_scope === 'string' ? v.environment_scope : '*' }));
50
+
51
+ // Where the code repo's CI gets the token. `{ known: false, why, kind }` when the repo's own list could not
52
+ // be read; otherwise `{ known: true, platform, project, org | groups }`, where each place is
53
+ // GitHub project: { set } org: { set: true|false|null, why }
54
+ // GitLab project: { set, vars: [{ protected, scope }] }
55
+ // groups: [{ path, set: true|false|null, vars, why }] — nearest group first
56
+ export function readTokenPlacement({ platform, gitUrl }, { runner = run, env = process.env, authCache = new Map() } = {}) {
57
+ const t = target({ platform, gitUrl }, { runner, env, authCache });
58
+ if (t.fail) return t.fail;
59
+ const { base, unknown } = t;
60
+ const { host, repo } = base;
61
+ if (base.platform === 'github') {
62
+ const what = `the Actions secrets of ${shown(repo)}`;
63
+ const r = api(runner, 'gh', host, `repos/${repo}/actions/secrets?per_page=${PAGE}`);
64
+ if (!r.ok || !Array.isArray(r.body?.secrets)) return unknown('other', r.ok ? `GitHub answered ${what} with something yad could not read` : whyFailed(r, { platform: 'github', host, what, plural: true }));
65
+ const set = r.body.secrets.some((s) => s?.name === TOKEN_NAME);
66
+ // A full page that does not hold the name proves nothing about the next one.
67
+ if (!set && r.body.secrets.length >= PAGE) return unknown('partial', `${shown(repo)} has more than ${PAGE} Actions secrets, and yad reads one page`);
68
+ if (set) return { ...base, known: true, project: { set: true } };
69
+ const o = api(runner, 'gh', host, `repos/${repo}/actions/organization-secrets?per_page=${PAGE}`);
70
+ const orgRead = o.ok && Array.isArray(o.body?.secrets);
71
+ const orgSet = orgRead ? o.body.secrets.some((s) => s?.name === TOKEN_NAME) : null;
72
+ const orgWhy = orgRead ? (!orgSet && o.body.secrets.length >= PAGE ? `it shares more than ${PAGE}, and yad reads one page` : null)
73
+ : (o.ok ? 'GitHub answered with something yad could not read' : whyFailed(o, { platform: 'github', host, what: 'the organisation secrets shared with it', plural: true }));
74
+ return { ...base, known: true, project: { set: false }, org: { set: orgWhy ? null : orgSet, why: orgWhy } };
75
+ }
76
+ const what = `the CI/CD variables of ${shown(repo)}`;
77
+ const r = api(runner, 'glab', host, `projects/${enc(repo)}/variables?per_page=${PAGE}`);
78
+ if (!r.ok || !Array.isArray(r.body)) return unknown('other', r.ok ? `GitLab answered ${what} with something yad could not read` : whyFailed(r, { platform: 'gitlab', host, what, plural: true }));
79
+ const vars = gitlabVars(r.body);
80
+ if (!vars.length && r.body.length >= PAGE) return unknown('partial', `${shown(repo)} has more than ${PAGE} CI/CD variables, and yad reads one page`);
81
+ // Its groups, nearest first: `a/b/c` is in `a/b`, which is in `a`. A group's variable reaches every
82
+ // project under it. Reading a group's variables needs a maintainer or owner there.
83
+ const parts = repo.split('/');
84
+ const groups = [];
85
+ // A project in a user's own namespace (`someone/app`) has no groups. The project's own answer says whose
86
+ // namespace it is, and anyone who can read its variables can read it — `namespaces/<user>` answers 404
87
+ // to all but that user and an admin (review 2).
88
+ const proj = api(runner, 'glab', host, `projects/${enc(repo)}`);
89
+ const userNs = proj.ok && proj.body?.namespace?.kind === 'user';
90
+ for (let i = userNs ? 0 : parts.length - 1; i >= 1; i--) {
91
+ const g = parts.slice(0, i).join('/');
92
+ const gr = api(runner, 'glab', host, `groups/${enc(g)}/variables?per_page=${PAGE}`);
93
+ if (!gr.ok || !Array.isArray(gr.body)) {
94
+ groups.push({ path: g, set: null, vars: [], why: gr.ok ? 'GitLab answered with something yad could not read' : whyFailed(gr, { platform: 'gitlab', host, what: `the CI/CD variables of the group ${shown(g)}`, plural: true }) });
95
+ continue;
96
+ }
97
+ const gv = gitlabVars(gr.body);
98
+ const full = !gv.length && gr.body.length >= PAGE;
99
+ groups.push({ path: g, set: full ? null : gv.length > 0, vars: gv, why: full ? `it has more than ${PAGE} CI/CD variables, and yad reads one page` : null });
100
+ }
101
+ return { ...base, known: true, project: { set: vars.length > 0, vars }, groups };
102
+ }
103
+
104
+ // What a set of GitLab variables misses: MR pipelines on unprotected branches never get a protected one,
105
+ // and get an environment-scoped one only in a job that names that environment (the gate jobs name none).
106
+ function reachProblem(vars) {
107
+ if (!vars.length) return null;
108
+ if (vars.some((v) => !v.protected && v.scope === '*')) return null;
109
+ if (vars.every((v) => v.protected)) return 'it is a PROTECTED variable, which only pipelines on protected branches get — so no merge request from a feature branch does';
110
+ return `it is limited to the environment ${vars.filter((v) => v.scope !== '*').map((v) => shown(v.scope)).join(', ')}, which the gate jobs do not name — so they never get it`;
111
+ }
112
+ const UNPROTECT = 'Settings → CI/CD → Variables: edit it, untick "Protect variable", keep "Mask variable", and set the environment to All (*)';
113
+
114
+ // One doctor line for one code repo: { status, message, hint }. `others(groupPath)` names the other
115
+ // registered repos in that group.
116
+ export function tokenLine(r, { name, others = () => [] } = {}) {
117
+ const who = name;
118
+ // A warn, as E70's "not known" is: doctor prints ok, warn and fail only (review 1).
119
+ if (!r.known) return { status: 'warn', message: `${who}: whether ${TOKEN_NAME} is set for its CI is not known — ${r.why}` };
120
+ const defer = 'contract-check, lineage-check, epic-open and reconcile-debt-check cannot read the Product there and only defer';
121
+ if (r.platform === 'github') {
122
+ if (r.project.set) return { status: 'ok', message: `${who}: ${TOKEN_NAME} is set as an Actions secret` };
123
+ if (r.org.set === true) return { status: 'ok', message: `${who}: ${TOKEN_NAME} comes from an organisation secret shared with it` };
124
+ const add = `add a token that can read the Product: gh secret set ${TOKEN_NAME} --repo ${shown(r.repo)}`;
125
+ if (r.org.set === null) return { status: 'warn', message: `${who}: ${TOKEN_NAME} is not an Actions secret of the repo, and the organisation secrets shared with it could not be read (${r.org.why}) — unless it is one of those, ${defer} on every PR`, hint: add };
126
+ return { status: 'warn', message: `${who}: ${TOKEN_NAME} is not set for its CI — ${defer} on every PR`, hint: add };
127
+ }
128
+ const groupSet = r.groups.filter((g) => g.set === true);
129
+ const unread = r.groups.filter((g) => g.set === null);
130
+ const groupNote = (g) => {
131
+ const also = others(g.path);
132
+ return `the group ${shown(g.path)} also sets ${TOKEN_NAME}, so every project in it gets a token that can read the Product${also.length ? ` (registered here: ${also.join(', ')})` : ''}`;
133
+ };
134
+ if (r.project.set) {
135
+ const miss = reachProblem(r.project.vars);
136
+ if (miss) return { status: 'warn', message: `${who}: ${TOKEN_NAME} is set on the project, but ${miss} and ${defer} on them`, hint: UNPROTECT };
137
+ if (groupSet.length) return { status: 'warn', message: `${who}: ${TOKEN_NAME} is set on the project, and ${groupNote(groupSet[0])}`, hint: `remove it from the group's CI/CD variables (Settings → CI/CD → Variables of ${shown(groupSet[0].path)}) unless every project there should read the Product` };
138
+ return { status: 'ok', message: `${who}: ${TOKEN_NAME} is set on the project` };
139
+ }
140
+ if (groupSet.length) {
141
+ const g = groupSet[0];
142
+ const miss = reachProblem(g.vars);
143
+ const also = others(g.path);
144
+ return {
145
+ status: 'warn',
146
+ message: `${who}: ${TOKEN_NAME} comes from the group ${shown(g.path)}, so every project in that group gets a token that can read the Product${also.length ? ` (registered here: ${also.join(', ')})` : ''}${miss ? `; and ${miss}` : ''}`,
147
+ hint: `set it on the project instead (Settings → CI/CD → Variables: masked, not protected, all environments), then remove it from the group ${shown(g.path)}`,
148
+ };
149
+ }
150
+ const add = `add a token that can read the Product as the ${TOKEN_NAME} CI/CD variable of ${shown(r.repo)} (Settings → CI/CD → Variables: masked, not protected, all environments)`;
151
+ if (unread.length) {
152
+ return { status: 'warn', message: `${who}: ${TOKEN_NAME} is not set on the project, and ${unread.length === 1 ? `the group ${shown(unread[0].path)} could` : `the groups ${unread.map((g) => shown(g.path)).join(', ')} could`} not be read (${unread[0].why}) — unless it is set there, ${defer} on every merge request`, hint: add };
153
+ }
154
+ return { status: 'warn', message: `${who}: ${TOKEN_NAME} is not set on the project or its groups — ${defer} on every merge request`, hint: add };
155
+ }
156
+
157
+ // A GitLab Product's own access tokens that can clone it and expire within EXPIRY_WARN_DAYS, or expired
158
+ // within the last EXPIRY_WARN_DAYS. `today` is
159
+ // YYYY-MM-DD (injectable for tests). `{ known: false, why }`, or `{ known: true, soon: [{ name, expires,
160
+ // days, scopes }] }`.
161
+ export function readExpiringProductTokens({ gitUrl }, { runner = run, env = process.env, authCache = new Map(), today = new Date().toISOString().slice(0, 10) } = {}) {
162
+ const t = target({ platform: 'gitlab', gitUrl }, { runner, env, authCache });
163
+ if (t.fail) return t.fail;
164
+ const { base, unknown } = t;
165
+ const what = `the access tokens of ${shown(base.repo)}`;
166
+ const r = api(runner, 'glab', base.host, `projects/${enc(base.repo)}/access_tokens?per_page=${PAGE}`);
167
+ if (!r.ok || !Array.isArray(r.body)) return unknown('other', r.ok ? `GitLab answered ${what} with something yad could not read` : whyFailed(r, { platform: 'gitlab', host: base.host, what, plural: true }));
168
+ const day = (d) => Date.parse(`${d}T00:00:00Z`) / 864e5;
169
+ const soon = [];
170
+ for (const tok of r.body) {
171
+ // An EXPIRED token is listed with `active: false`: kept, so doctor says it expired (review 1). Only a
172
+ // revoked one is gone on purpose.
173
+ if (!tok || tok.revoked === true) continue;
174
+ const scopes = Array.isArray(tok.scopes) ? tok.scopes.filter((s) => typeof s === 'string') : [];
175
+ if (!scopes.some((s) => s === 'read_repository' || s === 'api')) continue;
176
+ const exp = typeof tok.expires_at === 'string' && /^\d{4}-\d{2}-\d{2}/.test(tok.expires_at) ? tok.expires_at.slice(0, 10) : null;
177
+ if (!exp) continue;
178
+ const days = Math.round(day(exp) - day(today));
179
+ // Within 30 days either side: one that expired long ago is no news, and GitLab offers no way to remove
180
+ // an expired token from its list, so a line about it could never be cleared (review 3).
181
+ if (days <= EXPIRY_WARN_DAYS && days >= -EXPIRY_WARN_DAYS) soon.push({ id: Number.isInteger(tok.id) ? tok.id : null, name: typeof tok.name === 'string' ? tok.name : `#${tok.id}`, expires: exp, days, scopes });
182
+ }
183
+ // A full page proves nothing about the tokens past it (review 1).
184
+ if (r.body.length >= PAGE) return unknown('partial', `${shown(base.repo)} has more than ${PAGE} access tokens, and yad reads one page`);
185
+ return { ...base, known: true, soon };
186
+ }
@@ -4,6 +4,7 @@
4
4
  // strand required checks and fail verified-commits). This module is the single home of that guard.
5
5
  import { warn, fail, hand, run, forTerminal } from './lib.mjs';
6
6
  import { SETTINGS_EDIT_HINT, settingsEditHint } from './manifest.mjs';
7
+ import { worktreeAt } from './worktree-record.mjs';
7
8
 
8
9
  export const productGit = (root) => (...args) => run('git', args, { cwd: root });
9
10
 
@@ -30,6 +31,32 @@ export function resolveDefaultBranch(git, productConfig) {
30
31
  || 'main';
31
32
  }
32
33
 
34
+ // The branch a default-branch command commits on: the current one — or, in an epic's Product worktree
35
+ // (#115), which sits DETACHED because the default branch is checked out in the main tree, the default
36
+ // branch itself, so the commit is pushed as HEAD:<default>. Only when every commit HEAD holds that the
37
+ // default branch lacks (fetched first) is one of yad's own default-branch commits — each subject is
38
+ // `chore(product|gate): … [skip ci]`, so a `Revert "…"` of one, or a step's commit, is not. One a run made
39
+ // without --push, or whose push failed, is pushed by the next run, as in the main checkout. Anything else (a step's unreviewed work) must never reach the default branch. A detached
40
+ // HEAD anywhere else stays 'HEAD', and the guard below refuses it as before.
41
+ // `fetch: false` judges by the local origin/<default> — for a caller that writes a derived file and pushes
42
+ // nothing (the index refresh): a stale or missing ref can only make it skip — unless the default branch
43
+ // was rewound — and it asks no network.
44
+ export function branchToCommitOn(root, git, defaultBranch, { fetch = true } = {}) {
45
+ const branch = git('rev-parse', '--abbrev-ref', 'HEAD').stdout;
46
+ return branch === 'HEAD' && worktreeAt(root)?.repo === null && onlyYadCommitsAhead(git, defaultBranch, { fetch }) ? defaultBranch : branch;
47
+ }
48
+
49
+ // The subject every yad default-branch commit has (checkpoint, tidy, repo refresh, gate ci/repair/reopen).
50
+ export const YAD_COMMIT_SUBJECT = /^chore\((product|gate)\): .* \[skip ci\]$/;
51
+ // HEAD holds nothing origin/<default> lacks but yad's own `[skip ci]` commits. False when the fetch or the
52
+ // read fails: unknown is not safe.
53
+ export function onlyYadCommitsAhead(git, defaultBranch, { fetch = true } = {}) {
54
+ if (fetch && !git('fetch', '--quiet', 'origin', `+refs/heads/${defaultBranch}:refs/remotes/origin/${defaultBranch}`).ok) return false;
55
+ const ahead = git('log', '--format=%s', `origin/${defaultBranch}..HEAD`);
56
+ if (!ahead.ok) return false;
57
+ return ahead.stdout.split('\n').filter(Boolean).every((s) => YAD_COMMIT_SUBJECT.test(s));
58
+ }
59
+
33
60
  // Guard: only commit on the default branch. Returns true when OK; on a non-default branch it prints the
34
61
  // refusal + sets a non-zero exit code, unless `allowBranch` overrides (with a warning). `--allow-branch`
35
62
  // is the SINGLE documented override — never `--force` (which elsewhere only waives the atomic guard).
@@ -43,6 +70,12 @@ export function guardDefaultBranch(branch, defaultBranch, { allowBranch = false,
43
70
  return true;
44
71
  }
45
72
  fail(`on '${b}', not the default branch '${d}' — ${cmd} commits go to the default branch to stay out of PR-checked ranges`);
73
+ // An epic worktree (#115) refused here holds commits origin/<default> lacks, or could not fetch it.
74
+ if (branch === 'HEAD' && root && worktreeAt(root)?.repo === null) {
75
+ hand(`this epic worktree's HEAD has commits origin/${d} does not that are not yad's own (or the fetch failed) — a step's work goes on its branch and through review: \`git switch -c <step>/<epic>\` keeps it, then \`git fetch origin ${d}\` and \`git switch --detach origin/${d}\``);
76
+ process.exitCode = 1;
77
+ return false;
78
+ }
46
79
  hand(`switch to '${d}' and re-run, or pass --allow-branch to override (if '${d}' is wrong, set default_branch in ${root ? settingsEditHint(root) : SETTINGS_EDIT_HINT})`);
47
80
  process.exitCode = 1;
48
81
  return false;
@@ -714,3 +714,53 @@ function unknownHint(r) {
714
714
  default: return 'fix what the message names, then run `yad doctor` again; nothing about this repo\'s protection is assumed meanwhile';
715
715
  }
716
716
  }
717
+
718
+ // E160b — what `yad ci check` reads beyond protection and approvals: the rules that make yad's checks hold a
719
+ // merge. Read-only, the same calls `readProtection` makes plus a few GETs, and the same trap: a failed call is
720
+ // never "none". `readProtection` runs first, so a repo that cannot be read (no platform, reads turned off,
721
+ // no login…) comes back with only `protection`, and every platform row is "not known" with its reason.
722
+ // GitHub — `rules`: the active rules on the branch (null when not read; `full` when a whole page came
723
+ // back, which proves nothing about what is past it). `classic`: classic branch protection, the
724
+ // string 'none' when PROVEN absent (the branch reads `protected: false`, or GitHub answers 404 with
725
+ // exactly "Branch not protected"), or null — GitHub answers a bare 404 to anyone who is not an
726
+ // admin, even on a protected branch.
727
+ // GitLab — the project's merge settings, the protected-branch entries that match the branch (null when not
728
+ // read), the approval settings (Premium) and the push rule (Premium; a 404 is "no push rule").
729
+ export function readCiSettings(target, { runner: ask = run, env = process.env, authCache = new Map() } = {}) {
730
+ // One answer per call for this repo: `readProtection` and the reads below ask some of the same paths, and
731
+ // two answers to one question could disagree.
732
+ const answers = new Map();
733
+ const runner = (cmd, args, opts) => {
734
+ if (args[0] !== 'api') return ask(cmd, args, opts);
735
+ const key = [cmd, ...args].join('\0');
736
+ if (!answers.has(key)) answers.set(key, ask(cmd, args, opts));
737
+ return answers.get(key);
738
+ };
739
+ const protection = readProtection(target, { runner, env, authCache });
740
+ if (!protection.known) return { protection };
741
+ const { platform, host, repo, branch } = protection;
742
+ if (platform === 'github') {
743
+ const at = `repos/${repo.split('/').map(encodeURIComponent).join('/')}`;
744
+ const r = api(runner, 'gh', host, `${at}/rules/branches/${segment(branch)}?per_page=${PAGE}`);
745
+ const rules = r.ok && Array.isArray(r.body) ? r.body : null;
746
+ let classic = null;
747
+ if (protection.protected === false) classic = 'none';
748
+ else {
749
+ const c = api(runner, 'gh', host, `${at}/branches/${segment(branch)}/protection`);
750
+ if (c.ok && c.body && typeof c.body === 'object' && !Array.isArray(c.body)) classic = c.body;
751
+ else if (c.status === 404 && c.body?.message === 'Branch not protected') classic = 'none';
752
+ }
753
+ return { protection, rules, rulesFull: !!rules && rules.length >= PAGE, classic };
754
+ }
755
+ const at = `projects/${encodeURIComponent(repo)}`;
756
+ const obj = (res) => (res.ok && res.body && typeof res.body === 'object' && !Array.isArray(res.body) ? res.body : null);
757
+ const project = obj(api(runner, 'glab', host, at));
758
+ const pb = api(runner, 'glab', host, `${at}/protected_branches?per_page=${PAGE}`);
759
+ const list = pb.ok && Array.isArray(pb.body) ? pb.body : null;
760
+ const matched = list ? list.filter((p) => branchMatches(p?.name, branch)) : null;
761
+ const approvals = obj(api(runner, 'glab', host, `${at}/approvals`));
762
+ const pr = api(runner, 'glab', host, `${at}/push_rule`);
763
+ // No push rule is set: GitLab answers 404, or (on some versions) 200 with an empty body.
764
+ const pushRule = obj(pr) ?? (pr.ok || pr.status === 404 ? 'none' : null);
765
+ return { protection, project, matched, matchedFull: !!list && list.length >= PAGE, approvals, pushRule };
766
+ }
package/cli/recommend.mjs CHANGED
@@ -142,7 +142,9 @@ export const RECOMMENDATIONS = Object.freeze([
142
142
 
143
143
  // ---- checking an entry ------------------------------------------------------------------------------
144
144
 
145
- const POOLS = () => TOOLBOX.filter((t) => t.tier === 'recommended').map((t) => t.id);
145
+ // The skill pools: the recommended tools `yad skill bind` takes skills from. Docker MCP is recommended too,
146
+ // but it is a gateway, not a pool (#361).
147
+ const POOLS = () => TOOLBOX.filter((t) => t.tier === 'recommended' && t.usedBy.includes('yad skill bind')).map((t) => t.id);
146
148
  const bindable = (step) => !!stepDef(step)?.skill && STEPS.some((s) => s.id === step);
147
149
 
148
150
  // Every way an entry is malformed, as sentences; [] means it is well formed. The vetting record is
package/cli/reconcile.mjs CHANGED
@@ -1,10 +1,11 @@
1
1
  // `yad check` (report) and `yad check --fix` (reconcile) — and `yad update`
2
2
  // as a thin alias (--scope=changed). Inspects actual project state against the
3
3
  // manifest: missing setup, drifted files, stale code-context.
4
+ import { spawnSync } from 'node:child_process';
4
5
  import fs from 'node:fs';
5
6
  import path from 'node:path';
6
7
  import {
7
- c, log, ok, info, warn, hand, readJSON, writeJSON, exists, forTerminal,
8
+ c, log, ok, info, warn, fail, hand, readJSON, writeJSON, exists, forTerminal, run, samePath,
8
9
  } from './lib.mjs';
9
10
 
10
11
  const readFileSafe = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch { return ''; } };
@@ -12,12 +13,13 @@ const readFileSafe = (p) => { try { return fs.readFileSync(p, 'utf8'); } catch {
12
13
  import { preflightGuardReadiness } from './productcommit.mjs';
13
14
  import { VERSION, PROJECT_FILES, MANAGED_LEDGER, BACKUP_SUFFIX , productConfigPath, PRODUCT_LINK } from './manifest.mjs';
14
15
  import {
15
- moduleActions, repoActions, productActions, hookActions,
16
+ moduleActions, repoActions, productActions, hookActions, agentFileActions, agentGuardActions, orphanAgentGuardActions, allowListActions, orphanAllowListActions, repoOrphanAgentGuardActions,
16
17
  legacyModuleActions, removedModuleActions, orphanHookActions, captureHookActions, orphanCaptureHookActions, legacyHookScriptActions, legacyRepoActions, legacyProductActions,
17
18
  ideTargetStateFor, recordManagedWrites, gitHookActions, orphanGitHookActions, gitHookState, gitHookAdvice, renamedNameHits, withoutKeptRenames, PRODUCT_PROFILE_GATES, productProfileGap, productProfileEffect, PRODUCT_PROFILE_FIX, workflowsPassingProduct, productGateBlockers, oldProfileAdvice,
18
19
  } from './plan.mjs';
19
20
  import { gitHead, packRepo } from './setup.mjs';
20
- import { groupByRoot, commitUpdates, repoLabel } from './update-commit.mjs';
21
+ import { groupByRoot, commitUpdates, openUpdatePrs, repoLabel, updatePrBlocker, updateTargets, HELD_KINDS } from './update-commit.mjs';
22
+ import { createPr } from './platform.mjs';
21
23
  import { hasSiblingRepo, workspaceFileState, writeWorkspaceFile, WORKSPACE_FILE } from './find-product.mjs';
22
24
  import { offerToolbox } from './toolbox.mjs';
23
25
 
@@ -31,7 +33,7 @@ const repoShown = (repo) => `product (the code repo at ${forTerminal(repo.path)}
31
33
  const shown = (a) => a.shownScope ?? a.scope;
32
34
  const itemsOf = (actions) => actions.map((a) => ({ scope: a.scope, item: a.item, status: a.status, product: !a.fromRepo }));
33
35
 
34
- export async function reconcile(root, { fix = false, scope = 'all', force = false, push = false, allowBranch = false, overwriteLocal = false, toolbox: toolboxAt = null } = {}) {
36
+ export async function reconcile(root, { fix = false, scope = 'all', force = false, push = false, openPr = false, allowBranch = false, overwriteLocal = false, toolbox: toolboxAt = null, creator = createPr } = {}) {
35
37
  log(c.bold(`\nSDLC reconcile ${c.dim('v' + VERSION)}`));
36
38
  log(c.dim(`target: ${root}\n`));
37
39
 
@@ -60,6 +62,12 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
60
62
  ...moduleActions(root, ideTargets), ...legacyModuleActions(root, ideTargets), ...removedModuleActions(root, ideTargets),
61
63
  // E123: a renamed CI file the team edited is kept, and its new name is not installed beside it.
62
64
  ...withoutKeptRenames([...productActions(root), ...legacyProductActions(root)]), ...hookActions(root, ideTargets),
65
+ // E158: the rules block in AGENTS.md (and CLAUDE.md importing it), which every agent reads first.
66
+ ...agentFileActions(root, ideTargets),
67
+ // E158: the agent guard, before every shell command the agent runs.
68
+ ...agentGuardActions(root, ideTargets), ...orphanAgentGuardActions(root, ideTargets),
69
+ // E158 (#353): the read-only yad commands, pre-approved for Claude Code.
70
+ ...allowListActions(root, ideTargets), ...orphanAllowListActions(root, ideTargets),
63
71
  ...orphanHookActions(root, ideTargets),
64
72
  // E48: this clone's git pre-commit hook — the person's half of the ledger guard.
65
73
  ...gitHookActions(root), ...orphanGitHookActions(root),
@@ -80,7 +88,10 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
80
88
  });
81
89
  }
82
90
  for (const repo of registry.repos) {
83
- const own = withoutKeptRenames([...repoActions(root, repo), ...legacyRepoActions(root, repo)]);
91
+ const repoRoot = path.resolve(root, repo.path);
92
+ // E158b: a target that left takes yad's guard and allow-list entries out of the repo's own settings too.
93
+ const orphans = samePath(repoRoot, path.resolve(root)) ? [] : repoOrphanAgentGuardActions(repoRoot, ideTargets, { scope: repo.name });
94
+ const own = withoutKeptRenames([...repoActions(root, repo), ...legacyRepoActions(root, repo)]).concat(orphans);
84
95
  // Set on the action itself: later steps compare actions by identity. `true`, not the name, which may be empty.
85
96
  for (const a of own) { a.fromRepo = true; if (repo.name === 'product') a.shownScope = repoShown(repo); }
86
97
  actions.push(...own);
@@ -169,7 +180,10 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
169
180
  // A managed file the team edited is NEVER rewritten by a plain update — that silent clobber is what
170
181
  // #164 reported. It is reported on every run (honest drift) until either the edit is dropped or
171
182
  // `--overwrite-local` replaces it, which still saves the previous content beside it.
172
- const modified = actions.filter((a) => a.status === 'modified');
183
+ // An action that writes nothing (`writesNothing`: a settings file that does not parse, rules-block markers yad
184
+ // cannot trust) has said why at plan time, and `--overwrite-local` cannot fix it either: it is left out here
185
+ // and from what --fix applies, so no run says it was fixed.
186
+ const modified = actions.filter((a) => a.status === 'modified' && !a.writesNothing);
173
187
  for (const m of modified) {
174
188
  // The product-link record has no template: it is `modified` only when it is not a JSON object (E120).
175
189
  warn(m.item === PRODUCT_LINK
@@ -224,8 +238,9 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
224
238
  hand(`keep the edits (reported as \`modified\` on every check), or replace them with \`yad update --overwrite-local\` — each previous version is saved beside the file as <file>${BACKUP_SUFFIX}`);
225
239
  }
226
240
 
227
- const fixable = actions.filter((a) =>
241
+ let fixable = actions.filter((a) =>
228
242
  a.status !== 'ok'
243
+ && !a.writesNothing
229
244
  && (a.status !== 'modified' || overwriteLocal)
230
245
  && (scope === 'all' ? true : a.status !== 'missing'),
231
246
  );
@@ -238,21 +253,110 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
238
253
  let workspaceFile = wsNeeded ? workspaceFileState(root) : null;
239
254
  if (!fix) {
240
255
  if (workspaceFile === 'missing') info(`no ${WORKSPACE_FILE} beside the Product — \`yad check --fix\` writes it, so yad finds the Product from its code repos`);
241
- if (push) warn('--push has no effect without --fix (there is nothing applied to commit).');
256
+ if (push || openPr) warn(`${push ? '--push' : '--open-pr'} has no effect without --fix (there is nothing applied to commit).`);
242
257
  if (fixable.length || gaps.length) hand('run `yad check --fix` to reconcile (or `yad setup` for missing one-time setup).');
243
258
  // After the --fix hint, never above it: --fix installs no tool, and must not read as if it did.
244
259
  const toolbox = toolboxSection(root, toolboxAt);
245
260
  return { fix: false, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: [], workspaceFile, toolbox };
246
261
  }
247
262
 
263
+ // Each repo's default branch and platform, for --push and --open-pr.
264
+ const productSettings = readJSON(productConfigPath(root), {});
265
+ const defByRoot = new Map([[root, productSettings?.default_branch]]);
266
+ const platformByRoot = new Map([[root, productSettings?.platform]]);
267
+ for (const repo of registry.repos) {
268
+ const repoRoot = path.resolve(root, repo.path);
269
+ // A monorepo entry (`path: "."`) is the Product itself: its settings are the Product's.
270
+ if (repoRoot === root) continue;
271
+ defByRoot.set(repoRoot, repo.default_branch);
272
+ platformByRoot.set(repoRoot, repo.platform);
273
+ }
274
+
275
+ // --open-pr is all or nothing (E157 update reviews 2 and 3). The Product and every connected repo cloned
276
+ // here (`updateTargets`, the one list the guide reads too) are checked BEFORE anything is written: each must
277
+ // be on its default branch, not detached, with an origin and no local commits origin lacks. One that is not
278
+ // stops the whole run with nothing written, so no repo is left half updated, no one's feature work rides an
279
+ // update PR/MR, and no one is moved off their branch: the person fixes it and runs it again. A repo whose
280
+ // update is already on review (`open`) is left alone (`held`): nothing is written there until it merges.
281
+ let held = new Set();
282
+ let heldRows = [];
283
+ let reached = null;
284
+ if (openPr) {
285
+ const targets = updateTargets(root);
286
+ reached = new Set(targets.map((t) => t.root));
287
+ const checks = targets.map((t) => [t.root, updatePrBlocker(t.root, { defaultBranch: t.defaultBranch ?? defByRoot.get(t.root), productRoot: root, file: t.file })]);
288
+ const stop = checks.filter(([, b]) => b && !HELD_KINDS.includes(b.kind));
289
+ // Every row says why, in `reason` (a word) and `hint` (what to do): the agent relays it to the person.
290
+ const row = (r, b) => ({ label: b.label, product: r === root, branch: b.branch ?? null, committed: false, pushed: false, opened: false, pr: null, skipped: true, error: !HELD_KINDS.includes(b.kind), reason: b.kind, hint: b.message });
291
+ if (stop.length) {
292
+ log('');
293
+ for (const [, b] of stop) fail(`${b.label}: ${b.message}`);
294
+ fail(`--open-pr: ${stop.length} repo(s) cannot take the update as a PR/MR now — nothing was written; fix the above, then run it again`);
295
+ process.exitCode = 1;
296
+ const toolbox = toolboxSection(root, toolboxAt);
297
+ return { fix: true, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: stop.map(([r, b]) => row(r, b)), workspaceFile, toolbox };
298
+ }
299
+ held = new Set(checks.filter(([, b]) => b).map(([r]) => r));
300
+ heldRows = checks.filter(([, b]) => b).map(([r, b]) => row(r, b));
301
+ for (const [, b] of checks) if (b) info(`${b.label}: ${b.message}`);
302
+ if (held.size === checks.length) {
303
+ info('every repo\'s update is already merged or on review — nothing written');
304
+ const toolbox = toolboxSection(root, toolboxAt);
305
+ return { fix: true, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: checks.map(([r, b]) => row(r, b)), workspaceFile, toolbox };
306
+ }
307
+ fixable = fixable.filter((a) => (!a.root || reached.has(a.root)) && !held.has(a.root) && (!a.managed?.root || reached.has(a.managed.root)) && !held.has(a.managed?.root));
308
+ }
309
+ // Under --open-pr, only a repo it checked and did not hold is written (a registered repo not cloned here is
310
+ // `yad repo clone`'s business).
311
+ const reaches = (r) => !r || ((!reached || reached.has(r)) && !held.has(r));
312
+ const live = (a) => reaches(a.root) && reaches(a.managed?.root);
313
+
314
+ // A file the team co-owns (the agent settings that run yad's hooks) is never staged by `--push`. Under
315
+ // --open-pr it rides the PR/MR when it is yad's alone: exactly what is committed (or nothing) with yad's
316
+ // entries merged in — so a file this run creates rides too, and so does one a failed push left behind.
317
+ // Otherwise the person has their own edits in it, which never ride an update: said in a row of its own.
318
+ // Read BEFORE anything is applied. Several adapters can share one file, so it is one entry per file
319
+ // (E157 update review 11).
320
+ const shared = new Map();
321
+ const sharedText = (f) => (exists(f) ? fs.readFileSync(f, 'utf8') : null);
322
+ if (openPr) {
323
+ for (const a of actions) {
324
+ // Only a file this run writes, or one already right: a rules block `yad update` leaves out (an unwired
325
+ // repo's AGENTS.md is `missing`) or one it cannot write (`writesNothing`) is never staged or reported
326
+ // (E158 review 4).
327
+ if (!a.shared || !a.root || !live(a) || (a.status !== 'ok' && !fixable.includes(a))) continue;
328
+ const file = path.join(a.root, a.shared);
329
+ if (!shared.has(file)) {
330
+ // A text file is read as committed, not trimmed (`run` trims): its trailing lines are part of the text
331
+ // yad's block is merged into (E158 review 1).
332
+ let head;
333
+ if (a.kind === 'text') {
334
+ const r = spawnSync('git', ['show', `HEAD:${a.shared}`], { cwd: a.root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, windowsHide: true });
335
+ head = r.status === 0 ? r.stdout : null;
336
+ } else {
337
+ const r = run('git', ['show', `HEAD:${a.shared}`], { cwd: a.root, maxBuffer: 64 * 1024 * 1024 });
338
+ head = r.ok ? r.stdout : null;
339
+ }
340
+ shared.set(file, { a, merges: [], disk: sharedText(file), head });
341
+ }
342
+ shared.get(file).merges.push(a.mergeShared);
343
+ }
344
+ }
248
345
  // --- apply --- (collect the applied actions so --push can stage each repo's exact allowlist) ---
249
346
  log('');
250
347
  let applied = 0;
251
348
  const appliedActions = [];
349
+ // Under --open-pr a skill folder keeps a person's own files and is staged by the template's files only, so
350
+ // nothing of theirs is deleted from disk or rides the PR/MR (E157 update review 7).
351
+ const keepOwn = (a) => {
352
+ if (!openPr || typeof a.applyKeepingOwn !== 'function') { a.apply(); return a; }
353
+ const kept = a.applyKeepingOwn();
354
+ if (kept.length) info(`kept ${kept.length} file(s) the template does not have in ${shown(a)}/${a.item} — delete any that an older yadflow shipped`);
355
+ return { ...a, paths: a.ownPaths() };
356
+ };
252
357
  for (const a of fixable) {
253
- a.apply();
358
+ appliedActions.push(keepOwn(a));
254
359
  applied++;
255
- appliedActions.push(a);
256
360
  // A backup means the replaced content was not provably ours (a pre-ledger install, or an edit
257
361
  // --overwrite-local was told to discard). Never report that as an ordinary template adoption.
258
362
  info(`${a.status} → fixed: ${shown(a)}/${a.item}${a.backup ? ` ${c.yellow(`(previous content saved to ${path.basename(a.backup)})`)}` : ''}`);
@@ -260,19 +364,80 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
260
364
  if (force) {
261
365
  // --force re-copies what is already correct; it deliberately does NOT reach a `modified` file —
262
366
  // only --overwrite-local discards a local edit, and only after backing it up.
263
- for (const a of actions.filter((a) => a.status === 'ok')) { a.apply(); appliedActions.push(a); }
367
+ for (const a of actions.filter((a) => a.status === 'ok' && live(a))) appliedActions.push(keepOwn(a));
264
368
  }
265
369
  // A file that is right on disk but not committed as it stands, which --push must still commit: the
266
370
  // product-link record (E120) — the gates read it from the default branch, not from anyone's disk.
267
- if (push) for (const a of actions) if (a.pendingCommit && !appliedActions.includes(a)) appliedActions.push(a);
371
+ if (push || openPr) for (const a of actions) if (a.pendingCommit && live(a) && !appliedActions.includes(a)) appliedActions.push(a);
372
+ // --open-pr also stages every managed file already right on disk: `stageAllowlist` keeps only what differs
373
+ // from the commit, so an update a failed commit or push left in the working tree is carried by the next run.
374
+ // A folder is staged by its template's own files only, never the folder: a person's own file beside them
375
+ // (notes in a skill folder) must not ride an update PR/MR.
376
+ if (openPr) {
377
+ for (const a of actions) {
378
+ if (a.status !== 'ok' || !a.root || !Array.isArray(a.paths) || !live(a) || appliedActions.includes(a)) continue;
379
+ appliedActions.push(typeof a.ownPaths === 'function' ? { ...a, paths: a.ownPaths() } : a);
380
+ }
381
+ }
382
+ const sharedRows = [];
383
+ const lf = (t) => t.replace(/\r\n/g, '\n');
384
+ const parse = (t) => { try { const v = JSON.parse(t); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } };
385
+ // A settings file is JSON, merged as objects; a rules file (AGENTS.md, CLAUDE.md, E158) is text, with yad's
386
+ // block put into it. Each kind: how to read it, merge yad's part in, and compare.
387
+ const KINDS = {
388
+ // `eq` compares a file's text with what is committed: JSON trimmed (`run` trims git's output), text with its
389
+ // line endings evened out, since git may store LF where the disk holds CRLF (`core.autocrlf`).
390
+ json: { read: (t) => parse(t), empty: {}, merge: (o, m) => { if (!o) return undefined; const r = m(o); return r.unreadable ? undefined : r.settings; }, same: (a, b) => JSON.stringify(a) === JSON.stringify(b), eq: (a, b) => a.trim() === b.trim(), what: 'its entries (hooks, the read-only allow list)', reason: 'settings-uncommitted' },
391
+ text: { read: (t) => t, empty: null, merge: (t, m) => { const r = m(t); return r.refused ? undefined : r.text; }, same: (a, b) => lf(a) === lf(b), eq: (a, b) => lf(a) === lf(b), what: 'its yadflow rules block', reason: 'agents-uncommitted' },
392
+ };
393
+ for (const [file, e] of shared) {
394
+ const k = KINDS[e.a.kind ?? 'json'];
395
+ const now = sharedText(file);
396
+ if (now === null || (e.head !== null && k.eq(now, e.head))) continue;
397
+ const base = e.head === null ? k.empty : k.read(e.head);
398
+ // What yad alone would make of it: each adapter's part merged into what is committed.
399
+ // `undefined` when yad's part cannot be merged (a file that does not parse, markers it cannot trust).
400
+ const ours = e.merges.reduce((o, merge) => (o === undefined ? undefined : k.merge(o, merge)), base);
401
+ // yad's parts are all committed already: nothing of yad's is left out, and the person's own edits in the
402
+ // file are theirs to keep or share — no row (E157 update review 12).
403
+ if (ours !== undefined && base !== null && k.same(ours, base)) continue;
404
+ const was = e.disk === null ? null : k.read(e.disk);
405
+ const yadsAlone = e.disk === null ? e.head === null
406
+ : e.head !== null && k.eq(e.disk, e.head) ? true
407
+ : !!(ours !== undefined && was !== null && k.same(was, ours));
408
+ if (yadsAlone) { appliedActions.push({ ...e.a, paths: [e.a.shared] }); continue; }
409
+ const hint = `${e.a.shared} has changes that are not committed, so the update left ${k.what} out of the PR/MR: commit ${e.a.shared} as it now stands, through review on a branch of your own`;
410
+ info(`${repoLabel(root, e.a.root)}: ${hint}`);
411
+ sharedRows.push({ label: repoLabel(root, e.a.root), product: e.a.root === root, branch: null, committed: false, pushed: false, opened: false, pr: null, skipped: true, error: false, reason: k.reason, hint });
412
+ }
268
413
  // Refresh the version stamp and persist only the canonical targets used to build actions. This also
269
414
  // completes legacy/corrupt target migration even when no skill content itself needed an update.
270
- writeCanonicalStamp();
271
- appliedActions.push({ scope: 'product', item: PROJECT_FILES.version, status: 'stamp', root, paths: [PROJECT_FILES.version] });
415
+ if (!held.has(root)) {
416
+ writeCanonicalStamp();
417
+ appliedActions.push({ scope: 'product', item: PROJECT_FILES.version, status: 'stamp', root, paths: [PROJECT_FILES.version] });
418
+ }
272
419
  // Record what we wrote (and what was already correct) so the NEXT update can tell a stale managed
273
420
  // file from an edited one. Seeding the already-correct files is what migrates a pre-ledger install.
274
421
  // A file left as `modified` records nothing — it differs from the template by definition.
275
- for (const ledgerRoot of recordManagedWrites(actions)) {
422
+ const ledgerRoots = recordManagedWrites(actions.filter(live));
423
+ // A connected repo whose every managed file is the team's own (`modified`) records nothing above, so its
424
+ // ledger would name an older yadflow for good — and read as behind on every `yad guide`. Its version is
425
+ // brought up all the same: this release did look at it.
426
+ for (const repo of registry.repos) {
427
+ const repoRoot = path.resolve(root, repo.path);
428
+ const ledgerFile = path.join(repoRoot, MANAGED_LEDGER);
429
+ if (repoRoot === root || ledgerRoots.includes(repoRoot) || !reaches(repoRoot) || !exists(ledgerFile)) continue;
430
+ const ledger = readJSON(ledgerFile, null);
431
+ if (ledger && typeof ledger === 'object' && !Array.isArray(ledger) && ledger.version !== VERSION) {
432
+ writeJSON(ledgerFile, { ...ledger, version: VERSION });
433
+ ledgerRoots.push(repoRoot);
434
+ } else if (ledger && (push || openPr)) {
435
+ // Already restamped on disk by a run whose commit or push failed: still staged, so the next run carries
436
+ // it (staging keeps only what differs from the commit).
437
+ ledgerRoots.push(repoRoot);
438
+ }
439
+ }
440
+ for (const ledgerRoot of ledgerRoots) {
276
441
  appliedActions.push({
277
442
  scope: repoLabel(root, ledgerRoot), item: MANAGED_LEDGER, status: 'stamp',
278
443
  root: ledgerRoot, paths: [MANAGED_LEDGER],
@@ -293,17 +458,13 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
293
458
  // Each repo's `{ label, committed, pushed }`, for the --json answer (E1): a push that failed after a
294
459
  // commit landed is said per repo.
295
460
  let commits = [];
296
- if (push) {
297
- preflightGuardReadiness(root);
298
- const productConfig = readJSON(productConfigPath(root), {});
299
- const defByRoot = new Map([[root, productConfig?.default_branch]]);
300
- const platformByRoot = new Map([[root, productConfig?.platform]]);
301
- for (const repo of registry.repos) {
302
- const repoRoot = path.resolve(root, repo.path);
303
- defByRoot.set(repoRoot, repo.default_branch);
304
- platformByRoot.set(repoRoot, repo.platform);
305
- }
306
- commits = commitUpdates(root, groupByRoot(appliedActions), {
461
+ if (push || openPr) {
462
+ // Both commit: an unsigned commit fails the verified-commits check, on the default branch or on the PR/MR.
463
+ preflightGuardReadiness(root, openPr ? 'the PR/MR\'s verified-commits check requires a platform-Verified signature; an unsigned update commit fails it' : undefined);
464
+ // --open-pr: each repo's changes on their own branch, with a PR/MR a person merges.
465
+ // Every repo has a row: the held ones (with their reason and hint) first, then what was opened.
466
+ if (openPr) commits = heldRows.concat(openUpdatePrs(root, groupByRoot(appliedActions), { defaultBranchFor: (r) => defByRoot.get(r), platformFor: (r) => platformByRoot.get(r), creator, checked: true }), sharedRows);
467
+ else commits = commitUpdates(root, groupByRoot(appliedActions), {
307
468
  push: true, allowBranch,
308
469
  defaultBranchFor: (r) => defByRoot.get(r),
309
470
  // GitLab's yad-update-guard is an includable fragment: unlike a GitHub workflow it does nothing