agjan 0.0.30 → 0.0.31

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 (46) hide show
  1. package/README.md +3 -2
  2. package/dist/adapters/claude-code.js +39 -1
  3. package/dist/adapters/copilot.js +34 -1
  4. package/dist/baseline.js +3 -4
  5. package/dist/cli.js +5 -1
  6. package/dist/commands/areas.js +47 -0
  7. package/dist/commands/lint.js +2 -2
  8. package/dist/commands/map.js +6 -1
  9. package/dist/commands/review.js +3 -3
  10. package/dist/commands/setup.js +19 -16
  11. package/dist/commands/status.js +18 -2
  12. package/dist/commands/team.js +9 -3
  13. package/dist/commands/workflow.js +2 -1
  14. package/dist/config.js +55 -49
  15. package/dist/defaults-file.js +5 -3
  16. package/dist/mcp-config.js +1 -1
  17. package/dist/mcp.js +31 -3
  18. package/dist/review.js +7 -2
  19. package/dist/schema.js +4 -0
  20. package/dist/teams.js +117 -6
  21. package/dist/terminal.js +3 -0
  22. package/dist/validate.js +3 -3
  23. package/dist/worker.js +120 -0
  24. package/dist/workflow-view.js +15 -3
  25. package/docs/guide.md +58 -12
  26. package/docs/workflows-and-teams.md +43 -9
  27. package/kit/hooks/guard.mjs +55 -2
  28. package/kit/presets/generic.json +26 -0
  29. package/kit/presets/sap-btp.json +34 -0
  30. package/kit/skills/agjan-build/SKILL.md +9 -3
  31. package/kit/skills/agjan-design/SKILL.md +14 -11
  32. package/kit/skills/agjan-discover/SKILL.md +6 -0
  33. package/kit/skills/agjan-fix/SKILL.md +6 -0
  34. package/kit/skills/agjan-map/SKILL.md +14 -5
  35. package/kit/skills/agjan-spec/SKILL.md +6 -0
  36. package/kit/skills/agjan-worker/SKILL.md +36 -0
  37. package/kit/skills/agjan-worker/references/hand-off.md +32 -0
  38. package/kit/skills/backend-developer/SKILL.md +50 -0
  39. package/kit/skills/solution-architect/SKILL.md +54 -0
  40. package/kit/skills/technical-architect/SKILL.md +50 -0
  41. package/kit/skills/ui-developer/SKILL.md +48 -0
  42. package/kit/templates/project.md +3 -14
  43. package/package.json +1 -1
  44. package/schemas/config.defaults.json +8 -10
  45. package/schemas/config.schema.json +46 -35
  46. package/kit/domains/btp/domain.json +0 -29
package/dist/config.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readdirSync } from 'node:fs';
1
2
  import { join } from 'node:path';
2
3
  import { readJson } from './json-file.js';
3
4
  import { importedTeams } from './imports.js';
@@ -15,6 +16,15 @@ export const SESSION_MODEL = 'session';
15
16
  export const MODEL_TIERS = ['balanced', 'deep'];
16
17
  /** Every agent tier `agjan models` sets: the reviewers' and the QA agent's (decision 81). */
17
18
  export const AGENT_TIERS = [...MODEL_TIERS, 'qa'];
19
+ /**
20
+ * The model of a worker agent (decision 100): `models.<host>.worker` for agjan-worker,
21
+ * `models.<host>.worker-deep` for agjan-worker-deep; without one, the session's model (never
22
+ * a reviewer's, so the reviewers stay on models of their own).
23
+ */
24
+ export function workerModel(config, host, tier) {
25
+ const value = config.models?.[host]?.[tier === 'deep' ? 'worker-deep' : 'worker'];
26
+ return value && value !== SESSION_MODEL ? value : undefined;
27
+ }
18
28
  /** The model to write into an agent file, or undefined for the session's model. */
19
29
  export function agentModel(config, host, tier) {
20
30
  const models = config.models?.[host];
@@ -22,9 +32,8 @@ export function agentModel(config, host, tier) {
22
32
  const value = models?.[tier] ?? (tier === 'qa' ? models?.deep : undefined) ?? models?.balanced;
23
33
  return value && value !== SESSION_MODEL ? value : undefined;
24
34
  }
25
- /** Package defaults. Domain defaults and project overrides are layered on top. */
35
+ /** Package defaults; the project's agjan.config.json is layered on top. */
26
36
  export const DEFAULTS = {
27
- domains: ['btp'],
28
37
  hosts: ['claude-code'],
29
38
  language: 'en',
30
39
  git: { base: null },
@@ -32,6 +41,7 @@ export const DEFAULTS = {
32
41
  risk_paths: [],
33
42
  application: [],
34
43
  tests: {},
44
+ watched: [],
35
45
  fix: {
36
46
  max_total: 80,
37
47
  max_per_file: 50,
@@ -58,11 +68,43 @@ export function merge(base, override) {
58
68
  out[key] = merge(base[key], value);
59
69
  return out;
60
70
  }
61
- export function loadDomain(id) {
62
- const domain = readJson(new URL(`domains/${id}/domain.json`, KIT_DIR));
63
- if (!domain)
64
- throw new AgjanError(`unknown domain '${id}'`);
65
- return domain;
71
+ /** Area names: lowercase, as task ids and review steps (`build:<area>`) use them. */
72
+ export const AREA_NAME = /^[a-z][a-z0-9-]{0,31}$/;
73
+ /** The one area of a project that defines none: the whole application. */
74
+ export const DEFAULT_AREAS = {
75
+ app: { title: 'Application', description: 'What the application does, its main parts and how they fit together.' },
76
+ };
77
+ /** The areas of a project, resolved from its `areas` (decision 98): the default one when it defines none. */
78
+ export function resolveAreas(defined) {
79
+ const source = defined && Object.keys(defined).length ? defined : DEFAULT_AREAS;
80
+ return Object.fromEntries(Object.entries(source).map(([name, a]) => [name, {
81
+ id: name,
82
+ name,
83
+ title: a.title ?? name,
84
+ description: a.description ?? '',
85
+ skills: a.skills ?? [],
86
+ }]));
87
+ }
88
+ /** The per-area settings the rest of agjan reads, derived from `areas`. */
89
+ function areaSettings(defined) {
90
+ const entries = Object.entries(defined);
91
+ return {
92
+ scope: { implicit: Object.fromEntries(entries.map(([n, a]) => [n, a.implicit ?? []])) },
93
+ tests: Object.fromEntries(entries.map(([n, a]) => [n, a.tests ?? []])),
94
+ verify: Object.fromEntries(entries.map(([n, a]) => [n, a.verify ?? {}])),
95
+ lint: Object.fromEntries(entries.filter(([, a]) => a.lint !== undefined).map(([n, a]) => [n, a.lint ?? null])),
96
+ };
97
+ }
98
+ const PRESETS_DIR = new URL('presets/', KIT_DIR);
99
+ /** The presets `init` offers, generic first. */
100
+ export function presetIds() {
101
+ return readdirSync(PRESETS_DIR).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)).sort((a, b) => (a === 'generic' ? -1 : b === 'generic' ? 1 : a.localeCompare(b)));
102
+ }
103
+ export function loadPreset(id) {
104
+ const preset = /^[a-z][a-z0-9-]*$/.test(id) ? readJson(new URL(`${id}.json`, PRESETS_DIR)) : null;
105
+ if (!preset)
106
+ throw new AgjanError(`unknown preset '${id}' (presets: ${presetIds().join(', ')})`);
107
+ return preset;
66
108
  }
67
109
  /** The project's own `review` settings (agjan.config.json as written), by the configuration loadConfig made of it. */
68
110
  const writtenReview = new WeakMap();
@@ -76,8 +118,8 @@ export function projectSetsReview(config, key) {
76
118
  }
77
119
  /**
78
120
  * Loads the effective configuration of the project at `root`: package defaults, then
79
- * the enabled domains' defaults, then agjan.config.json. Also resolves the areas of all
80
- * enabled domains, keyed by both the short id and the canonical `domain:area` id.
121
+ * agjan.config.json. Resolves the project's areas (decision 98) and derives the per-area
122
+ * settings (implicit paths, tests, verify commands, linters) from them.
81
123
  */
82
124
  export function loadConfig(root) {
83
125
  const project = readJson(join(root, CONFIG_FILE)) ?? {};
@@ -88,49 +130,13 @@ export function loadConfig(root) {
88
130
  if (problems.length) {
89
131
  throw new AgjanError(`${CONFIG_FILE} does not match its schema (node_modules/agjan/schemas/config.schema.json):\n${problems.map((p) => ` - ${p}`).join('\n')}`);
90
132
  }
91
- const domainIds = project.domains ?? DEFAULTS.domains;
92
- let config = merge(DEFAULTS, {});
93
- const areas = {};
94
- const shortCount = {};
95
- for (const id of domainIds) {
96
- const domain = loadDomain(id);
97
- const implicit = {};
98
- const tests = {};
99
- const verify = {};
100
- const lint = {};
101
- for (const [name, area] of Object.entries(domain.areas)) {
102
- const canonical = `${id}:${name}`;
103
- areas[canonical] = { id: canonical, domain: id, name, role: area.role };
104
- shortCount[name] = (shortCount[name] ?? 0) + 1;
105
- implicit[name] = area.implicit ?? [];
106
- tests[name] = area.tests ?? [];
107
- verify[name] = area.verify ?? {};
108
- if (area.lint)
109
- lint[name] = area.lint;
110
- }
111
- config = merge(config, {
112
- scope: { implicit },
113
- tests,
114
- verify,
115
- lint,
116
- risk_paths: [...config.risk_paths, ...(domain.risk_paths ?? [])],
117
- application: [...config.application, ...(domain.application ?? [])],
118
- fix: { protected: [...config.fix.protected, ...(domain.protected ?? [])] },
119
- watched: [...(config.watched ?? []), ...(domain.watched ?? [])],
120
- });
121
- }
122
- // Short ids resolve only when they are unique among the enabled domains (design 3).
123
- for (const area of Object.values(areas)) {
124
- if (shortCount[area.name] === 1)
125
- areas[area.name] = area;
126
- }
127
- config = merge(config, project);
133
+ const { areas: defined, ...rest } = project;
134
+ const used = defined && Object.keys(defined).length ? defined : DEFAULT_AREAS;
135
+ const config = { ...merge(merge(DEFAULTS, rest), areaSettings(used)), areas: resolveAreas(used) };
128
136
  // Imported teams (decision 93) sit under the project's own: a project team of the same name wins.
129
137
  const imported = importedTeams(root);
130
138
  if (Object.keys(imported).length)
131
139
  config.teams = { ...imported, ...(config.teams ?? {}) };
132
- config.domains = domainIds;
133
- config.areas = areas;
134
140
  writtenReview.set(config, isObject(project.review) ? project.review : {});
135
141
  return config;
136
142
  }
@@ -151,7 +157,7 @@ export function ciSettingsAt(root, commit) {
151
157
  return null;
152
158
  }
153
159
  }
154
- /** Resolves a short or canonical area id; returns null when unknown or ambiguous. */
160
+ /** The area of that name, or null. */
155
161
  export function resolveArea(config, id) {
156
162
  return config.areas[id] ?? null;
157
163
  }
@@ -1,4 +1,4 @@
1
- import { DEFAULTS, merge } from './config.js';
1
+ import { DEFAULTS, DEFAULT_AREAS, merge } from './config.js';
2
2
  import { DEFAULT_TIERS } from './review-policy.js';
3
3
  /**
4
4
  * agjan's default settings as data: schemas/config.defaults.json, shipped in the package next
@@ -22,10 +22,12 @@ function reviewTiers() {
22
22
  return Object.fromEntries(Object.entries(DEFAULT_TIERS).filter(([, tier]) => ['fast', 'balanced', 'deep'].includes(tier)));
23
23
  }
24
24
  export function defaultsDocument() {
25
+ // The per-area settings are derived from `areas`; a project does not set them itself.
26
+ const { scope: _scope, tests: _tests, verify: _verify, lint: _lint, ...settable } = DEFAULTS;
25
27
  return {
26
- description: "agjan's defaults for agjan.config.json. Domains add their own on top (kit/domains/<id>/domain.json: per area implicit, tests, verify, lint; application, risk_paths and protected are appended), and the project's file overrides both. Objects merge, arrays replace. Review steps without a tier use balanced.",
28
+ description: "agjan's defaults for agjan.config.json; the project's file overrides them (agjan init --preset writes a preset's areas and paths into it). Objects merge, arrays replace. A project without areas has the one area shown here. Review steps without a tier use balanced.",
27
29
  format: 1,
28
- defaults: merge(merge(DEFAULTS, IMPLICIT_DEFAULTS), { review: { tiers: reviewTiers() } }),
30
+ defaults: merge(merge(settable, IMPLICIT_DEFAULTS), { areas: DEFAULT_AREAS, review: { tiers: reviewTiers() } }),
29
31
  };
30
32
  }
31
33
  export function defaultsFileText() {
@@ -13,7 +13,7 @@ export const PINNED = JSON.parse(readFileSync(new URL('../kit/mcp/servers.json',
13
13
  export const DEFAULT_SERVERS = Object.fromEntries(Object.entries(PINNED).map(([name, s]) => [name, { command: 'npx', args: ['-y', `${s.package}@${s.version}`], areas: s.areas }]));
14
14
  /**
15
15
  * The servers to write, and the names to remove (configured with `enabled: false`).
16
- * A server is written only when one of its areas belongs to an enabled domain.
16
+ * A server is written only when the project has one of its areas (kit servers: cap, fiori).
17
17
  */
18
18
  export function mcpServers(config) {
19
19
  const configured = { ...DEFAULT_SERVERS, ...(config.mcp?.servers ?? {}) };
package/dist/mcp.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { createInterface } from 'node:readline';
2
2
  import { createQaContext, createReviewContext, recordQa, recordReview } from './review.js';
3
- import { selectFeature } from './feature.js';
3
+ import { loadFeature, selectFeature } from './feature.js';
4
+ import { createWorkerContext } from './worker.js';
4
5
  import { AgjanError } from './errors.js';
5
6
  /**
6
7
  * The agjan MCP server (design 7.2): a minimal MCP implementation over stdio,
@@ -56,6 +57,27 @@ export const QA_TOOLS = [
56
57
  },
57
58
  },
58
59
  ];
60
+ /** The worker agents' tool (decision 100): their own server, so neither the main agent nor the reviewer sees it. */
61
+ export const WORKER_TOOLS = [
62
+ {
63
+ name: 'role_context',
64
+ title: 'agjan: get role context',
65
+ description: 'Returns your input as an agjan worker for one stage of a unit: your role and skills, what to do, what to ' +
66
+ 'read, the paths you may write and how to hand back. Call it first; the main agent names the stage (and for ' +
67
+ 'build the task) in its request.',
68
+ inputSchema: {
69
+ type: 'object',
70
+ properties: {
71
+ stage: { type: 'string', enum: ['spec', 'design', 'build', 'fix', 'map', 'proposal'] },
72
+ task: { type: 'string', description: 'The task id (build only), for example T1' },
73
+ feature: { type: 'string', description: 'The unit (feature slug, fixes/<id>, maps/<id>, discoveries/<slug>); optional when exactly one changed on the branch' },
74
+ },
75
+ required: ['stage'],
76
+ additionalProperties: false,
77
+ },
78
+ annotations: { readOnlyHint: false },
79
+ },
80
+ ];
59
81
  export const TOOLS = [
60
82
  {
61
83
  name: 'review_context',
@@ -98,6 +120,12 @@ function text(content, isError = false) {
98
120
  /** Handles one tools/call; tool failures are results with isError, not protocol errors. */
99
121
  function callTool(ctx, server, name, args = {}) {
100
122
  try {
123
+ if (server.role === 'worker') {
124
+ if (name !== 'role_context')
125
+ return null;
126
+ const unit = loadFeature(ctx.root, selectFeature(ctx.root, ctx.config, args.feature));
127
+ return text(createWorkerContext(ctx.root, ctx.config, unit, { stage: args.stage, task: args.task }).text);
128
+ }
101
129
  if (server.role === 'qa') {
102
130
  if (name === 'qa_context') {
103
131
  const feature = selectFeature(ctx.root, ctx.config, args.feature);
@@ -146,13 +174,13 @@ export function handleMessage(ctx, server, message) {
146
174
  protocolVersion: SUPPORTED_VERSIONS.includes(requested) ? requested : SUPPORTED_VERSIONS[0],
147
175
  capabilities: { tools: { listChanged: false } },
148
176
  serverInfo: { name: 'agjan', version: ctx.kit },
149
- instructions: 'agjan review tools. Only the agjan reviewer agent uses them.',
177
+ instructions: server.role === 'worker' ? 'agjan worker tools. Only the agjan worker agents use them.' : 'agjan review tools. Only the agjan reviewer agent uses them.',
150
178
  });
151
179
  }
152
180
  case 'ping':
153
181
  return reply({});
154
182
  case 'tools/list':
155
- return reply({ tools: server.role === 'qa' ? QA_TOOLS : TOOLS });
183
+ return reply({ tools: server.role === 'qa' ? QA_TOOLS : server.role === 'worker' ? WORKER_TOOLS : TOOLS });
156
184
  case 'tools/call': {
157
185
  const result = callTool(ctx, server, params?.name, params?.arguments);
158
186
  return result ? reply(result) : fail(-32602, `unknown tool '${params?.name}'`);
package/dist/review.js CHANGED
@@ -262,7 +262,8 @@ export function buildContextText(root, config, feature, parsed) {
262
262
  parts.push(section(docPath(feature, 'proposal.md'), fence(feature.proposal.text, 'md')));
263
263
  if (baselineText)
264
264
  parts.push(section(`${FEATURES_DIR}/project.md (the application)`, fence(baselineText, 'md')));
265
- parts.push(section('Sources to check claims against', 'The role skills in `.claude/skills/` (cap-developer, fiori-developer, btp-architect) and `.claude/skills/agjan-ask/references/sources.md`.'));
265
+ const skills = [...new Set(Object.values(config.areas).flatMap((a) => a.skills))];
266
+ parts.push(section('Sources to check claims against', `${skills.length ? `The skills of the project's areas in \`.claude/skills/\` (${skills.join(', ')}), the` : 'The'} skills of your team and \`.claude/skills/agjan-ask/references/sources.md\`.`));
266
267
  }
267
268
  else if (parsed.kind === 'map') {
268
269
  if (!baselineText)
@@ -555,6 +556,10 @@ export function createQaContext(root, config, { feature: slug }) {
555
556
  const runLocally = existsSync(baseline) ? (/^## Run locally\s*$([\s\S]*?)(?=^## |\s*$(?![\s\S]))/m.exec(readFileSync(baseline, 'utf8'))?.[1] ?? '').trim() : '';
556
557
  const areaNames = [...new Set(feature.tasks.parsed.tasks.map((t) => resolveArea(config, t.area)?.name).filter((name) => Boolean(name)))];
557
558
  const commands = areaNames.map((a) => `- ${a}: ${config.verify?.[a]?.test ?? 'npm test'} (tests: ${(config.tests[a] ?? []).join(', ') || '-'})`).join('\n');
559
+ // The testing references of the feature's areas' skills (decision 98).
560
+ const testingRefs = [...new Set(areaNames.flatMap((a) => config.areas[a]?.skills ?? []))]
561
+ .map((skill) => `.claude/skills/${skill}/references/testing.md`)
562
+ .filter((f) => existsSync(join(root, f)));
558
563
  const ui = Boolean(readJson(join(root, 'package.json'))?.scripts?.['test:ui']);
559
564
  const existing = qaTestFiles(root, feature.slug);
560
565
  const parts = [
@@ -570,7 +575,7 @@ export function createQaContext(root, config, { feature: slug }) {
570
575
  const tester = team?.team ? roleText(config, team.name, rolesFor(config, team.team, feature.kind, 'qa')) : null;
571
576
  return tester ? [section('Your team', tester)] : [];
572
577
  })()),
573
- section('Test conventions', `${commands}\n- UI tests: ${ui ? '`npx agjan ui-test` runs the Playwright tests (it skips them, with the reason, where no browser can start)' : 'the project has no Playwright setup (no `test:ui` script): write service tests only'}\n- How tests are written in this stack: \`.claude/skills/cap-developer/references/testing.md\` (cds.test) and \`.claude/skills/fiori-developer/references/testing.md\` (Playwright). Read those for the test mechanics only.`),
578
+ section('Test conventions', `${commands}\n- UI tests: ${ui ? '`npx agjan ui-test` runs the Playwright tests (it skips them, with the reason, where no browser can start)' : 'the project has no Playwright setup (no `test:ui` script): write service tests only'}${testingRefs.length ? `\n- How tests are written in this stack: ${testingRefs.map((f) => `\`${f}\``).join(' and ')}. Read those for the test mechanics only.` : ''}`),
574
579
  section('Your tests from earlier QA rounds', existing.length ? existing.map((f) => `- ${f}`).join('\n') : '(none: this is the first QA round)'),
575
580
  section('Earlier rounds', reviewHistory(feature)),
576
581
  section('Open findings', openFindings(feature, [QA_STEP])),
package/dist/schema.js CHANGED
@@ -77,6 +77,10 @@ export function validate(schema, value, root = schema, path = '') {
77
77
  errors.push(`${where}: unknown name; one of ${schema.propertyNames.enum.join(', ')}`);
78
78
  continue;
79
79
  }
80
+ if (schema.propertyNames?.pattern && !new RegExp(schema.propertyNames.pattern).test(key)) {
81
+ errors.push(`${where}: '${key}' is not a valid name (${schema.propertyNames.pattern})`);
82
+ continue;
83
+ }
80
84
  if (schema.properties?.[key])
81
85
  errors.push(...validate(schema.properties[key], item, root, where));
82
86
  else if (schema.additionalProperties === false)
package/dist/teams.js CHANGED
@@ -5,7 +5,26 @@ import { AgjanError } from './errors.js';
5
5
  import { WORKFLOWS } from './workflow.js';
6
6
  import { baseOf } from './customization.js';
7
7
  export const ROLES = ['implementer', 'reviewer', 'tester', 'analyst'];
8
- export const ROLE_AGENTS = ['main', 'reviewer', 'qa'];
8
+ export const ROLE_AGENTS = ['main', 'reviewer', 'qa', 'worker'];
9
+ /**
10
+ * The built-in worker roles (decision 100): a team gives them a stage under `stages` and
11
+ * skills under `roles`, like a role of the project's own.
12
+ */
13
+ export const WORKER_ROLES = {
14
+ architect: { agent: 'worker', tier: 'deep', description: 'designs how the approved spec is built and splits it into tasks' },
15
+ developer: { agent: 'worker', tier: 'balanced', description: 'builds one task of the design, with its tests' },
16
+ };
17
+ /** The stages a team may give to a role, per built-in workflow: those where the main agent writes. */
18
+ export const STAGE_KEYS = {
19
+ feature: ['spec', 'design', 'build'],
20
+ fix: ['fix'],
21
+ map: ['map'],
22
+ discovery: ['proposal'],
23
+ };
24
+ /** The worker agent of a tier. */
25
+ export function workerAgentName(tier) {
26
+ return tier === 'deep' ? 'agjan-worker-deep' : 'agjan-worker';
27
+ }
9
28
  /** The agent each built-in role reaches; implementer and analyst are the main agent in different workflows. */
10
29
  const BUILT_IN_AGENT = { implementer: 'main', analyst: 'main', reviewer: 'reviewer', tester: 'qa' };
11
30
  /** The built-in roles a workflow needs. */
@@ -16,7 +35,42 @@ const ROLES_OF = {
16
35
  discovery: ['analyst', 'reviewer'],
17
36
  };
18
37
  const ROLE_SKILLS = ['cap-developer', 'fiori-developer', 'btp-architect'];
38
+ const DEVELOPERS = ['backend-developer', 'ui-developer'];
39
+ /**
40
+ * The built-in teams (decision 99): stack-neutral ones first, so a project without a
41
+ * `team` setting starts with them; the SAP BTP ones, which the sap-btp preset makes the
42
+ * defaults.
43
+ */
19
44
  export const BUILT_IN_TEAMS = {
45
+ delivery: {
46
+ description: 'Implements a feature on any stack: an architect agent designs it, developer agents build each task.',
47
+ workflows: ['feature'],
48
+ stages: { design: 'architect', build: 'developer' },
49
+ roles: {
50
+ implementer: { skills: ['solution-architect', 'technical-architect', ...DEVELOPERS] },
51
+ architect: { skills: ['technical-architect'] },
52
+ developer: { skills: DEVELOPERS },
53
+ reviewer: { skills: ['solution-reviewer', 'technical-architect', ...DEVELOPERS] },
54
+ tester: { skills: ['qa-tester'] },
55
+ },
56
+ },
57
+ maintenance: {
58
+ description: 'Fixes a bounded defect, and maps an existing application, on any stack.',
59
+ workflows: ['fix', 'map'],
60
+ roles: {
61
+ implementer: { skills: DEVELOPERS },
62
+ analyst: { skills: ['technical-architect', ...DEVELOPERS] },
63
+ reviewer: { skills: ['solution-reviewer', ...DEVELOPERS] },
64
+ },
65
+ },
66
+ advisory: {
67
+ description: 'Explores a question and recommends an option: build or reuse, integration, feasibility.',
68
+ workflows: ['discovery'],
69
+ roles: {
70
+ analyst: { skills: ['solution-architect', 'technical-architect'] },
71
+ reviewer: { skills: ['solution-reviewer', 'solution-architect'] },
72
+ },
73
+ },
20
74
  'sap-delivery': {
21
75
  description: 'Implements a business feature on SAP BTP: CAP, Fiori elements and UI5, BTP services.',
22
76
  workflows: ['feature'],
@@ -47,11 +101,47 @@ export const BUILT_IN_TEAMS = {
47
101
  /** The built-in teams with the imported ones (loadConfig puts them in) and the project's own on top. */
48
102
  export function allTeams(config) {
49
103
  const defined = { ...BUILT_IN_TEAMS, ...(config.teams ?? {}) };
50
- return Object.fromEntries(Object.entries(defined).map(([name, team]) => [name, { description: team.description, workflows: team.workflows, roles: team.roles ?? {} }]));
104
+ return Object.fromEntries(Object.entries(defined).map(([name, team]) => [name, {
105
+ description: team.description,
106
+ workflows: team.workflows,
107
+ roles: team.roles ?? {},
108
+ ...(team.stages && Object.keys(team.stages).length ? { stages: team.stages } : {}),
109
+ }]));
110
+ }
111
+ /** A role's definition: a built-in one's, else the project's under `roles`. */
112
+ export function roleDefinition(config, role) {
113
+ const builtIn = BUILT_IN_AGENT[role];
114
+ if (builtIn)
115
+ return { agent: builtIn };
116
+ return WORKER_ROLES[role] ?? config.roles?.[role] ?? null;
51
117
  }
52
118
  /** The agent a role reaches: a built-in role's, or the one its definition under `roles` names. */
53
119
  export function roleAgent(config, role) {
54
- return BUILT_IN_AGENT[role] ?? config.roles?.[role]?.agent ?? null;
120
+ return roleDefinition(config, role)?.agent ?? null;
121
+ }
122
+ /** The stage key a unit's stage or log stage maps to: Proposal is `proposal`, discover's `proposal`. */
123
+ export function stageKey(stage) {
124
+ const key = stage.toLowerCase();
125
+ return key === 'discover' ? 'proposal' : key;
126
+ }
127
+ /** The role a team gives a stage, with its agent, or null when the workflow's own role does it. */
128
+ export function stageOwner(config, team, stage) {
129
+ const key = stageKey(stage);
130
+ const role = team?.stages?.[key];
131
+ if (!team || !role)
132
+ return null;
133
+ const def = roleDefinition(config, role);
134
+ if (!def || (def.agent !== 'main' && def.agent !== 'worker'))
135
+ return null;
136
+ const what = team.roles[role] ?? { skills: [] };
137
+ return {
138
+ stage: key,
139
+ role,
140
+ agent: def.agent,
141
+ ...(def.agent === 'worker' ? { worker: workerAgentName(def.tier) } : {}),
142
+ skills: what.skills ?? [],
143
+ ...(what.instructions?.trim() ? { instructions: what.instructions.trim() } : {}),
144
+ };
55
145
  }
56
146
  /**
57
147
  * The roles an agent works as in a workflow, with their skills: the built-in role first (the
@@ -117,22 +207,39 @@ export function teamProblems(root, config, name, kind) {
117
207
  if (kind && !serves(config, team, kind))
118
208
  problems.push(`team '${name}' does not serve the ${WORKFLOWS[kind]?.name ?? kind} workflow (it serves: ${team.workflows.join(', ')})`);
119
209
  const custom = Object.keys(config.roles ?? {});
210
+ const known = [...ROLES, ...Object.keys(WORKER_ROLES), ...custom];
120
211
  for (const [role, what] of Object.entries(team.roles)) {
121
212
  const agent = roleAgent(config, role);
122
213
  if (!agent)
123
- problems.push(`team '${name}': unknown role '${role}' (roles: ${[...ROLES, ...custom].join(', ')}; or define it under "roles")`);
214
+ problems.push(`team '${name}': unknown role '${role}' (roles: ${known.join(', ')}; or define it under "roles")`);
124
215
  for (const skill of what.skills ?? []) {
125
216
  if (!existsSync(join(root, '.claude', 'skills', skill, 'SKILL.md')))
126
217
  problems.push(`team '${name}', ${role}: no skill '${skill}' in .claude/skills/`);
127
218
  }
219
+ // A worker role works only through a stage the team gives it.
220
+ if (agent === 'worker' && !Object.values(team.stages ?? {}).includes(role))
221
+ problems.push(`team '${name}', ${role}: a worker role needs a stage under "stages" (one of ${stageKeys(config, team).join(', ')})`);
128
222
  // A role whose agent has no step in any of the team's workflows would never be used.
129
- if (agent && !ROLES.includes(role) && !(team.workflows ?? []).some((w) => WORKFLOWS[baseOf(config, w) ?? '']?.track.some((t) => t.steps.some((s) => s.actor === agent)))) {
223
+ if (agent && agent !== 'worker' && !ROLES.includes(role) && !(team.workflows ?? []).some((w) => WORKFLOWS[baseOf(config, w) ?? '']?.track.some((t) => t.steps.some((s) => s.actor === agent)))) {
130
224
  problems.push(`team '${name}', ${role}: its agent (${agent}) has no step in ${team.workflows.join(', ')}`);
131
225
  }
132
226
  }
133
227
  for (const role of custom)
134
- if (ROLES.includes(role))
228
+ if (ROLES.includes(role) || WORKER_ROLES[role])
135
229
  problems.push(`roles: '${role}' is a built-in role`);
230
+ // The stages: one the team's workflows have, given to a role of the main agent or a worker with skills in the team.
231
+ const stages = stageKeys(config, team);
232
+ for (const [stage, role] of Object.entries(team.stages ?? {})) {
233
+ if (!stages.includes(stage))
234
+ problems.push(`team '${name}': stages.${stage} is not a stage its workflows give a role (${stages.join(', ') || 'none'})`);
235
+ const agent = roleAgent(config, role);
236
+ if (!agent)
237
+ problems.push(`team '${name}': stages.${stage}: unknown role '${role}'`);
238
+ else if (agent !== 'main' && agent !== 'worker')
239
+ problems.push(`team '${name}': stages.${stage}: role '${role}' reaches the ${agent} agent; a stage needs the main agent or a worker`);
240
+ else if (!team.roles[role]?.skills?.length)
241
+ problems.push(`team '${name}': stages.${stage}: role '${role}' has no skills in the team`);
242
+ }
136
243
  for (const w of team.workflows ?? []) {
137
244
  for (const role of ROLES_OF[baseOf(config, w) ?? ''] ?? []) {
138
245
  if (!team.roles[role]?.skills?.length)
@@ -141,6 +248,10 @@ export function teamProblems(root, config, name, kind) {
141
248
  }
142
249
  return problems;
143
250
  }
251
+ /** The stages a team's workflows give a role. */
252
+ function stageKeys(config, team) {
253
+ return [...new Set((team.workflows ?? []).flatMap((w) => STAGE_KEYS[baseOf(config, w) ?? ''] ?? []))];
254
+ }
144
255
  /** The roles an agent works as, as it reads them: per role, the skill files, then the instructions. */
145
256
  export function roleText(config, team, roles) {
146
257
  if (!roles.length)
package/dist/terminal.js CHANGED
@@ -142,6 +142,9 @@ async function pickOnTerminal(question, picker) {
142
142
  }
143
143
  finally {
144
144
  write('\x1b[?25h');
145
+ // Back to line mode: a question after the picker reads Enter as the end of its line.
146
+ if (input.isRaw)
147
+ input.setRawMode(false);
145
148
  input.destroy();
146
149
  if (tty.output !== tty.input)
147
150
  closeSync(tty.output);
package/dist/validate.js CHANGED
@@ -10,8 +10,8 @@ export function documentProblems(feature) {
10
10
  return problems;
11
11
  }
12
12
  /**
13
- * Consistency between design, tasks, spec and configuration: areas exist and are
14
- * enabled, every task belongs to an approved area, every `covers` id is a spec AC, and
13
+ * Consistency between design, tasks, spec and configuration: areas exist in the
14
+ * project, every task belongs to an approved area, every `covers` id is a spec AC, and
15
15
  * every AC is covered by at least one task.
16
16
  */
17
17
  export function designProblems(feature, config) {
@@ -22,7 +22,7 @@ export function designProblems(feature, config) {
22
22
  for (const id of feature.design.parsed.areas) {
23
23
  const area = resolveArea(config, id);
24
24
  if (!area)
25
- problems.push(`design.md: area '${id}' is not an area of the enabled domains (${config.domains.join(', ')})`);
25
+ problems.push(`design.md: area '${id}' is not an area of this project (${Object.keys(config.areas).join(', ')})`);
26
26
  else
27
27
  designAreas.add(area.id);
28
28
  }
package/dist/worker.js ADDED
@@ -0,0 +1,120 @@
1
+ import { mkdirSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { AgjanError } from './errors.js';
4
+ import { FEATURES_DIR } from './feature.js';
5
+ import { PROJECT_MD } from './fix.js';
6
+ import { resolveArea } from './config.js';
7
+ import { readFix } from './commands/fix.js';
8
+ import { STAGE_KEYS, roleDefinition, stageOwner, unitTeam } from './teams.js';
9
+ /**
10
+ * Worker agents (decision 100). A team gives a stage (spec, design, build, fix, map,
11
+ * proposal) to a role whose agent is a worker: the main agent starts `agjan-worker` or
12
+ * `agjan-worker-deep`, which calls `role_context` for its role, its skills, its inputs and the
13
+ * paths it may write, does the stage's writing and hands back a summary or its questions. The
14
+ * main agent keeps the conversation with the user, the reviews, the gates and the commits.
15
+ *
16
+ * `role_context` writes `.agjan/worker-guard.json`: the guard hook denies a worker's file edits
17
+ * outside those paths where the host names the calling agent (Claude Code).
18
+ */
19
+ export const WORKER_GUARD = '.agjan/worker-guard.json';
20
+ /** What each stage asks of the worker, in plain words. */
21
+ const JOB = {
22
+ spec: 'Write `spec.md` from the request below: what and why, the users and roles, the scope, and testable acceptance criteria with their unhappy paths. Keep the template\'s headings.',
23
+ design: 'Write `design.md` (areas, decisions with what, why and the alternative, answers to the open technical questions) and `tasks.md` (tasks with their area, the ACs they cover and every path needed to implement and test them). Keep the templates\' headings and the YAML block of tasks.md.',
24
+ build: 'Build the task below: change only its paths and the implicit files of its area, write a test per AC named with the AC id, and run the area\'s test command until it passes.',
25
+ fix: 'Fix the defect below in the existing files, within the fix limits: the smallest change that fixes it, with a test where the project has tests.',
26
+ map: 'Describe the application in `agjan-docs/project.md`: one to two pages under the template\'s headings, with pointers to real files instead of copies.',
27
+ proposal: 'Write `proposal.md` for the question it states: context, at least two real options with their costs and risks, a recommendation, open questions and the sources you used.',
28
+ };
29
+ /** The paths a stage may write and those it never may. */
30
+ function scope(config, unit, stage, taskId) {
31
+ const dir = `${FEATURES_DIR}/${unit.slug}`;
32
+ if (stage === 'spec')
33
+ return { allow: [`${dir}/spec.md`], deny: [] };
34
+ if (stage === 'design')
35
+ return { allow: [`${dir}/design.md`, `${dir}/tasks.md`], deny: [] };
36
+ if (stage === 'map')
37
+ return { allow: [PROJECT_MD], deny: [] };
38
+ if (stage === 'proposal')
39
+ return { allow: [`${dir}/proposal.md`], deny: [] };
40
+ if (stage === 'fix')
41
+ return { allow: ['**'], deny: [`${FEATURES_DIR}/**`, ...config.fix.protected, ...config.risk_paths] };
42
+ // build: one task's paths, its area's implicit files and the approved amendments.
43
+ if (!taskId)
44
+ throw new AgjanError('role_context: the build stage needs a task (task: "T1")');
45
+ const task = unit.tasks?.parsed.tasks.find((t) => t.id === taskId);
46
+ if (!task)
47
+ throw new AgjanError(`role_context: no task '${taskId}' in tasks.md (tasks: ${(unit.tasks?.parsed.tasks ?? []).map((t) => t.id).join(', ') || 'none'})`);
48
+ const area = resolveArea(config, task.area ?? '');
49
+ const amended = unit.amendments.filter((a) => a.status === 'approved').flatMap((a) => a.paths);
50
+ return { allow: [...task.paths, ...(area ? config.scope.implicit[area.name] ?? [] : []), ...amended], deny: [`${FEATURES_DIR}/**`], task };
51
+ }
52
+ /**
53
+ * The skills of a build task's worker: the role's, without the skills of the project's other
54
+ * areas, plus the task area's own. A role's general skills (a company standard) stay.
55
+ */
56
+ export function taskSkills(config, owner, areaName) {
57
+ const area = areaName ? resolveArea(config, areaName) : null;
58
+ if (!area)
59
+ return owner.skills;
60
+ const others = new Set(Object.values(config.areas).filter((a) => a.name !== area.name).flatMap((a) => a.skills));
61
+ return [...new Set([...owner.skills.filter((s) => !others.has(s) || area.skills.includes(s)), ...area.skills])];
62
+ }
63
+ function section(title, body) {
64
+ return `## ${title}\n\n${body.trim()}\n`;
65
+ }
66
+ /**
67
+ * The worker's input for one stage of a unit (`role_context`): its role and skills, what to
68
+ * do, what to read, what it may write and how to hand back. Writes the worker guard.
69
+ */
70
+ export function createWorkerContext(root, config, unit, { stage, task: taskId }) {
71
+ const stages = STAGE_KEYS[unit.kind];
72
+ if (!stages.includes(stage))
73
+ throw new AgjanError(`role_context: a ${unit.kind} has no stage '${stage}' for a worker (stages: ${stages.join(', ')})`);
74
+ // A feature's stages come in order: no design before the spec is approved, no build before the design.
75
+ if (unit.kind === 'feature' && unit.stage !== stage) {
76
+ throw new AgjanError(`role_context: ${unit.key} is at the ${unit.stage} stage, not ${stage}`);
77
+ }
78
+ const team = unitTeam(config, unit.approvals.feature.team);
79
+ const owner = stageOwner(config, team?.team ?? null, stage);
80
+ if (!team || !owner || owner.agent !== 'worker') {
81
+ throw new AgjanError(`role_context: the team of ${unit.key} (${team?.name ?? 'none'}) gives the ${stage} stage to no worker; the main agent does it`);
82
+ }
83
+ const { allow, deny, task } = scope(config, unit, stage, taskId);
84
+ const skills = task ? taskSkills(config, owner, task.area) : owner.skills;
85
+ const dir = `${FEATURES_DIR}/${unit.slug}`;
86
+ const description = roleDefinition(config, owner.role)?.description;
87
+ const reading = [];
88
+ if (unit.spec && stage !== 'spec')
89
+ reading.push(`- \`${dir}/spec.md\` (approved)`);
90
+ if (stage === 'spec' && unit.spec)
91
+ reading.push(`- \`${dir}/spec.md\` (the draft so far)`);
92
+ if (stage === 'build')
93
+ reading.push(`- \`${dir}/design.md\` and \`${dir}/tasks.md\` (approved)`);
94
+ if (stage === 'design' && unit.design)
95
+ reading.push(`- \`${dir}/design.md\` and \`${dir}/tasks.md\` (the draft so far)`);
96
+ if (stage === 'proposal')
97
+ reading.push(`- \`${dir}/proposal.md\` (the question and the draft so far)`);
98
+ reading.push(`- \`${PROJECT_MD}\` (the application), when it exists`);
99
+ reading.push('- `npx agjan areas`: the project\'s areas and their skills');
100
+ const request = stage === 'fix' ? readFix(unit)?.what : undefined;
101
+ const parts = [
102
+ `# agjan worker: ${stage} of ${unit.key}${task ? `, task ${task.id}` : ''}\n`,
103
+ section('Your role', `${owner.role}${description ? `: ${description}` : ''}, in team ${team.name}.${owner.instructions ? `\n\n${owner.instructions}` : ''}`),
104
+ section('Your skills', skills.length ? skills.map((s) => `- \`.claude/skills/${s}/SKILL.md\` (and the references its table names for your topic)`).join('\n') : '(none: follow the project\'s conventions)'),
105
+ section('Your job', JOB[stage]),
106
+ ...(task ? [section(`Task ${task.id}: ${task.title}`, `- area: ${task.area}\n- covers: ${task.covers.join(', ')}\n- paths: ${task.paths.map((p) => `\`${p}\``).join(', ')}${task.verify ? `\n- verify: \`${task.verify}\`` : ''}\n- the area's test command: \`${config.verify[task.area]?.test ?? 'npm test'}\``)] : []),
107
+ ...(request ? [section('The defect', request)] : []),
108
+ section('Read', reading.join('\n')),
109
+ section('You may write', `${allow.map((p) => `- \`${p}\``).join('\n')}${deny.length ? `\n\nNever: ${deny.map((p) => `\`${p}\``).join(', ')}.` : ''}\n\nAnything else is out of your scope: if the work needs another file, stop and say which and why.`),
110
+ section('Hand back', [
111
+ 'You work alone: you cannot ask the user. When you need a decision you cannot take from the material above, stop and end your answer with a section `QUESTIONS:` that lists each question with the options you see. The main agent asks the user and starts you again with the answers.',
112
+ 'Otherwise end with a short summary: what you wrote or changed (files), what you ran and its result, and anything the reviewer should know.',
113
+ 'Never run `agjan approve`, `review`, `log`, `amend`, `new` or other commands that record; never commit, push or switch branches: the main agent does that after you.',
114
+ ].join('\n\n')),
115
+ ];
116
+ const guard = { unit: unit.slug, stage, ...(task ? { task: task.id } : {}), allow, deny };
117
+ mkdirSync(join(root, '.agjan'), { recursive: true });
118
+ writeFileSync(join(root, WORKER_GUARD), `${JSON.stringify(guard, null, 2)}\n`);
119
+ return { text: parts.join('\n'), guard };
120
+ }