agjan 0.0.22 → 0.0.25

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 (66) 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/browser.js +25 -8
  5. package/dist/cli.js +22 -4
  6. package/dist/commands/check.js +91 -7
  7. package/dist/commands/discover.js +54 -0
  8. package/dist/commands/fix.js +8 -3
  9. package/dist/commands/gates.js +48 -28
  10. package/dist/commands/import.js +73 -0
  11. package/dist/commands/log.js +3 -2
  12. package/dist/commands/map.js +6 -1
  13. package/dist/commands/new.js +7 -3
  14. package/dist/commands/pr-summary.js +20 -5
  15. package/dist/commands/progress.js +1 -1
  16. package/dist/commands/report.js +1 -1
  17. package/dist/commands/review.js +21 -9
  18. package/dist/commands/setup.js +51 -1
  19. package/dist/commands/status.js +118 -20
  20. package/dist/commands/summary.js +2 -1
  21. package/dist/commands/team.js +45 -0
  22. package/dist/commands/test.js +37 -0
  23. package/dist/config.js +9 -1
  24. package/dist/defaults-file.js +33 -0
  25. package/dist/discovery.js +42 -0
  26. package/dist/feature.js +14 -7
  27. package/dist/imports.js +197 -0
  28. package/dist/plan.js +1 -1
  29. package/dist/progress-view.js +46 -11
  30. package/dist/qa.js +27 -3
  31. package/dist/readiness.js +33 -0
  32. package/dist/review-policy.js +2 -1
  33. package/dist/review.js +68 -17
  34. package/dist/schema.js +4 -0
  35. package/dist/story.js +15 -8
  36. package/dist/teams.js +127 -0
  37. package/dist/test-run.js +101 -0
  38. package/dist/types.js +0 -4
  39. package/dist/workflow.js +83 -0
  40. package/docs/guide.md +166 -24
  41. package/kit/domains/btp/domain.json +1 -0
  42. package/kit/hooks/guard.mjs +134 -6
  43. package/kit/skills/agjan-ask/SKILL.md +20 -9
  44. package/kit/skills/agjan-build/SKILL.md +6 -5
  45. package/kit/skills/agjan-design/SKILL.md +2 -2
  46. package/kit/skills/agjan-discover/SKILL.md +87 -0
  47. package/kit/skills/agjan-fix/SKILL.md +10 -6
  48. package/kit/skills/agjan-map/SKILL.md +12 -8
  49. package/kit/skills/agjan-spec/SKILL.md +14 -7
  50. package/kit/skills/agjan-verify/SKILL.md +27 -17
  51. package/kit/skills/btp-architect/SKILL.md +1 -1
  52. package/kit/skills/btp-architect/references/security.md +1 -1
  53. package/kit/skills/cap-developer/SKILL.md +1 -1
  54. package/kit/skills/cap-developer/references/project-setup.md +1 -1
  55. package/kit/skills/cap-developer/references/validation-security.md +1 -1
  56. package/kit/skills/fiori-developer/SKILL.md +1 -1
  57. package/kit/skills/qa-tester/SKILL.md +4 -2
  58. package/kit/templates/agents-block.md +13 -6
  59. package/kit/templates/progress.html +2 -2
  60. package/kit/templates/proposal.md +22 -0
  61. package/package.json +1 -1
  62. package/schemas/approvals.schema.json +9 -1
  63. package/schemas/config.defaults.json +66 -0
  64. package/schemas/config.schema.json +33 -1
  65. package/schemas/log.schema.json +1 -1
  66. package/schemas/reviews.schema.json +2 -2
package/README.md CHANGED
@@ -28,8 +28,9 @@ agjan guides an AI coding agent through **Spec, Design, Build and Verify**:
28
28
  - **An isolated reviewer checks every stage.** It runs as a separate agent with read
29
29
  access and two agjan tools only, and records its own findings. Blockers stop the gate.
30
30
  - **Scripts enforce the rules, not the model.** `agjan check` verifies stamps, scope
31
- (only the approved task paths change), acceptance criteria covered by passing tests,
32
- and fresh reviews, in a pre-commit hook and in CI.
31
+ (only the approved task paths change), acceptance criteria covered by tests that passed
32
+ on this very change (`agjan test` records the run), and fresh reviews, in a pre-commit
33
+ hook and in CI.
33
34
  - **Cost is measurable.** `agjan report` shows time per step, waiting time at gates, and
34
35
  the actual models and tokens from the host's own session records.
35
36
 
@@ -79,8 +80,9 @@ npx agjan approve spec design
79
80
  ```
80
81
 
81
82
  Continue with `/agjan-build` and `/agjan-verify`. Small changes: `/agjan-fix`. An
82
- existing application: `/agjan-map` once. A general question about CAP, Fiori or BTP:
83
- `/agjan-ask`.
83
+ existing application: `/agjan-map` once. A decision to prepare before building (options,
84
+ trade-offs, a recommendation you approve, no code): `/agjan-discover`. A question about CAP,
85
+ Fiori or BTP, in general or about files you name: `/agjan-ask`.
84
86
 
85
87
  ## Documentation
86
88
 
@@ -14,7 +14,7 @@ const REVIEWERS = [
14
14
  { name: 'agjan-reviewer', tier: 'balanced' },
15
15
  { name: 'agjan-reviewer-deep', tier: 'deep' },
16
16
  ];
17
- const HUMAN_ONLY = ['approve', 'accept', 'reject', 'auto', 'models set'];
17
+ const HUMAN_ONLY = ['approve', 'accept', 'reject', 'auto', 'import', 'models set'];
18
18
  /** The agjan MCP server: Claude Code starts it for the reviewer and QA agents, never the main agent's shell. */
19
19
  const AGENTS_ONLY = ['mcp'];
20
20
  /**
@@ -41,8 +41,8 @@ export const GUARD_HOOK = {
41
41
  };
42
42
  const GUARD_PATH = 'node_modules/agjan/kit/hooks/guard.mjs';
43
43
  /** A guard entry written by an earlier agjan version (for example the exec form). */
44
- /** The tools the guard sees: the shell, and the file edit tools (agjan's records). */
45
- export const GUARD_MATCHER = 'Bash|Edit|Write|MultiEdit|NotebookEdit';
44
+ /** The tools the guard sees: the shell, the file edit tools (agjan's records) and the read tools (the QA agent's). */
45
+ export const GUARD_MATCHER = 'Bash|Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob';
46
46
  const isGuard = (hook) => JSON.stringify(hook).includes(GUARD_PATH);
47
47
  const isCurrent = (hook) => JSON.stringify(hook) === JSON.stringify(GUARD_HOOK);
48
48
  function hasGuard(data) {
package/dist/baseline.js CHANGED
@@ -8,8 +8,8 @@ import { repoFiles } from './tests-map.js';
8
8
  import { FEATURES_DIR } from './feature.js';
9
9
  import { PROJECT_MD } from './fix.js';
10
10
  /**
11
- * The baseline (design 8.6): docs/agjan/project.md, written by people and agents, and
12
- * docs/agjan/baseline.json, written by `agjan baseline refresh`, with the hashes of the
11
+ * The baseline (design 8.6): agjan-docs/project.md, written by people and agents, and
12
+ * agjan-docs/baseline.json, written by `agjan baseline refresh`, with the hashes of the
13
13
  * domains' watched files (models, services, app manifests, mta.yaml).
14
14
  */
15
15
  export const BASELINE_FILE = `${FEATURES_DIR}/baseline.json`;
package/dist/browser.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { spawnSync } from 'node:child_process';
2
+ import { platform } from 'node:os';
2
3
  import { join } from 'node:path';
3
4
  import { readJson } from './json-file.js';
4
5
  /**
5
6
  * UI tests are optional (design decision 75): they run in Playwright's Chromium where it
6
7
  * can start, and are skipped with the reason where it cannot. On macOS and Windows,
7
8
  * `npx playwright install chromium` is all it needs; on Linux, Chromium also needs system
8
- * libraries, which only an administrator adds. agjan never installs them.
9
+ * libraries, which only an administrator adds. agjan installs nothing on its own: `init` and
10
+ * `doctor` offer the steps on a terminal and run one only when the user says yes.
9
11
  */
10
12
  /** The npm script that runs a project's UI tests. */
11
13
  export const UI_SCRIPT = 'test:ui';
@@ -18,20 +20,16 @@ await browser.close();`;
18
20
  export function hasUiTests(root) {
19
21
  return Boolean(readJson(join(root, 'package.json'))?.scripts?.[UI_SCRIPT]);
20
22
  }
21
- /**
22
- * Starts and closes Chromium from the project. Returns { ready: true } or { ready: false,
23
- * reason, enable }. AGJAN_BROWSER_PROBE names a Node script that replaces the probe (tests).
24
- */
25
23
  export function probeBrowser(root) {
26
24
  const fake = process.env.AGJAN_BROWSER_PROBE;
27
25
  const run = spawnSync(process.execPath, fake ? [fake] : ['--input-type=module', '-e', PROBE], { cwd: root, encoding: 'utf8', timeout: 120_000 });
28
26
  if (run.status === 0)
29
27
  return { ready: true };
30
28
  if (run.status === 3)
31
- return { ready: false, reason: '@playwright/test is not installed', enable: 'npm install' };
29
+ return { ready: false, reason: '@playwright/test is not installed', enable: 'npm install', missing: 'package' };
32
30
  const output = `${run.stderr ?? ''}${run.stdout ?? ''}`;
33
31
  if (/Executable doesn't exist|playwright install/i.test(output) && !/install-deps|missing dependencies/i.test(output)) {
34
- return { ready: false, reason: 'Chromium is not downloaded', enable: 'npx playwright install chromium (no admin rights needed)' };
32
+ return { ready: false, reason: 'Chromium is not downloaded', enable: 'npx playwright install chromium (no admin rights needed)', missing: 'download' };
35
33
  }
36
34
  const library = /error while loading shared libraries: (\S+?):/.exec(output)?.[1];
37
35
  if (library || /missing dependencies|install-deps/i.test(output)) {
@@ -39,8 +37,27 @@ export function probeBrowser(root) {
39
37
  ready: false,
40
38
  reason: `Chromium cannot start: this Linux system lacks its libraries${library ? ` (${library})` : ''}`,
41
39
  enable: 'whoever maintains the machine or container image adds them once, for example with `npx playwright install-deps chromium` run as root in its Dockerfile',
40
+ missing: 'libraries',
42
41
  };
43
42
  }
44
43
  const first = output.split('\n').map((l) => l.trim()).find((l) => l && !l.startsWith('at ')) ?? (run.error ? run.error.message : `exit code ${run.status}`);
45
- return { ready: false, reason: `Chromium cannot start: ${first.replace(/^\w*Error: /, '')}`, enable: 'npx playwright install chromium, then npx agjan doctor' };
44
+ return { ready: false, reason: `Chromium cannot start: ${first.replace(/^\w*Error: /, '')}`, enable: 'npx playwright install chromium, then npx agjan doctor', missing: 'other' };
45
+ }
46
+ /** The Dockerfile line that keeps the system libraries across container rebuilds. */
47
+ export const DEPS_DOCKERFILE_LINE = 'RUN npx playwright install-deps chromium';
48
+ /** The command that adds the system libraries, or null when this user cannot run it unattended. */
49
+ export function depsCommand() {
50
+ if (platform() !== 'linux')
51
+ return null;
52
+ const install = ['npx', 'playwright', 'install-deps', 'chromium'];
53
+ if (process.getuid?.() === 0)
54
+ return { command: install[0], args: install.slice(1), shown: install.join(' ') };
55
+ // sudo -n never asks for a password: it fails at once where one would be needed.
56
+ if (spawnSync('sudo', ['-n', 'true'], { stdio: 'ignore' }).status !== 0)
57
+ return null;
58
+ return { command: 'sudo', args: ['-n', 'env', `PATH=${process.env.PATH ?? ''}`, ...install], shown: `sudo ${install.join(' ')}` };
59
+ }
60
+ /** Runs a setup command from the project with its output shown; true when it succeeded. */
61
+ export function runVisible(root, command, args) {
62
+ return spawnSync(command, args, { cwd: root, stdio: 'inherit' }).status === 0;
46
63
  }
package/dist/cli.js CHANGED
@@ -12,10 +12,14 @@ import * as setup from './commands/setup.js';
12
12
  import * as report from './commands/report.js';
13
13
  import * as fix from './commands/fix.js';
14
14
  import * as mapCommand from './commands/map.js';
15
+ import * as discoverCommand from './commands/discover.js';
16
+ import * as teamCommand from './commands/team.js';
17
+ import * as importCommand from './commands/import.js';
15
18
  import * as branch from './commands/branch.js';
16
19
  import * as progress from './commands/progress.js';
17
20
  import * as lint from './commands/lint.js';
18
21
  import * as uiTest from './commands/ui-test.js';
22
+ import * as testCommand from './commands/test.js';
19
23
  import * as models from './commands/models.js';
20
24
  import * as findings from './commands/findings.js';
21
25
  import * as summary from './commands/summary.js';
@@ -35,6 +39,7 @@ const COMMANDS = {
35
39
  check: check.run,
36
40
  lint: lint.run,
37
41
  'ui-test': uiTest.run,
42
+ test: testCommand.run,
38
43
  models: models.run,
39
44
  amend: gates.amend,
40
45
  approve: gates.approve,
@@ -50,6 +55,9 @@ const COMMANDS = {
50
55
  report: report.run,
51
56
  fix: fix.run,
52
57
  map: mapCommand.map,
58
+ discover: discoverCommand.discover,
59
+ team: teamCommand.run,
60
+ import: importCommand.run,
53
61
  baseline: mapCommand.baseline,
54
62
  mcp: review.mcp,
55
63
  };
@@ -87,20 +95,30 @@ Agent and human:
87
95
  new <slug> --key <KEY> create a feature folder with approvals.json and spec.md
88
96
  scaffold design create design.md and tasks.md from the templates
89
97
  progress [--open] regenerate the progress pages and show the overview
90
- (.agjan/progress.html, docs/agjan/<unit>/progress.md)
91
- status [--feature <s> | --all]
92
- show the state of the changed (or every) feature
98
+ (.agjan/progress.html, agjan-docs/<unit>/progress.md)
99
+ status [--feature <s> | --all] [--json]
100
+ show the state of the changed (or every) feature;
101
+ --json: workflow, stage, turn and next step for tools
93
102
  check [--staged | --ci] [--base <ref>]
94
103
  enforce the workflow rules
95
104
  lint [--all] [--base <ref>] run the area linters (UI5 linter for fiori) on the changed
96
105
  files of each app, without MCP
97
106
  ui-test [--require] run the UI tests (npm run test:ui, Playwright) where
98
107
  Chromium can start; else say why and skip (--require: exit 1)
108
+ test [--feature <s>] run the feature's tests (and UI tests) and record the run
109
+ with the change it ran on (tests.json); check --ci needs it
99
110
  amend --task <id> --paths <p,...> --reason "<why>"
100
111
  propose a scope amendment during Build
101
112
  fix start <slug> --key <KEY> --what "<text>" | fix check | fix record [--verify "…"]
102
113
  fast path for small changes (record folder under fixes/)
103
114
  map start start mapping an existing application (project.md)
115
+ discover start <slug> --key <KEY> --question "<text>"
116
+ a question that ends in a recommendation you approve, no code
117
+ import <git url> --commit <id> [--dry-run] | import list | import remove <name>
118
+ (human) skills and teams from another repository, at an
119
+ exact commit; shown first, confirmed in a terminal
120
+ team list | team show <name> the teams a unit can start with (new, fix start, discover
121
+ start take --team) and what their personas work with
104
122
  baseline refresh record the watched files in baseline.json
105
123
  skill <spec|design|build|verify>
106
124
  print the workflow skill (auto mode: the next skill of the run)
@@ -169,7 +187,7 @@ export async function main(args, options = {}) {
169
187
  stdout.write(`${pkg.version}\n`);
170
188
  return 0;
171
189
  }
172
- // Every recorded event regenerates the progress pages (docs/agjan/<unit>/progress.md, .agjan/).
190
+ // Every recorded event regenerates the progress pages (agjan-docs/<unit>/progress.md, .agjan/).
173
191
  onEvent((unitDir) => refreshAfterEvent(unitDir, pkg.version));
174
192
  const handler = COMMANDS[command];
175
193
  if (!handler) {
@@ -11,6 +11,10 @@ import { documentProblems, designProblems } from '../validate.js';
11
11
  import { allowedPatterns, matcher } from '../scope.js';
12
12
  import { acTestFiles } from '../tests-map.js';
13
13
  import { acResults, loadResults } from '../test-results.js';
14
+ import { testRunProblem, testRunState } from '../test-run.js';
15
+ import { proposalProblems, proposalReview } from '../discovery.js';
16
+ import { teamProblems, unitTeam } from '../teams.js';
17
+ import { importDrift } from '../imports.js';
14
18
  import { acceptanceState, buildProgress, verifyState } from '../progress.js';
15
19
  import { qaProblem } from '../qa.js';
16
20
  import { FIX_FILE, fixRules, freshReview } from '../fix.js';
@@ -29,6 +33,7 @@ export const NOT_ACCEPTED = 'not accepted yet';
29
33
  const POLICY_PATTERNS = [
30
34
  CONFIG_FILE,
31
35
  'agjan.lock.json',
36
+ 'agjan.imports.json',
32
37
  'AGENTS.md',
33
38
  'CLAUDE.md',
34
39
  'package.json',
@@ -114,6 +119,35 @@ function checkMap(report, root, config, run, level) {
114
119
  }
115
120
  return run;
116
121
  }
122
+ /** A discovery (decision 91): a complete proposal; in CI also its passing review and a person's approval of it. */
123
+ function checkDiscovery(report, unit, level) {
124
+ const scope = unit.slug;
125
+ if (level === 'staged')
126
+ return unit;
127
+ if (unit.state.proposal === 'stale')
128
+ report.error(scope, 'proposal.md changed after its approval; review it again and request approve proposal, or revert');
129
+ if (level !== 'ci')
130
+ return unit;
131
+ for (const p of proposalProblems(unit))
132
+ report.error(scope, p);
133
+ for (const p of proposalReview(unit).problems)
134
+ report.error(scope, p);
135
+ if (unit.state.proposal !== 'approved' && unit.state.proposal !== 'stale')
136
+ report.error(scope, `${NOT_ACCEPTED}: a human runs 'npx agjan approve proposal' in a terminal`);
137
+ return unit;
138
+ }
139
+ /** The unit's team (decision 92): known, unchanged since the unit started, its skills installed. */
140
+ function checkTeam(report, root, config, unit) {
141
+ const team = unitTeam(config, unit.approvals.feature.team);
142
+ if (!team)
143
+ return;
144
+ if (!team.team)
145
+ return report.error(unit.slug, `its team '${team.name}' is not defined (built in, or "teams" in agjan.config.json)`);
146
+ if (team.changed)
147
+ report.warn(unit.slug, `the definition of team '${team.name}' changed since this unit started; the agents now get the new one`);
148
+ for (const p of teamProblems(root, config, team.name).filter((x) => x.includes('in .claude/skills/')))
149
+ report.warn(unit.slug, `${p}; run: npx agjan sync`);
150
+ }
117
151
  /** review.md is rendered from reviews.json (design 8.5); a hand edit, or an older agjan, leaves it behind. */
118
152
  function checkReviewMd(report, unit) {
119
153
  if (!unit.reviews.records.length)
@@ -139,10 +173,14 @@ function checkFeature(report, root, config, slug, level) {
139
173
  checkRecords(report, feature);
140
174
  if (level !== 'staged')
141
175
  checkReviewMd(report, feature);
176
+ if (level !== 'staged')
177
+ checkTeam(report, root, config, feature);
142
178
  if (feature.kind === 'fix')
143
179
  return checkFix(report, root, config, feature, level);
144
180
  if (feature.kind === 'map')
145
181
  return checkMap(report, root, config, feature, level);
182
+ if (feature.kind === 'discovery')
183
+ return checkDiscovery(report, feature, level);
146
184
  const scope = slug;
147
185
  const ci = level === 'ci';
148
186
  // Approved documents must not change silently (design 9.5). The pre-commit hook only
@@ -191,7 +229,10 @@ function checkFeature(report, root, config, slug, level) {
191
229
  else
192
230
  report.warn(scope, `${ac.id} has no test yet`);
193
231
  }
194
- checkResults(report, root, config, feature, areaNames, ci);
232
+ if (config.test_evidence === 'names')
233
+ checkResults(report, root, config, feature, areaNames, ci);
234
+ else
235
+ checkTestRun(report, root, config, feature, ci);
195
236
  if (ci) {
196
237
  const progress = buildProgress(root, config, feature);
197
238
  for (const t of progress.tasks.filter((x) => !x.commit)) {
@@ -221,9 +262,39 @@ function checkFeature(report, root, config, slug, level) {
221
262
  return feature;
222
263
  }
223
264
  /**
224
- * With results configured (design 6.6): every automated AC needs a passing test case
225
- * and none failing. Without results files the coverage is by test names only, which is
226
- * reported, not failed: CI usually has no results of the change.
265
+ * The recorded test run (decision 88, `test_evidence: "run"`, the default): CI needs a
266
+ * passing run on this change, and with results files a passing test for every automated
267
+ * AC. Locally a failed or outdated run is reported; a missing one is normal during Build.
268
+ */
269
+ function checkTestRun(report, root, config, feature, ci) {
270
+ const scope = feature.slug;
271
+ const { state, run } = testRunState(root, config, feature);
272
+ const problem = testRunProblem(root, config, feature);
273
+ if (problem) {
274
+ if (ci)
275
+ report.error(scope, problem);
276
+ else if (state !== 'none')
277
+ report.warn(scope, problem);
278
+ }
279
+ if (!run?.results || state === 'stale')
280
+ return;
281
+ for (const ac of feature.spec.parsed.acs.filter((a) => a.verification !== 'manual')) {
282
+ const c = run.results[ac.id];
283
+ if (c?.failed)
284
+ report.error(scope, `${ac.id} has ${c.failed} failing test(s) in the test run`);
285
+ else if (!c?.passed) {
286
+ const message = `${ac.id} has no passing test in the test run`;
287
+ if (ci)
288
+ report.error(scope, message);
289
+ else
290
+ report.warn(scope, message);
291
+ }
292
+ }
293
+ }
294
+ /**
295
+ * `test_evidence: "names"`. With results configured (design 6.6): every automated AC needs
296
+ * a passing test case and none failing. Without results files the coverage is by test
297
+ * names only, which is reported, not failed.
227
298
  */
228
299
  function checkResults(report, root, config, feature, areaNames, ci) {
229
300
  const loaded = loadResults(root, config, areaNames);
@@ -272,8 +343,18 @@ function checkScope(report, features, config, files, level, ci) {
272
343
  // A branch carries features, or exactly one fix, or a map run (decision 57).
273
344
  const fixes = features.filter((f) => f.kind === 'fix');
274
345
  const maps = features.filter((f) => f.kind === 'map');
275
- if (fixes.length > 1 || (fixes.length && fixes.length !== features.length) || (maps.length && maps.length !== features.length)) {
276
- report.error('scope', `a branch carries either features, or one fix, or a map run; this one has ${features.map((f) => f.slug).join(', ')}`);
346
+ const discoveries = features.filter((f) => f.kind === 'discovery');
347
+ if (fixes.length > 1 || (fixes.length && fixes.length !== features.length) || (maps.length && maps.length !== features.length) || (discoveries.length && features.length !== 1)) {
348
+ report.error('scope', `a branch carries either features, or one fix, or a map run, or one discovery; this one has ${features.map((f) => f.slug).join(', ')}`);
349
+ return;
350
+ }
351
+ if (discoveries.length) {
352
+ // A discovery ends in a recommendation, not in code (decision 91).
353
+ for (const file of outside)
354
+ report.error('scope', `${file} changed, but a discovery only writes its proposal (${FEATURES_DIR}/${discoveries[0].slug}/)`);
355
+ for (const file of files.filter((f) => f.startsWith(docs) && !f.startsWith(`${docs}${discoveries[0].slug}/`))) {
356
+ report.error('scope', `${file} changed, but a discovery only writes its proposal (${FEATURES_DIR}/${discoveries[0].slug}/)`);
357
+ }
277
358
  return;
278
359
  }
279
360
  if (fixes.length === 1)
@@ -374,7 +455,7 @@ function checkPolicy(report, root, ci, files, base) {
374
455
  }
375
456
  // Editing a feature that already exists on the base branch (an archived feature).
376
457
  if (from) {
377
- for (const slug of new Set(files.filter((f) => f.startsWith(`${FEATURES_DIR}/`)).map((f) => f.split('/')[2]))) {
458
+ for (const slug of new Set(files.filter((f) => f.startsWith(`${FEATURES_DIR}/`)).map((f) => f.slice(FEATURES_DIR.length + 1).split('/')[0]))) {
378
459
  if (git(root, ['cat-file', '-e', `${from}:${FEATURES_DIR}/${slug}/approvals.json`], { allowFail: true }) !== null) {
379
460
  const message = `feature '${slug}' already exists on the base branch; follow-up work should start a new feature`;
380
461
  messages.push(message);
@@ -444,6 +525,9 @@ export function runChecks(ctx, level, explicitFeature) {
444
525
  }
445
526
  checkScope(report, [...features, ...others], config, files, level, ci);
446
527
  checkLocalFolder(report, root);
528
+ // Imported skills are what was imported, or a person re-imports them (decision 93).
529
+ for (const drift of importDrift(root))
530
+ report.error('imports', `${drift}; import it again or remove the package (npx agjan import)`);
447
531
  const policy = level === 'ci' ? checkPolicy(report, root, ci, files, base) : [];
448
532
  if (level !== 'staged') {
449
533
  checkManaged(report, ctx);
@@ -0,0 +1,54 @@
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.js';
5
+ import { APPROVALS_FILE, FEATURES_DIR, KEY, PROPOSAL_FILE, SLUG, changedFeatures, emptyApprovals, featureDir, listFeatures, loadFeature } from '../feature.js';
6
+ import { chooseTeam } from '../teams.js';
7
+ import { appendLog } from '../log.js';
8
+ import { AgjanError, UsageError } from '../errors.js';
9
+ const TEMPLATE = new URL('../../kit/templates/proposal.md', import.meta.url);
10
+ const USAGE = 'usage: agjan discover start <slug> --key <KEY> --question "<the question>" [--team <name>]';
11
+ /**
12
+ * agjan discover start <slug> --key <KEY> --question "<text>": a discovery (decision 91), a
13
+ * question that ends in a recommendation a person approves, and no code. Creates
14
+ * agjan-docs/discoveries/<slug>/ with its record and proposal.md from the template, on a
15
+ * branch that carries nothing else.
16
+ */
17
+ function start(ctx, argv) {
18
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { key: { type: 'string' }, question: { type: 'string' }, team: { type: 'string' } } });
19
+ const slug = positionals[0];
20
+ if (positionals.length !== 1 || !values.key || !values.question?.trim())
21
+ throw new UsageError(USAGE);
22
+ if (!SLUG.test(slug))
23
+ throw new UsageError(`invalid slug '${slug}': lowercase letters, digits and '-'`);
24
+ if (!KEY.test(values.key))
25
+ throw new UsageError(`invalid key '${values.key}': 2 to 6 capitals or digits, starting with a capital`);
26
+ const root = ctx.root;
27
+ const changed = changedFeatures(root, ctx.config);
28
+ if (changed.length)
29
+ throw new AgjanError(`this branch already carries ${changed.join(', ')}; a discovery runs on a branch of its own`);
30
+ const id = `discoveries/${slug}`;
31
+ const dir = featureDir(root, id);
32
+ if (existsSync(join(dir, APPROVALS_FILE)))
33
+ throw new AgjanError(`${FEATURES_DIR}/${id} exists already`);
34
+ for (const other of listFeatures(root)) {
35
+ if (loadFeature(root, other).key === values.key)
36
+ throw new AgjanError(`key ${values.key} is already used by '${other}'`);
37
+ }
38
+ const team = chooseTeam(root, ctx.config, 'discovery', values.team);
39
+ mkdirSync(dir, { recursive: true });
40
+ const approvals = emptyApprovals(slug, values.key, ctx.kit, ctx.now(), 'discovery');
41
+ if (team)
42
+ approvals.feature.team = team;
43
+ writeJson(join(dir, APPROVALS_FILE), approvals);
44
+ const proposal = readFileSync(TEMPLATE, 'utf8').replaceAll('{{SLUG}}', slug).replace('{{QUESTION}}', values.question.trim());
45
+ writeFileSync(join(dir, PROPOSAL_FILE), proposal);
46
+ appendLog(dir, ctx.now(), 'step', { stage: 'discover', skill: 'agjan-discover' });
47
+ ctx.out(`created ${FEATURES_DIR}/${id}/ (${PROPOSAL_FILE} from the template)`);
48
+ return 0;
49
+ }
50
+ export function discover(ctx, argv) {
51
+ if (argv[0] === 'start')
52
+ return start(ctx, argv.slice(1));
53
+ throw new UsageError(USAGE);
54
+ }
@@ -1,6 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
2
2
  import { join } from 'node:path';
3
3
  import { parseArgs } from 'node:util';
4
+ import { chooseTeam } from '../teams.js';
4
5
  import { writeJson, readJson } from '../json-file.js';
5
6
  import { APPROVALS_FILE, FEATURES_DIR, KEY, SLUG, changedFeatures, emptyApprovals, featureDir, listFeatures, loadFeature, selectFeature } from '../feature.js';
6
7
  import { FIX_FILE, FIX_MD, fixRules, freshReview } from '../fix.js';
@@ -31,10 +32,10 @@ function renderFixMd(fix, data) {
31
32
  }
32
33
  /** agjan fix start <slug> --key <KEY> --what "<text>" */
33
34
  function start(ctx, argv) {
34
- const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' }, what: { type: 'string' } }, allowPositionals: true });
35
+ const { values, positionals } = parseArgs({ args: argv, options: { key: { type: 'string' }, what: { type: 'string' }, team: { type: 'string' } }, allowPositionals: true });
35
36
  const [slug] = positionals;
36
37
  if (!slug || positionals.length !== 1 || !values.key || !values.what?.trim()) {
37
- throw new UsageError('usage: agjan fix start <slug> --key <KEY> --what "<what the fix changes>"');
38
+ throw new UsageError('usage: agjan fix start <slug> --key <KEY> --what "<what the fix changes>" [--team <name>]');
38
39
  }
39
40
  if (!SLUG.test(slug))
40
41
  throw new UsageError(`slug '${slug}' must be lowercase letters, digits and '-'`);
@@ -56,8 +57,12 @@ function start(ctx, argv) {
56
57
  const dir = featureDir(root, `fixes/${id}`);
57
58
  if (existsSync(dir))
58
59
  throw new AgjanError(`${FEATURES_DIR}/fixes/${id} already exists`);
60
+ const team = chooseTeam(root, ctx.config, 'fix', values.team);
59
61
  mkdirSync(dir, { recursive: true });
60
- writeJson(join(dir, APPROVALS_FILE), emptyApprovals(id, values.key, ctx.kit, ctx.now(), 'fix'));
62
+ const approvals = emptyApprovals(id, values.key, ctx.kit, ctx.now(), 'fix');
63
+ if (team)
64
+ approvals.feature.team = team;
65
+ writeJson(join(dir, APPROVALS_FILE), approvals);
61
66
  writeJson(join(dir, FIX_FILE), { schema: 1, what: values.what.trim(), started_at_utc: ctx.now() });
62
67
  appendLog(dir, ctx.now(), 'step', { stage: 'fix', skill: 'agjan-fix' });
63
68
  ctx.out(`created ${FEATURES_DIR}/fixes/${id}/ (key ${values.key})`);
@@ -8,9 +8,11 @@ import { documentProblems, designProblems } from '../validate.js';
8
8
  import { AgjanError, UsageError } from '../errors.js';
9
9
  import { blink, mark, markLine, pad, tone } from '../ui.js';
10
10
  import { git } from '../git.js';
11
- import { acceptanceState, verifyState } from '../progress.js';
12
- import { NOT_ACCEPTED, runChecks } from './check.js';
13
- import { qaProblem } from '../qa.js';
11
+ import { acceptanceState } from '../progress.js';
12
+ import { verification } from '../readiness.js';
13
+ import { runChecks } from './check.js';
14
+ import { proposalProblems, proposalReview } from '../discovery.js';
15
+ import { workflowOf } from '../workflow.js';
14
16
  import { AUTO_DEFAULT_FILE, readAutoDefault, removeAutoDefault, writeAutoDefault } from '../auto.js';
15
17
  function short(hash) {
16
18
  return hash ? hash.slice('sha256:'.length, 'sha256:'.length + 12) : '-';
@@ -124,41 +126,57 @@ export function pendingGate(feature) {
124
126
  return null;
125
127
  }
126
128
  /**
127
- * Gate 3 (decision 77): the human accepts the verified feature. Ready when the final
128
- * verify review is current and `check --ci` has no error but the missing acceptance.
129
+ * Gate 3 (decision 77): the human accepts the verified feature (`verification`), once per
130
+ * verified state.
129
131
  */
130
132
  function verifyReadiness(ctx, feature) {
133
+ const { problems, record, accepted } = verification(ctx, feature);
134
+ if (accepted)
135
+ return { problems: [`already accepted (verify review ${record.id}, unchanged since)`], record };
136
+ return { problems, record };
137
+ }
138
+ /**
139
+ * A discovery's gate (decision 91): the proposal is complete, its latest review saw exactly
140
+ * this proposal and passed, and the branch changed nothing outside the discovery's folder.
141
+ */
142
+ function proposalReadiness(ctx, feature) {
131
143
  const problems = [];
132
- if (feature.stage !== 'build')
133
- return { problems: [`the feature is in ${feature.stage}; it is accepted after /agjan-verify`], record: null };
134
- const qa = qaProblem(ctx.root, ctx.config, feature);
135
- if (qa)
136
- problems.push(qa);
137
- const verify = verifyState(ctx.root, ctx.config, feature);
138
- if (verify.state === 'none')
139
- problems.push('no final verify review recorded: /agjan-verify');
140
- else if (verify.state === 'blocked')
141
- problems.push(`the final verify review ${verify.record.id} is blocked`);
142
- else if (verify.state === 'stale')
143
- problems.push(`files changed after the final verify review ${verify.record.id}: /agjan-verify again`);
144
- else if (acceptanceState(ctx.root, ctx.config, feature, verify).state === 'accepted')
145
- problems.push(`already accepted (verify review ${verify.record.id}, unchanged since)`);
146
- if (verify.state === 'current') {
147
- const { report } = runChecks(ctx, 'ci', feature.slug);
148
- for (const item of report.items) {
149
- if (item.level === 'error' && !item.message.startsWith(NOT_ACCEPTED))
150
- problems.push(`check --ci: ${item.message}`);
151
- }
152
- }
153
- return { problems, record: verify.record };
144
+ if (feature.state.proposal === 'approved')
145
+ problems.push('proposal.md is already approved and unchanged');
146
+ problems.push(...proposalProblems(feature));
147
+ const review = proposalReview(feature);
148
+ problems.push(...review.problems);
149
+ const { report } = runChecks(ctx, 'default', feature.slug);
150
+ for (const item of report.items)
151
+ if (item.level === 'error' && item.scope === 'scope')
152
+ problems.push(`check: ${item.message}`);
153
+ return { problems, record: review.record };
154
+ }
155
+ /** agjan approve proposal: a person approves a discovery's recommendation. */
156
+ async function approveProposal(ctx, feature, values) {
157
+ const record = ready('approve the proposal', gateReadiness(ctx, feature, 'proposal'));
158
+ const proposal = feature.proposal;
159
+ const previous = feature.state.proposal === 'stale' ? ' (re-approval: changed since the last approval)' : '';
160
+ if (!(await confirmGate(ctx, feature, `approve the proposal${previous}: its recommendation is decided`, [`proposal ${short(proposal.hash)}`, reviewLine(ctx, record), openFindingsLine(feature)])))
161
+ return 1;
162
+ feature.approvals.approvals.proposal = { hash: proposal.hash, at_utc: ctx.now(), by: ctx.email() };
163
+ save(ctx, feature, 'approved', { gate: 'proposal' });
164
+ ctx.out(ctx.style.green(`approved the proposal of ${feature.slug}`));
165
+ await commitRecord(ctx, feature, values, proposedMessage(feature, 'proposal') || `${feature.key}: approve proposal`);
166
+ return 0;
154
167
  }
155
168
  /**
156
169
  * Everything that stands between a feature and the approval of `gate`, shared by
157
170
  * `approve`, `status` and `log --gate-requested`. No problems means the gate is ready.
158
171
  */
159
172
  export function gateReadiness(ctx, feature, gate) {
173
+ if (!workflowOf(feature.kind).gates.includes(gate)) {
174
+ return { problems: [`a ${workflowOf(feature.kind).name} has no '${gate}' gate (its gates: ${workflowOf(feature.kind).gates.join(', ') || 'none'})`], record: null };
175
+ }
160
176
  if (gate === 'verify')
161
177
  return verifyReadiness(ctx, feature);
178
+ if (gate === 'proposal')
179
+ return proposalReadiness(ctx, feature);
162
180
  const problems = [];
163
181
  let review;
164
182
  if (gate === 'spec') {
@@ -327,9 +345,11 @@ export function approve(ctx, argv) {
327
345
  return approveCombined(ctx, feature, values);
328
346
  if (what === 'verify')
329
347
  return approveVerify(ctx, feature, values);
348
+ if (what === 'proposal')
349
+ return approveProposal(ctx, feature, values);
330
350
  if (positionals[0] === 'amendment' && positionals.length === 2)
331
351
  return approveAmendment(ctx, feature, positionals[1], values);
332
- throw new UsageError('usage: agjan approve spec | design | spec design | verify | amendment <id> [--feature <slug>] [--no-commit]');
352
+ throw new UsageError('usage: agjan approve spec | design | spec design | verify | proposal | amendment <id> [--feature <slug>] [--no-commit]');
333
353
  }
334
354
  /**
335
355
  * agjan auto status [--feature <slug>]: the real settings, read-only: your default for new
@@ -0,0 +1,73 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { UsageError, AgjanError } from '../errors.js';
3
+ import { IMPORTS_FILE, applyImport, collisions, planChanges, planImport, readImports, removeImport } from '../imports.js';
4
+ const USAGE = 'usage: agjan import <git url or path> --commit <full commit id> [--dry-run] | agjan import list | agjan import remove <name>';
5
+ /** At most `max` names, then how many more. */
6
+ function names(list, max = 12) {
7
+ return list.length <= max ? list.join(', ') : `${list.slice(0, max).join(', ')} and ${list.length - max} more`;
8
+ }
9
+ /**
10
+ * agjan import (decision 93): skills and teams from another repository at an exact commit,
11
+ * shown before anything is written and confirmed by a person in a terminal (imported skills
12
+ * become instructions to the agents). `list` shows what is imported, `remove` takes it out.
13
+ */
14
+ export function run(ctx, argv) {
15
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { commit: { type: 'string' }, 'dry-run': { type: 'boolean' } } });
16
+ const s = ctx.style;
17
+ const root = ctx.root;
18
+ if (positionals[0] === 'list' && positionals.length === 1) {
19
+ const imports = Object.entries(readImports(root).imports);
20
+ if (!imports.length)
21
+ ctx.out(`nothing imported (${IMPORTS_FILE})`);
22
+ for (const [name, r] of imports) {
23
+ ctx.out(`${s.bold(name)} ${r.version} ${s.gray(`(${r.license}) ${r.source} @ ${r.commit.slice(0, 12)}, by ${r.by} at ${r.imported_at_utc}`)}`);
24
+ ctx.out(` skills ${names([...new Set(Object.keys(r.files).map((f) => f.split('/')[2]))]) || '-'}`);
25
+ ctx.out(` teams ${names(Object.keys(r.teams ?? {})) || '-'}`);
26
+ }
27
+ return 0;
28
+ }
29
+ if (positionals[0] === 'remove' && positionals.length === 2) {
30
+ const name = positionals[1];
31
+ const record = readImports(root).imports[name];
32
+ if (!record)
33
+ throw new AgjanError(`no imported package '${name}'`);
34
+ const summary = [s.bold(`agjan: remove the imported package ${name}`), ` files ${Object.keys(record.files).length}`, ` teams ${names(Object.keys(record.teams ?? {})) || '-'}`, ''].join('\n');
35
+ if (!ctx.confirm(summary, name)) {
36
+ ctx.out(s.yellow('cancelled, nothing changed'));
37
+ return 1;
38
+ }
39
+ const removed = removeImport(root, name);
40
+ ctx.out(s.green(`removed ${name}: ${removed.length} file(s); commit ${IMPORTS_FILE} and .claude/skills/`));
41
+ return 0;
42
+ }
43
+ if (positionals.length !== 1 || !values.commit)
44
+ throw new UsageError(USAGE);
45
+ const plan = planImport(positionals[0], values.commit);
46
+ const { name, version, license } = plan.manifest;
47
+ const change = planChanges(root, plan);
48
+ const taken = collisions(root, plan);
49
+ const lines = [
50
+ s.bold(`agjan: import ${name} ${version}`),
51
+ ` source ${plan.source} @ ${plan.commit}`,
52
+ ` license ${license}`,
53
+ ` skills added ${change.added.length}, changed ${change.changed.length}, removed ${change.removed.length} file(s)${change.added.length ? `: ${names(change.added)}` : ''}`,
54
+ ` teams ${[...change.teams.added.map((t) => `+${t}`), ...change.teams.changed.map((t) => `~${t}`), ...change.teams.removed.map((t) => `-${t}`)].join(', ') || 'unchanged'}`,
55
+ ' The skills become instructions to your agents: read them before you confirm.',
56
+ '',
57
+ ];
58
+ if (taken.length)
59
+ throw new AgjanError(`${name} would overwrite files it does not own: ${names(taken)}`);
60
+ if (values['dry-run']) {
61
+ for (const line of lines)
62
+ ctx.out(line);
63
+ ctx.out(s.gray('dry run: nothing written'));
64
+ return 0;
65
+ }
66
+ if (!ctx.confirm(lines.join('\n'), name)) {
67
+ ctx.out(s.yellow('cancelled, nothing written'));
68
+ return 1;
69
+ }
70
+ applyImport(root, plan, ctx.now(), ctx.email());
71
+ ctx.out(s.green(`imported ${name} ${version}: ${plan.files.size} file(s), ${Object.keys(plan.teams).length} team(s); commit ${IMPORTS_FILE} and .claude/skills/`));
72
+ return 0;
73
+ }