yadflow 4.10.0 → 4.12.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.
- package/CHANGELOG.md +152 -0
- package/README.md +14 -3
- package/bin/commands.mjs +7 -1
- package/bin/yad.mjs +163 -16
- package/cli/agent-guard-worker.mjs +13 -0
- package/cli/agent-guard.mjs +1053 -57
- package/cli/agent-rules.mjs +59 -3
- package/cli/argv-flags.mjs +2 -2
- package/cli/brain/vendor/LICENSE-graphology-library.txt +21 -0
- package/cli/brain/vendor/LICENSE-graphology.txt +21 -0
- package/cli/brain/vendor/LICENSE-sigma.txt +12 -0
- package/cli/brain/vendor/graphology-library.min.js +2 -0
- package/cli/brain/vendor/graphology.umd.min.js +2 -0
- package/cli/brain/vendor/sigma.min.js +1369 -0
- package/cli/brain/view/app.js +382 -0
- package/cli/brain/view/index.html +63 -0
- package/cli/brain/view/live.css +228 -0
- package/cli/brain/view/live.html +110 -0
- package/cli/brain/view/live.js +884 -0
- package/cli/brain/view/style.css +141 -0
- package/cli/brain-about.mjs +206 -0
- package/cli/brain-activity.mjs +285 -0
- package/cli/brain-skills.mjs +118 -0
- package/cli/brain-vendor.mjs +71 -0
- package/cli/brain-view.mjs +345 -0
- package/cli/brain.mjs +810 -0
- package/cli/brand-cmd.mjs +326 -0
- package/cli/brand.mjs +327 -0
- package/cli/ci-check.mjs +3 -3
- package/cli/doctor.mjs +145 -14
- package/cli/epic-state.mjs +93 -1
- package/cli/epic.mjs +15 -3
- package/cli/errors.mjs +2 -1
- package/cli/find-product.mjs +69 -15
- package/cli/foundation-publish.mjs +256 -0
- package/cli/gate.mjs +29 -3
- package/cli/git-read.mjs +38 -0
- package/cli/guard-stream.mjs +409 -0
- package/cli/guide.mjs +26 -3
- package/cli/hook.mjs +59 -9
- package/cli/issues-act.mjs +57 -13
- package/cli/issues-write.mjs +19 -6
- package/cli/issues.mjs +69 -24
- package/cli/lib.mjs +37 -2
- package/cli/local-page.mjs +138 -0
- package/cli/local-setup-record.mjs +71 -0
- package/cli/local-setup-steps.mjs +186 -0
- package/cli/local-setup.mjs +611 -0
- package/cli/machine.mjs +1 -1
- package/cli/manifest.mjs +55 -0
- package/cli/map/view/app.js +712 -0
- package/cli/map/view/index.html +50 -0
- package/cli/map/view/style.css +142 -0
- package/cli/map-view.mjs +190 -0
- package/cli/map.mjs +637 -0
- package/cli/members.mjs +9 -15
- package/cli/next.mjs +1 -1
- package/cli/openpr.mjs +2 -2
- package/cli/plain-text.mjs +22 -0
- package/cli/plan.mjs +310 -36
- package/cli/platform.mjs +5 -5
- package/cli/product-index.mjs +1 -1
- package/cli/protection.mjs +32 -0
- package/cli/reconcile.mjs +61 -13
- package/cli/report.mjs +9 -3
- package/cli/reports-dir.mjs +393 -0
- package/cli/reports.mjs +65 -0
- package/cli/run-checks.mjs +5 -2
- package/cli/scan.mjs +4 -6
- package/cli/secret-text.mjs +66 -0
- package/cli/setup.mjs +54 -8
- package/cli/standup.mjs +94 -72
- package/cli/status.mjs +6 -5
- package/cli/test-agents-file.mjs +614 -8
- package/cli/test-brain-activity.mjs +753 -0
- package/cli/test-brain-view.mjs +381 -0
- package/cli/test-brain.mjs +795 -0
- package/cli/test-brand.mjs +558 -0
- package/cli/test-guide.mjs +438 -0
- package/cli/test-local-setup.mjs +1188 -0
- package/cli/test-machine.mjs +59 -0
- package/cli/test-map.mjs +615 -0
- package/cli/test-reports.mjs +382 -0
- package/cli/test-run-checks.mjs +4 -0
- package/cli/test-worktree.mjs +24 -3
- package/cli/toolbox-connect.mjs +21 -6
- package/cli/toolbox.mjs +74 -5
- package/cli/update-commit.mjs +118 -9
- package/cli/usage.mjs +17 -7
- package/cli/workspace.mjs +11 -2
- package/package.json +8 -4
- package/skills/sdlc/module-help.csv +1 -0
- package/skills/yad-architecture/SKILL.md +22 -4
- package/skills/yad-brand/SKILL.md +69 -0
- package/skills/yad-change/SKILL.md +3 -1
- package/skills/yad-change/references/triage.md +2 -0
- package/skills/yad-checks/SKILL.md +2 -0
- package/skills/yad-checks/references/check-gates.md +8 -5
- package/skills/yad-checks/templates/checks/build-test-lint.sh +7 -0
- package/skills/yad-checks/templates/checks/install-deps.sh +6 -0
- package/skills/yad-checks/templates/checks/package-manager.sh +42 -0
- package/skills/yad-checks/templates/github/yad-checks.yml +3 -2
- package/skills/yad-checks/templates/gitlab/yad-checks.gitlab-ci.yml +3 -2
- package/skills/yad-checks/templates/hooks/local-setup-notice.mjs +96 -0
- package/skills/yad-checks/templates/hooks/yad-activity.mjs +238 -0
- package/skills/yad-connect-repos/SKILL.md +14 -0
- package/skills/yad-discovery/SKILL.md +11 -0
- package/skills/yad-discovery/references/foundation-schema.md +11 -0
- package/skills/yad-docs/templates/app/package-lock.json +18 -10
- package/skills/yad-docs/templates/app/package.json +6 -1
- package/skills/yad-epic/SKILL.md +3 -0
- package/skills/yad-epic/references/state-schema.md +35 -1
- package/skills/yad-guide/SKILL.md +10 -7
- package/skills/yad-implement/SKILL.md +76 -15
- package/skills/yad-issues/SKILL.md +2 -1
- package/skills/yad-pr-template/templates/checks/pr-template.sh +8 -4
- package/skills/yad-pr-template/templates/checks/pr-title.sh +8 -4
- package/skills/yad-spec/SKILL.md +19 -0
- package/skills/yad-stories/SKILL.md +22 -4
- package/skills/yad-stories/references/story-schema.md +1 -1
package/cli/reconcile.mjs
CHANGED
|
@@ -14,14 +14,15 @@ import { preflightGuardReadiness } from './productcommit.mjs';
|
|
|
14
14
|
import { VERSION, PROJECT_FILES, MANAGED_LEDGER, BACKUP_SUFFIX , productConfigPath, PRODUCT_LINK } from './manifest.mjs';
|
|
15
15
|
import {
|
|
16
16
|
moduleActions, repoActions, productActions, hookActions, agentFileActions, agentGuardActions, orphanAgentGuardActions, allowListActions, orphanAllowListActions, repoOrphanAgentGuardActions,
|
|
17
|
-
legacyModuleActions, removedModuleActions, orphanHookActions, captureHookActions, orphanCaptureHookActions, legacyHookScriptActions, legacyRepoActions, legacyProductActions,
|
|
18
|
-
ideTargetStateFor, recordManagedWrites, gitHookActions, orphanGitHookActions, gitHookState, gitHookAdvice, renamedNameHits, withoutKeptRenames, PRODUCT_PROFILE_GATES, productProfileGap, productProfileEffect, PRODUCT_PROFILE_FIX, workflowsPassingProduct, productGateBlockers, oldProfileAdvice,
|
|
17
|
+
legacyModuleActions, removedModuleActions, orphanHookActions, captureHookActions, orphanCaptureHookActions, activityHookActions, orphanActivityHookActions, repoOrphanActivityActions, legacyHookScriptActions, legacyRepoActions, legacyProductActions,
|
|
18
|
+
ideTargetStateFor, recordManagedWrites, gitHookActions, orphanGitHookActions, gitHookState, gitHookAdvice, localSetupNoticeActions, orphanLocalSetupNoticeActions, localSetupNoticeAdvice, renamedNameHits, withoutKeptRenames, PRODUCT_PROFILE_GATES, productProfileGap, productProfileEffect, PRODUCT_PROFILE_FIX, workflowsPassingProduct, productGateBlockers, oldProfileAdvice,
|
|
19
19
|
} from './plan.mjs';
|
|
20
20
|
import { gitHead, packRepo } from './setup.mjs';
|
|
21
|
-
import { groupByRoot, commitUpdates, openUpdatePrs, repoLabel, updatePrBlocker, updateTargets, HELD_KINDS } from './update-commit.mjs';
|
|
21
|
+
import { groupByRoot, commitUpdates, openUpdatePrs, repoLabel, updatePrBlocker, updateTargets, HELD_KINDS, ignoreFileLines, ignoreRules } from './update-commit.mjs';
|
|
22
22
|
import { createPr } from './platform.mjs';
|
|
23
23
|
import { hasSiblingRepo, workspaceFileState, writeWorkspaceFile, WORKSPACE_FILE } from './find-product.mjs';
|
|
24
24
|
import { offerToolbox } from './toolbox.mjs';
|
|
25
|
+
import { localSetupActions, localSetupSection } from './local-setup.mjs';
|
|
25
26
|
|
|
26
27
|
const MARK = { missing: c.red('missing'), new: c.cyan('new'), outdated: c.yellow('outdated'), modified: c.cyan('modified'), stale: c.yellow('stale'), legacy: c.yellow('legacy'), removed: c.yellow('removed'), ok: c.green('ok') };
|
|
27
28
|
|
|
@@ -33,7 +34,7 @@ const repoShown = (repo) => `product (the code repo at ${forTerminal(repo.path)}
|
|
|
33
34
|
const shown = (a) => a.shownScope ?? a.scope;
|
|
34
35
|
const itemsOf = (actions) => actions.map((a) => ({ scope: a.scope, item: a.item, status: a.status, product: !a.fromRepo }));
|
|
35
36
|
|
|
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 } = {}) {
|
|
37
|
+
export async function reconcile(root, { fix = false, scope = 'all', force = false, push = false, openPr = false, allowBranch = false, overwriteLocal = false, toolbox: toolboxAt = null, creator = createPr, invite = false } = {}) {
|
|
37
38
|
log(c.bold(`\nSDLC reconcile ${c.dim('v' + VERSION)}`));
|
|
38
39
|
log(c.dim(`target: ${root}\n`));
|
|
39
40
|
|
|
@@ -64,6 +65,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
64
65
|
...withoutKeptRenames([...productActions(root), ...legacyProductActions(root)]), ...hookActions(root, ideTargets),
|
|
65
66
|
// E158: the rules block in AGENTS.md (and CLAUDE.md importing it), which every agent reads first.
|
|
66
67
|
...agentFileActions(root, ideTargets),
|
|
68
|
+
// E185: the local setup script for each team member's machine — yad's steps rewritten, the team's kept.
|
|
69
|
+
...localSetupActions(root),
|
|
67
70
|
// E158: the agent guard, before every shell command the agent runs.
|
|
68
71
|
...agentGuardActions(root, ideTargets), ...orphanAgentGuardActions(root, ideTargets),
|
|
69
72
|
// E158 (#353): the read-only yad commands, pre-approved for Claude Code.
|
|
@@ -71,8 +74,12 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
71
74
|
...orphanHookActions(root, ideTargets),
|
|
72
75
|
// E48: this clone's git pre-commit hook — the person's half of the ledger guard.
|
|
73
76
|
...gitHookActions(root), ...orphanGitHookActions(root),
|
|
77
|
+
// E185 part 4: the notice after a pull — its script, and this clone's post-merge and post-rewrite hooks.
|
|
78
|
+
...localSetupNoticeActions(root), ...orphanLocalSetupNoticeActions(root),
|
|
74
79
|
// E43: the post-edit capture hook, in both ledger modes.
|
|
75
80
|
...captureHookActions(root, ideTargets), ...orphanCaptureHookActions(root, ideTargets),
|
|
81
|
+
// E178: the live activity record, only while the config says `"activity": true`.
|
|
82
|
+
...activityHookActions(root, ideTargets), ...orphanActivityHookActions(root, ideTargets),
|
|
76
83
|
// E113: the old shell-script hooks. LAST, so the entries above that named them are rewritten first.
|
|
77
84
|
...legacyHookScriptActions(root, ideTargets),
|
|
78
85
|
];
|
|
@@ -90,7 +97,11 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
90
97
|
for (const repo of registry.repos) {
|
|
91
98
|
const repoRoot = path.resolve(root, repo.path);
|
|
92
99
|
// E158b: a target that left takes yad's guard and allow-list entries out of the repo's own settings too.
|
|
93
|
-
|
|
100
|
+
// E178: and the activity record's, when the Product turned `activity` off.
|
|
101
|
+
const orphans = samePath(repoRoot, path.resolve(root)) ? [] : [
|
|
102
|
+
...repoOrphanAgentGuardActions(repoRoot, ideTargets, { scope: repo.name }),
|
|
103
|
+
...repoOrphanActivityActions(root, repoRoot, ideTargets, { scope: repo.name }),
|
|
104
|
+
];
|
|
94
105
|
const own = withoutKeptRenames([...repoActions(root, repo), ...legacyRepoActions(root, repo)]).concat(orphans);
|
|
95
106
|
// Set on the action itself: later steps compare actions by identity. `true`, not the name, which may be empty.
|
|
96
107
|
for (const a of own) { a.fromRepo = true; if (repo.name === 'product') a.shownScope = repoShown(repo); }
|
|
@@ -152,6 +163,9 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
152
163
|
// A hook yad may not write (someone else's, or a hooks folder a tool manages) has no action; say so.
|
|
153
164
|
const gitHookNote = gitHookAdvice(gitHookState(root));
|
|
154
165
|
if (gitHookNote) warn(gitHookNote);
|
|
166
|
+
// The pull notice is a convenience, not a guard: its one line for a hook yad left alone only on --fix/update.
|
|
167
|
+
const noticeNote = fix ? localSetupNoticeAdvice(root) : null;
|
|
168
|
+
if (noticeNote) info(noticeNote);
|
|
155
169
|
const shownInvalid = ideState.invalid.map((v) => {
|
|
156
170
|
try { return JSON.stringify(v) ?? String(v); } catch { return String(v); }
|
|
157
171
|
});
|
|
@@ -257,7 +271,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
257
271
|
if (fixable.length || gaps.length) hand('run `yad check --fix` to reconcile (or `yad setup` for missing one-time setup).');
|
|
258
272
|
// After the --fix hint, never above it: --fix installs no tool, and must not read as if it did.
|
|
259
273
|
const toolbox = toolboxSection(root, toolboxAt);
|
|
260
|
-
|
|
274
|
+
const localSetup = localSetupSection(root);
|
|
275
|
+
return { fix: false, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: [], workspaceFile, toolbox, localSetup };
|
|
261
276
|
}
|
|
262
277
|
|
|
263
278
|
// Each repo's default branch and platform, for --push and --open-pr.
|
|
@@ -294,7 +309,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
294
309
|
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
310
|
process.exitCode = 1;
|
|
296
311
|
const toolbox = toolboxSection(root, toolboxAt);
|
|
297
|
-
|
|
312
|
+
const localSetup = localSetupSection(root);
|
|
313
|
+
return { fix: true, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: stop.map(([r, b]) => row(r, b)), workspaceFile, toolbox, localSetup };
|
|
298
314
|
}
|
|
299
315
|
held = new Set(checks.filter(([, b]) => b).map(([r]) => r));
|
|
300
316
|
heldRows = checks.filter(([, b]) => b).map(([r, b]) => row(r, b));
|
|
@@ -302,7 +318,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
302
318
|
if (held.size === checks.length) {
|
|
303
319
|
info('every repo\'s update is already merged or on review — nothing written');
|
|
304
320
|
const toolbox = toolboxSection(root, toolboxAt);
|
|
305
|
-
|
|
321
|
+
const localSetup = localSetupSection(root);
|
|
322
|
+
return { fix: true, counts, gaps, items: itemsOf(actions), applied: 0, modified: modified.length, commits: checks.map(([r, b]) => row(r, b)), workspaceFile, toolbox, localSetup };
|
|
306
323
|
}
|
|
307
324
|
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
325
|
}
|
|
@@ -331,10 +348,10 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
331
348
|
// yad's block is merged into (E158 review 1).
|
|
332
349
|
let head;
|
|
333
350
|
if (a.kind === 'text') {
|
|
334
|
-
const r = spawnSync('git', ['show', `HEAD
|
|
351
|
+
const r = spawnSync('git', ['show', `HEAD:./${a.shared}`], { cwd: a.root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, windowsHide: true });
|
|
335
352
|
head = r.status === 0 ? r.stdout : null;
|
|
336
353
|
} else {
|
|
337
|
-
const r = run('git', ['show', `HEAD
|
|
354
|
+
const r = run('git', ['show', `HEAD:./${a.shared}`], { cwd: a.root, maxBuffer: 64 * 1024 * 1024 });
|
|
338
355
|
head = r.ok ? r.stdout : null;
|
|
339
356
|
}
|
|
340
357
|
shared.set(file, { a, merges: [], disk: sharedText(file), head });
|
|
@@ -381,7 +398,8 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
381
398
|
}
|
|
382
399
|
const sharedRows = [];
|
|
383
400
|
const lf = (t) => t.replace(/\r\n/g, '\n');
|
|
384
|
-
|
|
401
|
+
// A byte-order mark (some Windows editors add one) is read past, as the files' own readers do.
|
|
402
|
+
const parse = (t) => { try { const v = JSON.parse(t.charCodeAt(0) === 0xfeff ? t.slice(1) : t); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } };
|
|
385
403
|
// A settings file is JSON, merged as objects; a rules file (AGENTS.md, CLAUDE.md, E158) is text, with yad's
|
|
386
404
|
// block put into it. Each kind: how to read it, merge yad's part in, and compare.
|
|
387
405
|
const KINDS = {
|
|
@@ -401,12 +419,40 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
401
419
|
// yad's parts are all committed already: nothing of yad's is left out, and the person's own edits in the
|
|
402
420
|
// file are theirs to keep or share — no row (E157 update review 12).
|
|
403
421
|
if (ours !== undefined && base !== null && k.same(ours, base)) continue;
|
|
422
|
+
// A file with no committed copy that an ignore rule hides can never ride a PR/MR (git refuses to add it,
|
|
423
|
+
// #555). A rule whose line is in its ignore file's committed copy is the team's choice: the file stays on each machine,
|
|
424
|
+
// where each person's `yad update` or `yad check --fix` writes it — said once, no row. Any other rule (a
|
|
425
|
+
// global ignore, `.git/info/exclude`, or a `.gitignore` line not committed) is only this machine's: the row
|
|
426
|
+
// stays, naming the rule and the way out — also when the file is yad's alone, which staging would
|
|
427
|
+
// otherwise drop without a word.
|
|
428
|
+
const what = e.a.what ?? k.what;
|
|
429
|
+
const tracked = e.head !== null || run('git', ['ls-files', '--error-unmatch', '--', e.a.shared], { cwd: e.a.root }).ok;
|
|
430
|
+
const rule = tracked ? null : ignoreRules(e.a.root, [e.a.shared]).get(e.a.shared);
|
|
431
|
+
const at = rule ? `${rule.source}${rule.line ? `:${rule.line}` : ''}` : '';
|
|
432
|
+
// The team's rule is one its committed ignore file holds: the same line in `HEAD:<source>`, wherever it
|
|
433
|
+
// sits there, so an unrelated edit to that file not yet committed changes nothing (review 2). Read as
|
|
434
|
+
// committed, never trimmed as a whole (`run` trims).
|
|
435
|
+
const committedLines = () => {
|
|
436
|
+
const r = spawnSync('git', ['show', `HEAD:./${rule.source}`], { cwd: e.a.root, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, windowsHide: true });
|
|
437
|
+
return r.status === 0 ? ignoreFileLines(r.stdout) : [];
|
|
438
|
+
};
|
|
439
|
+
const teams = rule && !rule.outside && committedLines().includes(rule.pattern);
|
|
440
|
+
if (teams) {
|
|
441
|
+
info(`${repoLabel(root, e.a.root)}: ${e.a.shared} is ignored by ${at}, so it stays on each machine; the update leaves it out of the PR/MR`);
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (rule) {
|
|
445
|
+
const hint = `an ignore rule only this machine has (${at}, \`${rule.pattern}\`${rule.outside ? '' : ', not committed'}) hides ${e.a.shared}, so the update left ${what} out of the PR/MR: remove or narrow that rule, or commit it with \`git add -f ${e.a.shared}\`, through review on a branch of your own`;
|
|
446
|
+
info(`${repoLabel(root, e.a.root)}: ${hint}`);
|
|
447
|
+
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 });
|
|
448
|
+
continue;
|
|
449
|
+
}
|
|
404
450
|
const was = e.disk === null ? null : k.read(e.disk);
|
|
405
451
|
const yadsAlone = e.disk === null ? e.head === null
|
|
406
452
|
: e.head !== null && k.eq(e.disk, e.head) ? true
|
|
407
453
|
: !!(ours !== undefined && was !== null && k.same(was, ours));
|
|
408
454
|
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 ${
|
|
455
|
+
const hint = `${e.a.shared} has changes that are not committed, so the update left ${what} out of the PR/MR: commit ${e.a.shared} as it now stands, through review on a branch of your own`;
|
|
410
456
|
info(`${repoLabel(root, e.a.root)}: ${hint}`);
|
|
411
457
|
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
458
|
}
|
|
@@ -479,7 +525,9 @@ export async function reconcile(root, { fix = false, scope = 'all', force = fals
|
|
|
479
525
|
});
|
|
480
526
|
}
|
|
481
527
|
const toolbox = toolboxSection(root, toolboxAt);
|
|
482
|
-
|
|
528
|
+
// `invite`: `yad update` asks for the line inviting the team's own steps; `check --fix` does not (E185 part 3).
|
|
529
|
+
const localSetup = localSetupSection(root, { invite });
|
|
530
|
+
return { fix: true, counts, gaps, items: itemsOf(actions), applied, modified: modified.length, commits, workspaceFile, toolbox, localSetup };
|
|
483
531
|
}
|
|
484
532
|
|
|
485
533
|
// E85: `yad check` and `yad update` end with the toolbox check — the tools this Product uses that are not
|
package/cli/report.mjs
CHANGED
|
@@ -159,9 +159,15 @@ const OWN_FLAGS = new Set(['--json', '--post', '--confirm', '--kind']);
|
|
|
159
159
|
const withoutOwnFlags = (argv) => argv.filter((a) => !OWN_FLAGS.has(String(a).split('=')[0]));
|
|
160
160
|
|
|
161
161
|
// ---- open a URL (best-effort) -------------------------------------------------------------------
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
162
|
+
// Returns whether an opener was found, so a caller can say "open it yourself" when none was. On Windows
|
|
163
|
+
// `start` is a built-in of cmd.exe, not a program, so it is never on PATH and cannot be spawned without a
|
|
164
|
+
// shell: `explorer.exe` opens a URL or a file in its default app, and takes the argument with no shell to
|
|
165
|
+
// parse it (E177 review 1).
|
|
166
|
+
export function openUrl(url, { runner = run, platform = process.platform, exists = has } = {}) {
|
|
167
|
+
const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'explorer' : 'xdg-open';
|
|
168
|
+
if (!exists(cmd)) return false;
|
|
169
|
+
runner(cmd, [url]);
|
|
170
|
+
return true;
|
|
165
171
|
}
|
|
166
172
|
|
|
167
173
|
// ---- the flow -----------------------------------------------------------------------------------
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// The local reports folder (E180).
|
|
2
|
+
//
|
|
3
|
+
// A report shows the state of the work at one moment, and goes stale as soon as the work moves on. So
|
|
4
|
+
// every report yadflow writes — the standup, the usage and issues reports, the brain view page, and
|
|
5
|
+
// later the progress map and the doc sites — is saved on THIS machine only, in one folder beside the
|
|
6
|
+
// Product, and never committed or pushed unless the person asks for that themselves:
|
|
7
|
+
//
|
|
8
|
+
// acme/
|
|
9
|
+
// product/ <- the Product (its main checkout)
|
|
10
|
+
// product--EP-x/ <- a worktree of it (#115) — it saves into the same folder below
|
|
11
|
+
// product--reports/ <- the reports folder
|
|
12
|
+
// .gitignore `*`, so a folder that ends up inside a git tree is still never added
|
|
13
|
+
// index.html the catalog page: every saved report, newest first
|
|
14
|
+
// catalog.json the same list as data
|
|
15
|
+
// standup/2026-11-14-0900--standup--team--3-waiting.md
|
|
16
|
+
// usage/2026-11-01-1000--usage--team--all-time.html
|
|
17
|
+
//
|
|
18
|
+
// A file's name says what it is and what state it shows: `<date>-<time>--<kind>--<scope>--<state>.<ext>`.
|
|
19
|
+
// The date comes first, so sorting by name sorts by time. Each part is cut down to `a-z 0-9 -`, so the
|
|
20
|
+
// name is the same on every system (Windows refuses `:` and a few other characters).
|
|
21
|
+
//
|
|
22
|
+
// Where the folder is, first match wins:
|
|
23
|
+
// 1. `--out <file>` on the command — that file, exactly as before (the catalog is not touched);
|
|
24
|
+
// 2. YAD_REPORTS_DIR — a folder the person chose (for example on another disk);
|
|
25
|
+
// 3. `<main checkout>--reports`, beside the Product's main checkout. A run from a worktree, or from a
|
|
26
|
+
// code repo (yad finds the Product first), lands in the same one folder.
|
|
27
|
+
//
|
|
28
|
+
// The catalog records the Product commit each report was made at, so `yad reports list` can say which
|
|
29
|
+
// ones are stale: the Product's epics/ or .sdlc/ changed since then.
|
|
30
|
+
import fs from 'node:fs';
|
|
31
|
+
import path from 'node:path';
|
|
32
|
+
import { spawnSync } from 'node:child_process';
|
|
33
|
+
import { randomBytes } from 'node:crypto';
|
|
34
|
+
import { readJSONStrict, writeJSON } from './lib.mjs';
|
|
35
|
+
import { brandForPage } from './brand.mjs';
|
|
36
|
+
|
|
37
|
+
export const REPORTS_SUFFIX = '--reports';
|
|
38
|
+
export const CATALOG_FILE = 'catalog.json';
|
|
39
|
+
export const INDEX_FILE = 'index.html';
|
|
40
|
+
export const CATALOG_VERSION = 1;
|
|
41
|
+
export const REPORTS_ENV = 'YAD_REPORTS_DIR';
|
|
42
|
+
// A report may keep one side file beside it, `<file>.digest.json` (the progress map's item states, E181).
|
|
43
|
+
export const SIDE_SUFFIX = '.digest.json';
|
|
44
|
+
|
|
45
|
+
// The kinds of report. A kind is also its subfolder's name, so only these are accepted.
|
|
46
|
+
export const KINDS = Object.freeze({
|
|
47
|
+
'progress-map': 'Progress map',
|
|
48
|
+
'brain-view': 'Brain view',
|
|
49
|
+
usage: 'Usage report',
|
|
50
|
+
standup: 'Standup',
|
|
51
|
+
issues: 'Issues report',
|
|
52
|
+
'docs-site': 'Docs site',
|
|
53
|
+
timeline: 'Timeline',
|
|
54
|
+
defects: 'Defects report',
|
|
55
|
+
learning: 'Learning tutorial',
|
|
56
|
+
status: 'Status',
|
|
57
|
+
history: 'History',
|
|
58
|
+
claims: 'Claims',
|
|
59
|
+
doctor: 'Doctor',
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const git = (runner, cwd, args) => {
|
|
63
|
+
const r = runner('git', ['-C', cwd, ...args], { encoding: 'utf8' });
|
|
64
|
+
return { ok: r.status === 0, code: r.status, out: String(r.stdout ?? '').trim() };
|
|
65
|
+
};
|
|
66
|
+
|
|
67
|
+
// The Product's MAIN checkout: for a worktree, the folder that holds the shared .git; else `root` itself.
|
|
68
|
+
// Only when `root` is the TOP of its checkout: a Product folder inside some other repo (a test fixture,
|
|
69
|
+
// a monorepo) keeps its reports beside itself, never beside that other repo.
|
|
70
|
+
export function mainCheckout(root, { runner = spawnSync } = {}) {
|
|
71
|
+
const top = git(runner, root, ['rev-parse', '--show-toplevel']);
|
|
72
|
+
const real = (p) => { let r; try { r = fs.realpathSync.native(p); } catch { r = path.resolve(p); } return process.platform === 'win32' ? r.toLowerCase() : r; };
|
|
73
|
+
if (!top.ok || !top.out || real(top.out) !== real(root)) return path.resolve(root);
|
|
74
|
+
const r = git(runner, root, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
75
|
+
if (!r.ok || !r.out) return path.resolve(root);
|
|
76
|
+
const common = path.resolve(root, r.out);
|
|
77
|
+
// A normal checkout keeps its git data in `<checkout>/.git`; anything else (a bare repo) has no
|
|
78
|
+
// checkout to stand beside, so the folder given is used.
|
|
79
|
+
return path.basename(common) === '.git' ? path.dirname(common) : path.resolve(root);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// → { dir, via: 'env' | 'beside' }
|
|
83
|
+
export function reportsDir(root, { env = process.env, runner = spawnSync } = {}) {
|
|
84
|
+
const chosen = env[REPORTS_ENV];
|
|
85
|
+
if (chosen && String(chosen).trim()) return { dir: path.resolve(String(chosen).trim()), via: 'env' };
|
|
86
|
+
const main = mainCheckout(root, { runner });
|
|
87
|
+
return { dir: path.join(path.dirname(main), `${path.basename(main)}${REPORTS_SUFFIX}`), via: 'beside' };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// One part of a name: lower case, `a-z 0-9 -` only, no doubled or end dashes, at most `max` long.
|
|
91
|
+
export function slug(s, max = 40) {
|
|
92
|
+
const out = String(s ?? '')
|
|
93
|
+
.normalize('NFKD').replace(/[̀-ͯ]/g, '')
|
|
94
|
+
.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')
|
|
95
|
+
.slice(0, max).replace(/-+$/g, '');
|
|
96
|
+
return out || 'none';
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
100
|
+
// The local date and time, `YYYY-MM-DD-HHmm` — the person reads it in their own time.
|
|
101
|
+
export const stamp = (at) => `${at.getFullYear()}-${pad(at.getMonth() + 1)}-${pad(at.getDate())}-${pad(at.getHours())}${pad(at.getMinutes())}`;
|
|
102
|
+
|
|
103
|
+
const EXT_RE = /^[a-z0-9]{1,8}$/;
|
|
104
|
+
export function reportName({ kind, scope, state, at = new Date(), ext }) {
|
|
105
|
+
if (!Object.hasOwn(KINDS, kind)) throw new Error(`unknown report kind: ${kind}`);
|
|
106
|
+
if (!EXT_RE.test(String(ext))) throw new Error(`bad report extension: ${ext}`);
|
|
107
|
+
return `${stamp(at)}--${kind}--${slug(scope, 40)}--${slug(state, 40)}.${ext}`;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Write `content` as a NEW file in `dir`: `name`, else `name-2`, `name-3`… before the extension. Each name
|
|
111
|
+
// is taken with an exclusive create (`wx`), so two runs at the same moment never write the same file.
|
|
112
|
+
function writeFresh(dir, name, content) {
|
|
113
|
+
const dot = name.lastIndexOf('.');
|
|
114
|
+
const [base, ext] = dot > 0 ? [name.slice(0, dot), name.slice(dot)] : [name, ''];
|
|
115
|
+
for (let i = 1; i < 1000; i++) {
|
|
116
|
+
const n = i === 1 ? name : `${base}-${i}${ext}`;
|
|
117
|
+
try { fs.writeFileSync(path.join(dir, n), content, { flag: 'wx' }); return n; } catch (e) { if (e.code !== 'EEXIST') throw e; }
|
|
118
|
+
}
|
|
119
|
+
throw new Error(`no free name for ${name} in ${dir}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Hold `catalog.lock` while the catalog is read, changed and written, so a run at the same moment never
|
|
123
|
+
// loses an entry.
|
|
124
|
+
// - The lock appears WHOLE: its `<pid> <token>` is written to a temp file first, then hard-linked to
|
|
125
|
+
// `catalog.lock` (a link fails when the lock is there), so no run ever reads a half-made, empty lock.
|
|
126
|
+
// - It is taken over only when its content is ours to judge — `<pid> <token>`, with that process no
|
|
127
|
+
// longer alive — or it is older than 5 minutes. A takeover renames the lock aside, then checks that
|
|
128
|
+
// what it moved is what it judged; a fresh lock another run made in between is linked back.
|
|
129
|
+
// - On the way out a run removes the lock only while it still holds its own token.
|
|
130
|
+
// - A lock that cannot be read (a folder, no permission) is never spun on: the deadline still ends it.
|
|
131
|
+
// The pid is this machine's: a reports folder shared with another machine or a container can see a
|
|
132
|
+
// live lock there as dead. One residual race is left (a third run locking in the instant between the
|
|
133
|
+
// rename and the link-back); it needs a crashed run and three runs in the same moment.
|
|
134
|
+
const LOCK_FILE = 'catalog.lock';
|
|
135
|
+
const LOCK_STALE_MS = 5 * 60 * 1000;
|
|
136
|
+
const LOCK_RE = /^(\d+) [0-9a-f]{16}$/;
|
|
137
|
+
const alive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
138
|
+
function lockStale(held, age) {
|
|
139
|
+
if (age > LOCK_STALE_MS) return true;
|
|
140
|
+
const m = LOCK_RE.exec(String(held));
|
|
141
|
+
return !!m && !alive(Number(m[1]));
|
|
142
|
+
}
|
|
143
|
+
// A disk with no hard links (FAT, exFAT, some network shares) says so with one of these; there the lock is
|
|
144
|
+
// made with a plain exclusive create, which brings back the small "empty for an instant" window — a young
|
|
145
|
+
// lock yad cannot judge is waited on, never taken over, so that window costs a wait, not an entry.
|
|
146
|
+
const NO_LINKS = new Set(['EPERM', 'ENOTSUP', 'ENOSYS', 'EXDEV', 'EOPNOTSUPP']);
|
|
147
|
+
function tryLock(lock, token) {
|
|
148
|
+
const tmp = `${lock}.${randomBytes(6).toString('hex')}.new`;
|
|
149
|
+
try {
|
|
150
|
+
fs.writeFileSync(tmp, token, { flag: 'wx' });
|
|
151
|
+
fs.linkSync(tmp, lock);
|
|
152
|
+
return true;
|
|
153
|
+
} catch (e) {
|
|
154
|
+
if (e.code === 'EEXIST') return false;
|
|
155
|
+
if (!NO_LINKS.has(e.code)) throw e;
|
|
156
|
+
try { fs.writeFileSync(lock, token, { flag: 'wx' }); return true; } catch (e2) { if (e2.code === 'EEXIST') return false; throw e2; }
|
|
157
|
+
} finally { fs.rmSync(tmp, { force: true }); }
|
|
158
|
+
}
|
|
159
|
+
export function withCatalogLock(dir, fn, { waitMs = 5000 } = {}) {
|
|
160
|
+
const lock = path.join(dir, LOCK_FILE);
|
|
161
|
+
const token = `${process.pid} ${randomBytes(8).toString('hex')}`;
|
|
162
|
+
const until = Date.now() + waitMs;
|
|
163
|
+
for (;;) {
|
|
164
|
+
if (tryLock(lock, token)) break;
|
|
165
|
+
if (Date.now() > until) return { problem: `${lock} is held by another yad run that is still going`, held: true };
|
|
166
|
+
let held, age;
|
|
167
|
+
try { held = fs.readFileSync(lock, 'utf8'); age = Date.now() - fs.statSync(lock).mtimeMs; } catch (e) {
|
|
168
|
+
if (e.code === 'ENOENT') continue; // released between the two steps: try again
|
|
169
|
+
return { problem: `${lock} cannot be read (${e.code || e.message}) — remove it if no yad run is going`, held: true };
|
|
170
|
+
}
|
|
171
|
+
if (lockStale(held, age)) {
|
|
172
|
+
const aside = `${lock}.${randomBytes(6).toString('hex')}.stale`;
|
|
173
|
+
try { fs.renameSync(lock, aside); } catch { continue; } // another run moved it first
|
|
174
|
+
let moved = null; try { moved = fs.readFileSync(aside, 'utf8'); } catch { /* gone */ }
|
|
175
|
+
if (moved !== held && moved !== null) {
|
|
176
|
+
// Put the fresh lock back, exclusively: by a link, or on a disk with no hard links by writing its
|
|
177
|
+
// content again. Either fails when a newer lock is already there.
|
|
178
|
+
try { fs.linkSync(aside, lock); } catch (e) { if (NO_LINKS.has(e.code)) { try { fs.writeFileSync(lock, moved, { flag: 'wx' }); } catch { /* a newer lock is there */ } } }
|
|
179
|
+
}
|
|
180
|
+
fs.rmSync(aside, { force: true });
|
|
181
|
+
continue;
|
|
182
|
+
}
|
|
183
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
|
184
|
+
}
|
|
185
|
+
try { return fn(); } finally {
|
|
186
|
+
try { if (fs.readFileSync(lock, 'utf8') === token) fs.rmSync(lock, { force: true }); } catch { /* already gone */ }
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Make `dir` (and its parents), refusing a path that exists and is not a plain folder.
|
|
191
|
+
function ownDir(dir) {
|
|
192
|
+
let st = null;
|
|
193
|
+
try { st = fs.lstatSync(dir); } catch { /* new */ }
|
|
194
|
+
if (st && !st.isDirectory()) return `${dir} is not a plain folder (a file or a link) — remove it, or set ${REPORTS_ENV}`;
|
|
195
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
196
|
+
return null;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Write by a temp file and a rename, never through a link.
|
|
200
|
+
function writeNew(file, content) {
|
|
201
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
202
|
+
fs.rmSync(tmp, { force: true });
|
|
203
|
+
try {
|
|
204
|
+
fs.writeFileSync(tmp, content, { flag: 'wx' });
|
|
205
|
+
fs.renameSync(tmp, file);
|
|
206
|
+
} finally { fs.rmSync(tmp, { force: true }); }
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// The `.gitignore` that keeps the folder out of any git tree it may sit in. Written once; a person's own
|
|
210
|
+
// edit to it is left alone.
|
|
211
|
+
function ensureIgnored(dir) {
|
|
212
|
+
const f = path.join(dir, '.gitignore');
|
|
213
|
+
if (!fs.existsSync(f)) writeNew(f, '# yadflow reports — local to this machine, never committed (E180)\n*\n');
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// The catalog, or `{ problem }` when the file is there and cannot be read: it is never overwritten then.
|
|
217
|
+
export function readCatalog(dir) {
|
|
218
|
+
const file = path.join(dir, CATALOG_FILE);
|
|
219
|
+
let rec;
|
|
220
|
+
try { rec = readJSONStrict(file, null); } catch (e) { return { problem: `${file} cannot be read (${e.message.split('\n')[0]}) — fix or remove it; the catalog was not changed` }; }
|
|
221
|
+
if (rec === null) return { entries: [] };
|
|
222
|
+
if (typeof rec !== 'object' || Array.isArray(rec) || !Array.isArray(rec.entries)) return { problem: `${file} is not a reports catalog — fix or remove it; the catalog was not changed` };
|
|
223
|
+
if (rec.version !== CATALOG_VERSION) return { problem: `${file} is version ${JSON.stringify(rec.version ?? null)}, and this yadflow reads version ${CATALOG_VERSION} — the catalog was not changed` };
|
|
224
|
+
return { entries: rec.entries.filter((e) => e && typeof e.file === 'string') };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// The local date and time a report was made, as its file name spells it (`2026-11-14 09:05`).
|
|
228
|
+
const madeAt = (iso) => { const d = new Date(iso); return Number.isFinite(d.getTime()) ? stamp(d).replace(/^(\d{4}-\d{2}-\d{2})-(\d{2})(\d{2})$/, '$1 $2:$3') : '—'; };
|
|
229
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch]));
|
|
230
|
+
|
|
231
|
+
// The catalog page. Static: no script, no network; links are relative, so the folder can be moved.
|
|
232
|
+
export function renderIndex(entries, { brandCss = '' } = {}) {
|
|
233
|
+
const kinds = [...new Set(entries.map((e) => e.kind))].sort((a, b) => (KINDS[a] || a).localeCompare(KINDS[b] || b));
|
|
234
|
+
const section = (k) => {
|
|
235
|
+
const rows = entries.filter((e) => e.kind === k).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)));
|
|
236
|
+
return `<h2>${esc(KINDS[k] || k)} <small>${rows.length}</small></h2>\n<table><tr><th>Report</th><th>Scope</th><th>State</th><th>Made (local time)</th><th>Product at</th></tr>\n${rows.map((e) =>
|
|
237
|
+
`<tr><td><a href="${esc(e.file.split('/').map(encodeURIComponent).join('/'))}">${esc(path.posix.basename(e.file))}</a>${e.anonymous ? ' <span class="tag">anonymous</span>' : ''}</td><td>${esc(e.scope)}</td><td>${esc(e.state)}</td><td>${esc(madeAt(e.createdAt))}</td><td><code>${esc(e.productSha ? e.productSha.slice(0, 10) : '—')}</code> ${esc(e.productBranch || '')}</td></tr>`).join('\n')}\n</table>`;
|
|
238
|
+
};
|
|
239
|
+
return `<!doctype html>
|
|
240
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
241
|
+
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:">
|
|
242
|
+
<title>Saved reports</title>
|
|
243
|
+
<style>
|
|
244
|
+
:root{--bg:#fbfbfd;--ink:#1d2333;--muted:#667089;--line:#e3e6ee;--tag:#eef1f8;--link:#2457c5}
|
|
245
|
+
@media (prefers-color-scheme: dark){:root{--bg:#0d111c;--ink:#e6eaf4;--muted:#8d97ad;--line:#232a3b;--tag:#1b2233;--link:#8fb6ff}}
|
|
246
|
+
body{margin:0;padding:24px 16px;background:var(--bg);color:var(--ink);font:14px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
|
|
247
|
+
main{max-width:1100px;margin:0 auto}h1{font-size:20px;margin:0 0 4px}p{color:var(--muted);margin:0 0 18px}
|
|
248
|
+
h2{font-size:15px;margin:26px 0 8px}h2 small{color:var(--muted);font-weight:500}
|
|
249
|
+
table{border-collapse:collapse;width:100%;display:block;overflow-x:auto}th,td{text-align:left;padding:6px 10px;border-top:1px solid var(--line);white-space:nowrap}
|
|
250
|
+
th{color:var(--muted);font-weight:600;font-size:12px;border-top:0}a{color:var(--link)}
|
|
251
|
+
.tag{background:var(--tag);border-radius:4px;padding:1px 6px;font-size:12px;color:var(--muted)}code{font-size:12px}
|
|
252
|
+
${brandCss}
|
|
253
|
+
</style></head><body><main>
|
|
254
|
+
<h1>Saved reports</h1>
|
|
255
|
+
<p>Each report shows the state of the work when it was made. They are kept on this machine only and never committed. Run <code>yad reports list</code> to see which ones are stale.</p>
|
|
256
|
+
${entries.length ? kinds.map(section).join('\n') : '<p>No reports saved yet.</p>'}
|
|
257
|
+
</main></body></html>
|
|
258
|
+
`;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function productAt(root, runner) {
|
|
262
|
+
const sha = git(runner, root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
|
|
263
|
+
const br = git(runner, root, ['rev-parse', '--abbrev-ref', 'HEAD']);
|
|
264
|
+
return { productSha: sha.ok && /^[0-9a-f]{40,64}$/.test(sha.out) ? sha.out : null, productBranch: br.ok && br.out !== 'HEAD' ? br.out : null };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Save one report into the folder and add it to the catalog.
|
|
268
|
+
// → { file, dir, name, warnings: [] } | { problem }
|
|
269
|
+
// The report is written even when the catalog cannot be read: the person asked for the report, and
|
|
270
|
+
// the broken catalog is named in a warning, never overwritten.
|
|
271
|
+
export function saveReport(root, { kind, scope, state, ext, content, command = null, anonymous = false, at = new Date(), env = process.env, runner = spawnSync, lockWaitMs = 5000 } = {}) {
|
|
272
|
+
const { dir } = reportsDir(root, { env, runner });
|
|
273
|
+
const sub = path.join(dir, kind);
|
|
274
|
+
// A folder that cannot be made or written (a read-only parent, say) is a refusal, never a crash.
|
|
275
|
+
const cannot = (e) => ({ problem: `cannot save the report in ${dir} (${e.code || e.message}) — set ${REPORTS_ENV} to a folder you can write, or pass --out <file>` });
|
|
276
|
+
let file, name;
|
|
277
|
+
try {
|
|
278
|
+
const problem = ownDir(dir) || ownDir(sub);
|
|
279
|
+
if (problem) return { problem };
|
|
280
|
+
ensureIgnored(dir);
|
|
281
|
+
name = writeFresh(sub, reportName({ kind, scope, state, at, ext }), content);
|
|
282
|
+
file = path.join(sub, name);
|
|
283
|
+
} catch (e) { return cannot(e); }
|
|
284
|
+
const warnings = [];
|
|
285
|
+
try {
|
|
286
|
+
const done = withCatalogLock(dir, () => {
|
|
287
|
+
const cat = readCatalog(dir);
|
|
288
|
+
if (cat.problem) return cat;
|
|
289
|
+
const entry = { file: `${kind}/${name}`, kind, scope: String(scope ?? ''), state: String(state ?? ''), createdAt: at.toISOString(), ...productAt(root, runner), anonymous: !!anonymous, command };
|
|
290
|
+
const entries = [...cat.entries, entry];
|
|
291
|
+
writeJSON(path.join(dir, CATALOG_FILE), { version: CATALOG_VERSION, entries });
|
|
292
|
+
writeNew(path.join(dir, INDEX_FILE), renderIndex(entries, { brandCss: brandForPage(root, 'catalog').css }));
|
|
293
|
+
return {};
|
|
294
|
+
}, { waitMs: lockWaitMs });
|
|
295
|
+
if (done.problem) warnings.push(done.held ? `the report was saved at ${file}, but not added to the catalog: ${done.problem}. It is in the folder; open it by that path` : done.problem);
|
|
296
|
+
} catch (e) { warnings.push(`the report was saved, but the catalog was not updated (${e.code || e.message})`); }
|
|
297
|
+
return { file, dir, name, warnings };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// Is a report stale? → 'fresh' | 'stale' | 'unknown'. Stale: the Product's epics/ or .sdlc/ changed
|
|
301
|
+
// between the commit the report was made at and the Product's HEAD now. Changes not yet committed are
|
|
302
|
+
// not counted — the record is what is committed.
|
|
303
|
+
export function freshness(root, sha, { runner = spawnSync } = {}) {
|
|
304
|
+
if (!sha || !/^[0-9a-f]{40,64}$/.test(sha)) return 'unknown';
|
|
305
|
+
const r = git(runner, root, ['diff', '--quiet', sha, 'HEAD', '--', 'epics', '.sdlc']);
|
|
306
|
+
return r.code === 0 ? 'fresh' : r.code === 1 ? 'stale' : 'unknown';
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Every catalog entry, newest first, with `n` (1 = newest), whether its file is still there, and its freshness.
|
|
310
|
+
export function listReports(root, { env = process.env, runner = spawnSync } = {}) {
|
|
311
|
+
const { dir, via } = reportsDir(root, { env, runner });
|
|
312
|
+
if (!fs.existsSync(dir)) return { dir, via, entries: [] };
|
|
313
|
+
const linked = linkedDir(dir);
|
|
314
|
+
if (linked) return { dir, via, problem: linked };
|
|
315
|
+
const cat = readCatalog(dir);
|
|
316
|
+
if (cat.problem) return { dir, via, problem: cat.problem };
|
|
317
|
+
const seen = new Map(); // one git run per commit, however many reports were made at it
|
|
318
|
+
const fresh = (sha) => { if (!seen.has(sha)) seen.set(sha, freshness(root, sha, { runner })); return seen.get(sha); };
|
|
319
|
+
const entries = [...cat.entries]
|
|
320
|
+
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
321
|
+
.map((e, i) => ({ n: i + 1, ...e, present: insideDir(dir, e.file) && fs.existsSync(path.join(dir, e.file)), freshness: fresh(e.productSha) }));
|
|
322
|
+
return { dir, via, entries };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
// A catalog path must be exactly `<kind>/<file name>`, with the kind folder a plain folder (not a link)
|
|
326
|
+
// inside the real reports folder: a hand-edited `../x`, `.gitignore` or a linked kind folder is never
|
|
327
|
+
// opened or deleted.
|
|
328
|
+
const NAME_RE = /^[a-z0-9][a-z0-9-]*\.[a-z0-9]{1,8}$/;
|
|
329
|
+
function insideDir(dir, rel) {
|
|
330
|
+
if (typeof rel !== 'string') return false;
|
|
331
|
+
const parts = rel.split('/');
|
|
332
|
+
if (parts.length !== 2 || !Object.hasOwn(KINDS, parts[0]) || !NAME_RE.test(parts[1])) return false;
|
|
333
|
+
const sub = path.join(dir, parts[0]);
|
|
334
|
+
let st; try { st = fs.lstatSync(sub); } catch { return false; }
|
|
335
|
+
if (!st.isDirectory()) return false;
|
|
336
|
+
try { return fs.realpathSync(sub) === path.join(fs.realpathSync(dir), parts[0]); } catch { return false; }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
// The folder itself must be a plain folder: a link there is said, never followed for a delete.
|
|
340
|
+
function linkedDir(dir) {
|
|
341
|
+
let st; try { st = fs.lstatSync(dir); } catch { return null; }
|
|
342
|
+
return st.isDirectory() ? null : `${dir} is not a plain folder (a link or a file) — yad does not read or change it; set ${REPORTS_ENV} to a real folder`;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// The entries `prune` would remove: older than `days`, or whose file is gone.
|
|
346
|
+
// `days: null` drops only entries whose file is missing or not a report path — it deletes no file.
|
|
347
|
+
export function pruneReports(root, { days = null, apply = false, now = Date.now(), env = process.env, runner = spawnSync } = {}) {
|
|
348
|
+
const { dir } = reportsDir(root, { env, runner });
|
|
349
|
+
if (!fs.existsSync(dir)) return { dir, removed: [], kept: 0 };
|
|
350
|
+
const linked = linkedDir(dir);
|
|
351
|
+
if (linked) return { dir, problem: linked };
|
|
352
|
+
const plan = () => {
|
|
353
|
+
const cat = readCatalog(dir);
|
|
354
|
+
if (cat.problem) return { problem: cat.problem };
|
|
355
|
+
const cut = now - days * 864e5;
|
|
356
|
+
const old = (e) => { if (days === null) return false; const t = Date.parse(e.createdAt); return Number.isFinite(t) && t < cut; };
|
|
357
|
+
// The reason is decided BEFORE anything is deleted.
|
|
358
|
+
const marked = cat.entries.map((e) => ({ e, reason: !insideDir(dir, e.file) ? 'outside' : !fs.existsSync(path.join(dir, e.file)) ? 'missing' : old(e) ? 'old' : null }));
|
|
359
|
+
return { removed: marked.filter((m) => m.reason), kept: marked.filter((m) => !m.reason).map((m) => m.e) };
|
|
360
|
+
};
|
|
361
|
+
const act = () => {
|
|
362
|
+
const p = plan();
|
|
363
|
+
if (p.problem || !apply || !p.removed.length) return p;
|
|
364
|
+
for (const { e, reason } of p.removed) {
|
|
365
|
+
if (reason !== 'old') continue; // only a file proved inside the folder is deleted
|
|
366
|
+
const f = path.join(dir, e.file);
|
|
367
|
+
let st = null; try { st = fs.lstatSync(f); } catch { /* already gone */ }
|
|
368
|
+
if (st && (st.isFile() || st.isSymbolicLink())) fs.rmSync(f, { force: true });
|
|
369
|
+
// A report's own side file (the progress map's digest, E181) goes with it.
|
|
370
|
+
const side = `${f}${SIDE_SUFFIX}`;
|
|
371
|
+
let sst = null; try { sst = fs.lstatSync(side); } catch { /* none */ }
|
|
372
|
+
if (sst && (sst.isFile() || sst.isSymbolicLink())) fs.rmSync(side, { force: true });
|
|
373
|
+
}
|
|
374
|
+
writeJSON(path.join(dir, CATALOG_FILE), { version: CATALOG_VERSION, entries: p.kept });
|
|
375
|
+
writeNew(path.join(dir, INDEX_FILE), renderIndex(p.kept, { brandCss: brandForPage(root, 'catalog').css }));
|
|
376
|
+
return p;
|
|
377
|
+
};
|
|
378
|
+
let r;
|
|
379
|
+
try { r = apply ? withCatalogLock(dir, act) : plan(); } catch (e) { return { dir, problem: `cannot change ${dir} (${e.code || e.message})` }; }
|
|
380
|
+
if (r.problem) return { dir, problem: r.problem };
|
|
381
|
+
return { dir, removed: r.removed.map(({ e, reason }) => ({ file: e.file, createdAt: e.createdAt, reason })), kept: r.kept.length };
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// A command's report: to `out` when the person named a file (exactly as before E180, no catalog), else
|
|
385
|
+
// saved into the reports folder. → { file, warnings } | { problem }
|
|
386
|
+
export function writeOrSave(root, { out = null, ...rest }) {
|
|
387
|
+
if (out) {
|
|
388
|
+
fs.mkdirSync(path.dirname(path.resolve(out)), { recursive: true });
|
|
389
|
+
fs.writeFileSync(out, rest.content);
|
|
390
|
+
return { file: out, warnings: [], own: true };
|
|
391
|
+
}
|
|
392
|
+
return saveReport(root, rest);
|
|
393
|
+
}
|