specdojo 0.1.0

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.
package/dist/exec.js ADDED
@@ -0,0 +1,447 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { acquireSchedulerLock, buildEvent, canBlockTask, canCancelTask, canClaimTask, canCompleteTask, canUnblockTask, collectRepeatable, computeReadyIds, findDoingTasksForActor, foldEventsToState, readAllEventFiles, releaseSchedulerLock, schedulerLockPath, writeEventFile, } from './exec-events.js';
6
+ import { activateResolvedProjectPaths, eventsDirForProject, generatedDirForProject, resolveProjectPaths, } from './exec-project.js';
7
+ import { assertValidActor, loadConfig, loadMemberRoster, } from './specdojo-config.js';
8
+ import { buildScheduleIndex, computeCpm, exitWithCode, printValidateResult, selectNextTask, validateAll, writeCpmFiles, writeGeneratedCore, writeScheduleHashAndDiff, } from './exec-schedule.js';
9
+ import { nowUtcIsoSeconds, requireNonEmpty, safeSlug, tsForFilenameUtc } from './exec-shared.js';
10
+ const KNOWN_OWNER_LABELS = ['PO', 'BA', 'ARC', 'QE'];
11
+ const KNOWN_OWNER_LABELS_TEXT = KNOWN_OWNER_LABELS.join('|');
12
+ function addProjectOptions(cmd) {
13
+ return cmd.option('--project <projectId>', 'Project id in specdojo.config.json (e.g. shj-0001)');
14
+ }
15
+ function addLockOptions(cmd) {
16
+ return cmd
17
+ .option('--allow-multiple-doing', 'Allow this actor to hold multiple doing tasks', false)
18
+ .option('--lock-timeout-ms <ms>', 'Lock acquisition timeout in ms', '10000')
19
+ .option('--lock-stale-ms <ms>', 'Lock stale threshold in ms', '300000');
20
+ }
21
+ function addOwnerOptions(cmd) {
22
+ return cmd
23
+ .option('--owner <owner>', `Planned owner label for assignment checks (${KNOWN_OWNER_LABELS_TEXT}; defaults to SPECDOJO_OWNER or actor)`)
24
+ .option('--allow-owner-mismatch', 'Allow claiming a task assigned to a different owner', false);
25
+ }
26
+ function addCommonAddOptions(cmd) {
27
+ addProjectOptions(cmd);
28
+ return cmd
29
+ .requiredOption('--task <taskId>', 'Task/Milestone ID')
30
+ .requiredOption('--by <actor>', 'Actor (human/agent)')
31
+ .requiredOption('--msg <message>', 'Short message')
32
+ .option('--run-id <id>', 'Correlation id')
33
+ .option('--ref <k=v...>', 'refs key=value (repeatable)', collectRepeatable, [])
34
+ .option('--meta <k=v...>', 'meta key=value (repeatable)', collectRepeatable, []);
35
+ }
36
+ function resolveProjectContext(opts) {
37
+ const resolvedPaths = resolveProjectPaths({ project: opts.project });
38
+ activateResolvedProjectPaths(resolvedPaths);
39
+ return resolvedPaths;
40
+ }
41
+ function loadRosterForOpts(opts) {
42
+ const { config, configPath } = loadConfig();
43
+ if (!config)
44
+ return null;
45
+ const projectId = opts.project?.trim() ||
46
+ process.env.SPECDOJO_PROJECT?.trim() ||
47
+ Object.keys(config.projects)[0] ||
48
+ '';
49
+ const project = config.projects[projectId];
50
+ if (!project)
51
+ return null;
52
+ const baseDir = dirname(configPath);
53
+ return loadMemberRoster(baseDir, project);
54
+ }
55
+ function resolveClaimOwner(opts, actor) {
56
+ const cliOwner = typeof opts.owner === 'string' ? opts.owner.trim().toUpperCase() : '';
57
+ const envOwner = typeof process.env.SPECDOJO_OWNER === 'string'
58
+ ? process.env.SPECDOJO_OWNER.trim().toUpperCase()
59
+ : '';
60
+ if (cliOwner && !KNOWN_OWNER_LABELS.includes(cliOwner)) {
61
+ throw new Error(`Invalid --owner value: ${cliOwner}. Use one of: ${KNOWN_OWNER_LABELS_TEXT}.`);
62
+ }
63
+ if (envOwner && !KNOWN_OWNER_LABELS.includes(envOwner)) {
64
+ throw new Error(`Invalid SPECDOJO_OWNER value: ${envOwner}. Use one of: ${KNOWN_OWNER_LABELS_TEXT}.`);
65
+ }
66
+ return cliOwner || envOwner || actor;
67
+ }
68
+ function printCommandError(error, fail = true) {
69
+ const message = error instanceof Error ? error.message : String(error);
70
+ process.stdout.write(message + '\n');
71
+ if (fail)
72
+ exitWithCode(false);
73
+ else
74
+ process.exitCode = 1;
75
+ }
76
+ function runTaskCatalogBuild(schedulePath, executionPath) {
77
+ const currentFileDir = dirname(fileURLToPath(import.meta.url));
78
+ const scriptPath = resolve(currentFileDir, '../../docs/src/gen-task-catalog.ts');
79
+ const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
80
+ const result = spawnSync(npxCmd, ['tsx', scriptPath, '--schedule-path', schedulePath, '--execution-path', executionPath], {
81
+ encoding: 'utf8',
82
+ env: process.env,
83
+ });
84
+ if (result.status !== 0) {
85
+ const stderr = (result.stderr ?? '').trim();
86
+ const stdout = (result.stdout ?? '').trim();
87
+ const details = [stdout, stderr].filter(Boolean).join('\n');
88
+ throw new Error(`task-catalog generation failed: ${scriptPath}` + (details ? `\n${details}` : ''));
89
+ }
90
+ }
91
+ function runAgentBriefBuild(schedulePath, executionPath, cliProject = '') {
92
+ const currentFileDir = dirname(fileURLToPath(import.meta.url));
93
+ const scriptPath = resolve(currentFileDir, '../../docs/src/gen-agent-briefs.ts');
94
+ const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
95
+ const result = spawnSync(npxCmd, [
96
+ 'tsx',
97
+ scriptPath,
98
+ '--schedule-path',
99
+ schedulePath,
100
+ '--execution-path',
101
+ executionPath,
102
+ '--cli-project',
103
+ cliProject,
104
+ ], {
105
+ encoding: 'utf8',
106
+ env: process.env,
107
+ });
108
+ if (result.status !== 0) {
109
+ const stderr = (result.stderr ?? '').trim();
110
+ const stdout = (result.stdout ?? '').trim();
111
+ const details = [stdout, stderr].filter(Boolean).join('\n');
112
+ throw new Error(`agent-brief generation failed: ${scriptPath}` + (details ? `\n${details}` : ''));
113
+ }
114
+ }
115
+ function saveClaimBriefSnapshot(executionPath, taskId, actor, eventTs) {
116
+ const sourcePath = join(executionPath, 'generated', 'agent-briefs', `${taskId}.md`);
117
+ if (!existsSync(sourcePath)) {
118
+ throw new Error(`agent brief source not found for snapshot: ${sourcePath}`);
119
+ }
120
+ const snapshotDir = join(executionPath, 'exec', 'agent-briefs', 'claims', taskId);
121
+ mkdirSync(snapshotDir, { recursive: true });
122
+ const fileName = `${tsForFilenameUtc(eventTs)}--${safeSlug(actor)}.md`;
123
+ copyFileSync(sourcePath, join(snapshotDir, fileName));
124
+ writeClaimBriefSnapshotIndex(executionPath);
125
+ }
126
+ function writeClaimBriefSnapshotIndex(executionPath) {
127
+ const claimsDir = join(executionPath, 'exec', 'agent-briefs', 'claims');
128
+ mkdirSync(claimsDir, { recursive: true });
129
+ const taskDirs = readdirSync(claimsDir)
130
+ .map(name => ({ name, path: join(claimsDir, name) }))
131
+ .filter(entry => statSync(entry.path).isDirectory())
132
+ .sort((a, b) => a.name.localeCompare(b.name));
133
+ const lines = [];
134
+ lines.push('# Claim Brief Snapshot Index');
135
+ lines.push('');
136
+ lines.push('claim 時点で固定保存した Agent ブリーフの一覧。');
137
+ lines.push('');
138
+ lines.push('| task_id | snapshots | latest | latest_file |');
139
+ lines.push('|---|---:|---|---|');
140
+ for (const taskDir of taskDirs) {
141
+ const files = readdirSync(taskDir.path)
142
+ .filter(name => name.endsWith('.md'))
143
+ .sort((a, b) => a.localeCompare(b));
144
+ const latest = files.at(-1);
145
+ if (!latest)
146
+ continue;
147
+ lines.push(`| ${taskDir.name} | ${files.length} | ${latest.replace(/\.md$/, '')} | [${latest}](./${taskDir.name}/${latest}) |`);
148
+ }
149
+ lines.push('');
150
+ writeFileSync(join(claimsDir, 'index.md'), `${lines.join('\n')}\n`, 'utf8');
151
+ }
152
+ function loadValidatedExecState(projectPath) {
153
+ const res = validateAll(projectPath);
154
+ if (!res.ok) {
155
+ printValidateResult(res);
156
+ exitWithCode(false);
157
+ return null;
158
+ }
159
+ const schedule = buildScheduleIndex(projectPath);
160
+ const events = readAllEventFiles(projectPath);
161
+ const snapshot = foldEventsToState(events, schedule, projectPath);
162
+ return { schedule, events, snapshot };
163
+ }
164
+ function ensureActorCanClaimNext(snapshot, actor, allowMultipleDoing) {
165
+ const doingTasks = findDoingTasksForActor(snapshot, actor);
166
+ if (allowMultipleDoing || doingTasks.length === 0)
167
+ return true;
168
+ process.stdout.write(`Actor ${actor} already has doing task(s): ${doingTasks.join(', ')}\n` +
169
+ `Use --allow-multiple-doing to override.\n`);
170
+ exitWithCode(false);
171
+ return false;
172
+ }
173
+ function runSimpleEventCommand(opts, type) {
174
+ try {
175
+ const { schedulePath } = resolveProjectContext(opts);
176
+ const actor = requireNonEmpty('by', opts.by);
177
+ assertValidActor(actor, loadRosterForOpts(opts));
178
+ const event = buildEvent(type, opts);
179
+ const out = writeEventFile(schedulePath, event);
180
+ process.stdout.write(out + '\n');
181
+ exitWithCode(true);
182
+ }
183
+ catch (error) {
184
+ printCommandError(error, false);
185
+ }
186
+ }
187
+ function runLockedEventCommand(opts, action) {
188
+ let lockDir = '';
189
+ try {
190
+ const { schedulePath, executionPath } = resolveProjectContext(opts);
191
+ const actor = requireNonEmpty('by', opts.by);
192
+ assertValidActor(actor, loadRosterForOpts(opts));
193
+ const taskId = requireNonEmpty('task', opts.task);
194
+ const allowMultipleDoing = !!opts.allowMultipleDoing;
195
+ const lockTimeoutMs = Number(opts.lockTimeoutMs);
196
+ const lockStaleMs = Number(opts.lockStaleMs);
197
+ lockDir = acquireSchedulerLock(schedulePath, { actor, lockTimeoutMs, lockStaleMs });
198
+ const state = loadValidatedExecState(schedulePath);
199
+ if (!state)
200
+ return;
201
+ if (action.requireSingleDoing &&
202
+ !ensureActorCanClaimNext(state.snapshot, actor, allowMultipleDoing)) {
203
+ return;
204
+ }
205
+ const check = action.check(state, taskId, actor, opts);
206
+ if (!check.ok) {
207
+ process.stdout.write(`Cannot ${action.type} ${taskId}: ${check.reason}\n`);
208
+ exitWithCode(false);
209
+ return;
210
+ }
211
+ const event = buildEvent(action.type, opts);
212
+ if (action.type === 'claim') {
213
+ const plannedOwner = state.schedule.nodes.get(taskId)?.owner;
214
+ const claimOwner = resolveClaimOwner(opts, actor);
215
+ const cpm = computeCpm(state.schedule, schedulePath);
216
+ writeGeneratedCore(schedulePath, state.events, state.schedule, cpm);
217
+ writeScheduleHashAndDiff(schedulePath, state.schedule);
218
+ writeCpmFiles(schedulePath, cpm, state.snapshot);
219
+ runTaskCatalogBuild(schedulePath, executionPath);
220
+ runAgentBriefBuild(schedulePath, executionPath, opts.project ?? process.env.SPECDOJO_PROJECT ?? '');
221
+ saveClaimBriefSnapshot(executionPath, taskId, actor, event.ts);
222
+ event.meta = {
223
+ ...(event.meta ?? {}),
224
+ claim_owner: claimOwner,
225
+ };
226
+ if (plannedOwner)
227
+ event.meta.planned_owner = plannedOwner;
228
+ if (plannedOwner && claimOwner !== plannedOwner && opts.allowOwnerMismatch) {
229
+ event.meta.owner_override = true;
230
+ }
231
+ }
232
+ const out = writeEventFile(schedulePath, event);
233
+ process.stdout.write(out + '\n');
234
+ exitWithCode(true);
235
+ }
236
+ catch (error) {
237
+ printCommandError(error);
238
+ }
239
+ finally {
240
+ if (lockDir) {
241
+ try {
242
+ releaseSchedulerLock(lockDir);
243
+ }
244
+ catch { }
245
+ }
246
+ }
247
+ }
248
+ export function registerExecCommands(program) {
249
+ const exec = program.command('exec').description('Execution helpers');
250
+ const lockedActions = {
251
+ claim: {
252
+ type: 'claim',
253
+ requireSingleDoing: true,
254
+ check: ({ schedule, snapshot }, taskId, actor, opts) => canClaimTask(schedule, snapshot, taskId, resolveClaimOwner(opts, actor), !!opts.allowOwnerMismatch),
255
+ },
256
+ complete: {
257
+ type: 'complete',
258
+ check: ({ schedule, snapshot }, taskId, actor) => canCompleteTask(schedule, snapshot, taskId, actor),
259
+ },
260
+ block: {
261
+ type: 'block',
262
+ check: ({ schedule, snapshot }, taskId, actor) => canBlockTask(schedule, snapshot, taskId, actor),
263
+ },
264
+ unblock: {
265
+ type: 'unblock',
266
+ check: ({ schedule, snapshot }, taskId) => canUnblockTask(schedule, snapshot, taskId),
267
+ },
268
+ cancel: {
269
+ type: 'cancel',
270
+ check: ({ schedule, snapshot }, taskId, actor) => canCancelTask(schedule, snapshot, taskId, actor),
271
+ },
272
+ };
273
+ const types = [
274
+ 'claim',
275
+ 'note',
276
+ 'block',
277
+ 'unblock',
278
+ 'complete',
279
+ 'cancel',
280
+ 'link',
281
+ 'estimate',
282
+ ];
283
+ for (const t of types) {
284
+ const cmd = exec.command(t).description(`Write ${t} event JSON into exec/events/ (UTC)`);
285
+ addCommonAddOptions(cmd);
286
+ if (t in lockedActions)
287
+ addLockOptions(cmd);
288
+ if (t === 'claim')
289
+ addOwnerOptions(cmd);
290
+ if (t in lockedActions) {
291
+ cmd.action(opts => runLockedEventCommand(opts, lockedActions[t]));
292
+ }
293
+ else {
294
+ cmd.action(opts => runSimpleEventCommand(opts, t));
295
+ }
296
+ }
297
+ const vcmd = exec.command('validate').description('Validate schedule + events');
298
+ addProjectOptions(vcmd);
299
+ vcmd.action(opts => {
300
+ try {
301
+ const { schedulePath } = resolveProjectContext(opts);
302
+ const res = validateAll(schedulePath);
303
+ printValidateResult(res);
304
+ exitWithCode(res.ok);
305
+ }
306
+ catch (error) {
307
+ printCommandError(error, false);
308
+ }
309
+ });
310
+ const bcmd = exec.command('build').description('Generate all files under generated/');
311
+ addProjectOptions(bcmd);
312
+ bcmd.action(opts => {
313
+ try {
314
+ const { schedulePath, executionPath } = resolveProjectContext(opts);
315
+ const res = validateAll(schedulePath);
316
+ printValidateResult(res);
317
+ if (!res.ok) {
318
+ exitWithCode(false);
319
+ return;
320
+ }
321
+ const schedule = buildScheduleIndex(schedulePath);
322
+ const events = readAllEventFiles(schedulePath);
323
+ const cpm = computeCpm(schedule, schedulePath);
324
+ const snapshot = writeGeneratedCore(schedulePath, events, schedule, cpm);
325
+ writeScheduleHashAndDiff(schedulePath, schedule);
326
+ writeCpmFiles(schedulePath, cpm, snapshot);
327
+ runTaskCatalogBuild(schedulePath, executionPath);
328
+ runAgentBriefBuild(schedulePath, executionPath, opts.project ?? process.env.SPECDOJO_PROJECT ?? '');
329
+ process.stdout.write(`\nGenerated: ${generatedDirForProject(schedulePath)}\n`);
330
+ exitWithCode(true);
331
+ }
332
+ catch (error) {
333
+ printCommandError(error, false);
334
+ }
335
+ });
336
+ const scmd = exec
337
+ .command('scheduler')
338
+ .description('Auto-claim next task safely (with project-level lock).');
339
+ addProjectOptions(scmd);
340
+ scmd.requiredOption('--by <actor>', 'Actor (agent name)');
341
+ addOwnerOptions(scmd);
342
+ scmd.option('--strategy <strategy>', 'critical-first|fifo', 'critical-first');
343
+ scmd.option('--dry-run', 'Do not write; print selected task only', false);
344
+ scmd.option('--msg <message>', 'Claim message', 'auto-claim');
345
+ addLockOptions(scmd);
346
+ scmd.action(opts => {
347
+ let lockDir = '';
348
+ try {
349
+ const { schedulePath } = resolveProjectContext(opts);
350
+ const actor = requireNonEmpty('by', opts.by);
351
+ assertValidActor(actor, loadRosterForOpts(opts));
352
+ const strategy = String(opts.strategy);
353
+ const dryRun = !!opts.dryRun;
354
+ const msg = String(opts.msg ?? 'auto-claim');
355
+ const claimOwner = resolveClaimOwner(opts, actor);
356
+ const allowOwnerMismatch = !!opts.allowOwnerMismatch;
357
+ const allowMultipleDoing = !!opts.allowMultipleDoing;
358
+ const lockTimeoutMs = Number(opts.lockTimeoutMs);
359
+ const lockStaleMs = Number(opts.lockStaleMs);
360
+ lockDir = acquireSchedulerLock(schedulePath, { actor, lockTimeoutMs, lockStaleMs });
361
+ const state = loadValidatedExecState(schedulePath);
362
+ if (!state)
363
+ return;
364
+ if (!ensureActorCanClaimNext(state.snapshot, actor, allowMultipleDoing))
365
+ return;
366
+ const ready = computeReadyIds(state.schedule, state.snapshot);
367
+ let cpm = null;
368
+ try {
369
+ cpm = computeCpm(state.schedule, schedulePath);
370
+ }
371
+ catch {
372
+ cpm = null;
373
+ }
374
+ const readyForOwner = ready.filter(taskId => {
375
+ const claimCheck = canClaimTask(state.schedule, state.snapshot, taskId, claimOwner, allowOwnerMismatch);
376
+ return claimCheck.ok;
377
+ });
378
+ const next = selectNextTask(readyForOwner, cpm, strategy);
379
+ if (!next) {
380
+ if (ready.length > 0 && !allowOwnerMismatch) {
381
+ process.stdout.write(`No ready task assigned to owner ${claimOwner}. Use --owner <${KNOWN_OWNER_LABELS_TEXT}>, SPECDOJO_OWNER, or --allow-owner-mismatch.\n`);
382
+ }
383
+ else {
384
+ process.stdout.write('No ready task to claim.\n');
385
+ }
386
+ exitWithCode(true);
387
+ return;
388
+ }
389
+ if (dryRun) {
390
+ process.stdout.write(next + '\n');
391
+ exitWithCode(true);
392
+ return;
393
+ }
394
+ const ev = {
395
+ v: 1,
396
+ ts: nowUtcIsoSeconds(),
397
+ type: 'claim',
398
+ task_id: next,
399
+ by: actor,
400
+ msg,
401
+ meta: {
402
+ claim_owner: claimOwner,
403
+ planned_owner: state.schedule.nodes.get(next)?.owner,
404
+ scheduler_strategy: strategy,
405
+ claimed_via: 'dojo-exec-scheduler',
406
+ },
407
+ };
408
+ if (ev.meta?.planned_owner &&
409
+ ev.meta.claim_owner !== ev.meta.planned_owner &&
410
+ allowOwnerMismatch) {
411
+ ev.meta.owner_override = true;
412
+ }
413
+ const out = writeEventFile(schedulePath, ev);
414
+ process.stdout.write(out + '\n');
415
+ exitWithCode(true);
416
+ }
417
+ catch (error) {
418
+ printCommandError(error);
419
+ }
420
+ finally {
421
+ if (lockDir) {
422
+ try {
423
+ releaseSchedulerLock(lockDir);
424
+ }
425
+ catch {
426
+ // ignore
427
+ }
428
+ }
429
+ }
430
+ });
431
+ const wcmd = exec.command('where').description('Print resolved paths');
432
+ addProjectOptions(wcmd);
433
+ wcmd.action(opts => {
434
+ try {
435
+ const resolvedPaths = resolveProjectContext(opts);
436
+ process.stdout.write(`schedule-path: ${resolvedPaths.schedulePath}\n`);
437
+ process.stdout.write(`execution-path: ${resolvedPaths.executionPath}\n`);
438
+ const projectPath = resolvedPaths.schedulePath;
439
+ process.stdout.write(`exec/events : ${eventsDirForProject(projectPath)}\n`);
440
+ process.stdout.write(`generated : ${generatedDirForProject(projectPath)}\n`);
441
+ process.stdout.write(`scheduler-lock: ${schedulerLockPath(projectPath)}\n`);
442
+ }
443
+ catch (error) {
444
+ printCommandError(error, false);
445
+ }
446
+ });
447
+ }
@@ -0,0 +1,150 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { dirname, resolve } from 'node:path';
3
+ import dotenv from 'dotenv';
4
+ import yaml from 'js-yaml';
5
+ function findUpward(startDir, name) {
6
+ let currentDir = resolve(startDir);
7
+ while (true) {
8
+ const candidate = resolve(currentDir, name);
9
+ if (existsSync(candidate))
10
+ return candidate;
11
+ const parentDir = resolve(currentDir, '..');
12
+ if (parentDir === currentDir)
13
+ return null;
14
+ currentDir = parentDir;
15
+ }
16
+ }
17
+ export function specdojoRootDir() {
18
+ const configPath = findUpward(process.cwd(), 'specdojo.config.json');
19
+ if (configPath)
20
+ return dirname(configPath);
21
+ const gitMarker = findUpward(process.cwd(), '.git');
22
+ if (gitMarker)
23
+ return dirname(gitMarker);
24
+ return process.cwd();
25
+ }
26
+ export function loadEnv() {
27
+ // Load .env from the repository root if present.
28
+ // Safe if missing.
29
+ dotenv.config({ path: resolve(specdojoRootDir(), '.env') });
30
+ }
31
+ export function defaultConfigPath() {
32
+ return resolve(specdojoRootDir(), 'specdojo.config.json');
33
+ }
34
+ export function getProjectSchedulePath(project) {
35
+ return project.schedule_path;
36
+ }
37
+ export function getProjectExecutionPath(project) {
38
+ return project.execution_path;
39
+ }
40
+ export function getProjectMembersPath(project) {
41
+ return project.members_path;
42
+ }
43
+ export function loadMemberRoster(baseDir, project) {
44
+ const membersPath = project.members_path;
45
+ if (!membersPath || !membersPath.trim())
46
+ return null;
47
+ const fullPath = resolve(baseDir, membersPath.trim());
48
+ if (!existsSync(fullPath)) {
49
+ throw new Error(`members_path not found: ${fullPath}`);
50
+ }
51
+ const raw = readFileSync(fullPath, 'utf8');
52
+ const parsed = yaml.load(raw);
53
+ if (!parsed || !Array.isArray(parsed.members)) {
54
+ throw new Error(`Invalid members file: ${fullPath} (expected { members: [...] })`);
55
+ }
56
+ return parsed;
57
+ }
58
+ export function assertValidActor(actor, roster) {
59
+ if (!roster)
60
+ return;
61
+ const known = roster.members.map(m => m.nickname);
62
+ if (!known.includes(actor)) {
63
+ throw new Error(`Unknown actor: "${actor}". Must be one of: ${known.join(', ')}\n` +
64
+ `Register the nickname in members_path file before use.`);
65
+ }
66
+ }
67
+ function isValidProjectConfig(project) {
68
+ if (!project || typeof project !== 'object' || Array.isArray(project))
69
+ return false;
70
+ const candidate = project;
71
+ if (typeof candidate.schedule_path !== 'string' || candidate.schedule_path.trim().length === 0) {
72
+ return false;
73
+ }
74
+ if (typeof candidate.execution_path !== 'string' ||
75
+ candidate.execution_path.trim().length === 0) {
76
+ return false;
77
+ }
78
+ return true;
79
+ }
80
+ export function loadConfig() {
81
+ loadEnv();
82
+ const configPath = defaultConfigPath();
83
+ if (!existsSync(configPath)) {
84
+ return { configPath, config: null };
85
+ }
86
+ const raw = readFileSync(configPath, 'utf8');
87
+ const parsed = JSON.parse(raw);
88
+ if (!parsed || parsed.version !== 1 || typeof parsed.projects !== 'object') {
89
+ throw new Error(`Invalid specdojo.config.json: expected { version: 1, projects: { ... } }`);
90
+ }
91
+ for (const [projectId, project] of Object.entries(parsed.projects)) {
92
+ if (!isValidProjectConfig(project)) {
93
+ throw new Error(`Invalid specdojo.config.json: projects.${projectId} must be { schedule_path, execution_path }`);
94
+ }
95
+ }
96
+ return { configPath, config: parsed };
97
+ }
98
+ export function writeConfig(config) {
99
+ const configPath = defaultConfigPath();
100
+ writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', 'utf8');
101
+ }
102
+ export function registerConfigCommands(program) {
103
+ const cfg = program.command('config').description('Config helpers (specdojo.config.json)');
104
+ cfg
105
+ .command('init')
106
+ .description('Create specdojo.config.json template (does not overwrite existing)')
107
+ .action(() => {
108
+ const { configPath, config } = loadConfig();
109
+ if (config) {
110
+ process.stdout.write(`Already exists: ${configPath}\n`);
111
+ return;
112
+ }
113
+ const template = {
114
+ version: 1,
115
+ projects: {
116
+ 'shj-0001': {
117
+ schedule_path: 'docs/ja/sdh-ja-projects/prj-0001/060-schedule',
118
+ execution_path: 'docs/ja/sdh-ja-projects/prj-0001/070-execution',
119
+ },
120
+ },
121
+ };
122
+ writeConfig(template);
123
+ process.stdout.write(`Created: ${configPath}\n`);
124
+ });
125
+ }
126
+ export function registerProjectCommands(program) {
127
+ const pj = program.command('project').description('Project registry commands');
128
+ pj.command('list')
129
+ .description('List projects from specdojo.config.json')
130
+ .action(() => {
131
+ const { configPath, config } = loadConfig();
132
+ if (!config) {
133
+ process.stdout.write(`No config found: ${configPath}\n`);
134
+ process.stdout.write(`Run: specdojo config init\n`);
135
+ process.exitCode = 1;
136
+ return;
137
+ }
138
+ const entries = Object.entries(config.projects).sort((a, b) => a[0].localeCompare(b[0]));
139
+ if (entries.length === 0) {
140
+ process.stdout.write(`No projects in ${configPath}\n`);
141
+ return;
142
+ }
143
+ for (const [id, project] of entries) {
144
+ const schedulePath = getProjectSchedulePath(project);
145
+ const executionPath = getProjectExecutionPath(project);
146
+ const suffix = executionPath ? `\t${executionPath}` : '';
147
+ process.stdout.write(`${id}\t${schedulePath}${suffix}\n`);
148
+ }
149
+ });
150
+ }
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { registerConfigCommands, registerProjectCommands } from './specdojo-config.js';
4
+ import { registerExecCommands } from './exec.js';
5
+ function main() {
6
+ const program = new Command();
7
+ program.name('specdojo').description('SpecDojo helper CLI').version('0.4.0');
8
+ registerConfigCommands(program);
9
+ registerProjectCommands(program);
10
+ registerExecCommands(program);
11
+ program.parse(process.argv);
12
+ }
13
+ main();
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "specdojo",
3
+ "version": "0.1.0",
4
+ "description": "CLI for SpecDojo specification-driven execution workflows.",
5
+ "license": "MIT",
6
+ "author": "naoji3x",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/specdojo/specdojo-handbook.git",
10
+ "directory": "tools/specdojo"
11
+ },
12
+ "homepage": "https://github.com/specdojo/specdojo-handbook/tree/main/tools/specdojo",
13
+ "bugs": {
14
+ "url": "https://github.com/specdojo/specdojo-handbook/issues"
15
+ },
16
+ "keywords": [
17
+ "specdojo",
18
+ "cli",
19
+ "specification",
20
+ "project-management",
21
+ "workflow"
22
+ ],
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "README.md"
29
+ ],
30
+ "private": false,
31
+ "type": "module",
32
+ "bin": {
33
+ "specdojo": "dist/specdojo.js"
34
+ },
35
+ "scripts": {
36
+ "prepare": "npm run build",
37
+ "build": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\" && tsc -p tsconfig.json",
38
+ "dev": "tsx src/specdojo.ts",
39
+ "start": "node dist/specdojo.js"
40
+ },
41
+ "dependencies": {
42
+ "commander": "^12.1.0",
43
+ "dotenv": "^16.4.5",
44
+ "js-yaml": "^4.1.0"
45
+ },
46
+ "devDependencies": {
47
+ "@types/js-yaml": "^4.0.9",
48
+ "@types/node": "^22.10.0",
49
+ "tsx": "^4.21.0",
50
+ "typescript": "^5.6.3"
51
+ }
52
+ }