agjan 0.0.20 → 0.0.22

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 (59) hide show
  1. package/README.md +2 -1
  2. package/dist/adapters/claude-code.js +9 -3
  3. package/dist/auto.js +4 -0
  4. package/dist/baseline.js +11 -8
  5. package/dist/commands/check.js +65 -13
  6. package/dist/commands/gates.js +9 -1
  7. package/dist/commands/lint.js +16 -5
  8. package/dist/commands/new.js +4 -3
  9. package/dist/commands/setup.js +91 -81
  10. package/dist/config.js +24 -0
  11. package/dist/fix.js +13 -10
  12. package/dist/git.js +57 -9
  13. package/dist/launcher.js +9 -3
  14. package/dist/progress-view.js +35 -23
  15. package/dist/progress.js +103 -38
  16. package/dist/qa.js +18 -9
  17. package/dist/review-policy.js +12 -4
  18. package/dist/review.js +82 -35
  19. package/dist/schema.js +85 -0
  20. package/dist/scope.js +12 -4
  21. package/dist/tests-map.js +17 -11
  22. package/docs/guide.md +46 -7
  23. package/kit/domains/btp/domain.json +2 -2
  24. package/kit/hooks/guard.mjs +53 -9
  25. package/kit/skills/agjan-ask/SKILL.md +69 -0
  26. package/kit/skills/agjan-ask/references/sources.md +45 -0
  27. package/kit/skills/agjan-design/SKILL.md +13 -0
  28. package/kit/skills/agjan-fix/SKILL.md +1 -1
  29. package/kit/skills/agjan-spec/SKILL.md +7 -1
  30. package/kit/skills/agjan-spec/references/elicitation.md +135 -0
  31. package/kit/skills/btp-architect/SKILL.md +8 -3
  32. package/kit/skills/btp-architect/references/deployment.md +43 -0
  33. package/kit/skills/btp-architect/references/security.md +59 -4
  34. package/kit/skills/cap-developer/SKILL.md +20 -8
  35. package/kit/skills/cap-developer/references/agents.md +90 -0
  36. package/kit/skills/cap-developer/references/handlers.md +88 -9
  37. package/kit/skills/cap-developer/references/modeling.md +41 -0
  38. package/kit/skills/cap-developer/references/project-setup.md +57 -7
  39. package/kit/skills/cap-developer/references/services.md +172 -7
  40. package/kit/skills/cap-developer/references/testing.md +79 -6
  41. package/kit/skills/cap-developer/references/typescript.md +8 -7
  42. package/kit/skills/cap-developer/references/validation-security.md +74 -2
  43. package/kit/skills/fiori-developer/SKILL.md +22 -2
  44. package/kit/skills/fiori-developer/references/accessibility.md +65 -0
  45. package/kit/skills/fiori-developer/references/app-setup.md +10 -3
  46. package/kit/skills/fiori-developer/references/elements-cookbook.md +71 -0
  47. package/kit/skills/fiori-developer/references/elements.md +82 -9
  48. package/kit/skills/fiori-developer/references/freestyle-ts.md +27 -0
  49. package/kit/skills/fiori-developer/references/testing.md +5 -0
  50. package/kit/skills/fiori-developer/references/ui5-basics.md +34 -1
  51. package/kit/skills/qa-tester/SKILL.md +11 -4
  52. package/kit/skills/qa-tester/references/techniques.md +123 -0
  53. package/kit/skills/solution-reviewer/SKILL.md +10 -0
  54. package/kit/skills/solution-reviewer/references/defects.md +154 -0
  55. package/kit/templates/agents-block.md +3 -2
  56. package/kit/templates/agjan-ci.yml +3 -0
  57. package/package.json +1 -1
  58. package/schemas/config.schema.json +1 -1
  59. package/schemas/reviews.schema.json +1 -1
package/dist/git.js CHANGED
@@ -1,8 +1,15 @@
1
1
  import { execFileSync } from 'node:child_process';
2
+ import { lstatSync, readlinkSync } from 'node:fs';
3
+ import { join } from 'node:path';
2
4
  import { AgjanError } from './errors.js';
3
- export function git(cwd, args, { allowFail = false } = {}) {
5
+ /**
6
+ * The most output git may return. Node's default (1 MiB) is easily passed by a diff with a
7
+ * lockfile or by the history of a long-lived repository, and the command then fails.
8
+ */
9
+ const MAX_OUTPUT = 512 * 1024 * 1024;
10
+ export function git(cwd, args, { allowFail = false, input } = {}) {
4
11
  try {
5
- return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
12
+ return execFileSync('git', args, { cwd, encoding: 'utf8', input, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], maxBuffer: MAX_OUTPUT });
6
13
  }
7
14
  catch (error) {
8
15
  if (allowFail)
@@ -51,8 +58,13 @@ export function mergeBase(root, base) {
51
58
  return null;
52
59
  return git(root, ['merge-base', 'HEAD', base], { allowFail: true })?.trim() || null;
53
60
  }
54
- function lines(out) {
55
- return out ? out.split('\n').filter(Boolean) : [];
61
+ /**
62
+ * The paths git lists with `-z`: separated by NUL and never quoted. Without `-z` git quotes a
63
+ * path with non-ASCII characters, tabs or quotes ("srv/\303\274bersicht.js"), and such a path
64
+ * would not match a pattern or name a file.
65
+ */
66
+ export function paths(out) {
67
+ return out ? out.split('\0').filter(Boolean) : [];
56
68
  }
57
69
  /**
58
70
  * Files the operating system writes on its own (macOS Finder, Windows Explorer). They are
@@ -67,22 +79,58 @@ const osFile = (path) => OS_FILES.has(path.slice(path.lastIndexOf('/') + 1));
67
79
  */
68
80
  export function changedFiles(root, base, { staged = false } = {}) {
69
81
  if (staged)
70
- return lines(git(root, ['diff', '--cached', '--name-only', '--no-renames'])).filter((f) => !osFile(f));
82
+ return paths(git(root, ['diff', '--cached', '--name-only', '--no-renames', '-z'])).filter((f) => !osFile(f));
71
83
  const from = mergeBase(root, base);
72
84
  const files = new Set();
73
85
  if (from) {
74
- for (const f of lines(git(root, ['diff', '--name-only', '--no-renames', from])))
86
+ for (const f of paths(git(root, ['diff', '--name-only', '--no-renames', '-z', from])))
75
87
  files.add(f);
76
88
  }
77
89
  else if (git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })) {
78
- for (const f of lines(git(root, ['diff', '--name-only', '--no-renames', 'HEAD'])))
90
+ for (const f of paths(git(root, ['diff', '--name-only', '--no-renames', '-z', 'HEAD'])))
79
91
  files.add(f);
80
92
  }
81
93
  else {
82
- for (const f of lines(git(root, ['diff', '--cached', '--name-only', '--no-renames'])))
94
+ for (const f of paths(git(root, ['diff', '--cached', '--name-only', '--no-renames', '-z'])))
83
95
  files.add(f);
84
96
  }
85
- for (const f of lines(git(root, ['ls-files', '--others', '--exclude-standard'])))
97
+ for (const f of paths(git(root, ['ls-files', '--others', '--exclude-standard', '-z'])))
86
98
  files.add(f);
87
99
  return [...files].filter((f) => !osFile(f)).sort();
88
100
  }
101
+ /** Paths per `git hash-object` call: short enough for any command line, Windows included. */
102
+ const HASH_BATCH = 200;
103
+ /**
104
+ * What each path holds now, as git would store it: the blob id after git's clean filters
105
+ * (line endings from `core.autocrlf` or `.gitattributes`, LFS and other filters), so a CRLF
106
+ * checkout on Windows and an LF checkout in CI give the same id for the same commit. A
107
+ * symbolic link is the blob of its target, as git stores it (Windows checks such a link out
108
+ * as a file holding the target); a folder (an untracked link to one, a nested repository)
109
+ * is only named. Paths that do not exist (deleted) are not in the map. Paths are relative
110
+ * to `root`, POSIX.
111
+ */
112
+ export function contentIds(root, paths) {
113
+ const ids = new Map();
114
+ const files = [];
115
+ for (const path of paths) {
116
+ let stat;
117
+ try {
118
+ stat = lstatSync(join(root, path));
119
+ }
120
+ catch {
121
+ continue;
122
+ }
123
+ if (stat.isSymbolicLink())
124
+ ids.set(path, `blob:${git(root, ['hash-object', '--stdin'], { input: readlinkSync(join(root, path)) }).trim()}`);
125
+ else if (stat.isFile())
126
+ files.push(path);
127
+ else
128
+ ids.set(path, stat.isDirectory() ? '(folder)' : '(not a regular file)');
129
+ }
130
+ for (let i = 0; i < files.length; i += HASH_BATCH) {
131
+ const batch = files.slice(i, i + HASH_BATCH);
132
+ const out = git(root, ['hash-object', '--', ...batch]).split('\n').filter(Boolean);
133
+ batch.forEach((path, j) => ids.set(path, `blob:${out[j]}`));
134
+ }
135
+ return ids;
136
+ }
package/dist/launcher.js CHANGED
@@ -11,6 +11,12 @@ import { askOnTerminal } from './terminal.js';
11
11
  const GLOBAL_COMMANDS = new Set(['init', 'help', '--help', '-h', 'version', '--version', '-v']);
12
12
  /** Set for the process the launcher starts, so that it never delegates again. */
13
13
  const DELEGATED = 'AGJAN_DELEGATED';
14
+ /**
15
+ * `AGJAN_LAUNCHER=0` turns the launcher off: the agjan that was started runs the command
16
+ * itself. The CI workflow sets it, so `npx agjan@<version pinned on the base branch>` checks
17
+ * the pull request, not a version the pull request pins (design 4.1).
18
+ */
19
+ export const LAUNCHER = 'AGJAN_LAUNCHER';
14
20
  const OWN_PACKAGE = realpathSync(fileURLToPath(new URL('..', import.meta.url)));
15
21
  /** The nearest folder up from `dir` with an agjan.config.json; null outside an agjan project. */
16
22
  export function findProject(dir) {
@@ -38,13 +44,13 @@ function defaultDelegate(bin, args, env) {
38
44
  * command runs in the agjan version the project pins (node_modules), so a project is
39
45
  * never driven by whichever version happens to be installed globally. When the pinned
40
46
  * version is not installed (a fresh clone), it is installed first, after asking
41
- * (`--yes` as the first argument skips the question). Outside an agjan project, and in
42
- * the project's own agjan, the command runs here.
47
+ * (`--yes` as the first argument skips the question). Outside an agjan project, in the
48
+ * project's own agjan, and with `AGJAN_LAUNCHER=0`, the command runs here.
43
49
  */
44
50
  export async function launch(args, { cwd = process.cwd(), env = process.env, stderr = process.stderr, ask = askOnTerminal, install = installDependencies, delegate = defaultDelegate, } = {}) {
45
51
  const yes = args[0] === '--yes' || args[0] === '-y';
46
52
  const rest = yes ? args.slice(1) : args;
47
- if (rest[0] === undefined || GLOBAL_COMMANDS.has(rest[0]) || env[DELEGATED])
53
+ if (rest[0] === undefined || GLOBAL_COMMANDS.has(rest[0]) || env[DELEGATED] || env[LAUNCHER] === '0')
48
54
  return { run: rest };
49
55
  const root = findProject(cwd);
50
56
  if (!root)
@@ -1,19 +1,20 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
- import { git } from './git.js';
3
+ import { readJson } from './json-file.js';
4
4
  import { agentModel, loadConfig } from './config.js';
5
- import { FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.js';
5
+ import { APPROVALS_FILE, FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.js';
6
6
  import { readLog } from './log.js';
7
- import { acceptanceState, buildProgress, verifyState } from './progress.js';
7
+ import { acceptanceState, buildProgress, headHistory, prefetchFiles, repoMemo, verifyState } from './progress.js';
8
8
  import { reviewerFor, roundLimit } from './review-policy.js';
9
9
  import { acTestFiles } from './tests-map.js';
10
10
  import { acResults, loadResults } from './test-results.js';
11
11
  import { freshReview } from './fix.js';
12
12
  import { spans } from './commands/report.js';
13
+ import { REVIEW_MD, renderReviewMd } from './review.js';
13
14
  /**
14
15
  * Progress pages (design decision 66): what happened in each unit (feature, fix, map run),
15
- * who worked on it, how the review loops went, and whose turn it is. agjan regenerates them
16
- * after every event it records:
16
+ * who worked on it, how the review loops went, and whose turn it is. agjan regenerates them,
17
+ * and the unit's review.md, after every event it records:
17
18
  * - docs/agjan/<unit>/progress.md: committed with the unit, visible in the pull request;
18
19
  * - .agjan/progress.md and .agjan/progress.html: the project overview, local (not
19
20
  * committed, so parallel branches do not conflict). The HTML is self-contained.
@@ -45,15 +46,11 @@ function readFileSyncSafe(file) {
45
46
  }
46
47
  }
47
48
  /** Commits of the unit anywhere in the history: subjects starting with `<KEY>:` or `<KEY>-T<n>:`. */
48
- function unitCommits(root, key) {
49
- const log = git(root, ['log', '--format=%h%x09%cI%x09%s', 'HEAD'], { allowFail: true }) ?? '';
49
+ function unitCommits(root, key, memo) {
50
50
  const pattern = new RegExp(`^${key}(-T[1-9][0-9]*)?:`);
51
- return log
52
- .split('\n')
53
- .filter(Boolean)
54
- .map((line) => line.split('\t'))
55
- .filter(([, , subject]) => pattern.test(subject ?? ''))
56
- .map(([sha, at, subject]) => ({ sha, at: iso(Date.parse(at)), subject }))
51
+ return headHistory(root, memo)
52
+ .filter((c) => pattern.test(c.subject))
53
+ .map((c) => ({ sha: c.short, at: iso(Date.parse(c.at)), subject: c.subject }))
57
54
  .reverse();
58
55
  }
59
56
  /** Stage track and whose turn it is. */
@@ -92,10 +89,11 @@ function stageOf(ctx, unit, onBase, extra) {
92
89
  // In Build a feature always has its tasks and a verify state.
93
90
  const progress = extra.progress;
94
91
  const verify = extra.verify;
95
- const pending = unit.amendments.filter((a) => a.status === 'pending');
96
- const verified = progress.complete && progress.due.length === 0 && verify.state === 'current';
92
+ // Before the due reviews, which a merged feature does not need (they cost git calls).
97
93
  if (onBase && progress.complete && verify.record && !stillBlocked(unit, verify.record))
98
94
  return { names, at: 5, turn: 'merged', now: 'merged' };
95
+ const pending = unit.amendments.filter((a) => a.status === 'pending');
96
+ const verified = progress.complete && progress.due.length === 0 && verify.state === 'current';
99
97
  if (verified) {
100
98
  if (acceptanceState(ctx.root, ctx.config, unit, verify).state === 'accepted')
101
99
  return { names, at: 5, turn: 'done', now: 'implemented, verified and accepted' };
@@ -139,17 +137,20 @@ export function finalSteps(root, unit, { manual = [], accepted = false } = {}) {
139
137
  optional: [pr],
140
138
  };
141
139
  }
142
- /** The data of one unit for the progress pages. */
143
- export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {}) {
140
+ /**
141
+ * The data of one unit for the progress pages. `memo` shares git's answers between the units
142
+ * of one run (projectModels); a single call makes its own.
143
+ */
144
+ export function unitModel(ctx, slug, { onBase = false, now = Date.now(), memo = repoMemo() } = {}) {
144
145
  const unit = loadFeature(ctx.root, slug);
145
146
  const config = ctx.config;
146
147
  const events = readLog(unit.dir);
147
148
  const isFeature = unit.kind === 'feature';
148
- const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase }) : null;
149
- const verify = isFeature ? verifyState(ctx.root, config, unit) : null;
150
- const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind) : null;
149
+ const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase, memo }) : null;
150
+ const verify = isFeature ? verifyState(ctx.root, config, unit, memo) : null;
151
+ const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind, memo) : null;
151
152
  const stage = waitingFor(events, stageOf(ctx, unit, onBase, { progress, verify, review }));
152
- const commits = unitCommits(ctx.root, unit.key);
153
+ const commits = unitCommits(ctx.root, unit.key, memo);
153
154
  const times = [...events.map((e) => Date.parse(e.at_utc)), ...commits.map((c) => Date.parse(c.at))].filter(Number.isFinite);
154
155
  const start = times.length ? Math.min(...times) : now;
155
156
  const last = times.length ? Math.max(...times) : now;
@@ -205,7 +206,7 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {})
205
206
  const automated = unit.spec.parsed.acs.filter((ac) => ac.verification !== 'manual');
206
207
  const loaded = loadResults(ctx.root, config, areaNames);
207
208
  const results = loaded.files.length ? acResults(loaded, unit.key) : null;
208
- const tests = acTestFiles(ctx.root, config, areaNames, unit.key);
209
+ const tests = acTestFiles(ctx.root, config, areaNames, unit.key, memo);
209
210
  acs = {
210
211
  total: unit.spec.parsed.acs.length,
211
212
  automated: automated.length,
@@ -300,10 +301,17 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now() } = {})
300
301
  export function projectModels(ctx, { now = Date.now() } = {}) {
301
302
  const changed = new Set(changedFeatures(ctx.root, ctx.config));
302
303
  const all = listFeatures(ctx.root);
304
+ // One history and one batch of commit file lists for all units, not one git call per unit.
305
+ const memo = repoMemo();
306
+ const keys = all.map((slug) => readJson(join(ctx.root, FEATURES_DIR, slug, APPROVALS_FILE))?.feature?.key).filter((key) => typeof key === 'string');
307
+ if (keys.length) {
308
+ const task = new RegExp(`^(?:${keys.join('|')})-T[1-9][0-9]*:`);
309
+ prefetchFiles(ctx.root, headHistory(ctx.root, memo).filter((c) => task.test(c.subject)).map((c) => c.sha), memo);
310
+ }
303
311
  const models = [];
304
312
  for (const slug of all) {
305
313
  try {
306
- models.push(unitModel(ctx, slug, { onBase: !changed.has(slug), now }));
314
+ models.push(unitModel(ctx, slug, { onBase: !changed.has(slug), now, memo }));
307
315
  }
308
316
  catch {
309
317
  // A damaged unit must not stop the pages; check reports it.
@@ -464,6 +472,10 @@ export function writeProgress(ctx, { only = null, now = Date.now() } = {}) {
464
472
  continue;
465
473
  const file = join(ctx.root, FEATURES_DIR, m.slug, PROGRESS_MD);
466
474
  writeFileSync(file, unitMarkdown(m, { generatedAt }));
475
+ // review.md shows each finding's status, which accepting a finding changes too.
476
+ const unit = loadFeature(ctx.root, m.slug);
477
+ if (unit.reviews.records.length)
478
+ writeFileSync(join(unit.dir, REVIEW_MD), renderReviewMd(unit));
467
479
  }
468
480
  const dir = join(ctx.root, LOCAL_DIR);
469
481
  if (!existsSync(dir))
package/dist/progress.js CHANGED
@@ -1,8 +1,38 @@
1
- import { git, mergeBase, resolveBase } from './git.js';
1
+ import { git, mergeBase, paths, resolveBase } from './git.js';
2
2
  import { resolveArea } from './config.js';
3
3
  import { matcher } from './scope.js';
4
4
  import { latestReview, stillBlocked } from './feature.js';
5
- import { scriptOwned, treeHash } from './review.js';
5
+ import { isRecord, treeHash } from './review.js';
6
+ export function repoMemo() {
7
+ return { files: new Map(), ancestry: new Map(), texts: new Map() };
8
+ }
9
+ /** The history of HEAD, newest first (once per memo). */
10
+ export function headHistory(root, memo) {
11
+ if (memo?.history)
12
+ return memo.history;
13
+ const out = git(root, ['log', '--format=%H%x09%h%x09%cI%x09%s', 'HEAD'], { allowFail: true }) ?? '';
14
+ const history = out.split('\n').filter(Boolean).map((line) => {
15
+ const [sha, short, at, ...subject] = line.split('\t');
16
+ return { sha, short, at, subject: subject.join('\t') };
17
+ });
18
+ if (memo)
19
+ memo.history = history;
20
+ return history;
21
+ }
22
+ /** Loads the files of many commits with one git call (`git show` in batches), into the memo. */
23
+ export function prefetchFiles(root, shas, memo) {
24
+ const wanted = [...new Set(shas)].filter((sha) => !memo.files.has(sha));
25
+ for (let i = 0; i < wanted.length; i += 200) {
26
+ const out = git(root, ['show', '--name-only', '-z', '--format=%x01%H', ...wanted.slice(i, i + 200)], { allowFail: true });
27
+ if (out === null)
28
+ return; // filesOf asks commit by commit
29
+ // Each commit: \x01<sha>\0, then its files, NUL-separated, the first after a newline.
30
+ for (const chunk of out.split('\x01').filter(Boolean)) {
31
+ const [sha, ...names] = chunk.split('\0');
32
+ memo.files.set(sha, names.map((n, j) => (j === 0 ? n.replace(/^\n/, '') : n)).filter(Boolean));
33
+ }
34
+ }
35
+ }
6
36
  /**
7
37
  * Build progress, derived from commits (design 8.3): a task is done when a commit on
8
38
  * the branch has a subject starting with `<KEY>-<task id>:`, for example `ORDF-T1: …`.
@@ -10,37 +40,57 @@ import { scriptOwned, treeHash } from './review.js';
10
40
  * A commit that changes only agjan's records (reviews, log, progress) is not task work:
11
41
  * it never makes a review due, as the reviews' tree hash does not see it either.
12
42
  */
13
- export function taskCommits(root, config, feature, { history = false } = {}) {
14
- const from = history ? null : mergeBase(root, resolveBase(root, config.git?.base));
15
- const range = from ? `${from}..HEAD` : 'HEAD';
16
- const log = git(root, ['log', '--format=%H%x09%s', range], { allowFail: true }) ?? '';
43
+ export function taskCommits(root, config, feature, { history = false, memo } = {}) {
44
+ let commits;
45
+ if (history) {
46
+ commits = headHistory(root, memo);
47
+ }
48
+ else {
49
+ const from = mergeBase(root, resolveBase(root, config.git?.base));
50
+ const log = git(root, ['log', '--format=%H%x09%s', from ? `${from}..HEAD` : 'HEAD'], { allowFail: true }) ?? '';
51
+ commits = log.split('\n').filter(Boolean).map((line) => {
52
+ const [sha, ...subject] = line.split('\t');
53
+ return { sha, subject: subject.join('\t') };
54
+ });
55
+ }
17
56
  const done = new Map();
18
57
  const prefix = new RegExp(`^${feature.key}-(T[1-9][0-9]*):`);
19
- const records = scriptOwned(feature.slug);
20
58
  // git log lists newest first; keep the newest commit of each task.
21
- for (const line of log.split('\n').filter(Boolean)) {
22
- const [sha, subject] = line.split('\t');
23
- const match = prefix.exec(subject ?? '');
59
+ for (const { sha, subject } of commits) {
60
+ const match = prefix.exec(subject);
24
61
  if (!match || done.has(match[1]))
25
62
  continue;
26
- const files = filesOf(root, sha);
27
- if (files.length && files.every((f) => records.has(f) || f.startsWith('.agjan/')))
63
+ const files = filesOf(root, sha, memo);
64
+ if (files.length && files.every((f) => isRecord(f) || f.startsWith('.agjan/')))
28
65
  continue;
29
66
  done.set(match[1], sha);
30
67
  }
31
68
  return done;
32
69
  }
33
- function filesOf(root, sha) {
34
- return (git(root, ['show', '--name-only', '--format=', sha]) ?? '').split('\n').filter(Boolean);
70
+ function filesOf(root, sha, memo) {
71
+ const known = memo?.files.get(sha);
72
+ if (known)
73
+ return known;
74
+ const files = paths(git(root, ['show', '--name-only', '--format=', '-z', sha]));
75
+ memo?.files.set(sha, files);
76
+ return files;
35
77
  }
36
- function isAncestor(root, ancestor, descendant) {
78
+ function isAncestor(root, ancestor, descendant, memo) {
37
79
  if (!ancestor || !descendant)
38
80
  return false;
39
- return git(root, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true }) !== null;
81
+ if (ancestor === descendant)
82
+ return true;
83
+ const key = `${ancestor}..${descendant}`;
84
+ const known = memo?.ancestry.get(key);
85
+ if (known !== undefined)
86
+ return known;
87
+ const answer = git(root, ['merge-base', '--is-ancestor', ancestor, descendant], { allowFail: true }) !== null;
88
+ memo?.ancestry.set(key, answer);
89
+ return answer;
40
90
  }
41
91
  /** A passing review of `step` that saw the given commit (its head contains the commit). */
42
- function reviewedSince(root, feature, step, sha) {
43
- return feature.reviews.records.some((r) => r.step === step && !stillBlocked(feature, r) && isAncestor(root, sha, r.head_commit));
92
+ function reviewedSince(root, feature, step, sha, memo) {
93
+ return feature.reviews.records.some((r) => r.step === step && !stillBlocked(feature, r) && isAncestor(root, sha, r.head_commit, memo));
44
94
  }
45
95
  /**
46
96
  * Tasks with their state, the next task, and the build reviews that are due
@@ -48,46 +98,61 @@ function reviewedSince(root, feature, step, sha) {
48
98
  * always per task for tasks whose commit touched a risk path.
49
99
  */
50
100
  export function buildProgress(root, config, feature, options = {}) {
101
+ const { memo } = options;
51
102
  const tasks = feature.tasks?.parsed.tasks ?? [];
52
103
  const done = taskCommits(root, config, feature, options);
53
- const isRisk = matcher(config.risk_paths ?? []);
54
104
  const list = tasks.map((t) => ({
55
105
  ...t,
56
106
  areaName: resolveArea(config, t.area ?? '')?.name ?? t.area,
57
107
  commit: done.get(t.id) ?? null,
58
108
  }));
59
- const due = [];
60
- const perTask = config.review?.build === 'task';
61
- for (const task of list.filter((t) => t.commit)) {
62
- const risky = filesOf(root, task.commit).some(isRisk);
63
- if ((perTask || risky) && !reviewedSince(root, feature, `build:${task.id}`, task.commit)) {
64
- due.push({ step: `build:${task.id}`, reason: risky ? 'touches a risk path' : 'review per task' });
109
+ const dueReviews = () => {
110
+ const isRisk = matcher(config.risk_paths ?? []);
111
+ const due = [];
112
+ const perTask = config.review?.build === 'task';
113
+ for (const task of list.filter((t) => t.commit)) {
114
+ const risky = filesOf(root, task.commit, memo).some(isRisk);
115
+ if ((perTask || risky) && !reviewedSince(root, feature, `build:${task.id}`, task.commit, memo)) {
116
+ due.push({ step: `build:${task.id}`, reason: risky ? 'touches a risk path' : 'review per task' });
117
+ }
65
118
  }
66
- }
67
- if (!perTask) {
68
- for (const area of [...new Set(list.map((t) => t.areaName))]) {
69
- const areaTasks = list.filter((t) => t.areaName === area);
70
- if (areaTasks.some((t) => !t.commit))
71
- continue;
72
- const last = areaTasks.map((t) => t.commit).find((sha) => areaTasks.every((o) => isAncestor(root, o.commit, sha)));
73
- if (!reviewedSince(root, feature, `build:${area}`, last))
74
- due.push({ step: `build:${area}`, reason: 'all tasks of the area are done' });
119
+ if (!perTask) {
120
+ for (const area of [...new Set(list.map((t) => t.areaName))]) {
121
+ const areaTasks = list.filter((t) => t.areaName === area);
122
+ if (areaTasks.some((t) => !t.commit))
123
+ continue;
124
+ const last = areaTasks.map((t) => t.commit).find((sha) => areaTasks.every((o) => isAncestor(root, o.commit, sha, memo)));
125
+ if (!reviewedSince(root, feature, `build:${area}`, last, memo))
126
+ due.push({ step: `build:${area}`, reason: 'all tasks of the area are done' });
127
+ }
75
128
  }
76
- }
129
+ return due;
130
+ };
77
131
  const next = list.find((t) => !t.commit) ?? null;
78
- return { tasks: list, next, due, complete: list.length > 0 && !next };
132
+ let due;
133
+ return {
134
+ tasks: list,
135
+ next,
136
+ complete: list.length > 0 && !next,
137
+ // Worked out when asked: a merged feature on the base branch never needs it.
138
+ get due() {
139
+ due ??= dueReviews();
140
+ return due;
141
+ },
142
+ };
79
143
  }
80
144
  /**
81
145
  * The final verify review (design 8.4): `none`, `blocked`, `stale` (files changed after
82
146
  * it) or `current`. Shared by `check --ci` and `status`.
83
147
  */
84
- export function verifyState(root, config, feature) {
148
+ export function verifyState(root, config, feature, memo) {
85
149
  const record = latestReview(feature.reviews, ['verify']);
86
150
  if (!record)
87
151
  return { state: 'none', record: null };
88
152
  if (stillBlocked(feature, record))
89
153
  return { state: 'blocked', record };
90
- if (record.tree_hash !== treeHash(root, config, feature.slug))
154
+ const tree = memo ? (memo.tree ??= treeHash(root, config)) : treeHash(root, config);
155
+ if (record.tree_hash !== tree)
91
156
  return { state: 'stale', record };
92
157
  return { state: 'current', record };
93
158
  }
package/dist/qa.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readFileSync, readdirSync } from 'node:fs';
2
+ import { existsSync, readdirSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { contentIds } from './git.js';
4
5
  import { latestReview, stillBlocked } from './feature.js';
5
6
  /**
6
7
  * The QA step (design decision 81): in Verify, the QA agent (`agjan-qa`, the qa-tester
@@ -38,19 +39,23 @@ function filesUnder(root, dir) {
38
39
  export function qaTestFiles(root, slug) {
39
40
  return qaDirs(slug).flatMap((dir) => filesUnder(root, dir)).sort();
40
41
  }
41
- /** Hash of the feature's QA tests as they are now: a change after QA makes it stale. */
42
+ /**
43
+ * Hash of the feature's QA tests as they are now: a change after QA makes it stale. The
44
+ * content as git stores it, so a CRLF checkout and CI agree (`contentIds`).
45
+ */
42
46
  export function qaTestsHash(root, slug) {
47
+ const files = qaTestFiles(root, slug);
48
+ const ids = contentIds(root, files);
43
49
  const hash = createHash('sha256');
44
- for (const file of qaTestFiles(root, slug)) {
45
- hash.update(file).update('\0').update(createHash('sha256').update(readFileSync(join(root, file))).digest('hex')).update('\0');
46
- }
50
+ for (const file of files)
51
+ hash.update(file).update('\0').update(ids.get(file) ?? 'deleted').update('\0');
47
52
  return `sha256:${hash.digest('hex')}`;
48
53
  }
49
54
  /**
50
55
  * Where QA stands: `off` (light mode, or turned off), `due` (no QA round yet), `blocked`
51
- * (its blockers are open: fix the code, then QA again), `stale` (the QA tests changed
52
- * after the round: QA again) or `passed`. Code changes after a passing round are the
53
- * final review's to judge, not QA's.
56
+ * (its blockers are open: fix the code, then QA again), `stale` (the spec was revised or
57
+ * the QA tests changed after the round: QA again) or `passed`. Code changes after a
58
+ * passing round are the final review's to judge, not QA's.
54
59
  */
55
60
  export function qaState(root, config, feature) {
56
61
  if (!qaApplies(config, feature))
@@ -60,8 +65,10 @@ export function qaState(root, config, feature) {
60
65
  return { state: 'due', record: null };
61
66
  if (stillBlocked(feature, record))
62
67
  return { state: 'blocked', record };
68
+ if (record.documents?.spec !== feature.spec?.hash)
69
+ return { state: 'stale', record, reason: 'spec' };
63
70
  if (record.qa_tests_hash !== qaTestsHash(root, feature.slug))
64
- return { state: 'stale', record };
71
+ return { state: 'stale', record, reason: 'tests' };
65
72
  return { state: 'passed', record };
66
73
  }
67
74
  /** Why the final review and the acceptance wait for QA, or null when they need not. */
@@ -71,6 +78,8 @@ export function qaProblem(root, config, feature) {
71
78
  return 'QA has not run yet: delegate step qa to agjan-qa';
72
79
  if (qa.state === 'blocked')
73
80
  return `the QA round ${qa.record.id} is blocked: fix the code (never the QA tests), then run QA again`;
81
+ if (qa.state === 'stale' && qa.reason === 'spec')
82
+ return `the spec changed after the QA round ${qa.record.id}: run QA again`;
74
83
  if (qa.state === 'stale')
75
84
  return `the QA tests changed after the QA round ${qa.record.id}: run QA again`;
76
85
  return null;
@@ -35,16 +35,21 @@ export function fixAttempts(config) {
35
35
  }
36
36
  /** The gate approvals that close a correction loop of a review step. */
37
37
  const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'] };
38
+ /** Steps whose loop a later spec or design approval closes: a revision (decision 84) starts them again. */
39
+ const AFTER_GATES = (step) => step === 'qa' || step === 'verify' || step.startsWith('build:');
38
40
  /**
39
41
  * The round the next review of `step` gets (design 7.4). Rounds count within one
40
42
  * correction loop: a loop ends with a review without findings (`pass`), with the gate's
41
- * approval after its last review, or, for build steps, with a passing verify review after
43
+ * approval after its last review, for build, QA and verify steps with a spec or design
44
+ * approval after it (a revision), or, for build steps, with a passing verify review after
42
45
  * it. A later change, for example after the human's Gate 3 review, starts a new loop at
43
46
  * round 1.
44
47
  */
45
48
  export function nextRound(feature, step) {
46
49
  const records = feature.reviews.records.filter((r) => r.step === step);
47
- const approvals = (CLOSING_APPROVALS[step] ?? []).map((gate) => feature.approvals.approvals[gate]?.at_utc).filter((at) => Boolean(at));
50
+ const stamp = (gate) => feature.approvals.approvals[gate]?.at_utc;
51
+ const approvals = (CLOSING_APPROVALS[step] ?? []).map(stamp).filter((at) => Boolean(at));
52
+ const revisions = AFTER_GATES(step) ? ['spec', 'design'].map(stamp).filter((at) => Boolean(at)) : [];
48
53
  if (step.startsWith('build:')) {
49
54
  const verified = feature.reviews.records.filter((r) => r.step === 'verify' && !stillBlocked(feature, r));
50
55
  approvals.push(...verified.map((r) => r.at_utc));
@@ -52,7 +57,7 @@ export function nextRound(feature, step) {
52
57
  let round = 1;
53
58
  for (let i = records.length - 1; i >= 0; i--) {
54
59
  const r = records[i];
55
- if (r.verdict === 'pass' || approvals.some((at) => at >= r.at_utc))
60
+ if (r.verdict === 'pass' || approvals.some((at) => at >= r.at_utc) || revisions.some((at) => at > r.at_utc))
56
61
  break;
57
62
  round += 1;
58
63
  }
@@ -69,7 +74,10 @@ export function roundState(feature, config, step) {
69
74
  const extra = extraRounds(feature, step);
70
75
  const limit = roundLimit(config) + extra;
71
76
  const round = last?.round ?? 0;
72
- return { last, round, next: nextRound(feature, step), limit, extra, exhausted: stillBlocked(feature, last) && round >= limit };
77
+ // Exhausted: still blocked, and the next round would pass the limit; a loop that an approval
78
+ // or a passing verify review closed starts again at round 1 (nextRound).
79
+ const next = nextRound(feature, step);
80
+ return { last, round, next, limit, extra, exhausted: stillBlocked(feature, last) && next > limit };
73
81
  }
74
82
  /**
75
83
  * Rounds the user granted beyond the limit in the current correction loop of `step`