agjan 0.0.0-stage → 0.0.2

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 (84) hide show
  1. package/LICENSE +201 -0
  2. package/NOTICE +11 -0
  3. package/README.md +105 -2
  4. package/bin/agjan.mjs +12 -0
  5. package/docs/brand/agjan-icon.svg +14 -0
  6. package/docs/brand/agjan-logo-dark.svg +17 -0
  7. package/docs/brand/agjan-logo-light.svg +17 -0
  8. package/docs/guide.md +232 -0
  9. package/kit/domains/btp/domain.json +27 -0
  10. package/kit/hooks/guard.mjs +61 -0
  11. package/kit/mcp/servers.json +5 -0
  12. package/kit/skills/agjan-build/SKILL.md +61 -0
  13. package/kit/skills/agjan-design/SKILL.md +95 -0
  14. package/kit/skills/agjan-fix/SKILL.md +55 -0
  15. package/kit/skills/agjan-map/SKILL.md +51 -0
  16. package/kit/skills/agjan-spec/SKILL.md +111 -0
  17. package/kit/skills/agjan-verify/SKILL.md +60 -0
  18. package/kit/skills/btp-architect/SKILL.md +51 -0
  19. package/kit/skills/btp-architect/references/deployment.md +72 -0
  20. package/kit/skills/btp-architect/references/security.md +54 -0
  21. package/kit/skills/cap-developer/SKILL.md +49 -0
  22. package/kit/skills/cap-developer/references/handlers.md +47 -0
  23. package/kit/skills/cap-developer/references/modeling.md +52 -0
  24. package/kit/skills/cap-developer/references/services.md +53 -0
  25. package/kit/skills/cap-developer/references/testing.md +39 -0
  26. package/kit/skills/cap-developer/references/validation-security.md +49 -0
  27. package/kit/skills/fiori-developer/SKILL.md +64 -0
  28. package/kit/skills/fiori-developer/references/elements.md +77 -0
  29. package/kit/skills/fiori-developer/references/freestyle-ts.md +45 -0
  30. package/kit/skills/fiori-developer/references/testing.md +32 -0
  31. package/kit/skills/fiori-developer/references/ui5-basics.md +52 -0
  32. package/kit/skills/solution-reviewer/SKILL.md +51 -0
  33. package/kit/templates/agents-block.md +20 -0
  34. package/kit/templates/agjan-ci.yml +40 -0
  35. package/kit/templates/design.md +17 -0
  36. package/kit/templates/project.md +28 -0
  37. package/kit/templates/spec.md +33 -0
  38. package/kit/templates/tasks.md +13 -0
  39. package/package.json +50 -4
  40. package/schemas/approvals.schema.json +93 -0
  41. package/schemas/config.schema.json +79 -0
  42. package/schemas/log.schema.json +30 -0
  43. package/schemas/reviews.schema.json +68 -0
  44. package/schemas/tasks.schema.json +26 -0
  45. package/src/adapters/claude-code.mjs +115 -0
  46. package/src/adapters/copilot.mjs +88 -0
  47. package/src/baseline.mjs +66 -0
  48. package/src/cli.mjs +133 -0
  49. package/src/commands/check.mjs +363 -0
  50. package/src/commands/fix.mjs +116 -0
  51. package/src/commands/gates.mjs +264 -0
  52. package/src/commands/log.mjs +53 -0
  53. package/src/commands/map.mjs +47 -0
  54. package/src/commands/new.mjs +53 -0
  55. package/src/commands/pr-summary.mjs +134 -0
  56. package/src/commands/report.mjs +110 -0
  57. package/src/commands/review.mjs +49 -0
  58. package/src/commands/setup.mjs +269 -0
  59. package/src/commands/status.mjs +176 -0
  60. package/src/config.mjs +98 -0
  61. package/src/context.mjs +58 -0
  62. package/src/documents.mjs +188 -0
  63. package/src/errors.mjs +16 -0
  64. package/src/feature.mjs +214 -0
  65. package/src/fix.mjs +108 -0
  66. package/src/git.mjs +66 -0
  67. package/src/hash.mjs +33 -0
  68. package/src/hook.mjs +48 -0
  69. package/src/json-file.mjs +24 -0
  70. package/src/log.mjs +37 -0
  71. package/src/managed.mjs +178 -0
  72. package/src/mcp-config.mjs +83 -0
  73. package/src/mcp.mjs +142 -0
  74. package/src/plan.mjs +41 -0
  75. package/src/progress.mjs +85 -0
  76. package/src/review-policy.mjs +49 -0
  77. package/src/review.mjs +336 -0
  78. package/src/scope.mjs +30 -0
  79. package/src/terminal.mjs +98 -0
  80. package/src/test-results.mjs +111 -0
  81. package/src/tests-map.mjs +29 -0
  82. package/src/ui.mjs +110 -0
  83. package/src/usage.mjs +118 -0
  84. package/src/validate.mjs +41 -0
@@ -0,0 +1,264 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join, relative } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.mjs';
5
+ import { appendLog, readLog } from '../log.mjs';
6
+ import { APPROVALS_FILE, FEATURES_DIR, gateReview, loadFeature, selectFeature } from '../feature.mjs';
7
+ import { documentProblems, designProblems } from '../validate.mjs';
8
+ import { AgjanError, UsageError } from '../errors.mjs';
9
+ import { tone } from '../ui.mjs';
10
+ import { git } from '../git.mjs';
11
+
12
+ function short(hash) {
13
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
14
+ }
15
+
16
+ function refuse(what, problems) {
17
+ throw new AgjanError(`cannot ${what}:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
18
+ }
19
+
20
+ function save(ctx, feature, event, fields) {
21
+ writeJson(join(feature.dir, APPROVALS_FILE), feature.approvals);
22
+ appendLog(feature.dir, ctx.now(), event, fields);
23
+ }
24
+
25
+ /** Shows what is being approved and asks the human to type the feature key (design 9.4). */
26
+ function confirmGate(ctx, feature, title, lines) {
27
+ const summary = [
28
+ '',
29
+ ctx.style.bold(`agjan: ${title}`),
30
+ ` feature ${ctx.style.bold(feature.slug)} (${ctx.style.cyan(feature.key)})`,
31
+ ...lines.map((l) => ` ${l}`),
32
+ ` approver ${ctx.email()}`,
33
+ '',
34
+ ].join('\n');
35
+ if (!ctx.confirm(summary, feature.key)) {
36
+ ctx.out(ctx.style.yellow('cancelled, nothing recorded'));
37
+ return false;
38
+ }
39
+ return true;
40
+ }
41
+
42
+ /** One line, no control characters, at most 200 characters. */
43
+ export function cleanMessage(text) {
44
+ return String(text ?? '').replace(/[\x00-\x1f\x7f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 200);
45
+ }
46
+
47
+ /** The commit message the agent proposed when it handed `gate` over (`log --gate-requested --message`). */
48
+ function proposedMessage(feature, gate) {
49
+ const request = readLog(feature.dir).findLast((e) => e.event === 'gate-requested' && e.gate === gate);
50
+ return cleanMessage(request?.message);
51
+ }
52
+
53
+ /**
54
+ * After a recorded decision: commits the feature folder (the approved documents and the
55
+ * record) with a message the human confirms or edits. Only that folder goes into the
56
+ * commit, whatever else is staged; the pre-commit hook still runs. A failed or skipped
57
+ * commit leaves the decision recorded and says how to commit it.
58
+ */
59
+ async function commitRecord(ctx, feature, values, proposal) {
60
+ const s = ctx.style;
61
+ const folder = relative(ctx.root, feature.dir).split('\\').join('/');
62
+ const manual = s.yellow(`not committed; commit ${folder}/ yourself`);
63
+ if (values['no-commit']) return ctx.out(manual);
64
+ if (!git(ctx.root, ['status', '--porcelain', '--', folder]).trim()) return undefined;
65
+ const message = cleanMessage(await ctx.edit(`${s.bold('Commit message')} (Enter to commit, empty to skip): `, proposal));
66
+ if (!message) return ctx.out(manual);
67
+ git(ctx.root, ['add', '-A', '--', folder]);
68
+ const result = spawnSync('git', ['commit', '-q', '-m', message, '--', folder], { cwd: ctx.root, encoding: 'utf8' });
69
+ if (result.status !== 0) {
70
+ ctx.out(`${result.stdout ?? ''}${result.stderr ?? ''}`.trimEnd(), s.red(`the commit failed; the decision is recorded but ${folder}/ is not committed`));
71
+ return undefined;
72
+ }
73
+ const sha = git(ctx.root, ['rev-parse', '--short', 'HEAD']).trim();
74
+ return ctx.out(`${s.green('committed')} ${s.gray(sha)} ${message}`);
75
+ }
76
+
77
+ function reviewLine(ctx, review) {
78
+ const notes = review.findings?.length ? `, ${review.findings.length} finding(s)` : '';
79
+ return `review ${review.id} ${review.step} round ${review.round}: ${tone(ctx.style, review.verdict)}${notes}`;
80
+ }
81
+
82
+ function specGateProblems(feature) {
83
+ const problems = [];
84
+ if (!feature.spec) problems.push('spec.md does not exist');
85
+ else problems.push(...feature.spec.parsed.problems.map((p) => `spec.md: ${p}`));
86
+ return problems;
87
+ }
88
+
89
+ function designGateProblems(ctx, feature) {
90
+ const problems = [];
91
+ if (!feature.design) problems.push('design.md does not exist');
92
+ if (!feature.tasks) problems.push('tasks.md does not exist');
93
+ problems.push(...documentProblems(feature).filter((p) => !p.startsWith('spec.md')));
94
+ problems.push(...designProblems(feature, ctx.config));
95
+ return problems;
96
+ }
97
+
98
+ /** The gate a feature waits for: 'spec', 'spec design' (light mode) or 'design'; null in Build. */
99
+ export function pendingGate(feature) {
100
+ if (feature.stage === 'spec') return feature.design?.parsed.mode === 'light' ? 'spec design' : 'spec';
101
+ if (feature.stage === 'design') return 'design';
102
+ return null;
103
+ }
104
+
105
+ /**
106
+ * Everything that stands between a feature and the approval of `gate`, shared by
107
+ * `approve`, `status` and `log --gate-requested`. No problems means the gate is ready.
108
+ */
109
+ export function gateReadiness(ctx, feature, gate) {
110
+ const problems = [];
111
+ let review;
112
+ if (gate === 'spec') {
113
+ if (feature.state.spec === 'approved') problems.push('spec.md is already approved and unchanged');
114
+ problems.push(...specGateProblems(feature));
115
+ review = gateReview(feature, 'spec');
116
+ if (feature.design?.parsed.mode === 'light') problems.push("design.md is in light mode: approve both together with 'agjan approve spec design'");
117
+ } else if (gate === 'design') {
118
+ if (feature.state.spec !== 'approved') problems.push(`the spec must be approved first (it is ${feature.state.spec})`);
119
+ if (feature.state.design === 'approved') problems.push('design.md and tasks.md are already approved and unchanged');
120
+ problems.push(...designGateProblems(ctx, feature));
121
+ if (feature.design?.parsed.mode === 'light') problems.push("light-mode designs are approved together with the spec ('agjan approve spec design')");
122
+ review = gateReview(feature, 'design');
123
+ } else {
124
+ if (feature.state.spec === 'approved' && feature.state.design === 'approved') problems.push('spec and design are already approved and unchanged');
125
+ problems.push(...specGateProblems(feature), ...designGateProblems(ctx, feature));
126
+ if (feature.design && feature.design.parsed.mode !== 'light') problems.push("design.md is in full mode: approve the spec first, then 'agjan approve design'");
127
+ review = gateReview(feature, 'design');
128
+ if (review.record && review.record.step !== 'design:light') problems.push(`the latest review is ${review.record.step}; a combined approval needs a design:light review`);
129
+ }
130
+ problems.push(...review.problems);
131
+ return { problems, record: review.record };
132
+ }
133
+
134
+ async function approveSpec(ctx, feature, values) {
135
+ const { problems, record } = gateReadiness(ctx, feature, 'spec');
136
+ if (problems.length) refuse('approve the spec', problems);
137
+ const previous = feature.state.spec === 'stale' ? ' (re-approval: changed since the last approval)' : '';
138
+ if (!confirmGate(ctx, feature, `approve spec${previous}`, [`spec.md ${short(feature.spec.hash)}`, reviewLine(ctx, record)])) return 1;
139
+ feature.approvals.approvals.spec = { hash: feature.spec.hash, at_utc: ctx.now(), by: ctx.email() };
140
+ // A new spec approval invalidates the design: its spec_hash no longer matches.
141
+ save(ctx, feature, 'approved', { gate: 'spec' });
142
+ ctx.out(ctx.style.green(`approved spec of ${feature.slug}`));
143
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'spec') || `${feature.key}: approve spec`);
144
+ return 0;
145
+ }
146
+
147
+ async function approveDesign(ctx, feature, values) {
148
+ const { problems, record } = gateReadiness(ctx, feature, 'design');
149
+ if (problems.length) refuse('approve the design', problems);
150
+ const lines = [`design ${short(feature.designHash)} (design.md + tasks.md, mode ${feature.design.parsed.mode})`, reviewLine(ctx, record)];
151
+ if (!confirmGate(ctx, feature, 'approve design', lines)) return 1;
152
+ feature.approvals.approvals.design = { hash: feature.designHash, spec_hash: feature.spec.hash, at_utc: ctx.now(), by: ctx.email() };
153
+ save(ctx, feature, 'approved', { gate: 'design' });
154
+ ctx.out(ctx.style.green(`approved design of ${feature.slug}`));
155
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'design') || `${feature.key}: approve design`);
156
+ return 0;
157
+ }
158
+
159
+ async function approveCombined(ctx, feature, values) {
160
+ const { problems, record } = gateReadiness(ctx, feature, 'spec design');
161
+ if (problems.length) refuse('approve spec and design', problems);
162
+ const lines = [
163
+ `spec.md ${short(feature.spec.hash)}`,
164
+ `design ${short(feature.designHash)} (design.md + tasks.md, mode light)`,
165
+ reviewLine(ctx, record),
166
+ ];
167
+ if (!confirmGate(ctx, feature, 'approve spec and design (light mode)', lines)) return 1;
168
+ const at = ctx.now();
169
+ const by = ctx.email();
170
+ feature.approvals.approvals.spec = { hash: feature.spec.hash, at_utc: at, by };
171
+ feature.approvals.approvals.design = { hash: feature.designHash, spec_hash: feature.spec.hash, at_utc: at, by };
172
+ save(ctx, feature, 'approved', { gate: 'spec design' });
173
+ ctx.out(ctx.style.green(`approved spec and design of ${feature.slug}`));
174
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'spec design') || `${feature.key}: approve spec and design`);
175
+ return 0;
176
+ }
177
+
178
+ async function approveAmendment(ctx, feature, id, values) {
179
+ if (feature.state.design !== 'approved') throw new AgjanError(`amendments need an approved design (it is ${feature.state.design})`);
180
+ const amendment = feature.approvals.amendments.find((a) => a.id === id);
181
+ if (!amendment) throw new AgjanError(`no amendment ${id} in ${feature.slug}`);
182
+ if (amendment.approved_at_utc && amendment.design_hash === feature.approvals.approvals.design.hash) {
183
+ throw new AgjanError(`${id} is already approved`);
184
+ }
185
+ const lines = [`amendment ${id} for ${amendment.task}`, `paths ${amendment.paths.join(', ')}`, `reason ${amendment.reason}`];
186
+ if (!confirmGate(ctx, feature, 'approve scope amendment', lines)) return 1;
187
+ Object.assign(amendment, { approved_at_utc: ctx.now(), by: ctx.email(), design_hash: feature.approvals.approvals.design.hash });
188
+ save(ctx, feature, 'approved', { gate: 'amendment', amendment: id });
189
+ ctx.out(ctx.style.green(`approved ${id}`));
190
+ await commitRecord(ctx, feature, values, `${feature.key}: approve amendment ${id}`);
191
+ return 0;
192
+ }
193
+
194
+ const FEATURE_OPTION = { feature: { type: 'string' }, 'no-commit': { type: 'boolean' } };
195
+
196
+ /** agjan approve spec | design | spec design | amendment <id> [--feature <slug>] [--no-commit] */
197
+ export function approve(ctx, argv) {
198
+ const { values, positionals } = parseArgs({ args: argv, options: FEATURE_OPTION, allowPositionals: true });
199
+ const what = positionals.join(' ');
200
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
201
+ if (what === 'spec') return approveSpec(ctx, feature, values);
202
+ if (what === 'design') return approveDesign(ctx, feature, values);
203
+ if (what === 'spec design' || what === 'design spec') return approveCombined(ctx, feature, values);
204
+ if (positionals[0] === 'amendment' && positionals.length === 2) return approveAmendment(ctx, feature, positionals[1], values);
205
+ throw new UsageError('usage: agjan approve spec | design | spec design | amendment <id> [--feature <slug>] [--no-commit]');
206
+ }
207
+
208
+ /** agjan accept <finding-id> --reason "…" [--feature <slug>] [--no-commit] */
209
+ export async function accept(ctx, argv) {
210
+ const { values, positionals } = parseArgs({ args: argv, options: { ...FEATURE_OPTION, reason: { type: 'string' } }, allowPositionals: true });
211
+ const [id] = positionals;
212
+ if (!id || positionals.length !== 1 || !values.reason?.trim()) throw new UsageError('usage: agjan accept <finding-id> --reason "<why>" [--feature <slug>] [--no-commit]');
213
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
214
+ const finding = feature.findings.find((f) => f.id === id);
215
+ if (!finding) throw new AgjanError(`no finding ${id} in ${feature.slug}`);
216
+ if (finding.status !== 'open') throw new AgjanError(`${id} is already ${finding.status}`);
217
+ const lines = [`finding ${id} [${finding.severity}] ${finding.file ?? ''}`.trimEnd(), `issue ${finding.issue}`, `reason ${values.reason}`];
218
+ if (!confirmGate(ctx, feature, 'accept finding', lines)) return 1;
219
+ feature.approvals.accepted.push({ finding: id, reason: values.reason, at_utc: ctx.now(), by: ctx.email() });
220
+ save(ctx, feature, 'accepted', { finding: id, severity: finding.severity });
221
+ ctx.out(ctx.style.green(`accepted ${id}`));
222
+ await commitRecord(ctx, feature, values, `${feature.key}: accept ${id}`);
223
+ return 0;
224
+ }
225
+
226
+ /** agjan reject spec|design --reason "…" [--feature <slug>] [--no-commit]: sends a gate back (for quality signals). */
227
+ export async function reject(ctx, argv) {
228
+ const { values, positionals } = parseArgs({ args: argv, options: { ...FEATURE_OPTION, reason: { type: 'string' } }, allowPositionals: true });
229
+ const [gate] = positionals;
230
+ if (!['spec', 'design'].includes(gate) || positionals.length !== 1 || !values.reason?.trim()) {
231
+ throw new UsageError('usage: agjan reject spec|design --reason "<why>" [--feature <slug>] [--no-commit]');
232
+ }
233
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
234
+ if (!confirmGate(ctx, feature, `reject ${gate}`, [`reason ${values.reason}`])) return 1;
235
+ feature.approvals.rejections.push({ gate, reason: values.reason, at_utc: ctx.now(), by: ctx.email() });
236
+ save(ctx, feature, 'rejected', { gate });
237
+ ctx.out(`recorded rejection of ${gate} for ${feature.slug}; the document stays draft`);
238
+ await commitRecord(ctx, feature, values, `${feature.key}: reject ${gate}`);
239
+ return 0;
240
+ }
241
+
242
+ /** agjan amend --task <id> --paths <p1,p2> --reason "…": proposes a scope amendment (agent-run). */
243
+ export function amend(ctx, argv) {
244
+ const { values } = parseArgs({
245
+ args: argv,
246
+ options: { ...FEATURE_OPTION, task: { type: 'string' }, paths: { type: 'string' }, reason: { type: 'string' } },
247
+ });
248
+ const paths = (values.paths ?? '').split(',').map((p) => p.trim()).filter(Boolean);
249
+ if (!values.task || paths.length === 0 || !values.reason?.trim()) {
250
+ throw new UsageError('usage: agjan amend --task <id> --paths <path,...> --reason "<why>" [--feature <slug>]');
251
+ }
252
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
253
+ if (feature.state.design !== 'approved') throw new AgjanError(`amendments need an approved design (it is ${feature.state.design})`);
254
+ if (!feature.tasks.parsed.tasks.some((t) => t.id === values.task)) throw new AgjanError(`no task ${values.task} in tasks.md`);
255
+ for (const p of paths) {
256
+ if (p.includes('\\') || p.startsWith('/') || p.split('/').includes('..')) throw new UsageError(`path '${p}' must be relative, POSIX, without '..'`);
257
+ }
258
+ const id = `${feature.key}-A${feature.approvals.amendments.length + 1}`;
259
+ feature.approvals.amendments.push({ id, task: values.task, paths, reason: values.reason, proposed_at_utc: ctx.now() });
260
+ save(ctx, feature, 'amendment-proposed', { amendment: id, task: values.task });
261
+ ctx.out(`proposed ${id} in ${FEATURES_DIR}/${feature.slug}/${APPROVALS_FILE}`);
262
+ ctx.out(`a human must approve it in a terminal: agjan approve amendment ${id}`);
263
+ return 0;
264
+ }
@@ -0,0 +1,53 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { appendLog } from '../log.mjs';
3
+ import { loadFeature, selectFeature } from '../feature.mjs';
4
+ import { AgjanError, UsageError } from '../errors.mjs';
5
+ import { cleanMessage, gateReadiness } from './gates.mjs';
6
+
7
+ const STAGES = ['map', 'spec', 'design', 'build', 'verify', 'fix'];
8
+ const GATES = ['spec', 'design', 'spec design'];
9
+
10
+ /**
11
+ * agjan log --stage <stage> [--role r] [--task T1] [--skill s] [--host h] [--model m]
12
+ * agjan log --gate-requested <gate> [--message "<commit message>"]
13
+ * Called once at the start of each step (design 12.1); the end of a step is inferred
14
+ * from the next event. `--message` proposes the commit message `approve` offers the human.
15
+ */
16
+ export function run(ctx, argv) {
17
+ const { values } = parseArgs({
18
+ args: argv,
19
+ options: {
20
+ feature: { type: 'string' },
21
+ stage: { type: 'string' },
22
+ role: { type: 'string' },
23
+ task: { type: 'string' },
24
+ skill: { type: 'string' },
25
+ host: { type: 'string' },
26
+ model: { type: 'string' },
27
+ 'gate-requested': { type: 'string' },
28
+ message: { type: 'string' },
29
+ },
30
+ });
31
+ const gate = values['gate-requested'];
32
+ if (!gate && !values.stage) throw new UsageError('usage: agjan log --stage <stage> [--role r] [--task T1] [--skill s] | --gate-requested <gate> [--message "<text>"]');
33
+ if (gate && !GATES.includes(gate)) throw new UsageError(`--gate-requested must be one of: ${GATES.join(', ')}`);
34
+ if (values.stage && !STAGES.includes(values.stage)) throw new UsageError(`--stage must be one of: ${STAGES.join(', ')}`);
35
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
36
+
37
+ if (gate) {
38
+ // A gate is handed to the human only when approving it can succeed.
39
+ const { problems } = gateReadiness(ctx, feature, gate);
40
+ if (problems.length) {
41
+ throw new AgjanError(`the ${gate} gate is not ready; nothing logged:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
42
+ }
43
+ const message = cleanMessage(values.message);
44
+ appendLog(feature.dir, ctx.now(), 'gate-requested', message ? { gate, message } : { gate });
45
+ } else {
46
+ const fields = { stage: values.stage };
47
+ for (const key of ['role', 'task', 'skill', 'host']) if (values[key]) fields[key] = values[key];
48
+ // The configured model only; the actual model comes from host transcripts (design 12.2).
49
+ if (values.model) fields.configured_model = values.model;
50
+ appendLog(feature.dir, ctx.now(), 'step', fields);
51
+ }
52
+ return 0;
53
+ }
@@ -0,0 +1,47 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.mjs';
5
+ import { APPROVALS_FILE, FEATURES_DIR, changedFeatures, emptyApprovals, featureDir } from '../feature.mjs';
6
+ import { PROJECT_MD } from '../fix.mjs';
7
+ import { BASELINE_FILE, refreshBaseline } from '../baseline.mjs';
8
+ import { appendLog } from '../log.mjs';
9
+ import { AgjanError, UsageError } from '../errors.mjs';
10
+
11
+ const TEMPLATE = new URL('../../kit/templates/project.md', import.meta.url);
12
+ /** Map runs need finding ids but no unique key: their findings stay in their own folder. */
13
+ const MAP_KEY = 'MAP';
14
+
15
+ /** agjan map start: a record folder for this map run, and project.md from the template if absent. */
16
+ function start(ctx) {
17
+ const root = ctx.root;
18
+ const changed = changedFeatures(root, ctx.config);
19
+ if (changed.length) throw new AgjanError(`this branch already carries ${changed.join(', ')}; map the project on its own branch`);
20
+ const date = ctx.now().slice(0, 10);
21
+ let id = date;
22
+ for (let n = 2; existsSync(featureDir(root, `maps/${id}`)); n += 1) id = `${date}-${n}`;
23
+ const dir = featureDir(root, `maps/${id}`);
24
+ mkdirSync(dir, { recursive: true });
25
+ writeJson(join(dir, APPROVALS_FILE), emptyApprovals(id, MAP_KEY, ctx.kit, ctx.now(), 'map'));
26
+ appendLog(dir, ctx.now(), 'step', { stage: 'map', skill: 'agjan-map' });
27
+ ctx.out(`created ${FEATURES_DIR}/maps/${id}/`);
28
+ if (!existsSync(join(root, PROJECT_MD))) {
29
+ writeFileSync(join(root, PROJECT_MD), readFileSync(TEMPLATE, 'utf8'));
30
+ ctx.out(`created ${PROJECT_MD} from the template`);
31
+ }
32
+ return 0;
33
+ }
34
+
35
+ export function map(ctx, argv) {
36
+ if (argv[0] === 'start' && argv.length === 1) return start(ctx);
37
+ throw new UsageError('usage: agjan map start');
38
+ }
39
+
40
+ /** agjan baseline refresh: records the hashes of the watched files in baseline.json. */
41
+ export function baseline(ctx, argv) {
42
+ const { positionals } = parseArgs({ args: argv, allowPositionals: true });
43
+ if (positionals.join(' ') !== 'refresh') throw new UsageError('usage: agjan baseline refresh');
44
+ const data = refreshBaseline(ctx.root, ctx.config, ctx.now());
45
+ ctx.out(`wrote ${BASELINE_FILE}: ${Object.keys(data.watched).length} watched file(s)`);
46
+ return 0;
47
+ }
@@ -0,0 +1,53 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { writeJson } from '../json-file.mjs';
5
+ import { APPROVALS_FILE, FEATURES_DIR, KEY, SLUG, emptyApprovals, featureDir, listFeatures, loadFeature, selectFeature } from '../feature.mjs';
6
+ import { AgjanError, UsageError } from '../errors.mjs';
7
+
8
+ const TEMPLATES = new URL('../../kit/templates/', import.meta.url);
9
+
10
+ export function renderTemplate(name, { slug, key }) {
11
+ return readFileSync(new URL(name, TEMPLATES), 'utf8').replaceAll('{{SLUG}}', slug).replaceAll('{{KEY}}', key);
12
+ }
13
+
14
+ /** agjan scaffold design [--feature <slug>]: creates design.md and tasks.md from the templates. */
15
+ export function scaffold(ctx, argv) {
16
+ const { values, positionals } = parseArgs({ args: argv, options: { feature: { type: 'string' } }, allowPositionals: true });
17
+ if (positionals.join(' ') !== 'design') throw new UsageError('usage: agjan scaffold design [--feature <slug>]');
18
+ const feature = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, values.feature));
19
+ for (const name of ['design.md', 'tasks.md']) {
20
+ const file = join(feature.dir, name);
21
+ if (existsSync(file)) {
22
+ ctx.out(`${FEATURES_DIR}/${feature.slug}/${name} exists; not changed`);
23
+ continue;
24
+ }
25
+ writeFileSync(file, renderTemplate(name, { slug: feature.slug, key: feature.key }));
26
+ ctx.out(`created ${FEATURES_DIR}/${feature.slug}/${name}`);
27
+ }
28
+ return 0;
29
+ }
30
+
31
+ /** agjan new <slug> --key <KEY>: creates the feature folder, approvals.json and spec.md. */
32
+ export function run(ctx, argv) {
33
+ const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' } }, allowPositionals: true });
34
+ const [slug] = positionals;
35
+ if (!slug || positionals.length > 1 || !values.key) throw new UsageError('usage: agjan new <slug> --key <KEY>');
36
+ if (!SLUG.test(slug)) throw new UsageError(`slug '${slug}' must be lowercase letters, digits and '-', at most 48 characters`);
37
+ if (slug === 'fixes') throw new UsageError("'fixes' is reserved");
38
+ const key = values.key;
39
+ if (!KEY.test(key)) throw new UsageError(`key '${key}' must be 2 to 6 uppercase letters or digits, starting with a letter`);
40
+
41
+ const root = ctx.root;
42
+ const dir = featureDir(root, slug);
43
+ if (existsSync(dir)) throw new AgjanError(`${FEATURES_DIR}/${slug} already exists`);
44
+ for (const other of listFeatures(root)) {
45
+ if (loadFeature(root, other).key === key) throw new AgjanError(`key ${key} is already used by feature '${other}'`);
46
+ }
47
+
48
+ mkdirSync(dir, { recursive: true });
49
+ writeJson(join(dir, APPROVALS_FILE), emptyApprovals(slug, key, ctx.kit, ctx.now()));
50
+ writeFileSync(join(dir, 'spec.md'), renderTemplate('spec.md', { slug, key }));
51
+ ctx.out(`created ${FEATURES_DIR}/${slug}/ (key ${key}): ${APPROVALS_FILE}, spec.md`);
52
+ return 0;
53
+ }
@@ -0,0 +1,134 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { resolveArea } from '../config.mjs';
3
+ import { FEATURES_DIR } from '../feature.mjs';
4
+ import { acTestFiles } from '../tests-map.mjs';
5
+ import { acResults, loadResults, resultLabel } from '../test-results.mjs';
6
+ import { overrideBase, runChecks } from './check.mjs';
7
+ import { readFix } from './fix.mjs';
8
+ import { highlightMarkdown } from '../ui.mjs';
9
+
10
+ function short(hash) {
11
+ return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
12
+ }
13
+
14
+ /** A fix or a map run in the PR summary. */
15
+ function recordSection(feature) {
16
+ const out = [`### ${feature.kind === 'fix' ? 'Fix' : 'Map run'} ${feature.slug} (${feature.key})`, ''];
17
+ if (feature.kind === 'fix') {
18
+ const fix = readFix(feature);
19
+ out.push(`**What:** ${fix?.what ?? '(not stated)'}`, '');
20
+ if (fix?.files) {
21
+ out.push(`**Size:** ${fix.total} changed lines (limit ${fix.limits.max_total}, per file ${fix.limits.max_per_file})`, '');
22
+ out.push(`**Verified with:** ${fix.verify ?? 'not stated'}`, '');
23
+ } else {
24
+ out.push('**Not recorded yet** (`npx agjan fix record`).', '');
25
+ }
26
+ } else {
27
+ out.push('Writes the baseline `docs/agjan/project.md` and `docs/agjan/baseline.json`.', '');
28
+ }
29
+ for (const r of feature.reviews.records) out.push(`- ${r.id} ${r.step} round ${r.round}: ${r.verdict} (${r.findings?.length ?? 0} findings, isolation ${r.reviewer?.isolation ?? 'unknown'})`);
30
+ if (feature.reviews.records.length) out.push('');
31
+ return out;
32
+ }
33
+
34
+ function featureSection(ctx, feature) {
35
+ if (feature.kind !== 'feature') return recordSection(feature);
36
+ const out = [];
37
+ const mode = feature.design?.parsed.mode ?? '-';
38
+ out.push(`### ${feature.slug} (${feature.key})`, '');
39
+ out.push('| Document | State | Hash | Approved |', '|---|---|---|---|');
40
+ const spec = feature.approvals.approvals.spec;
41
+ const design = feature.approvals.approvals.design;
42
+ out.push(`| spec.md | ${feature.state.spec} | ${short(feature.spec?.hash)} | ${spec ? `${spec.at_utc} by ${spec.by}` : '-'} |`);
43
+ out.push(`| design (${mode}) | ${feature.state.design} | ${short(feature.designHash)} | ${design ? `${design.at_utc} by ${design.by}` : '-'} |`, '');
44
+
45
+ if (feature.spec && feature.tasks) {
46
+ const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(ctx.config, t.area)?.name).filter(Boolean))];
47
+ const tests = acTestFiles(ctx.root, ctx.config, areaNames, feature.key);
48
+ const tasksFor = (id) => feature.tasks.parsed.tasks.filter((t) => t.covers.includes(id)).map((t) => t.id).join(', ') || '-';
49
+ const loaded = loadResults(ctx.root, ctx.config, areaNames);
50
+ const results = loaded.files.length ? acResults(loaded, feature.key) : null;
51
+ out.push('**Acceptance criteria**', '');
52
+ out.push(results ? '| AC | Verification | Tasks | Tests | Result |' : '| AC | Verification | Tasks | Tests |');
53
+ out.push(results ? '|---|---|---|---|---|' : '|---|---|---|---|');
54
+ for (const ac of feature.spec.parsed.acs) {
55
+ const files = [...(tests.get(ac.id) ?? [])].join(', ');
56
+ const manual = ac.verification === 'manual';
57
+ const row = `| ${ac.id} | ${ac.verification} | ${tasksFor(ac.id)} | ${manual ? 'manual' : files || '**missing**'} |`;
58
+ if (!results) out.push(row);
59
+ else out.push(`${row} ${manual ? '-' : resultLabel(results.get(ac.id)).replace(/^(failed|not run|skipped)$/, '**$1**')} |`);
60
+ }
61
+ out.push('');
62
+ if (results) out.push(`Results from ${loaded.files.map((f) => `\`${f.file}\``).join(', ')}.`, '');
63
+ else out.push('Test coverage is by AC id in test files (existence only).', '');
64
+ const manual = feature.spec.parsed.acs.filter((ac) => ac.verification === 'manual');
65
+ if (manual.length) {
66
+ out.push('**Verify before merge (manual ACs):**', '');
67
+ for (const ac of manual) out.push(`- [ ] ${ac.id}`);
68
+ out.push('');
69
+ }
70
+ }
71
+
72
+ if (feature.reviews.records.length) {
73
+ out.push('**Reviews**', '', '| Review | Step | Round | Verdict | Findings | Isolation |', '|---|---|---|---|---|---|');
74
+ for (const r of feature.reviews.records) {
75
+ out.push(`| ${r.id} | ${r.step} | ${r.round} | ${r.verdict} | ${r.findings?.length ?? 0} | ${r.reviewer?.isolation ?? 'unknown'} |`);
76
+ }
77
+ out.push('');
78
+ const weak = feature.reviews.records.filter((r) => r.reviewer?.isolation !== 'agent');
79
+ if (weak.length) out.push(`Reviews without an isolated reviewer agent: ${weak.map((r) => r.id).join(', ')}.`, '');
80
+ }
81
+
82
+ const open = feature.findings.filter((f) => f.status === 'open');
83
+ const accepted = feature.findings.filter((f) => f.status === 'accepted');
84
+ if (open.length) {
85
+ out.push('**Open findings**', '');
86
+ for (const f of open) out.push(`- ${f.id} [${f.severity}] ${f.issue}`);
87
+ out.push('');
88
+ }
89
+ if (accepted.length) {
90
+ out.push('**Accepted findings**', '');
91
+ for (const f of accepted) {
92
+ const a = feature.approvals.accepted.find((x) => x.finding === f.id);
93
+ out.push(`- ${f.id} [${f.severity}] ${f.issue} (accepted by ${a.by}: ${a.reason})`);
94
+ }
95
+ out.push('');
96
+ }
97
+ const amendments = feature.amendments.filter((a) => a.status !== 'lapsed');
98
+ if (amendments.length) {
99
+ out.push('**Scope amendments**', '');
100
+ for (const a of amendments) out.push(`- ${a.id} (${a.task}, ${a.status}): ${a.paths.join(', ')}: ${a.reason}`);
101
+ out.push('');
102
+ }
103
+ return out;
104
+ }
105
+
106
+ /** agjan pr-summary [--feature <slug>]: prints the PR description in Markdown (design 6.6). */
107
+ export function run(ctx, argv) {
108
+ const { values } = parseArgs({ args: argv, options: { feature: { type: 'string' }, base: { type: 'string' } } });
109
+ overrideBase(ctx, values.base);
110
+ const { report, features, files, policy } = runChecks(ctx, 'ci', values.feature);
111
+ const out = ['## agjan summary', ''];
112
+
113
+ if (features.length === 0) out.push('No agjan feature in this change.', '');
114
+ for (const feature of features) out.push(...featureSection(ctx, feature));
115
+
116
+ const code = files.filter((f) => !f.startsWith(`${FEATURES_DIR}/`) && !f.startsWith('.agjan/'));
117
+ out.push(`**Changed files** (${code.length} outside ${FEATURES_DIR}/)`, '');
118
+ for (const f of code) out.push(`- ${f}`);
119
+ if (code.length) out.push('');
120
+ if (files.includes(`${FEATURES_DIR}/project.md`)) out.push('The baseline `docs/agjan/project.md` is updated in this change.', '');
121
+
122
+ if (policy.length) {
123
+ out.push('**Policy changes** (these change the rules that check this PR)', '');
124
+ for (const p of policy) out.push(`- ${p}`);
125
+ out.push('');
126
+ }
127
+
128
+ const state = report.errors > 0 ? `**failing**: ${report.errors} error(s)` : 'passing';
129
+ out.push(`**agjan check --ci**: ${state}, ${report.warnings} warning(s)`, '');
130
+ for (const item of report.items.filter((i) => i.level === 'error')) out.push(`- ${item.scope}: ${item.message}`);
131
+ if (report.errors) out.push('');
132
+ ctx.out(highlightMarkdown(ctx.style, out.join('\n').trimEnd()));
133
+ return 0;
134
+ }