agjan 0.0.11 → 0.0.13

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 (114) hide show
  1. package/README.md +2 -2
  2. package/bin/agjan.mjs +9 -2
  3. package/dist/adapters/claude-code.js +136 -0
  4. package/dist/adapters/copilot.js +110 -0
  5. package/dist/auto.js +24 -0
  6. package/dist/baseline.js +66 -0
  7. package/dist/browser.js +46 -0
  8. package/dist/cli.js +170 -0
  9. package/dist/commands/branch.js +71 -0
  10. package/dist/commands/check.js +424 -0
  11. package/dist/commands/fix.js +122 -0
  12. package/dist/commands/gates.js +475 -0
  13. package/dist/commands/lint.js +76 -0
  14. package/dist/commands/log.js +74 -0
  15. package/dist/commands/map.js +47 -0
  16. package/dist/commands/models.js +90 -0
  17. package/dist/commands/new.js +65 -0
  18. package/dist/commands/pr-summary.js +176 -0
  19. package/dist/commands/progress.js +42 -0
  20. package/dist/commands/report.js +105 -0
  21. package/dist/commands/review.js +149 -0
  22. package/dist/commands/setup.js +393 -0
  23. package/dist/commands/status.js +323 -0
  24. package/dist/commands/ui-test.js +39 -0
  25. package/dist/config.js +114 -0
  26. package/dist/context.js +56 -0
  27. package/dist/copilot-mcp.js +56 -0
  28. package/dist/documents.js +207 -0
  29. package/dist/errors.js +15 -0
  30. package/dist/feature.js +221 -0
  31. package/dist/fix.js +117 -0
  32. package/dist/git.js +88 -0
  33. package/{src/hash.mjs → dist/hash.js} +11 -14
  34. package/dist/hook.js +47 -0
  35. package/dist/json-file.js +26 -0
  36. package/dist/log.js +50 -0
  37. package/dist/managed.js +182 -0
  38. package/dist/mcp-config.js +76 -0
  39. package/dist/mcp.js +187 -0
  40. package/dist/plan.js +40 -0
  41. package/dist/progress-view.js +494 -0
  42. package/dist/progress.js +106 -0
  43. package/dist/qa.js +77 -0
  44. package/dist/review-policy.js +84 -0
  45. package/dist/review.js +534 -0
  46. package/dist/scope.js +34 -0
  47. package/dist/terminal.js +127 -0
  48. package/dist/test-results.js +101 -0
  49. package/dist/tests-map.js +29 -0
  50. package/dist/types.js +5 -0
  51. package/dist/ui.js +136 -0
  52. package/dist/usage.js +116 -0
  53. package/dist/validate.js +46 -0
  54. package/docs/guide.md +80 -40
  55. package/kit/hooks/guard.mjs +48 -119
  56. package/kit/skills/agjan-build/SKILL.md +6 -2
  57. package/kit/skills/agjan-design/SKILL.md +9 -2
  58. package/kit/skills/agjan-fix/SKILL.md +8 -16
  59. package/kit/skills/agjan-map/SKILL.md +8 -16
  60. package/kit/skills/agjan-spec/SKILL.md +24 -17
  61. package/kit/skills/agjan-verify/SKILL.md +50 -16
  62. package/kit/skills/qa-tester/SKILL.md +74 -0
  63. package/kit/templates/agents-block.md +3 -3
  64. package/package.json +11 -3
  65. package/schemas/approvals.schema.json +23 -2
  66. package/schemas/config.schema.json +3 -7
  67. package/schemas/log.schema.json +1 -1
  68. package/schemas/reviews.schema.json +3 -1
  69. package/src/adapters/claude-code.mjs +0 -121
  70. package/src/adapters/copilot.mjs +0 -89
  71. package/src/baseline.mjs +0 -66
  72. package/src/browser.mjs +0 -49
  73. package/src/cli.mjs +0 -165
  74. package/src/commands/branch.mjs +0 -95
  75. package/src/commands/check.mjs +0 -376
  76. package/src/commands/fix.mjs +0 -116
  77. package/src/commands/gates.mjs +0 -267
  78. package/src/commands/lint.mjs +0 -74
  79. package/src/commands/log.mjs +0 -60
  80. package/src/commands/map.mjs +0 -47
  81. package/src/commands/new.mjs +0 -53
  82. package/src/commands/pr-summary.mjs +0 -137
  83. package/src/commands/progress.mjs +0 -40
  84. package/src/commands/report.mjs +0 -115
  85. package/src/commands/review.mjs +0 -141
  86. package/src/commands/setup.mjs +0 -393
  87. package/src/commands/status.mjs +0 -250
  88. package/src/commands/ui-test.mjs +0 -38
  89. package/src/config.mjs +0 -122
  90. package/src/context.mjs +0 -67
  91. package/src/copilot-mcp.mjs +0 -56
  92. package/src/documents.mjs +0 -188
  93. package/src/errors.mjs +0 -16
  94. package/src/feature.mjs +0 -225
  95. package/src/fix.mjs +0 -108
  96. package/src/git.mjs +0 -83
  97. package/src/hook.mjs +0 -48
  98. package/src/json-file.mjs +0 -24
  99. package/src/log.mjs +0 -51
  100. package/src/managed.mjs +0 -178
  101. package/src/mcp-config.mjs +0 -83
  102. package/src/mcp.mjs +0 -147
  103. package/src/plan.mjs +0 -45
  104. package/src/progress-view.mjs +0 -466
  105. package/src/progress.mjs +0 -85
  106. package/src/review-policy.mjs +0 -91
  107. package/src/review.mjs +0 -416
  108. package/src/scope.mjs +0 -30
  109. package/src/terminal.mjs +0 -118
  110. package/src/test-results.mjs +0 -111
  111. package/src/tests-map.mjs +0 -29
  112. package/src/ui.mjs +0 -136
  113. package/src/usage.mjs +0 -118
  114. package/src/validate.mjs +0 -41
package/README.md CHANGED
@@ -21,8 +21,8 @@ read-only reviewer at every step.
21
21
 
22
22
  agjan guides an AI coding agent through **Spec, Design, Build and Verify**:
23
23
 
24
- - **You hold the gates.** You approve the spec and the design in a terminal and merge the
25
- pull request. Approvals are stamped by a script with a UTC time and a content hash; if
24
+ - **You hold the gates.** You approve the spec and the design in a terminal, and accept
25
+ the verified result there too (`npx agjan approve verify`). Approvals are stamped by a script with a UTC time and a content hash; if
26
26
  an approved document changes, the approval is stale.
27
27
  - **An isolated reviewer checks every stage.** It runs as a separate agent with read
28
28
  access and two agjan tools only, and records its own findings. Blockers stop the gate.
package/bin/agjan.mjs CHANGED
@@ -1,10 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { main } from '../src/cli.mjs';
2
+ // @ts-check
3
+ import { existsSync } from 'node:fs';
4
+
5
+ // In the agjan repository Node runs the TypeScript sources directly; the npm package
6
+ // ships them compiled to dist/ (Node does not strip types inside node_modules).
7
+ const source = new URL('../src/cli.ts', import.meta.url);
8
+ /** @type {typeof import('../src/cli.ts')} */
9
+ const { main } = await import(existsSync(source) ? source.href : new URL('../dist/cli.js', import.meta.url).href);
3
10
 
4
11
  // A reader that stops early (`agjan status | head`) is not an error.
5
12
  for (const stream of [process.stdout, process.stderr]) {
6
13
  stream.on('error', (error) => {
7
- if (error.code === 'EPIPE') process.exit(process.exitCode ?? 0);
14
+ if (/** @type {NodeJS.ErrnoException} */ (error).code === 'EPIPE') process.exit(process.exitCode ?? 0);
8
15
  throw error;
9
16
  });
10
17
  }
@@ -0,0 +1,136 @@
1
+ import { stringify as toYaml } from 'yaml';
2
+ import { skillBody } from '../managed.js';
3
+ import { agentModel } from '../config.js';
4
+ /**
5
+ * Claude Code adapter (design 13): the generated reviewer agents and the deny rules for
6
+ * the human-only commands. Results of the host experiments shape both
7
+ * (docs/host-experiments.md, items 1, 1b and 5).
8
+ */
9
+ export const HOST = 'claude-code';
10
+ /** The models earlier versions used when none were configured; `sync` writes them for such projects. */
11
+ export const LEGACY_MODELS = { balanced: 'sonnet', deep: 'opus' };
12
+ /** One agent per reviewer tier; workflow skills pick the tier per step (design 7.3). */
13
+ const REVIEWERS = [
14
+ { name: 'agjan-reviewer', tier: 'balanced' },
15
+ { name: 'agjan-reviewer-deep', tier: 'deep' },
16
+ ];
17
+ const HUMAN_ONLY = ['approve', 'accept', 'reject', 'auto', 'models set'];
18
+ /** Every way an agent's shell might start agjan. Indirect forms are stopped by the terminal check. */
19
+ const LAUNCHERS = ['agjan', 'npx agjan', 'npx --no-install agjan', 'npx -y agjan', 'npm exec agjan', 'npm exec -- agjan'];
20
+ export const DENY_RULES = HUMAN_ONLY.flatMap((cmd) => LAUNCHERS.map((l) => `Bash(${l} ${cmd}:*)`));
21
+ /**
22
+ * The guard as a PreToolUse hook. It also catches wrapped forms the prefix deny rules miss
23
+ * (`sh -c "agjan approve …"`). If it cannot start (agjan not installed), Claude Code
24
+ * treats the error as non-blocking.
25
+ *
26
+ * Shell form, as in Claude Code's documentation (it runs hooks with bash, on Windows
27
+ * through Git Bash). Not the exec form (`command` + `args`): the GitHub Copilot CLI also
28
+ * runs the hooks of `.claude/settings.json`, ignores `args`, and denies every tool call
29
+ * when a hook fails (host experiments, GitHub Copilot CLI, 5b).
30
+ */
31
+ export const GUARD_HOOK = {
32
+ type: 'command',
33
+ command: 'node "$CLAUDE_PROJECT_DIR/node_modules/agjan/kit/hooks/guard.mjs"',
34
+ timeout: 10,
35
+ };
36
+ const GUARD_PATH = 'node_modules/agjan/kit/hooks/guard.mjs';
37
+ /** A guard entry written by an earlier agjan version (for example the exec form). */
38
+ /** The tools the guard sees: the shell, and the file edit tools (agjan's records). */
39
+ export const GUARD_MATCHER = 'Bash|Edit|Write|MultiEdit|NotebookEdit';
40
+ const isGuard = (hook) => JSON.stringify(hook).includes(GUARD_PATH);
41
+ const isCurrent = (hook) => JSON.stringify(hook) === JSON.stringify(GUARD_HOOK);
42
+ function hasGuard(data) {
43
+ const groups = data.hooks?.PreToolUse ?? [];
44
+ const guards = groups.flatMap((group) => (group.hooks ?? []).filter(isGuard).map((hook) => ({ group, hook })));
45
+ return guards.length === 1 && isCurrent(guards[0].hook) && guards[0].group.matcher === GUARD_MATCHER;
46
+ }
47
+ /**
48
+ * PreToolUse without any guard entry (earlier forms, or the current one under an older
49
+ * matcher such as 'Bash'); a group left empty is dropped. The caller adds the current one.
50
+ */
51
+ function withoutGuards(groups) {
52
+ return groups
53
+ .map((group) => (group.hooks?.some(isGuard) ? { ...group, hooks: group.hooks.filter((h) => !isGuard(h)) } : group))
54
+ .filter((group) => !Array.isArray(group.hooks) || group.hooks.length > 0);
55
+ }
56
+ /**
57
+ * The QA agent (decision 81): the qa-tester skill, a shell and file edits for its tests,
58
+ * and the agjan server in the QA role (qa_context, qa_record), scoped to this agent.
59
+ */
60
+ function qaAgent(model, skill) {
61
+ const frontmatter = {
62
+ name: 'agjan-qa',
63
+ description: "agjan's tester for the QA step of /agjan-verify: writes and runs tests from the spec alone. Use only when " +
64
+ 'an agjan workflow skill asks for step qa; it records its result itself.',
65
+ tools: 'Read, Grep, Glob, Edit, Write, Bash, mcp__agjan__qa_context, mcp__agjan__qa_record',
66
+ ...(model ? { model } : {}),
67
+ mcpServers: [
68
+ {
69
+ agjan: {
70
+ type: 'stdio',
71
+ command: 'npx',
72
+ args: ['--no-install', 'agjan', 'mcp', '--host', HOST, '--isolation', 'agent', '--role', 'qa'],
73
+ },
74
+ },
75
+ ],
76
+ };
77
+ return [
78
+ '---',
79
+ toYaml(frontmatter, { lineWidth: 0 }).trimEnd(),
80
+ '---',
81
+ '<!-- Generated by agjan sync from the qa-tester skill. Do not edit; run agjan sync. -->',
82
+ '',
83
+ skillBody(skill),
84
+ ].join('\n');
85
+ }
86
+ function reviewerAgent(name, tier, model, skill) {
87
+ const frontmatter = {
88
+ name,
89
+ description: `agjan's read-only reviewer (${tier} tier). Use only when an agjan workflow skill asks for the ` +
90
+ 'review of a step; it records its result itself.',
91
+ tools: 'Read, Grep, Glob, mcp__agjan__review_context, mcp__agjan__review_record',
92
+ ...(model ? { model } : {}),
93
+ // Scoped to this agent only: the writer session must not have review_record.
94
+ mcpServers: [
95
+ {
96
+ agjan: {
97
+ type: 'stdio',
98
+ command: 'npx',
99
+ args: ['--no-install', 'agjan', 'mcp', '--host', HOST, '--isolation', 'agent'],
100
+ },
101
+ },
102
+ ],
103
+ };
104
+ return [
105
+ '---',
106
+ toYaml(frontmatter, { lineWidth: 0 }).trimEnd(),
107
+ '---',
108
+ '<!-- Generated by agjan sync from the solution-reviewer skill. Do not edit; run agjan sync. -->',
109
+ '',
110
+ skillBody(skill),
111
+ ].join('\n');
112
+ }
113
+ /** The plan items this adapter contributes. */
114
+ export function plan(config, skills) {
115
+ const skill = skills['solution-reviewer/SKILL.md'];
116
+ const items = REVIEWERS.map(({ name, tier }) => ({
117
+ kind: 'file',
118
+ path: `.claude/agents/${name}.md`,
119
+ content: reviewerAgent(name, tier, agentModel(config, HOST, tier), skill),
120
+ }));
121
+ items.push({ kind: 'file', path: '.claude/agents/agjan-qa.md', content: qaAgent(agentModel(config, HOST, 'qa'), skills['qa-tester/SKILL.md']) });
122
+ items.push({
123
+ kind: 'json',
124
+ path: '.claude/settings.json',
125
+ present: (data) => DENY_RULES.every((rule) => data.permissions?.deny?.includes(rule)) && hasGuard(data),
126
+ merge: (data) => {
127
+ const deny = [...new Set([...(data.permissions?.deny ?? []), ...DENY_RULES])];
128
+ let hooks = data.hooks ?? {};
129
+ if (!hasGuard(data)) {
130
+ hooks = { ...hooks, PreToolUse: [...withoutGuards(hooks.PreToolUse ?? []), { matcher: GUARD_MATCHER, hooks: [GUARD_HOOK] }] };
131
+ }
132
+ return { ...data, permissions: { ...(data.permissions ?? {}), deny }, hooks };
133
+ },
134
+ });
135
+ return items;
136
+ }
@@ -0,0 +1,110 @@
1
+ import { stringify as toYaml } from 'yaml';
2
+ import { skillBody } from '../managed.js';
3
+ import { agentModel } from '../config.js';
4
+ /**
5
+ * GitHub Copilot adapter (design 13), verified with the Copilot CLI
6
+ * (docs/host-experiments.md): reviewer agents in `.github/agents/` with the agjan MCP
7
+ * server inline, and a `preToolUse` guard hook in `.github/hooks/`, because the
8
+ * Copilot CLI has no persistent deny setting. Skills need nothing: Copilot reads
9
+ * `.claude/skills/`.
10
+ *
11
+ * VS Code ignores `mcp-servers` in agent files and does not run hooks; see the open
12
+ * item in design section 19.
13
+ */
14
+ export const HOST = 'copilot';
15
+ export const HOOK_FILE = '.github/hooks/agjan-guard.json';
16
+ export const GUARD = 'node_modules/agjan/kit/hooks/guard.mjs';
17
+ /** The models earlier versions used when none were configured: the session's model. */
18
+ export const LEGACY_MODELS = {};
19
+ const REVIEWERS = [
20
+ { name: 'agjan-reviewer', tier: 'balanced' },
21
+ { name: 'agjan-reviewer-deep', tier: 'deep' },
22
+ ];
23
+ /**
24
+ * The QA agent (decision 81): the qa-tester skill, `edit` and `shell` for its tests
25
+ * (Copilot CLI 1.0.100 tested), and the agjan server in the QA role, scoped to it.
26
+ */
27
+ function qaAgent(model, skill) {
28
+ const frontmatter = {
29
+ name: 'agjan-qa',
30
+ description: "agjan's tester for the QA step of /agjan-verify: writes and runs tests from the spec alone. Use only when " +
31
+ 'an agjan workflow skill asks for step qa; it records its result itself.',
32
+ tools: ['read', 'search', 'edit', 'shell', 'agjan/qa_context', 'agjan/qa_record'],
33
+ ...(model ? { model } : {}),
34
+ 'mcp-servers': {
35
+ agjan: {
36
+ type: 'local',
37
+ command: 'npx',
38
+ args: ['--no-install', 'agjan', 'mcp', '--host', HOST, '--isolation', 'agent', '--role', 'qa'],
39
+ tools: ['*'],
40
+ },
41
+ },
42
+ };
43
+ return [
44
+ '---',
45
+ toYaml(frontmatter, { lineWidth: 0 }).trimEnd(),
46
+ '---',
47
+ '<!-- Generated by agjan sync from the qa-tester skill. Do not edit; run agjan sync. -->',
48
+ '',
49
+ skillBody(skill),
50
+ ].join('\n');
51
+ }
52
+ function reviewerAgent(name, tier, model, skill) {
53
+ const frontmatter = {
54
+ name,
55
+ description: `agjan's read-only reviewer (${tier} tier). Use only when an agjan workflow skill asks for the ` +
56
+ 'review of a step; it records its result itself.',
57
+ tools: ['read', 'search', 'agjan/review_context', 'agjan/review_record'],
58
+ ...(model ? { model } : {}),
59
+ // Scoped to this agent only: the writer session must not have review_record.
60
+ 'mcp-servers': {
61
+ agjan: {
62
+ type: 'local',
63
+ command: 'npx',
64
+ args: ['--no-install', 'agjan', 'mcp', '--host', HOST, '--isolation', 'agent'],
65
+ tools: ['*'],
66
+ },
67
+ },
68
+ };
69
+ return [
70
+ '---',
71
+ toYaml(frontmatter, { lineWidth: 0 }).trimEnd(),
72
+ '---',
73
+ '<!-- Generated by agjan sync from the solution-reviewer skill. Do not edit; run agjan sync. -->',
74
+ '',
75
+ skillBody(skill),
76
+ ].join('\n');
77
+ }
78
+ /**
79
+ * The guard hook. If agjan is not installed the guard cannot start; the hook then
80
+ * allows (`|| true`, `exit 0`) instead of failing closed and blocking every tool call.
81
+ */
82
+ export function hookConfig() {
83
+ const hook = {
84
+ version: 1,
85
+ hooks: {
86
+ preToolUse: [
87
+ {
88
+ type: 'command',
89
+ bash: `node ${GUARD} || true`,
90
+ powershell: `node ${GUARD}; exit 0`,
91
+ cwd: '.',
92
+ timeoutSec: 10,
93
+ },
94
+ ],
95
+ },
96
+ };
97
+ return `${JSON.stringify(hook, null, 2)}\n`;
98
+ }
99
+ /** The plan items this adapter contributes. */
100
+ export function plan(config, skills) {
101
+ const skill = skills['solution-reviewer/SKILL.md'];
102
+ const items = REVIEWERS.map(({ name, tier }) => ({
103
+ kind: 'file',
104
+ path: `.github/agents/${name}.agent.md`,
105
+ content: reviewerAgent(name, tier, agentModel(config, HOST, tier), skill),
106
+ }));
107
+ items.push({ kind: 'file', path: '.github/agents/agjan-qa.agent.md', content: qaAgent(agentModel(config, HOST, 'qa'), skills['qa-tester/SKILL.md']) });
108
+ items.push({ kind: 'file', path: HOOK_FILE, content: hookConfig() });
109
+ return items;
110
+ }
package/dist/auto.js ADDED
@@ -0,0 +1,24 @@
1
+ import { existsSync, mkdirSync, rmSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { readJson, writeJson } from './json-file.js';
4
+ /**
5
+ * The personal auto mode default (decision 79): a git-ignored file in this checkout,
6
+ * written only by `agjan auto on --default` (a human, in a terminal). While it exists,
7
+ * every feature created here starts with auto mode on; teammates' checkouts are not
8
+ * affected. The guard denies agents any access to it.
9
+ */
10
+ export const AUTO_DEFAULT_FILE = '.agjan/auto.json';
11
+ export function readAutoDefault(root) {
12
+ const data = readJson(join(root, AUTO_DEFAULT_FILE));
13
+ return data && typeof data.by === 'string' && typeof data.at_utc === 'string' ? { by: data.by, at_utc: data.at_utc } : null;
14
+ }
15
+ export function writeAutoDefault(root, value) {
16
+ const file = join(root, AUTO_DEFAULT_FILE);
17
+ mkdirSync(dirname(file), { recursive: true });
18
+ writeJson(file, value);
19
+ }
20
+ export function removeAutoDefault(root) {
21
+ const file = join(root, AUTO_DEFAULT_FILE);
22
+ if (existsSync(file))
23
+ rmSync(file);
24
+ }
@@ -0,0 +1,66 @@
1
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { createHash } from 'node:crypto';
4
+ import { git } from './git.js';
5
+ import { readJson, writeJson } from './json-file.js';
6
+ import { headings } from './documents.js';
7
+ import { matcher } from './scope.js';
8
+ import { repoFiles } from './tests-map.js';
9
+ import { FEATURES_DIR } from './feature.js';
10
+ import { PROJECT_MD } from './fix.js';
11
+ /**
12
+ * The baseline (design 8.6): docs/agjan/project.md, written by people and agents, and
13
+ * docs/agjan/baseline.json, written by `agjan baseline refresh`, with the hashes of the
14
+ * domains' watched files (models, services, app manifests, mta.yaml).
15
+ */
16
+ export const BASELINE_FILE = `${FEATURES_DIR}/baseline.json`;
17
+ /** Required `##` headings of project.md: general ones plus the BTP domain's areas. */
18
+ export function projectHeadings(config) {
19
+ const general = ['Overview', 'Conventions', 'Do-not-touch list'];
20
+ return config.domains.includes('btp') ? ['Overview', 'CAP', 'Fiori', 'BTP', 'Conventions', 'Do-not-touch list'] : general;
21
+ }
22
+ export function projectProblems(root, config) {
23
+ const file = join(root, PROJECT_MD);
24
+ if (!existsSync(file))
25
+ return [`${PROJECT_MD} does not exist`];
26
+ const present = new Set(headings(readFileSync(file, 'utf8')));
27
+ return projectHeadings(config).filter((h) => !present.has(h)).map((h) => `${PROJECT_MD}: missing heading '## ${h}'`);
28
+ }
29
+ function fileHash(root, file) {
30
+ return `sha256:${createHash('sha256').update(readFileSync(join(root, file))).digest('hex')}`;
31
+ }
32
+ export function watchedHashes(root, config) {
33
+ const isWatched = matcher(config.watched ?? []);
34
+ const out = {};
35
+ for (const file of repoFiles(root).filter(isWatched).sort()) {
36
+ if (existsSync(join(root, file)))
37
+ out[file] = fileHash(root, file);
38
+ }
39
+ return out;
40
+ }
41
+ /** agjan baseline refresh: records the current state of the watched files. */
42
+ export function refreshBaseline(root, config, now) {
43
+ const head = git(root, ['rev-parse', '--verify', '--quiet', 'HEAD'], { allowFail: true })?.trim() ?? null;
44
+ const data = { schema: 1, refreshed_at_utc: now, based_on_commit: head, watched: watchedHashes(root, config) };
45
+ mkdirSync(dirname(join(root, BASELINE_FILE)), { recursive: true });
46
+ writeJson(join(root, BASELINE_FILE), data);
47
+ return data;
48
+ }
49
+ /** Watched files that differ from the baseline: changed, added or removed since the refresh. */
50
+ export function baselineDrift(root, config) {
51
+ const baseline = readJson(join(root, BASELINE_FILE));
52
+ if (!baseline?.watched)
53
+ return null;
54
+ const current = watchedHashes(root, config);
55
+ const drift = [];
56
+ for (const [file, hash] of Object.entries(current)) {
57
+ if (baseline.watched[file] === undefined)
58
+ drift.push(`${file} (new)`);
59
+ else if (baseline.watched[file] !== hash)
60
+ drift.push(file);
61
+ }
62
+ for (const file of Object.keys(baseline.watched))
63
+ if (current[file] === undefined)
64
+ drift.push(`${file} (removed)`);
65
+ return drift;
66
+ }
@@ -0,0 +1,46 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { join } from 'node:path';
3
+ import { readJson } from './json-file.js';
4
+ /**
5
+ * UI tests are optional (design decision 75): they run in Playwright's Chromium where it
6
+ * can start, and are skipped with the reason where it cannot. On macOS and Windows,
7
+ * `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
+ */
10
+ /** The npm script that runs a project's UI tests. */
11
+ export const UI_SCRIPT = 'test:ui';
12
+ // Exit code 3: the project has no Playwright.
13
+ const PROBE = `let pw;
14
+ try { pw = await import('@playwright/test'); } catch { process.exit(3); }
15
+ const browser = await pw.chromium.launch();
16
+ await browser.close();`;
17
+ /** Whether the project defines the UI test script. */
18
+ export function hasUiTests(root) {
19
+ return Boolean(readJson(join(root, 'package.json'))?.scripts?.[UI_SCRIPT]);
20
+ }
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
+ export function probeBrowser(root) {
26
+ const fake = process.env.AGJAN_BROWSER_PROBE;
27
+ const run = spawnSync(process.execPath, fake ? [fake] : ['--input-type=module', '-e', PROBE], { cwd: root, encoding: 'utf8', timeout: 120_000 });
28
+ if (run.status === 0)
29
+ return { ready: true };
30
+ if (run.status === 3)
31
+ return { ready: false, reason: '@playwright/test is not installed', enable: 'npm install' };
32
+ const output = `${run.stderr ?? ''}${run.stdout ?? ''}`;
33
+ 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)' };
35
+ }
36
+ const library = /error while loading shared libraries: (\S+?):/.exec(output)?.[1];
37
+ if (library || /missing dependencies|install-deps/i.test(output)) {
38
+ return {
39
+ ready: false,
40
+ reason: `Chromium cannot start: this Linux system lacks its libraries${library ? ` (${library})` : ''}`,
41
+ 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',
42
+ };
43
+ }
44
+ 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' };
46
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,170 @@
1
+ import { createContext, pkg } from './context.js';
2
+ import { AgjanError } from './errors.js';
3
+ import { blink, createStyle, mark } from './ui.js';
4
+ import * as newCommand from './commands/new.js';
5
+ import * as gates from './commands/gates.js';
6
+ import * as check from './commands/check.js';
7
+ import * as status from './commands/status.js';
8
+ import * as review from './commands/review.js';
9
+ import * as log from './commands/log.js';
10
+ import * as prSummary from './commands/pr-summary.js';
11
+ import * as setup from './commands/setup.js';
12
+ import * as report from './commands/report.js';
13
+ import * as fix from './commands/fix.js';
14
+ import * as mapCommand from './commands/map.js';
15
+ import * as branch from './commands/branch.js';
16
+ import * as progress from './commands/progress.js';
17
+ import * as lint from './commands/lint.js';
18
+ import * as uiTest from './commands/ui-test.js';
19
+ import * as models from './commands/models.js';
20
+ import { onEvent } from './log.js';
21
+ import { refreshAfterEvent } from './progress-view.js';
22
+ const COMMANDS = {
23
+ init: setup.init,
24
+ sync: setup.sync,
25
+ doctor: setup.doctor,
26
+ hook: setup.hook,
27
+ branch: branch.run,
28
+ progress: progress.run,
29
+ new: newCommand.run,
30
+ scaffold: newCommand.scaffold,
31
+ status: status.run,
32
+ check: check.run,
33
+ lint: lint.run,
34
+ 'ui-test': uiTest.run,
35
+ models: models.run,
36
+ amend: gates.amend,
37
+ approve: gates.approve,
38
+ accept: gates.accept,
39
+ reject: gates.reject,
40
+ auto: gates.auto,
41
+ review: review.run,
42
+ log: log.run,
43
+ 'pr-summary': prSummary.run,
44
+ report: report.run,
45
+ fix: fix.run,
46
+ map: mapCommand.map,
47
+ baseline: mapCommand.baseline,
48
+ mcp: review.mcp,
49
+ };
50
+ const HELP = `agjan ${pkg.version}
51
+
52
+ Spec-driven workflow kit for AI coding agents, with human approval gates
53
+ and a read-only reviewer at every step. Closed beta (0.x); the user guide is\nin this package: docs/guide.md
54
+
55
+ Usage: agjan <command> [options]
56
+
57
+ Setup (human):
58
+ init [--domains btp] [--hosts claude-code,copilot] [--base <ref>]
59
+ [--no-hook] [--no-ci] [--prepare] [--copilot-mcp | --no-copilot-mcp]
60
+ set up agjan in this repository
61
+ sync [--force] [--copilot-mcp]
62
+ regenerate managed files (skills, agents, blocks, settings);
63
+ --copilot-mcp adds missing MCP servers to Copilot
64
+ hook install install the pre-commit hook
65
+ models [set <balanced|deep|qa> <model> [--host <h>]]
66
+ show the reviewers' models, or choose one (the deep reviewer
67
+ on another model family than the writer catches other things)
68
+ doctor check the environment and the project setup
69
+
70
+ Agent and human:
71
+ branch <name> | --list | --use <name>
72
+ create the branch for a feature, fix or map run, list
73
+ the existing ones, or switch to one (after asking the user)
74
+ new <slug> --key <KEY> create a feature folder with approvals.json and spec.md
75
+ scaffold design create design.md and tasks.md from the templates
76
+ progress [--open] regenerate the progress pages and show the overview
77
+ (.agjan/progress.html, docs/agjan/<unit>/progress.md)
78
+ status [--feature <s> | --all]
79
+ show the state of the changed (or every) feature
80
+ check [--staged | --ci] [--base <ref>]
81
+ enforce the workflow rules
82
+ lint [--all] [--base <ref>] run the area linters (UI5 linter for fiori) on the changed
83
+ files of each app, without MCP
84
+ ui-test [--require] run the UI tests (npm run test:ui, Playwright) where
85
+ Chromium can start; else say why and skip (--require: exit 1)
86
+ amend --task <id> --paths <p,...> --reason "<why>"
87
+ propose a scope amendment during Build
88
+ fix start <slug> --key <KEY> --what "<text>" | fix check | fix record [--verify "…"]
89
+ fast path for small changes (record folder under fixes/)
90
+ map start start mapping an existing application (project.md)
91
+ baseline refresh record the watched files in baseline.json
92
+ review show [--step <step>] list review records, or print a step's review context
93
+ review report [--step <step>] the latest review round for the user: verdict, findings,
94
+ rounds, what happens next (agents show it after each review)
95
+ review extend <step> one more round for a step still blocked at its round
96
+ limit (after the user said yes)
97
+ log --stage <stage> [--role r] [--task T1] [--skill s]
98
+ log --gate-requested <gate> [--message "<commit message>"]
99
+ record a step start or a gate handed to the human
100
+ pr-summary print the PR description (Markdown), with check --ci results
101
+ report write report.md: durations, gate waits, models and tokens
102
+
103
+ Reviewer agent (through the host's MCP configuration):
104
+ mcp [--host <h>] [--isolation agent|shared|fork|none] [--role review|qa]
105
+ agjan MCP server on stdio: review_context, review_record
106
+ (--role qa: qa_context, qa_record for the agjan-qa agent)
107
+
108
+ Human only, in a terminal:
109
+ approve spec | design | spec design | verify | amendment <id>
110
+ accept <finding-id> --reason "<why>"
111
+ reject spec|design --reason "<why>"
112
+ auto on|off [--default] auto mode for one feature (--default: every new feature in this
113
+ checkout): spec and design are approved automatically once
114
+ their reviews pass (approve verify stays yours)
115
+ each records the decision, then commits the feature
116
+ folder with a message you can edit (--no-commit skips)
117
+
118
+ Other:
119
+ --version, --help
120
+ `;
121
+ /**
122
+ * Runs the CLI and returns the process exit code.
123
+ * `options` (streams, clock, confirmation) are passed to the command context for tests.
124
+ */
125
+ export async function main(args, options = {}) {
126
+ const stdout = options.stdout ?? process.stdout;
127
+ const stderr = options.stderr ?? process.stderr;
128
+ const [command, ...rest] = args;
129
+ if (command === undefined || command === '--help' || command === '-h' || command === 'help') {
130
+ const s = createStyle(stdout);
131
+ if (!s.brand) {
132
+ stdout.write(HELP);
133
+ return 0;
134
+ }
135
+ // On a terminal: the agjan mark instead of the first line, and bold section headings.
136
+ const body = HELP.split('\n').slice(1).map((l) => (/^\S.*:$/.test(l) ? s.bold(l) : l));
137
+ const logo = mark(s, pkg.version);
138
+ stdout.write(`${logo.join('\n')}\n`);
139
+ await blink({ isTTY: Boolean(stdout.isTTY), write: (text) => stdout.write(text) }, logo);
140
+ stdout.write(body.slice(1).join('\n'));
141
+ return 0;
142
+ }
143
+ if (command === '--version' || command === '-v' || command === 'version') {
144
+ stdout.write(`${pkg.version}\n`);
145
+ return 0;
146
+ }
147
+ // Every recorded event regenerates the progress pages (docs/agjan/<unit>/progress.md, .agjan/).
148
+ onEvent((unitDir) => refreshAfterEvent(unitDir, pkg.version));
149
+ const handler = COMMANDS[command];
150
+ if (!handler) {
151
+ stderr.write(`agjan: unknown command '${command}'. Run 'agjan --help'.\n`);
152
+ return 2;
153
+ }
154
+ try {
155
+ return await handler(createContext({ ...options, stdout, stderr }), rest);
156
+ }
157
+ catch (error) {
158
+ if (error instanceof AgjanError) {
159
+ const s = createStyle(stderr);
160
+ stderr.write(`${s.bold(s.red(`agjan ${command}:`))} ${error.message}\n`);
161
+ return error.exitCode;
162
+ }
163
+ const failure = error;
164
+ if (typeof failure?.code === 'string' && failure.code.startsWith('ERR_PARSE_ARGS')) {
165
+ stderr.write(`agjan ${command}: ${failure.message}\n`);
166
+ return 2;
167
+ }
168
+ throw error;
169
+ }
170
+ }
@@ -0,0 +1,71 @@
1
+ import { parseArgs } from 'node:util';
2
+ import { git, currentBranch, resolveBase } from '../git.js';
3
+ import { AgjanError, UsageError } from '../errors.js';
4
+ /** Problems with a proposed branch name: git's rules, existence. */
5
+ export function branchProblems(root, config, name) {
6
+ const problems = [];
7
+ if (git(root, ['check-ref-format', '--branch', name], { allowFail: true }) === null)
8
+ problems.push(`'${name}' is not a valid branch name`);
9
+ if (git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${name}`], { allowFail: true }) !== null)
10
+ problems.push(`branch '${name}' already exists`);
11
+ return problems;
12
+ }
13
+ /** Local branches other than the base branch, most recent commit first. */
14
+ export function existingBranches(root, config) {
15
+ const base = (resolveBase(root, config.git?.base) ?? '').replace(/^origin\//, '');
16
+ const out = git(root, ['for-each-ref', '--sort=-committerdate', '--format=%(refname:short)\t%(committerdate:relative)', 'refs/heads'], { allowFail: true }) ?? '';
17
+ return out.split('\n').filter(Boolean).map((line) => {
18
+ const [name, when] = line.split('\t');
19
+ return { name, when };
20
+ }).filter((b) => b.name !== base);
21
+ }
22
+ /** Creates the branch `name` from the current one and switches to it. */
23
+ function create(ctx, name) {
24
+ const s = ctx.style;
25
+ const problems = branchProblems(ctx.root, ctx.config, name);
26
+ if (problems.length)
27
+ throw new AgjanError(`cannot create the branch:\n${problems.map((p) => ` - ${p}`).join('\n')}`);
28
+ const from = currentBranch(ctx.root);
29
+ git(ctx.root, ['switch', '-q', '-c', name]);
30
+ ctx.out(`${s.green('created branch')} ${s.bold(name)}${from ? s.gray(` (from ${from})`) : ''}`);
31
+ const base = resolveBase(ctx.root, ctx.config.git?.base);
32
+ if (from && base && from !== base.replace(/^origin\//, ''))
33
+ ctx.out(s.yellow(`note: created from ${from}, not from the base branch ${base}`));
34
+ return 0;
35
+ }
36
+ /**
37
+ * agjan branch <name> | --list | --use <name>: the branch for a feature, fix or map run.
38
+ * The agent asks the user first (create a branch, with its proposed name or one the user
39
+ * types, or use an existing one; design decision 62), then runs this: <name> creates the
40
+ * branch and switches to it, --list shows the existing ones, --use switches to one.
41
+ */
42
+ export async function run(ctx, argv) {
43
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: { list: { type: 'boolean' }, use: { type: 'string' } } });
44
+ const s = ctx.style;
45
+ if (values.list) {
46
+ if (positionals.length || values.use)
47
+ throw new UsageError('usage: agjan branch --list');
48
+ const current = currentBranch(ctx.root);
49
+ const branches = existingBranches(ctx.root, ctx.config);
50
+ if (!branches.length)
51
+ ctx.out(s.gray('no branches besides the base branch'));
52
+ for (const b of branches)
53
+ ctx.out(`${b.name === current ? s.green('* ') : ' '}${s.bold(b.name)} ${s.gray(`(${b.when})`)}`);
54
+ return 0;
55
+ }
56
+ if (values.use !== undefined) {
57
+ if (positionals.length)
58
+ throw new UsageError('usage: agjan branch --use <name>');
59
+ const name = values.use;
60
+ if (!existingBranches(ctx.root, ctx.config).some((b) => b.name === name)) {
61
+ throw new AgjanError(`'${name}' is not an existing branch other than the base branch (npx agjan branch --list)`);
62
+ }
63
+ if (currentBranch(ctx.root) !== name)
64
+ git(ctx.root, ['switch', '-q', name]);
65
+ ctx.out(`${s.green('on branch')} ${s.bold(name)}`);
66
+ return 0;
67
+ }
68
+ if (positionals.length !== 1)
69
+ throw new UsageError('usage: agjan branch <name> | --list | --use <name>');
70
+ return create(ctx, positionals[0]);
71
+ }