agjan 0.0.22 → 0.0.23

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 (62) hide show
  1. package/README.md +6 -4
  2. package/dist/adapters/claude-code.js +3 -3
  3. package/dist/baseline.js +2 -2
  4. package/dist/cli.js +22 -4
  5. package/dist/commands/check.js +91 -7
  6. package/dist/commands/discover.js +54 -0
  7. package/dist/commands/fix.js +8 -3
  8. package/dist/commands/gates.js +48 -28
  9. package/dist/commands/import.js +73 -0
  10. package/dist/commands/log.js +3 -2
  11. package/dist/commands/map.js +6 -1
  12. package/dist/commands/new.js +7 -3
  13. package/dist/commands/pr-summary.js +20 -5
  14. package/dist/commands/progress.js +1 -1
  15. package/dist/commands/report.js +1 -1
  16. package/dist/commands/review.js +21 -9
  17. package/dist/commands/status.js +118 -20
  18. package/dist/commands/summary.js +2 -1
  19. package/dist/commands/team.js +45 -0
  20. package/dist/commands/test.js +37 -0
  21. package/dist/config.js +8 -0
  22. package/dist/discovery.js +42 -0
  23. package/dist/feature.js +14 -7
  24. package/dist/imports.js +197 -0
  25. package/dist/plan.js +1 -1
  26. package/dist/progress-view.js +46 -11
  27. package/dist/qa.js +27 -3
  28. package/dist/readiness.js +33 -0
  29. package/dist/review-policy.js +2 -1
  30. package/dist/review.js +68 -17
  31. package/dist/schema.js +4 -0
  32. package/dist/story.js +15 -8
  33. package/dist/teams.js +127 -0
  34. package/dist/test-run.js +101 -0
  35. package/dist/types.js +0 -4
  36. package/dist/workflow.js +83 -0
  37. package/docs/guide.md +161 -23
  38. package/kit/domains/btp/domain.json +1 -0
  39. package/kit/hooks/guard.mjs +134 -6
  40. package/kit/skills/agjan-ask/SKILL.md +20 -9
  41. package/kit/skills/agjan-build/SKILL.md +6 -5
  42. package/kit/skills/agjan-design/SKILL.md +2 -2
  43. package/kit/skills/agjan-discover/SKILL.md +87 -0
  44. package/kit/skills/agjan-fix/SKILL.md +10 -6
  45. package/kit/skills/agjan-map/SKILL.md +12 -8
  46. package/kit/skills/agjan-spec/SKILL.md +14 -7
  47. package/kit/skills/agjan-verify/SKILL.md +27 -17
  48. package/kit/skills/btp-architect/SKILL.md +1 -1
  49. package/kit/skills/btp-architect/references/security.md +1 -1
  50. package/kit/skills/cap-developer/SKILL.md +1 -1
  51. package/kit/skills/cap-developer/references/project-setup.md +1 -1
  52. package/kit/skills/cap-developer/references/validation-security.md +1 -1
  53. package/kit/skills/fiori-developer/SKILL.md +1 -1
  54. package/kit/skills/qa-tester/SKILL.md +4 -2
  55. package/kit/templates/agents-block.md +13 -6
  56. package/kit/templates/progress.html +2 -2
  57. package/kit/templates/proposal.md +22 -0
  58. package/package.json +1 -1
  59. package/schemas/approvals.schema.json +9 -1
  60. package/schemas/config.schema.json +33 -1
  61. package/schemas/log.schema.json +1 -1
  62. package/schemas/reviews.schema.json +2 -2
package/dist/feature.js CHANGED
@@ -5,17 +5,20 @@ import { readJson } from './json-file.js';
5
5
  import { parseSpec, parseDesign, parseTasks } from './documents.js';
6
6
  import { changedFiles, resolveBase } from './git.js';
7
7
  import { AgjanError, UsageError } from './errors.js';
8
- export const FEATURES_DIR = 'docs/agjan';
8
+ import { CONTAINERS, WORKFLOWS } from './workflow.js';
9
+ export const FEATURES_DIR = 'agjan-docs';
9
10
  export const APPROVALS_FILE = 'approvals.json';
10
11
  export const REVIEWS_FILE = 'reviews.json';
12
+ export const PROPOSAL_FILE = 'proposal.md';
11
13
  /**
12
- * Record folders under docs/agjan (decision 57). A unit's id is its path below
13
- * docs/agjan: a feature `order-filter`, a fix `fixes/2026-10-17-order-label`, a map run
14
+ * Record folders under agjan-docs (decision 57). A unit's id is its path below
15
+ * agjan-docs: a feature `order-filter`, a fix `fixes/2026-10-17-order-label`, a map run
14
16
  * `maps/2026-10-17`. All have approvals.json (key, accepted findings), reviews.json and
15
17
  * log.jsonl; only features have spec, design and tasks.
16
18
  */
17
- export const CONTAINERS = { fixes: 'fix', maps: 'map' };
19
+ export { CONTAINERS } from './workflow.js';
18
20
  const RESERVED = new Set(Object.keys(CONTAINERS));
21
+ const NON_FEATURE_KINDS = Object.keys(WORKFLOWS).filter((k) => k !== 'feature');
19
22
  export const SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/;
20
23
  export const KEY = /^[A-Z][A-Z0-9]{1,5}$/;
21
24
  /** Review steps whose passing record allows each gate (design 7.3). */
@@ -38,7 +41,7 @@ export function listFeatures(root) {
38
41
  const others = Object.keys(CONTAINERS).flatMap((c) => unitFolders(join(dir, c)).map((e) => `${c}/${e.name}`).sort());
39
42
  return [...features, ...others];
40
43
  }
41
- /** The unit id a repository path belongs to, or null (docs/agjan/project.md, ...). */
44
+ /** The unit id a repository path belongs to, or null (agjan-docs/project.md, ...). */
42
45
  export function unitOf(file) {
43
46
  const prefix = `${FEATURES_DIR}/`;
44
47
  if (!file.startsWith(prefix))
@@ -97,7 +100,7 @@ function validateApprovals(data, slug) {
97
100
  }
98
101
  if (!KEY.test(data.feature.key ?? ''))
99
102
  throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: invalid feature key`);
100
- if (data.feature.kind !== undefined && !['fix', 'map'].includes(data.feature.kind)) {
103
+ if (data.feature.kind !== undefined && !NON_FEATURE_KINDS.includes(data.feature.kind)) {
101
104
  throw new AgjanError(`${FEATURES_DIR}/${slug}/${APPROVALS_FILE}: unknown kind '${data.feature.kind}'`);
102
105
  }
103
106
  for (const list of ['amendments', 'accepted', 'rejections']) {
@@ -165,6 +168,9 @@ export function loadFeature(root, slug) {
165
168
  const design = read('design.md', parseDesign);
166
169
  const tasks = read('tasks.md', parseTasks);
167
170
  const designHash = design && tasks ? hashParts([['design.md', design.text], ['tasks.md', tasks.text]]) : null;
171
+ // A discovery's one document: its proposal (decision 91).
172
+ const proposal = kind === 'discovery' ? readDoc(dir, PROPOSAL_FILE) : null;
173
+ const proposalState = kind === 'discovery' ? docState(proposal, approvals.approvals.proposal, proposal?.hash) : 'missing';
168
174
  const specApproval = approvals.approvals.spec;
169
175
  const designApproval = approvals.approvals.design;
170
176
  const specState = docState(spec, specApproval, spec?.hash);
@@ -187,7 +193,8 @@ export function loadFeature(root, slug) {
187
193
  design,
188
194
  tasks,
189
195
  designHash,
190
- state: { spec: specState, design: designState },
196
+ proposal,
197
+ state: { spec: specState, design: designState, proposal: proposalState },
191
198
  stage,
192
199
  amendments,
193
200
  findings: findingStatus(reviews, approvals),
@@ -0,0 +1,197 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
4
+ import { tmpdir } from 'node:os';
5
+ import { dirname, join, relative } from 'node:path';
6
+ import { readJson, writeJson } from './json-file.js';
7
+ import { AgjanError } from './errors.js';
8
+ import { loadSchema, validate } from './schema.js';
9
+ /**
10
+ * Imports (decision 93): skills and teams from another repository, at an exact commit.
11
+ *
12
+ * The source declares what it offers in `agjan-package.json` (name, version, license,
13
+ * skill folders, teams) and nothing else: no hooks, agents, MCP servers or settings, so an
14
+ * import cannot grant itself any permission. Its skills land in `.claude/skills/<package>-<skill>/`
15
+ * and its teams as `<package>/<team>`. `agjan.imports.json` records the source, the commit,
16
+ * the license and a hash of every imported file; `check` reports a file changed by hand.
17
+ * Nothing in the source runs. A person confirms every import in a terminal: imported skills
18
+ * become instructions to the agents.
19
+ */
20
+ export const IMPORTS_FILE = 'agjan.imports.json';
21
+ export const MANIFEST = 'agjan-package.json';
22
+ const NAME = /^[a-z][a-z0-9-]{1,30}$/;
23
+ const COMMIT = /^[0-9a-f]{40}$/;
24
+ const MAX_FILE = 1024 * 1024;
25
+ const MAX_TOTAL = 5 * 1024 * 1024;
26
+ export function readImports(root) {
27
+ return readJson(join(root, IMPORTS_FILE)) ?? { schema: 1, imports: {} };
28
+ }
29
+ /** The imported teams, by their namespaced names. */
30
+ export function importedTeams(root) {
31
+ return Object.assign({}, ...Object.values(readImports(root).imports).map((i) => i.teams ?? {}));
32
+ }
33
+ const sha = (content) => `sha256:${createHash('sha256').update(content).digest('hex')}`;
34
+ function manifestProblems(data) {
35
+ if (!data || typeof data !== 'object')
36
+ return [`${MANIFEST} is missing or not JSON`];
37
+ const problems = [];
38
+ const allowed = new Set(['name', 'version', 'license', 'description', 'skills', 'teams']);
39
+ for (const key of Object.keys(data))
40
+ if (!allowed.has(key))
41
+ problems.push(`${MANIFEST}: '${key}' is not allowed (a package offers skills and teams only)`);
42
+ if (!NAME.test(data.name ?? ''))
43
+ problems.push(`${MANIFEST}: name must be 2 to 31 lowercase letters, digits or '-'`);
44
+ if (typeof data.version !== 'string' || !data.version)
45
+ problems.push(`${MANIFEST}: version is missing`);
46
+ if (typeof data.license !== 'string' || !data.license)
47
+ problems.push(`${MANIFEST}: license is missing`);
48
+ if (data.skills !== undefined && (!Array.isArray(data.skills) || data.skills.some((s) => typeof s !== 'string')))
49
+ problems.push(`${MANIFEST}: skills must be a list of folders`);
50
+ if (data.teams !== undefined) {
51
+ for (const p of validate(loadSchema('config'), { teams: data.teams }))
52
+ problems.push(`${MANIFEST}: ${p}`);
53
+ }
54
+ return problems;
55
+ }
56
+ /** Every regular file under `dir`; links and oversized files are refused. */
57
+ function filesUnder(dir, base = dir) {
58
+ const out = [];
59
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
60
+ const path = join(dir, entry.name);
61
+ if (lstatSync(path).isSymbolicLink())
62
+ throw new AgjanError(`${relative(base, path)} is a symbolic link; packages contain plain files only`);
63
+ if (entry.isDirectory())
64
+ out.push(...filesUnder(path, base));
65
+ else if (entry.isFile())
66
+ out.push(path);
67
+ }
68
+ return out;
69
+ }
70
+ /**
71
+ * Fetches the source at `commit` into a temporary folder and builds the plan: nothing in
72
+ * the source runs (a clone and a checkout, no hooks: `core.hooksPath` points nowhere).
73
+ */
74
+ export function planImport(source, commit) {
75
+ if (!COMMIT.test(commit))
76
+ throw new AgjanError(`--commit must be a full 40-character commit id, not a branch or tag: '${commit}'`);
77
+ const dir = mkdtempSync(join(tmpdir(), 'agjan-import-'));
78
+ try {
79
+ const git = (args, cwd) => execFileSync('git', ['-c', 'core.hooksPath=/dev/null', '-c', 'protocol.ext.allow=never', ...args], { cwd, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf8' });
80
+ try {
81
+ git(['clone', '--quiet', '--no-checkout', source, join(dir, 'src')]);
82
+ git(['checkout', '--quiet', commit], join(dir, 'src'));
83
+ }
84
+ catch (error) {
85
+ throw new AgjanError(`could not fetch ${source} at ${commit}: ${String(error.stderr ?? error).trim().split('\n').at(-1)}`);
86
+ }
87
+ const root = join(dir, 'src');
88
+ let manifest;
89
+ try {
90
+ manifest = JSON.parse(readFileSync(join(root, MANIFEST), 'utf8'));
91
+ }
92
+ catch {
93
+ manifest = null;
94
+ }
95
+ const problems = manifestProblems(manifest);
96
+ if (problems.length)
97
+ throw new AgjanError(`${source} at ${commit.slice(0, 12)} is not an agjan package:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
98
+ const files = new Map();
99
+ const skillNames = new Map();
100
+ let total = 0;
101
+ for (const folder of manifest.skills ?? []) {
102
+ const abs = join(root, folder);
103
+ if (relative(root, abs).startsWith('..') || !existsSync(join(abs, 'SKILL.md')))
104
+ throw new AgjanError(`${MANIFEST}: skill folder '${folder}' has no SKILL.md`);
105
+ const local = `${manifest.name}-${folder.replace(/\/+$/, '').split('/').at(-1)}`;
106
+ skillNames.set(folder.replace(/\/+$/, '').split('/').at(-1), local);
107
+ for (const file of filesUnder(abs)) {
108
+ let content = readFileSync(file);
109
+ if (content.length > MAX_FILE)
110
+ throw new AgjanError(`${relative(root, file)} is larger than 1 MiB`);
111
+ total += content.length;
112
+ if (relative(abs, file) === 'SKILL.md') {
113
+ // The skill's name is its namespaced folder, so it cannot pose as another skill.
114
+ content = Buffer.from(content.toString('utf8').replace(/^(---\n[\s\S]*?^name:\s*).*$/m, `$1${local}`));
115
+ }
116
+ files.set(`.claude/skills/${local}/${relative(abs, file).split('\\').join('/')}`, content);
117
+ }
118
+ }
119
+ if (total > MAX_TOTAL)
120
+ throw new AgjanError('the package is larger than 5 MiB');
121
+ const teams = {};
122
+ for (const [name, team] of Object.entries(manifest.teams ?? {})) {
123
+ const personas = Object.fromEntries(Object.entries(team.personas).map(([role, p]) => [role, { ...p, skills: p.skills.map((s) => skillNames.get(s) ?? s) }]));
124
+ teams[`${manifest.name}/${name}`] = { ...team, personas };
125
+ }
126
+ return { manifest, source, commit, files, teams };
127
+ }
128
+ finally {
129
+ rmSync(dir, { recursive: true, force: true });
130
+ }
131
+ }
132
+ /** What applying a plan changes, against what the project has from this package now. */
133
+ export function planChanges(root, plan) {
134
+ const current = readImports(root).imports[plan.manifest.name];
135
+ const before = current?.files ?? {};
136
+ const added = [...plan.files.keys()].filter((f) => !(f in before));
137
+ const changed = [...plan.files.keys()].filter((f) => f in before && before[f] !== sha(plan.files.get(f)));
138
+ const removed = Object.keys(before).filter((f) => !plan.files.has(f));
139
+ const oldTeams = current?.teams ?? {};
140
+ return {
141
+ added,
142
+ changed,
143
+ removed,
144
+ teams: {
145
+ added: Object.keys(plan.teams).filter((t) => !(t in oldTeams)),
146
+ changed: Object.keys(plan.teams).filter((t) => t in oldTeams && JSON.stringify(oldTeams[t]) !== JSON.stringify(plan.teams[t])),
147
+ removed: Object.keys(oldTeams).filter((t) => !(t in plan.teams)),
148
+ },
149
+ };
150
+ }
151
+ /** Skill folders the package would take over from someone else: the project's own, or another package's. */
152
+ export function collisions(root, plan) {
153
+ const imports = readImports(root).imports;
154
+ const ours = new Set(Object.keys(imports[plan.manifest.name]?.files ?? {}));
155
+ const others = new Set(Object.entries(imports).filter(([n]) => n !== plan.manifest.name).flatMap(([, i]) => Object.keys(i.files)));
156
+ return [...plan.files.keys()].filter((f) => others.has(f) || (!ours.has(f) && existsSync(join(root, f))));
157
+ }
158
+ export function applyImport(root, plan, at, by) {
159
+ const imports = readImports(root);
160
+ for (const file of Object.keys(imports.imports[plan.manifest.name]?.files ?? {}))
161
+ if (!plan.files.has(file))
162
+ rmSync(join(root, file), { force: true });
163
+ const files = {};
164
+ for (const [file, content] of plan.files) {
165
+ mkdirSync(dirname(join(root, file)), { recursive: true });
166
+ writeFileSync(join(root, file), content);
167
+ files[file] = sha(content);
168
+ }
169
+ const { name, version, license, description } = plan.manifest;
170
+ imports.imports[name] = { source: plan.source, commit: plan.commit, version, license, ...(description ? { description } : {}), imported_at_utc: at, by, files, teams: plan.teams };
171
+ writeJson(join(root, IMPORTS_FILE), imports);
172
+ }
173
+ export function removeImport(root, name) {
174
+ const imports = readImports(root);
175
+ const record = imports.imports[name];
176
+ if (!record)
177
+ throw new AgjanError(`no imported package '${name}' (${IMPORTS_FILE})`);
178
+ for (const file of Object.keys(record.files))
179
+ rmSync(join(root, file), { force: true });
180
+ delete imports.imports[name];
181
+ writeJson(join(root, IMPORTS_FILE), imports);
182
+ return Object.keys(record.files);
183
+ }
184
+ /** Imported files that are missing or no longer what was imported. */
185
+ export function importDrift(root) {
186
+ const out = [];
187
+ for (const [name, record] of Object.entries(readImports(root).imports)) {
188
+ for (const [file, hash] of Object.entries(record.files)) {
189
+ const path = join(root, file);
190
+ if (!existsSync(path))
191
+ out.push(`${file} (from ${name}) is missing`);
192
+ else if (sha(readFileSync(path)) !== hash)
193
+ out.push(`${file} (from ${name}) changed after the import`);
194
+ }
195
+ }
196
+ return out;
197
+ }
package/dist/plan.js CHANGED
@@ -23,7 +23,7 @@ export function buildPlan(config) {
23
23
  // .claude/skills/ for every host: both read them from there.
24
24
  if (hosts.includes(claudeCode.HOST))
25
25
  items.push({ kind: 'block', path: 'CLAUDE.md', style: 'md', content: '@AGENTS.md', skip: importsAgents });
26
- items.push({ kind: 'block', path: '.gitattributes', style: 'hash', content: 'docs/agjan/** text eol=lf\nagjan.lock.json text eol=lf' },
26
+ items.push({ kind: 'block', path: '.gitattributes', style: 'hash', content: 'agjan-docs/** text eol=lf\nagjan.lock.json text eol=lf' },
27
27
  // node_modules too: a new project often has no .gitignore of its own (design decision 69).
28
28
  { kind: 'block', path: '.gitignore', style: 'hash', content: '.agjan/\nnode_modules/\n.DS_Store\nThumbs.db' });
29
29
  for (const host of hosts) {
@@ -4,18 +4,21 @@ import { readJson } from './json-file.js';
4
4
  import { agentModel, loadConfig } from './config.js';
5
5
  import { APPROVALS_FILE, FEATURES_DIR, changedFeatures, listFeatures, loadFeature, stillBlocked } from './feature.js';
6
6
  import { readLog } from './log.js';
7
- import { acceptanceState, buildProgress, headHistory, prefetchFiles, repoMemo, verifyState } from './progress.js';
7
+ import { buildProgress, headHistory, prefetchFiles, repoMemo, verifyState } from './progress.js';
8
+ import { verification } from './readiness.js';
8
9
  import { reviewerFor, roundLimit } from './review-policy.js';
9
10
  import { acTestFiles } from './tests-map.js';
10
11
  import { acResults, loadResults } from './test-results.js';
11
12
  import { freshReview } from './fix.js';
13
+ import { workflowOf } from './workflow.js';
14
+ import { proposalReview } from './discovery.js';
12
15
  import { spans } from './commands/report.js';
13
16
  import { REVIEW_MD, renderReviewMd } from './review.js';
14
17
  /**
15
18
  * Progress pages (design decision 66): what happened in each unit (feature, fix, map run),
16
19
  * who worked on it, how the review loops went, and whose turn it is. agjan regenerates them,
17
20
  * and the unit's review.md, after every event it records:
18
- * - docs/agjan/<unit>/progress.md: committed with the unit, visible in the pull request;
21
+ * - agjan-docs/<unit>/progress.md: committed with the unit, visible in the pull request;
19
22
  * - .agjan/progress.md and .agjan/progress.html: the project overview, local (not
20
23
  * committed, so parallel branches do not conflict). The HTML is self-contained.
21
24
  */
@@ -30,7 +33,11 @@ function titleOf(unit) {
30
33
  return fix.what ?? unit.slug;
31
34
  }
32
35
  if (unit.kind === 'map')
33
- return 'Map of the application (docs/agjan/project.md)';
36
+ return 'Map of the application (agjan-docs/project.md)';
37
+ if (unit.kind === 'discovery') {
38
+ const question = /^## Question\s*$\s*^(.+)$/m.exec(unit.proposal?.text ?? '')?.[1].trim() ?? unit.slug;
39
+ return question.length > 110 ? `${question.slice(0, 107)}…` : question;
40
+ }
34
41
  const lines = (unit.spec?.text ?? '').split('\n');
35
42
  const start = lines.findIndex((l) => l.trim() === '## Summary');
36
43
  const text = start === -1 ? '' : lines.slice(start + 1).find((l) => l.trim() && !l.startsWith('#')) ?? '';
@@ -56,8 +63,10 @@ function unitCommits(root, key, memo) {
56
63
  /** Stage track and whose turn it is. */
57
64
  function stageOf(ctx, unit, onBase, extra) {
58
65
  const { review } = extra;
66
+ if (unit.kind === 'discovery')
67
+ return discoveryStage(unit, onBase);
59
68
  if (unit.kind !== 'feature') {
60
- const names = unit.kind === 'fix' ? ['Fix', 'Review', 'Merged'] : ['Map', 'Review', 'Merged'];
69
+ const names = [...workflowOf(unit.kind).stages, 'Merged'];
61
70
  const last = unit.reviews.records.at(-1);
62
71
  if (onBase && last && !stillBlocked(unit, last))
63
72
  return { names, at: 3, turn: 'merged', now: 'merged' };
@@ -65,10 +74,10 @@ function stageOf(ctx, unit, onBase, extra) {
65
74
  return { names, at: 2, turn: 'you', now: 'review and merge the pull request' };
66
75
  if (last)
67
76
  return { names, at: 1, turn: 'agent', now: review?.problem ?? 'review' };
68
- return { names, at: 0, turn: 'agent', now: unit.kind === 'fix' ? 'making the change' : 'writing docs/agjan/project.md' };
77
+ return { names, at: 0, turn: 'agent', now: unit.kind === 'fix' ? 'making the change' : 'writing agjan-docs/project.md' };
69
78
  }
70
79
  const mode = unit.design?.parsed.mode;
71
- const names = ['Spec', mode === 'light' ? 'Design (light)' : 'Design', 'Build', 'Verify', onBase ? 'Merged' : 'Done'];
80
+ const names = [...workflowOf(unit.kind).stages.map((s) => (s === 'Design' && mode === 'light' ? 'Design (light)' : s)), onBase ? 'Merged' : 'Done'];
72
81
  const events = readLog(unit.dir);
73
82
  const lastGate = events.filter((e) => ['gate-requested', 'approved', 'rejected'].includes(e.event)).at(-1);
74
83
  const waiting = lastGate?.event === 'gate-requested';
@@ -95,7 +104,11 @@ function stageOf(ctx, unit, onBase, extra) {
95
104
  const pending = unit.amendments.filter((a) => a.status === 'pending');
96
105
  const verified = progress.complete && progress.due.length === 0 && verify.state === 'current';
97
106
  if (verified) {
98
- if (acceptanceState(ctx.root, ctx.config, unit, verify).state === 'accepted')
107
+ // The final review passed; the same answer as the acceptance gate decides the rest.
108
+ const { problems, accepted } = verification(ctx, unit);
109
+ if (problems.length)
110
+ return { names, at: 3, turn: 'agent', now: `not verified yet: ${problems[0]}` };
111
+ if (accepted)
99
112
  return { names, at: 5, turn: 'done', now: 'implemented, verified and accepted' };
100
113
  const manual = unit.spec.parsed.acs.filter((ac) => ac.verification === 'manual').map((ac) => ac.id);
101
114
  return { names, at: 4, turn: 'you', now: `verified: ${manual.length ? `check ${manual.join(', ')} by hand, then ` : ''}accept it in a terminal (npx agjan approve verify)` };
@@ -112,6 +125,22 @@ function stageOf(ctx, unit, onBase, extra) {
112
125
  return unit.approvals.auto ? { names, at: 3, turn: 'agent', now: 'auto mode: the verification is next' } : { names, at: 3, turn: 'you', now: 'start the verification: /agjan-verify' };
113
126
  return { names, at: 3, turn: 'agent', now: verify.state === 'none' ? 'verify' : `verify (${verify.state})` };
114
127
  }
128
+ /**
129
+ * A discovery (decision 91): the agent writes the proposal and has it reviewed; then a
130
+ * person approves the recommendation; after that, building it is new work (/agjan-spec).
131
+ */
132
+ function discoveryStage(unit, onBase) {
133
+ const names = [...workflowOf('discovery').stages, onBase ? 'Merged' : 'Done'];
134
+ if (unit.state.proposal === 'approved') {
135
+ return onBase ? { names, at: 3, turn: 'merged', now: 'merged' } : { names, at: 3, turn: 'done', now: 'recommendation approved; to build it, start a feature with /agjan-spec' };
136
+ }
137
+ const review = proposalReview(unit);
138
+ if (!review.record)
139
+ return { names, at: 0, turn: 'agent', now: 'writing the proposal' };
140
+ if (review.problems.length)
141
+ return { names, at: 1, turn: 'agent', now: `revising the proposal: ${review.problems[0]}` };
142
+ return { names, at: 2, turn: 'you', now: 'decide on the recommendation: approve it in a terminal (npx agjan approve proposal)' };
143
+ }
115
144
  /**
116
145
  * While the agent would be working, a `waiting` event after its last step means it stopped
117
146
  * for the user (an error it cannot resolve, a decision): their turn, with the reason.
@@ -128,7 +157,7 @@ function waitingFor(events, stage) {
128
157
  */
129
158
  export function finalSteps(root, unit, { manual = [], accepted = false } = {}) {
130
159
  const project = readFileSyncSafe(join(root, FEATURES_DIR, 'project.md'));
131
- const tryIt = /^## Run locally\s*$/m.test(project) ? 'try it locally: docs/agjan/project.md, section "Run locally" (start command, URL, users)' : 'try it locally';
160
+ const tryIt = /^## Run locally\s*$/m.test(project) ? 'try it locally: agjan-docs/project.md, section "Run locally" (start command, URL, users)' : 'try it locally';
132
161
  const pr = 'open a pull request (ask the agent: "open the PR"), review it, merge it';
133
162
  if (accepted)
134
163
  return { yours: [], optional: [tryIt, pr] };
@@ -148,7 +177,7 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now(), memo =
148
177
  const isFeature = unit.kind === 'feature';
149
178
  const progress = isFeature && unit.tasks ? buildProgress(ctx.root, config, unit, { history: onBase, memo }) : null;
150
179
  const verify = isFeature ? verifyState(ctx.root, config, unit, memo) : null;
151
- const review = !isFeature ? freshReview(ctx.root, config, unit, unit.kind, memo) : null;
180
+ const review = unit.kind === 'fix' || unit.kind === 'map' ? freshReview(ctx.root, config, unit, unit.kind, memo) : null;
152
181
  const stage = waitingFor(events, stageOf(ctx, unit, onBase, { progress, verify, review }));
153
182
  const commits = unitCommits(ctx.root, unit.key, memo);
154
183
  const times = [...events.map((e) => Date.parse(e.at_utc)), ...commits.map((c) => Date.parse(c.at))].filter(Number.isFinite);
@@ -161,7 +190,9 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now(), memo =
161
190
  const steps = list.filter((s) => s.kind === 'step');
162
191
  const gates = list.filter((s) => s.kind === 'gate');
163
192
  const host = unit.reviews.records.find((r) => r.reviewer?.host)?.reviewer.host ?? events.find((e) => e.host)?.host ?? null;
164
- const reviews = unit.reviews.records.map((r) => ({
193
+ // What a review step looks at: a later round saw a revision only when that changed.
194
+ const seenBy = (r) => r.step === 'spec' ? r.documents?.spec : r.step === 'design' ? r.documents?.design : r.step === 'design:light' ? `${r.documents?.spec} ${r.documents?.design}` : r.tree_hash;
195
+ const reviews = unit.reviews.records.map((r, i, all) => ({
165
196
  id: r.id,
166
197
  step: r.step,
167
198
  round: r.round,
@@ -172,6 +203,10 @@ export function unitModel(ctx, slug, { onBase = false, now = Date.now(), memo =
172
203
  isolation: r.reviewer?.isolation ?? null,
173
204
  findings: (r.findings ?? []).map((f) => f.id),
174
205
  resolves: r.resolves ?? [],
206
+ /** Whether what the step looks at changed since its previous round; null for a first round. */
207
+ changed: ((prev) => (prev ? seenBy(prev) !== seenBy(r) : null))(all.slice(0, i).findLast((x) => x.step === r.step)),
208
+ /** The QA tests a QA round left. */
209
+ tests: r.qa_tests?.length ?? null,
175
210
  }));
176
211
  const resolvedBy = {};
177
212
  for (const r of reviews)
@@ -371,7 +406,7 @@ export function timelineRows(model) {
371
406
  rows.push([c.at, '🤖 main agent', `commit \`${c.sha}\` ${c.subject}`]);
372
407
  return rows.sort((a, b) => a[0].localeCompare(b[0]));
373
408
  }
374
- /** docs/agjan/<unit>/progress.md */
409
+ /** agjan-docs/<unit>/progress.md */
375
410
  export function unitMarkdown(model, { generatedAt }) {
376
411
  const out = [];
377
412
  const md = (s) => String(s).replace(/\|/g, '\\|');
package/dist/qa.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { existsSync, readdirSync } from 'node:fs';
3
- import { join } from 'node:path';
2
+ import { existsSync, mkdirSync, readdirSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
4
  import { contentIds } from './git.js';
5
- import { latestReview, stillBlocked } from './feature.js';
5
+ import { writeJson } from './json-file.js';
6
+ import { FEATURES_DIR, latestReview, stillBlocked } from './feature.js';
6
7
  /**
7
8
  * The QA step (design decision 81): in Verify, the QA agent (`agjan-qa`, the qa-tester
8
9
  * skill) writes and runs tests from the spec alone, without the design, the diff or the
@@ -14,6 +15,29 @@ export const QA_STEP = 'qa';
14
15
  export function qaDirs(slug) {
15
16
  return [`test/qa/${slug}/`, `test/ui/qa/${slug}/`];
16
17
  }
18
+ /** What the QA agent may not read, for the guard (decision 87); written by qa_context. */
19
+ export const QA_GUARD_FILE = '.agjan/qa-guard.json';
20
+ /** The agent name the hosts report for the QA agent's tool calls. */
21
+ export const QA_AGENT = 'agjan-qa';
22
+ /**
23
+ * The QA agent's black box (decision 87): agjan's records, the application code
24
+ * (`application`) and every area's tests are hidden; the spec, the project map and its own
25
+ * QA folders stay visible. Globs; a path is hidden when it matches `hidden` and no `visible`.
26
+ */
27
+ export function qaGuard(config, slug) {
28
+ const tests = Object.values(config.tests).flat();
29
+ return {
30
+ feature: slug,
31
+ hidden: [...new Set([`${FEATURES_DIR}/**`, ...config.application, ...tests])],
32
+ visible: [`${FEATURES_DIR}/${slug}/spec.md`, `${FEATURES_DIR}/project.md`, ...qaDirs(slug).map((dir) => `${dir}**`)],
33
+ };
34
+ }
35
+ /** Writes the QA guard file for the feature QA is about to test. */
36
+ export function writeQaGuard(root, config, slug) {
37
+ const file = join(root, QA_GUARD_FILE);
38
+ mkdirSync(dirname(file), { recursive: true });
39
+ writeJson(file, qaGuard(config, slug));
40
+ }
17
41
  /** QA runs for full-mode features unless the project turns it off (`review.qa: "off"`). */
18
42
  export function qaApplies(config, feature) {
19
43
  return feature.kind === 'feature' && feature.design?.parsed.mode === 'full' && config.review?.qa !== 'off';
@@ -0,0 +1,33 @@
1
+ import { NOT_ACCEPTED, runChecks } from './commands/check.js';
2
+ import { acceptanceState, verifyState } from './progress.js';
3
+ import { qaProblem } from './qa.js';
4
+ /**
5
+ * Whether a feature is verified (decision 77): QA passed, the final verify review is current,
6
+ * and `check --ci` has no error but the missing acceptance. The one answer for the
7
+ * acceptance gate, `status --done`, the completion screen and the progress pages, so none of
8
+ * them calls a feature verified while another reports what blocks it.
9
+ */
10
+ export function verification(ctx, feature) {
11
+ if (feature.stage !== 'build')
12
+ return { problems: [`the feature is in ${feature.stage}; it is accepted after /agjan-verify`], record: null, accepted: false };
13
+ const problems = [];
14
+ const qa = qaProblem(ctx.root, ctx.config, feature);
15
+ if (qa)
16
+ problems.push(qa);
17
+ const verify = verifyState(ctx.root, ctx.config, feature);
18
+ if (verify.state === 'none')
19
+ problems.push('no final verify review recorded: /agjan-verify');
20
+ else if (verify.state === 'blocked')
21
+ problems.push(`the final verify review ${verify.record.id} is blocked`);
22
+ else if (verify.state === 'stale')
23
+ problems.push(`files changed after the final verify review ${verify.record.id}: /agjan-verify again`);
24
+ if (verify.state === 'current') {
25
+ const { report } = runChecks(ctx, 'ci', feature.slug);
26
+ for (const item of report.items) {
27
+ if (item.level === 'error' && !item.message.startsWith(NOT_ACCEPTED))
28
+ problems.push(`check --ci: ${item.message}`);
29
+ }
30
+ }
31
+ const accepted = verify.state === 'current' && problems.length === 0 && acceptanceState(ctx.root, ctx.config, feature, verify).state === 'accepted';
32
+ return { problems, record: verify.record, accepted };
33
+ }
@@ -15,6 +15,7 @@ export const DEFAULT_TIERS = {
15
15
  verify: 'deep',
16
16
  fix: 'balanced',
17
17
  map: 'balanced',
18
+ proposal: 'deep',
18
19
  qa: 'qa',
19
20
  };
20
21
  /** `build:cap` and `build:T2` are both of kind `build`. */
@@ -34,7 +35,7 @@ export function fixAttempts(config) {
34
35
  return config.build?.fix_attempts ?? 3;
35
36
  }
36
37
  /** The gate approvals that close a correction loop of a review step. */
37
- const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'] };
38
+ const CLOSING_APPROVALS = { spec: ['spec'], design: ['design'], 'design:light': ['spec', 'design'], proposal: ['proposal'] };
38
39
  /** Steps whose loop a later spec or design approval closes: a revision (decision 84) starts them again. */
39
40
  const AFTER_GATES = (step) => step === 'qa' || step === 'verify' || step.startsWith('build:');
40
41
  /**