specdojo 0.9.0 → 0.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.github/agents/specdojo-orchestrator.md +7 -0
  2. package/CHANGELOG.md +36 -0
  3. package/README.md +4 -4
  4. package/dist/commands/agent.js +15 -24
  5. package/dist/commands/init.js +8 -5
  6. package/dist/commands/orchestrator.js +11 -88
  7. package/dist/dashboard/shared.js +2 -2
  8. package/dist/dashboard/timeline.js +2 -2
  9. package/dist/deliverable/trash.js +2 -1
  10. package/dist/devcontainer/command.js +1 -1
  11. package/dist/devcontainer/scaffold.js +6 -5
  12. package/dist/exec/agent-config.js +4 -0
  13. package/dist/exec/commands.js +54 -4
  14. package/dist/exec/executor-outcome-checks.js +104 -0
  15. package/dist/exec/migrate-records.js +3 -1
  16. package/dist/exec/opencode-permissions.js +117 -0
  17. package/dist/exec/parent-validation.js +66 -15
  18. package/dist/exec/pipeline-state.js +16 -0
  19. package/dist/exec/register-foreign-wait.js +1 -3
  20. package/dist/exec/register.js +4 -0
  21. package/dist/exec/repo-trace.js +2 -1
  22. package/dist/exec/run/agent-pipeline.js +44 -3
  23. package/dist/exec/run/agent.js +1 -1
  24. package/dist/exec/run/change-scope.js +2 -2
  25. package/dist/exec/run/in-place.js +1 -1
  26. package/dist/exec/run/register-command.js +9 -0
  27. package/dist/exec/run/register-core.js +2 -1
  28. package/dist/exec/run/register-resume.js +19 -2
  29. package/dist/exec/run/register-worktree.js +2 -1
  30. package/dist/exec/run/resume-notes.js +50 -0
  31. package/dist/exec/run/shared.js +5 -0
  32. package/dist/exec/shared.js +1 -1
  33. package/dist/exec/task-repos.js +25 -4
  34. package/dist/exec/validation-process-group.js +98 -0
  35. package/dist/exec/worktree-command.js +3 -1
  36. package/dist/grade/command-inspect.js +3 -1
  37. package/dist/grade/command-run.js +1 -0
  38. package/dist/grade/command-shared.js +10 -0
  39. package/dist/grade/run.js +58 -6
  40. package/dist/grade/targets.js +106 -0
  41. package/dist/register/create-commands.js +30 -3
  42. package/dist/register/events.js +1 -1
  43. package/dist/register/item.js +1 -0
  44. package/dist/register/maintenance-commands.js +3 -1
  45. package/dist/register/renumber.js +15 -4
  46. package/dist/register/section.js +114 -0
  47. package/dist/register/update.js +18 -0
  48. package/dist/shared/antigravity-block.js +24 -0
  49. package/dist/shared/plan-conventions.js +11 -0
  50. package/dist/shared/provider-scaffold.js +4 -0
  51. package/dist/shared/specdojo-config.js +5 -4
  52. package/dist/shared/text.js +8 -0
  53. package/dist/shared/where-alias.js +2 -2
  54. package/docs/ja/specdojo/guides/exec-config-guide.md +15 -12
  55. package/docs/ja/specdojo/guides/exec-operation-guide.md +21 -7
  56. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +6 -4
  57. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  58. package/docs/ja/specdojo/guides/register-operation-guide.md +1 -1
  59. package/docs/ja/specdojo/guides/timeline-design-guide.md +1 -1
  60. package/docs/ja/specdojo/references/command-reference.md +76 -51
  61. package/docs/ja/specdojo/references/specdojo-config-reference.md +11 -9
  62. package/docs/ja/specdojo/rulebooks/dec-rulebook.md +10 -42
  63. package/docs/ja/specdojo/rulebooks/ntp-rulebook.md +10 -50
  64. package/docs/ja/specdojo/samples/dec-sample.md +3 -30
  65. package/docs/ja/specdojo/samples/dss-sample.md +12 -12
  66. package/docs/ja/specdojo/samples/ntp-sample.md +3 -30
  67. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +18 -0
  68. package/docs/specdojo/schemas/v1/register-events.schema.yaml +1 -0
  69. package/package.json +1 -1
  70. package/templates/antigravity/orchestrator.md +7 -0
  71. package/templates/claude/agents/specdojo-orchestrator.md +7 -0
  72. package/templates/codex/agents/specdojo-orchestrator.toml +7 -0
  73. package/templates/codex/orchestrator.md +7 -0
  74. package/templates/opencode/agents/specdojo-orchestrator.md +7 -0
@@ -9,7 +9,7 @@ import { integratedRepoNames } from "../pipeline-state.js";
9
9
  import { resolveProductBranches } from "../product-branches.js";
10
10
  import { adoptForeignWaitRecords, countForeignCommits, findForeignWaitRecords, } from "../register-foreign-wait.js";
11
11
  import { findResumableRegisterRun, resolveRegisterResumeArtifacts, } from "../register-resume.js";
12
- import { requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, ticketPathFromItem, } from "../register.js";
12
+ import { requireRunnableRegisterItem, resolveRegisterRunTarget, registerProductTargetHints, sanitizeRegisterConclusion, ticketPathFromItem, } from "../register.js";
13
13
  import { syncTaskWorktreesWithIntegrationTargets, } from "../repo-integration.js";
14
14
  import { readResultFrontmatterSnapshot } from "../results.js";
15
15
  import { qualifyTaskId } from "../shared.js";
@@ -22,6 +22,7 @@ import { repoRelativePath } from "./mode-shared.js";
22
22
  import { registerReporterManagedPaths, spawnRegisterTransition, } from "./register-core.js";
23
23
  import { copyRepoPaths, overlayRegisterTicketLifecycle, rebuildRootRegisterViews, registerBookkeepingPaths, registerTransitionPaths, } from "./register-state.js";
24
24
  import { finalizeRegisterWorktreeRun } from "./register-worktree.js";
25
+ import { appendResumeNotesToPlan, nextResumeNotes } from "./resume-notes.js";
25
26
  import { isWorktreeCleanupInProgress, worktreeCleanupInProgressReason, } from "../worktree-cleanup-lock.js";
26
27
  import { rateLimitRecoveryReason, resolveAgentOverride, resolvePinnedRateLimitRunOptions, } from "./shared.js";
27
28
  // reporter 再開に使う agent を解決する。--reporter-by を優先し、省略時は再開対象 run の
@@ -394,8 +395,15 @@ export async function resumeSingleRegisterItemWorktree(context, opts, pjrId, lif
394
395
  return refuse(`plan not found for the resumed run: ${artifacts.planRef}; merge the branch that holds ` +
395
396
  `the wait commit of run ${target.runId} into ${currentBranch(repoRoot)} and resume again, ` +
396
397
  `or discard the run with --force-restart (without --resume)`);
397
- const prompt = expandPromptRefs(readPlanFile(promptPlanPath));
398
+ let prompt = expandPromptRefs(readPlanFile(promptPlanPath));
398
399
  if (target.stage === "executor") {
400
+ // PJR-5F1Y: --resume-note は worktree の plan(統合で plan の変更を許す executor 再開の入力)へ
401
+ // 足す。root の plan は wait commit の checkpoint のまま残す。
402
+ const resumeNotes = (opts.resumeNote ?? []).map((note) => note.trim()).filter(Boolean);
403
+ if (resumeNotes.length > 0 && promptPlanPath !== worktreePlanPath) {
404
+ return refuse(`plan not found in the worktree: ${artifacts.planRef}; --resume-note requires the plan ` +
405
+ `of run ${target.runId} in the worktree`);
406
+ }
399
407
  const executor = resolveRegisterResumeExecutor(context.roster, opts, context.execDefaults, target.state.stages.executor.actor);
400
408
  if (executor.kind === "error")
401
409
  return refuse(executor.message);
@@ -408,6 +416,13 @@ export async function resumeSingleRegisterItemWorktree(context, opts, pjrId, lif
408
416
  const beginFailure = await begin(executor.candidate.actor, "executor resumed");
409
417
  if (beginFailure)
410
418
  return beginFailure;
419
+ const resumeNoteEntry = resumeNotes.length > 0 ? { at: new Date().toISOString(), notes: resumeNotes } : undefined;
420
+ if (resumeNoteEntry) {
421
+ appendResumeNotesToPlan(worktreePlanPath, resumeNoteEntry);
422
+ prompt = expandPromptRefs(readPlanFile(worktreePlanPath));
423
+ process.stdout.write(` [resume] added ${resumeNotes.length} resume note(s) to ${artifacts.planRef}\n`);
424
+ }
425
+ const recordedResumeNotes = nextResumeNotes(target.state.resume_notes, resumeNoteEntry);
411
426
  const resultScaffold = readResultFrontmatterSnapshot(worktreeResultPath);
412
427
  const outcome = await runAgentPipeline({
413
428
  repoRoot,
@@ -423,6 +438,7 @@ export async function resumeSingleRegisterItemWorktree(context, opts, pjrId, lif
423
438
  registerPaths: registerReporterManagedPaths(registerPaths),
424
439
  executorResumeHint: executorStageResumeHint({ kind: "register", itemId: item.id }),
425
440
  execDefaults: context.execDefaults,
441
+ productTargetHints: registerProductTargetHints(item),
426
442
  resumedExecutor: true,
427
443
  runId: target.runId,
428
444
  initialChangeTargets: target.initialChanges,
@@ -430,6 +446,7 @@ export async function resumeSingleRegisterItemWorktree(context, opts, pjrId, lif
430
446
  providerConcurrencyGate: context.providerConcurrencyGate,
431
447
  productWorktrees: worktree.repos,
432
448
  ...(integrationBranchOverrides ? { integrationBranchOverrides } : {}),
449
+ ...(recordedResumeNotes.length > 0 ? { resumeNotes: recordedResumeNotes } : {}),
433
450
  executorRateLimitOptions: resolvePinnedRateLimitRunOptions(opts, context.execDefaults, context.roster, "executor", executor.candidate),
434
451
  reporterRateLimitOptions: resolvePinnedRateLimitRunOptions(opts, context.execDefaults, context.roster, "reporter", reporter.candidate),
435
452
  });
@@ -13,7 +13,7 @@ import { buildInPlaceStem } from "../plans.js";
13
13
  import { resolveProductBranches } from "../product-branches.js";
14
14
  import { registerProductMessage } from "../register-product-message.js";
15
15
  import { findResumableRegisterRun } from "../register-resume.js";
16
- import { generateRegisterPlan, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, ticketPathFromItem, } from "../register.js";
16
+ import { generateRegisterPlan, requireRunnableRegisterItem, resolveRegisterRunTarget, registerProductTargetHints, sanitizeRegisterConclusion, ticketPathFromItem, } from "../register.js";
17
17
  import { commitProductWorktrees, integrateTaskRepositories, PROJECT_REPO_NAME, projectMergeBlockers, RepoIntegrationError, } from "../repo-integration.js";
18
18
  import { productIntegrationTrace, recordResultTrace, registerProjectMergeMessage, traceKey, } from "../repo-trace.js";
19
19
  import { readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus } from "../results.js";
@@ -650,6 +650,7 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
650
650
  registerPaths: registerReporterManagedPaths(registerPaths),
651
651
  executorResumeHint: executorStageResumeHint({ kind: "register", itemId: item.id }),
652
652
  execDefaults: context.execDefaults,
653
+ productTargetHints: registerProductTargetHints(item),
653
654
  providerConcurrencyGate: context.providerConcurrencyGate,
654
655
  productWorktrees: worktree.repos,
655
656
  ...(integrationBranchOverrides ? { integrationBranchOverrides } : {}),
@@ -0,0 +1,50 @@
1
+ import { readFileSync, writeFileSync } from "node:fs";
2
+ import { insertBeforePlanConventions } from "../../shared/plan-conventions.js";
3
+ import { parseRegisterIds } from "../register.js";
4
+ // PJR-5F1Y: 再開の前に plan へ指示を足す `--resume-note`。worktree の plan を書き換えるため、
5
+ // plan の変更を統合で許す executor の明示再開(--resume-from executor)に限る。
6
+ export const RESUME_NOTES_HEADING = "再開の指示";
7
+ /** Returns the reason to stop before any project path, lock, or register state is touched. */
8
+ export function resumeNoteOptionError(opts) {
9
+ const notes = opts.resumeNote;
10
+ if (notes === undefined || notes.length === 0)
11
+ return undefined;
12
+ if (notes.some((note) => !note.trim()))
13
+ return "--resume-note requires a non-empty text.";
14
+ if (!opts.resume || opts.resumeFrom !== "executor") {
15
+ return "--resume-note requires --resume --resume-from executor.";
16
+ }
17
+ if (opts.registerFilter || !opts.register) {
18
+ return "--resume-note requires --register with a single item ID.";
19
+ }
20
+ let ids;
21
+ try {
22
+ ids = parseRegisterIds(opts.register).ids;
23
+ }
24
+ catch {
25
+ return "--resume-note requires --register with a single item ID.";
26
+ }
27
+ if (ids.length !== 1)
28
+ return "--resume-note requires --register with a single item ID.";
29
+ return undefined;
30
+ }
31
+ /** Markdown section added to the plan; continuation lines stay inside their list item. */
32
+ export function resumeNotesSection(entry) {
33
+ const items = entry.notes.map((note) => `- ${note.trim().split(/\r?\n/).join("\n ")}`);
34
+ return [
35
+ `## ${RESUME_NOTES_HEADING}(${entry.at})`,
36
+ "",
37
+ "利用者が再開の前に足した指示である。これまでの申し送りとあわせて、この指示に従って作業を続ける。",
38
+ "",
39
+ ...items,
40
+ ].join("\n");
41
+ }
42
+ /** Insert the section before the conventions reference and keep that reference unchanged. */
43
+ export function appendResumeNotesToPlan(planPath, entry) {
44
+ const plan = readFileSync(planPath, "utf8");
45
+ writeFileSync(planPath, insertBeforePlanConventions(plan, resumeNotesSection(entry)), "utf8");
46
+ }
47
+ /** Earlier resume notes carried over from the checkpoint, plus this resume's entry if any. */
48
+ export function nextResumeNotes(recorded, entry) {
49
+ return [...(recorded ?? []), ...(entry ? [entry] : [])];
50
+ }
@@ -1,6 +1,7 @@
1
1
  import { basename, resolve } from "node:path";
2
2
  import { defaultExecDefaultsPath, hasMemberCommandSource, loadExecDefaultsConfig, resolveMaxConcurrentRuns, resolveMemberCommand, resolveRegisterExecution, resolvePinnedRateLimitPolicy, } from "../agent-config.js";
3
3
  import { resolveProjectPaths } from "../project.js";
4
+ import { isBlockedProvider } from "../../shared/antigravity-block.js";
4
5
  import { buildInitialStateFromStrategy } from "../schedule/initial.js";
5
6
  import { buildScheduleIndex } from "../schedule/schedule.js";
6
7
  import { listFilesRecursive, readYaml } from "../shared.js";
@@ -243,6 +244,10 @@ export function selectCandidates(requirements, roster, taskMode, busyActors, exe
243
244
  // are skipped during auto-selection.
244
245
  if (m.disabled === true)
245
246
  return false;
247
+ // Antigravity members are never launched (0.9.2); drop them so selection moves on to the
248
+ // next member instead of failing the whole candidate list.
249
+ if (isBlockedProvider(m.provider))
250
+ return false;
246
251
  // Opt-in tier: never enter an automatic primary/fallback pool implicitly, even when
247
252
  // every ordinary member is busy. Named selections resolve outside this function.
248
253
  if (m.proficiency === "frontier" && proficiency !== "frontier")
@@ -5,7 +5,7 @@ export { formatDateOnlyUtc, isUtcIsoSeconds, normalizeDateOnly, nowUtcIsoSeconds
5
5
  export { randomHex } from "../shared/random.js";
6
6
  export { isSchYamlFilename, toScheduleFilePath } from "../shared/schedule-paths.js";
7
7
  export function tsForFilenameUtc(ts) {
8
- return ts.replace(/[-:]/g, "").replace("T", "T");
8
+ return ts.replace(/[-:]/g, "");
9
9
  }
10
10
  // worktree/branch 生成専用。project 修飾した task ID(`<projectId>:<taskId>`)を返す。
11
11
  // projectId が未解決(env path override 等)の場合は bare のままにして後方互換を保つ。
@@ -3,6 +3,7 @@ import { existsSync, readdirSync, rmdirSync } from "node:fs";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { getProjectRepos, getProjectSchedulePath, loadConfig, PROJECT_REPO_WORKTREE_DIRNAME, resolveRepoRoot, specdojoRootDir, } from "../shared/specdojo-config.js";
5
5
  import { ensureExecWorktree, execWorktreePath, findExecWorktree, generateWorktreeArtifacts, gitOutput, gitResult, installWorktreeDependencies, listRegisteredWorktrees, worktreeNameFromTaskId, } from "./worktree.js";
6
+ import { OPENCODE_CONFIG_CONTENT_ENV, opencodeAgentNameFromCommand, opencodeExtraRootConfig, } from "./opencode-permissions.js";
6
7
  import { assertProductBranchAvailable, existingProductTaskBranch, forgetProductBranch, productBranchExists, productBranchRecords, recordedProductBranch, reserveProductBranch, } from "./product-branch-records.js";
7
8
  // PJR-98G4: 1 つのタスクがプロジェクトリポジトリと宣言済みのプロダクトリポジトリ(`repos`)を
8
9
  // 変更する場合の worktree を扱う。`repos` を持たない project では、ここの関数はどれも空の結果を
@@ -307,6 +308,12 @@ export function pendingProductWorktreeChanges(worktree) {
307
308
  }
308
309
  return pending;
309
310
  }
311
+ /** Whether a product worktree has uncommitted changes or exec-branch commits to integrate. */
312
+ export function productHasPendingWork(product) {
313
+ if (!existsSync(product.path))
314
+ return false;
315
+ return statusPaths(product.path).length > 0 || commitsAhead(product) > 0;
316
+ }
310
317
  export function assertNoPendingProductChanges(worktree) {
311
318
  const pending = pendingProductWorktreeChanges(worktree);
312
319
  if (pending.length === 0)
@@ -555,8 +562,8 @@ function shellQuote(value) {
555
562
  }
556
563
  /**
557
564
  * Provider arguments that add the product worktrees as extra roots with write access. The agent
558
- * keeps the project worktree as cwd. Returns [] for providers without a launch flag. OpenCode's
559
- * orchestrator entry injects `permission.external_directory` through its runtime config instead.
565
+ * keeps the project worktree as cwd. Returns [] for providers without a launch flag. OpenCode has
566
+ * no such flag; withAgentExtraRoots injects its permissions through `OPENCODE_CONFIG_CONTENT`.
560
567
  */
561
568
  export function agentExtraRootArguments(provider, dirs) {
562
569
  if (dirs.length === 0)
@@ -580,8 +587,22 @@ export function agentExtraRootArguments(provider, dirs) {
580
587
  return [];
581
588
  }
582
589
  }
583
- /** Append the extra-root arguments to a resolved shell command (unchanged when there are none). */
584
- export function withAgentExtraRoots(command, provider, dirs) {
590
+ /**
591
+ * Give the agent write access to the extra roots in a resolved shell command (unchanged when there
592
+ * are none). Most providers get launch arguments appended. OpenCode gets an
593
+ * `OPENCODE_CONFIG_CONTENT` assignment prefixed to the command, scoped to the `--agent` in the
594
+ * command and merged with the inherited value from `options.env`; `edit` patterns are relative
595
+ * to `options.cwd`, the agent's working directory.
596
+ */
597
+ export function withAgentExtraRoots(command, provider, dirs, options = {}) {
598
+ if (provider === "opencode" && dirs.length > 0) {
599
+ const agentName = opencodeAgentNameFromCommand(command);
600
+ if (!agentName) {
601
+ throw new Error(`OpenCode command needs --agent <name> to scope the product worktree permissions: ${command}`);
602
+ }
603
+ const config = opencodeExtraRootConfig((options.env ?? process.env)[OPENCODE_CONFIG_CONTENT_ENV], agentName, dirs, options.cwd ?? process.cwd());
604
+ return `${OPENCODE_CONFIG_CONTENT_ENV}=${shellQuote(config)} ${command}`;
605
+ }
585
606
  const args = agentExtraRootArguments(provider, dirs);
586
607
  if (args.length === 0)
587
608
  return command;
@@ -0,0 +1,98 @@
1
+ /** Wait after SIGTERM to the validation's process tree before SIGKILL (PJR-V277). */
2
+ export const VALIDATION_KILL_GRACE_MS = 10_000;
3
+ /** Wait after SIGKILL for the output pipes to close before returning without them. */
4
+ export const VALIDATION_CLOSE_GRACE_MS = 5_000;
5
+ /**
6
+ * POSIX runs each parent validation in its own process group so a timeout reaches npm's
7
+ * descendants (vitest and the CLIs it spawns). Windows has no process groups; there the runner
8
+ * signals the direct child only and relies on the bounded pipe wait to return.
9
+ */
10
+ export const VALIDATION_USES_PROCESS_GROUP = process.platform !== "win32";
11
+ const FORWARDED_SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
12
+ const activeGroups = new Set();
13
+ function signalGroup(pid, signal) {
14
+ try {
15
+ process.kill(-pid, signal);
16
+ return true;
17
+ }
18
+ catch (error) {
19
+ if (error.code === "ESRCH")
20
+ return false;
21
+ throw error;
22
+ }
23
+ }
24
+ /**
25
+ * Send `signal` to the child's process group, or to the child itself when it has no group.
26
+ * Returns false when no process of the group remained to receive it.
27
+ */
28
+ export function signalValidationProcessTree(child, signal) {
29
+ if (VALIDATION_USES_PROCESS_GROUP && child.pid !== undefined) {
30
+ try {
31
+ return signalGroup(child.pid, signal);
32
+ }
33
+ catch {
34
+ // EPERM などで group へ送れない場合は、直接の子にだけ送る従来の動きへ戻す。
35
+ }
36
+ }
37
+ return child.kill(signal);
38
+ }
39
+ /** Whether any process of the child's group is still alive (always false without a group). */
40
+ export function hasValidationProcessTreeSurvivors(child) {
41
+ if (!VALIDATION_USES_PROCESS_GROUP || child.pid === undefined)
42
+ return false;
43
+ try {
44
+ return signalGroup(child.pid, 0);
45
+ }
46
+ catch {
47
+ // EPERM は別ユーザーの同じ group が残っていることを示すため、生存として扱う。
48
+ return true;
49
+ }
50
+ }
51
+ function terminateActiveGroups() {
52
+ for (const pid of activeGroups) {
53
+ try {
54
+ signalGroup(pid, "SIGTERM");
55
+ }
56
+ catch {
57
+ // 終了処理の途中のため、送れない group は残して先へ進む。
58
+ }
59
+ }
60
+ }
61
+ function forwardSignal(signal) {
62
+ terminateActiveGroups();
63
+ // 他に listener が無い場合は既定の動き(終了)を保つため、外してから送り直す。
64
+ if (process.listenerCount(signal) > 1)
65
+ return;
66
+ removeForwarding();
67
+ process.kill(process.pid, signal);
68
+ }
69
+ const signalHandlers = new Map(FORWARDED_SIGNALS.map((signal) => [signal, () => forwardSignal(signal)]));
70
+ function installForwarding() {
71
+ for (const [signal, handler] of signalHandlers)
72
+ process.on(signal, handler);
73
+ process.on("exit", terminateActiveGroups);
74
+ }
75
+ function removeForwarding() {
76
+ for (const [signal, handler] of signalHandlers)
77
+ process.off(signal, handler);
78
+ process.off("exit", terminateActiveGroups);
79
+ }
80
+ /**
81
+ * A detached group no longer receives the terminal's Ctrl-C, so the runner forwards SIGINT,
82
+ * SIGTERM and SIGHUP (and its own exit) to the active validation groups while they run.
83
+ * Returns the function that stops tracking the group.
84
+ */
85
+ export function trackValidationProcessGroup(child) {
86
+ const pid = child.pid;
87
+ if (!VALIDATION_USES_PROCESS_GROUP || pid === undefined)
88
+ return () => undefined;
89
+ if (activeGroups.size === 0)
90
+ installForwarding();
91
+ activeGroups.add(pid);
92
+ return () => {
93
+ if (!activeGroups.delete(pid))
94
+ return;
95
+ if (activeGroups.size === 0)
96
+ removeForwarding();
97
+ };
98
+ }
@@ -261,7 +261,9 @@ async function agent(opts) {
261
261
  requireInsideWorktree(context.repoRoot, worktree);
262
262
  const resolved = resolveAgent(context, opts.task, opts);
263
263
  const productDirs = (worktree.repos ?? []).map((product) => product.path);
264
- const command = withAgentExtraRoots(resolved.command, resolved.provider, productDirs);
264
+ const command = withAgentExtraRoots(resolved.command, resolved.provider, productDirs, {
265
+ cwd: worktree.path,
266
+ });
265
267
  if (opts.dryRun) {
266
268
  process.stdout.write(`[dry-run] actor: ${resolved.actor}\n`);
267
269
  process.stdout.write(`[dry-run] command: ${command}\n`);
@@ -1,3 +1,4 @@
1
+ import { warnDeprecated } from "../shared/deprecation.js";
1
2
  import { addGradeSelectionOptions as addSelection, commandError, collectPathOption, requirePipelineStatus, requirePositiveInteger, requireTarget, } from "./command-shared.js";
2
3
  import { discoverGradeTargets } from "./target-discovery.js";
3
4
  import { listExhaustedGradePipelineStates, readGradePipelineState, recordGradePipelineStage, } from "./pipeline-state.js";
@@ -116,13 +117,14 @@ export function registerGradeInspectionCommands(grade) {
116
117
  });
117
118
  grade
118
119
  .command("migrate")
119
- .description("Move legacy inline grade snapshots and findings to result sidecars")
120
+ .description("Deprecated: inline grade migration is no longer needed; result sidecars are standard (will be removed in 0.10.0)")
120
121
  .option("--target <target>", "Restrict migration to kata or deliverable", requireTarget)
121
122
  .option("--project <projectId>", "Project id in specdojo.config.json")
122
123
  .option("--path <path>", "Migrate only this Markdown document (repeatable)", collectPathOption, [])
123
124
  .option("--dry-run", "List updates without writing", false)
124
125
  .action((options) => {
125
126
  try {
127
+ warnDeprecated("grade migrate", "Inline grade migration is no longer needed as result sidecars are standard. Use grade run instead. This command will be removed in 0.10.0.");
126
128
  const changed = migrateInlineGrades({
127
129
  project: options.project,
128
130
  target: options.target,
@@ -31,6 +31,7 @@ export function registerGradeRunCommand(grade, runtime) {
31
31
  ...options,
32
32
  target: requireTarget(options.target),
33
33
  paths: options.path,
34
+ kata: options.kata,
34
35
  by: options.by ?? options.stage1Executor,
35
36
  execDefaultsPath: options.execDefaults,
36
37
  }, runtime);
@@ -1,6 +1,15 @@
1
1
  export function collectPathOption(value, previous) {
2
2
  return [...previous, value];
3
3
  }
4
+ export function collectKataOption(value, previous) {
5
+ return [
6
+ ...previous,
7
+ ...value
8
+ .split(",")
9
+ .map((s) => s.trim())
10
+ .filter(Boolean),
11
+ ];
12
+ }
4
13
  export function requireTarget(value) {
5
14
  if (value !== "kata" && value !== "deliverable")
6
15
  throw new Error("--target must be kata or deliverable");
@@ -55,6 +64,7 @@ export function addGradeSelectionOptions(command) {
55
64
  .requiredOption("--target <target>", "kata or deliverable")
56
65
  .option("--project <projectId>", "Project id in specdojo.config.json")
57
66
  .option("--path <path>", "Grade only this Markdown or YAML document (repeatable)", collectPathOption, [])
67
+ .option("--kata <name>", "Grade rulebook and sample for this kata name or prefix (repeatable)", collectKataOption, [])
58
68
  .option("--changed-only", "Select documents changed since their latest grade", false)
59
69
  .option("--dependency-changed", "Select documents whose dependencies have been graded more recently", false)
60
70
  .option("--rulebook-changed", "Select documents whose declared rulebook has been graded more recently", false)
package/dist/grade/run.js CHANGED
@@ -8,7 +8,7 @@ import { readGradePipelineState, recordGradePipelineStage } from "./pipeline-sta
8
8
  import { writeGradePlans } from "./plan.js";
9
9
  import { gradeContentHash, gradeFindingCount, readGradeResultForDocument } from "./result.js";
10
10
  import { discoverGradeTargets } from "./target-discovery.js";
11
- import { loadViewpoints, repoRelativePath, resolveDeliverableDoneCriteria, resolveGradeSourceHashes, resolveProject, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
11
+ import { loadViewpoints, repoRelativePath, resolveDeliverableDoneCriteria, resolveGradeSourceHashes, resolveKataBatchTargets, resolveProject, resolveSafeMarkdownPath, resolveSafeRepositoryPath, } from "./targets.js";
12
12
  /**
13
13
  * A run that stopped with documents left ungraded. Callers such as scheduled jobs tell a
14
14
  * partial run (2) from a run without any completed document (1) and from a rate limit (75),
@@ -88,6 +88,14 @@ async function runGradeUnlocked(opts, runtime) {
88
88
  throw new Error("Invalid --kind");
89
89
  if (opts.target !== "kata" && opts.kind !== undefined)
90
90
  throw new Error("--kind is only valid for kata");
91
+ if (opts.target !== "kata" && (opts.kata?.length ?? 0) > 0)
92
+ throw new Error("--kata is only valid for kata");
93
+ if (opts.paths?.length && (opts.kata?.length ?? 0) > 0)
94
+ throw new Error("Use either --path or --kata");
95
+ let documentsByKata;
96
+ if (opts.kata && opts.kata.length > 0) {
97
+ documentsByKata = resolveKataBatchTargets(opts.kata, specdojoRootDir()).documentsByKata;
98
+ }
91
99
  const maxFailures = opts.maxStageFailures ?? 3;
92
100
  if (!Number.isSafeInteger(maxFailures) || maxFailures < 1)
93
101
  throw new Error("Invalid --max-stage-failures");
@@ -136,11 +144,18 @@ async function runGradeUnlocked(opts, runtime) {
136
144
  }
137
145
  }
138
146
  else {
139
- let paths = discoverGradeTargets({ ...opts, project: projectId });
140
- if (opts.target === "kata" && kind !== "all")
141
- paths = paths.filter((path) => repoRelativePath(path).split("/").includes(`${kind}s`));
142
- if (opts.limit !== undefined)
143
- paths = paths.slice(0, opts.limit);
147
+ let paths;
148
+ if (documentsByKata) {
149
+ const flattened = Array.from(documentsByKata.values()).flat();
150
+ paths = Array.from(new Set(flattened));
151
+ }
152
+ else {
153
+ paths = discoverGradeTargets({ ...opts, project: projectId });
154
+ if (opts.target === "kata" && kind !== "all")
155
+ paths = paths.filter((path) => repoRelativePath(path).split("/").includes(`${kind}s`));
156
+ if (opts.limit !== undefined)
157
+ paths = paths.slice(0, opts.limit);
158
+ }
144
159
  state = {
145
160
  version: 1,
146
161
  request,
@@ -211,6 +226,8 @@ async function runGradeUnlocked(opts, runtime) {
211
226
  }
212
227
  writeState(statePath, state);
213
228
  const failures = [];
229
+ let rateLimited = false;
230
+ let rateLimitedActor;
214
231
  for (const [index, document] of state.documents.entries()) {
215
232
  const reference = references.get(document.path);
216
233
  if (document.status === "complete") {
@@ -282,6 +299,11 @@ async function runGradeUnlocked(opts, runtime) {
282
299
  // A rate limit is not a document failure: keep the stage retryable in this run id.
283
300
  document.status = "pending";
284
301
  writeState(statePath, state);
302
+ if (documentsByKata) {
303
+ rateLimited = true;
304
+ rateLimitedActor = actualActor;
305
+ continue;
306
+ }
285
307
  const unstarted = state.documents
286
308
  .filter((item) => item.status !== "complete")
287
309
  .map((item) => item.path);
@@ -375,6 +397,36 @@ async function runGradeUnlocked(opts, runtime) {
375
397
  failures.push(`${document.path}: ${document.error}`);
376
398
  }
377
399
  }
400
+ if (documentsByKata && documentsByKata.size > 0) {
401
+ process.stdout.write("kata results:\n");
402
+ for (const [name, docs] of documentsByKata) {
403
+ const statuses = docs.map((docPath) => {
404
+ const repoPath = repoRelativePath(docPath);
405
+ const doc = state.documents.find((item) => item.path === repoPath);
406
+ return doc?.status ?? "pending";
407
+ });
408
+ let verdictJa = "未実行";
409
+ let verdictEn = "pending";
410
+ if (statuses.every((s) => s === "complete")) {
411
+ verdictJa = "完了";
412
+ verdictEn = "complete";
413
+ }
414
+ else if (statuses.some((s) => s === "failed")) {
415
+ verdictJa = "失敗";
416
+ verdictEn = "failed";
417
+ }
418
+ process.stdout.write(` ${name}: ${verdictJa} (${verdictEn})\n`);
419
+ }
420
+ }
421
+ if (rateLimited) {
422
+ const unstarted = state.documents
423
+ .filter((item) => item.status !== "complete")
424
+ .map((item) => item.path);
425
+ throw new GradeRunIncompleteError([
426
+ `grade run stopped by rate limit: agent=${rateLimitedActor ?? actor} run_id=${opts.runId}; rerun with the same --run-id to resume`,
427
+ ...unstarted.map((path) => `grade run remaining: ${path}`),
428
+ ].join("\n"), GRADE_RUN_RATE_LIMIT_EXIT_CODE);
429
+ }
378
430
  if (failures.length) {
379
431
  const completed = state.documents.filter((document) => document.status === "complete").length;
380
432
  throw new GradeRunIncompleteError(`grade run incomplete: completed=${completed} failed=${failures.length} run_id=${opts.runId}\n${failures.join("\n")}`, completed > 0 ? GRADE_RUN_PARTIAL_EXIT_CODE : 1);
@@ -7,6 +7,8 @@ import { collectResolvedDeliverables, loadCatalogDocs } from "../catalog/build.j
7
7
  import { isTrashedPath, resolveBasePath } from "../catalog/paths.js";
8
8
  import { listFilesRecursive } from "../shared/fs.js";
9
9
  import { gradeContentHash } from "./result.js";
10
+ import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
11
+ import { resolveAuthoredKataPathIfExists } from "../kata/authoring.js";
10
12
  import { GRADE_TARGETS, KATA_DIRS, KATA_REFERENCE_EXTENSIONS, KATA_REFERENCE_FIELDS, gradedViewpoints, isRecord, parseGradeDocument, } from "./core.js";
11
13
  import { commonViewpointsPath, resolveViewpointsDoc } from "../review/plan.js";
12
14
  import { assertValidActor, getProjectCatalogPath, getProjectMembersPath, getProjectRolesPath, getProjectSchedulePath, getProjectViewpointsPath, loadConfig, resolveAgentMember, resolveRepoRoot, specdojoRootDir, } from "../shared/specdojo-config.js";
@@ -456,3 +458,107 @@ export function resolveGradeSourceHashes(opts, rootDir = specdojoRootDir()) {
456
458
  export function sourceHashesChanged(stored, current) {
457
459
  return Object.entries(current).some(([key, hash]) => stored?.[key] !== hash);
458
460
  }
461
+ /** Resolve rulebook and sample documents for a single kata name or prefix. */
462
+ export function resolveKataDocuments(kataName, rootDir = specdojoRootDir()) {
463
+ const normalized = kataName.trim().replace(/-rulebook(\.md)?$/, "");
464
+ if (!normalized)
465
+ return [];
466
+ const found = [];
467
+ // 1. rulebook
468
+ const rulebookCandidate = join(rootDir, `docs/ja/specdojo/rulebooks/${normalized}-rulebook.md`);
469
+ if (existsSync(rulebookCandidate)) {
470
+ found.push(repoRelativePath(rulebookCandidate));
471
+ }
472
+ else {
473
+ const authored = resolveAuthoredKataPathIfExists(`${normalized}-rulebook`, "rulebook", "md", rootDir);
474
+ if (authored && existsSync(authored.absolutePath)) {
475
+ found.push(repoRelativePath(authored.absolutePath));
476
+ }
477
+ }
478
+ // 2. sample
479
+ let foundSample = false;
480
+ if (found.length > 0) {
481
+ const rulebookPath = resolve(rootDir, found[0]);
482
+ try {
483
+ const content = readFileSync(rulebookPath, "utf8");
484
+ const fm = readSpecdojoNamespace(content);
485
+ if (fm.sample && typeof fm.sample === "string") {
486
+ if (fm.sample !== "not-needed" && fm.sample !== "none" && fm.sample !== "undecided") {
487
+ const sampleId = fm.sample;
488
+ const extensions = ["md", "yaml", "yml", "json"];
489
+ for (const ext of extensions) {
490
+ const authored = resolveAuthoredKataPathIfExists(sampleId, "sample", ext, rootDir);
491
+ if (authored && existsSync(authored.absolutePath)) {
492
+ found.push(repoRelativePath(authored.absolutePath));
493
+ foundSample = true;
494
+ break;
495
+ }
496
+ }
497
+ }
498
+ else {
499
+ // Explicitly not-needed or none
500
+ foundSample = true;
501
+ }
502
+ }
503
+ }
504
+ catch {
505
+ // Ignore rulebook read error and fall through to filename lookup
506
+ }
507
+ }
508
+ if (!foundSample) {
509
+ const sampleExtensions = ["md", "yaml", "yml", "json"];
510
+ for (const ext of sampleExtensions) {
511
+ const sampleCandidate = join(rootDir, `docs/ja/specdojo/samples/${normalized}-sample.${ext}`);
512
+ if (existsSync(sampleCandidate)) {
513
+ found.push(repoRelativePath(sampleCandidate));
514
+ break;
515
+ }
516
+ }
517
+ }
518
+ // Fallback for sample-only kata without rulebook
519
+ if (found.length === 0) {
520
+ const sampleExtensions = ["md", "yaml", "yml", "json"];
521
+ for (const ext of sampleExtensions) {
522
+ const sampleCandidate = join(rootDir, `docs/ja/specdojo/samples/${normalized}-sample.${ext}`);
523
+ if (existsSync(sampleCandidate)) {
524
+ found.push(repoRelativePath(sampleCandidate));
525
+ break;
526
+ }
527
+ }
528
+ }
529
+ return found;
530
+ }
531
+ /**
532
+ * Validate and resolve target documents for multiple kata names.
533
+ * Unknown kata names cause an error before execution.
534
+ */
535
+ export function resolveKataBatchTargets(kataNames, rootDir = specdojoRootDir()) {
536
+ const documentsByKata = new Map();
537
+ const unknown = [];
538
+ for (const rawName of kataNames) {
539
+ const name = rawName.trim();
540
+ if (!name)
541
+ continue;
542
+ if (documentsByKata.has(name))
543
+ continue;
544
+ const docs = resolveKataDocuments(name, rootDir);
545
+ if (docs.length === 0) {
546
+ unknown.push(name);
547
+ }
548
+ else {
549
+ documentsByKata.set(name, docs);
550
+ }
551
+ }
552
+ if (unknown.length > 0) {
553
+ throw new Error(`Unknown kata: ${unknown.join(", ")}`);
554
+ }
555
+ const allDocuments = [];
556
+ for (const docs of documentsByKata.values()) {
557
+ for (const doc of docs) {
558
+ if (!allDocuments.includes(doc)) {
559
+ allDocuments.push(doc);
560
+ }
561
+ }
562
+ }
563
+ return { documentsByKata, allDocuments };
564
+ }