specdojo 0.9.1 → 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 (62) hide show
  1. package/.github/agents/specdojo-orchestrator.md +7 -0
  2. package/CHANGELOG.md +23 -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 +6 -11
  7. package/dist/dashboard/timeline.js +2 -2
  8. package/dist/devcontainer/command.js +1 -1
  9. package/dist/devcontainer/scaffold.js +6 -5
  10. package/dist/exec/agent-config.js +4 -0
  11. package/dist/exec/commands.js +54 -4
  12. package/dist/exec/executor-outcome-checks.js +104 -0
  13. package/dist/exec/migrate-records.js +3 -1
  14. package/dist/exec/parent-validation.js +66 -15
  15. package/dist/exec/pipeline-state.js +16 -0
  16. package/dist/exec/register.js +4 -0
  17. package/dist/exec/run/agent-pipeline.js +44 -3
  18. package/dist/exec/run/register-command.js +9 -0
  19. package/dist/exec/run/register-core.js +2 -1
  20. package/dist/exec/run/register-resume.js +19 -2
  21. package/dist/exec/run/register-worktree.js +2 -1
  22. package/dist/exec/run/resume-notes.js +50 -0
  23. package/dist/exec/run/shared.js +5 -0
  24. package/dist/exec/task-repos.js +6 -0
  25. package/dist/exec/validation-process-group.js +98 -0
  26. package/dist/grade/command-inspect.js +3 -1
  27. package/dist/grade/command-run.js +1 -0
  28. package/dist/grade/command-shared.js +10 -0
  29. package/dist/grade/run.js +58 -6
  30. package/dist/grade/targets.js +106 -0
  31. package/dist/register/create-commands.js +30 -3
  32. package/dist/register/events.js +1 -1
  33. package/dist/register/item.js +1 -0
  34. package/dist/register/maintenance-commands.js +3 -1
  35. package/dist/register/renumber.js +14 -1
  36. package/dist/register/section.js +114 -0
  37. package/dist/register/update.js +18 -0
  38. package/dist/shared/antigravity-block.js +24 -0
  39. package/dist/shared/plan-conventions.js +11 -0
  40. package/dist/shared/provider-scaffold.js +4 -0
  41. package/dist/shared/specdojo-config.js +5 -4
  42. package/dist/shared/where-alias.js +2 -2
  43. package/docs/ja/specdojo/guides/exec-config-guide.md +15 -12
  44. package/docs/ja/specdojo/guides/exec-operation-guide.md +21 -7
  45. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +5 -3
  46. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
  47. package/docs/ja/specdojo/guides/register-operation-guide.md +1 -1
  48. package/docs/ja/specdojo/guides/timeline-design-guide.md +1 -1
  49. package/docs/ja/specdojo/references/command-reference.md +76 -51
  50. package/docs/ja/specdojo/rulebooks/dec-rulebook.md +10 -42
  51. package/docs/ja/specdojo/rulebooks/ntp-rulebook.md +10 -50
  52. package/docs/ja/specdojo/samples/dec-sample.md +3 -30
  53. package/docs/ja/specdojo/samples/dss-sample.md +12 -12
  54. package/docs/ja/specdojo/samples/ntp-sample.md +3 -30
  55. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +18 -0
  56. package/docs/specdojo/schemas/v1/register-events.schema.yaml +1 -0
  57. package/package.json +1 -1
  58. package/templates/antigravity/orchestrator.md +7 -0
  59. package/templates/claude/agents/specdojo-orchestrator.md +7 -0
  60. package/templates/codex/agents/specdojo-orchestrator.toml +7 -0
  61. package/templates/codex/orchestrator.md +7 -0
  62. package/templates/opencode/agents/specdojo-orchestrator.md +7 -0
@@ -4,6 +4,7 @@ import { performance } from "node:perf_hooks";
4
4
  import { StringDecoder } from "node:string_decoder";
5
5
  import { recordValidationGateWait, validationMetric, ValidationTestFiles, } from "./validation-metrics.js";
6
6
  import { gitEnvironment } from "./worktree.js";
7
+ import { hasValidationProcessTreeSurvivors, signalValidationProcessTree, trackValidationProcessGroup, VALIDATION_CLOSE_GRACE_MS, VALIDATION_KILL_GRACE_MS, VALIDATION_USES_PROCESS_GROUP, } from "./validation-process-group.js";
7
8
  import { acquirePoolSlot, getActiveExecLocksDir, releaseLock } from "./slot-lock.js";
8
9
  import { MAX_CHANGE_FILES, redactSensitiveText } from "./evidence.js";
9
10
  import { PROJECT_REPO_WORKTREE_DIRNAME, REPO_NAME_PATTERN } from "../shared/specdojo-config.js";
@@ -303,12 +304,25 @@ export function parentValidationDisplayCommands(entries) {
303
304
  ? assignment.definition.displayCommand
304
305
  : `${assignment.definition.displayCommand} (in ${assignment.repo})`);
305
306
  }
306
- async function invokeParentValidation(definition, cwd) {
307
+ /**
308
+ * Spawn one parent validation. On timeout the runner stops the whole process tree (SIGTERM, then
309
+ * SIGKILL after a grace period) and, if a descendant outside the group still holds the output
310
+ * pipes, returns without waiting for them so the batch moves on (PJR-V277). Runs that finish
311
+ * before the timeout settle on `close` exactly as before.
312
+ */
313
+ export async function invokeParentValidation(definition, cwd, options = {}) {
314
+ const killGraceMs = options.killGraceMs ?? VALIDATION_KILL_GRACE_MS;
315
+ const closeGraceMs = options.closeGraceMs ?? VALIDATION_CLOSE_GRACE_MS;
307
316
  return await new Promise((resolve) => {
308
317
  const stdoutCapture = { chunks: [], totalBytes: 0 };
309
318
  const stderrCapture = { chunks: [], totalBytes: 0 };
310
319
  let settled = false;
311
320
  let timedOut = false;
321
+ let timeoutStartedAt = 0;
322
+ let survivorsAfterTerm;
323
+ let killSent = false;
324
+ let killTimer;
325
+ let closeTimer;
312
326
  const testFiles = new ValidationTestFiles();
313
327
  const stdoutDecoder = new StringDecoder("utf8");
314
328
  const child = spawn(definition.command, [...definition.args], {
@@ -317,7 +331,9 @@ async function invokeParentValidation(definition, cwd) {
317
331
  shell: false,
318
332
  stdio: ["ignore", "pipe", "pipe"],
319
333
  windowsHide: true,
334
+ detached: VALIDATION_USES_PROCESS_GROUP,
320
335
  });
336
+ const untrack = trackValidationProcessGroup(child);
321
337
  child.stdout.on("data", (chunk) => {
322
338
  appendBounded(stdoutCapture, chunk);
323
339
  testFiles.observe(stdoutDecoder.write(chunk));
@@ -325,21 +341,67 @@ async function invokeParentValidation(definition, cwd) {
325
341
  child.stderr.on("data", (chunk) => {
326
342
  appendBounded(stderrCapture, chunk);
327
343
  });
344
+ const forceKill = () => {
345
+ survivorsAfterTerm = hasValidationProcessTreeSurvivors(child) || child.exitCode === null;
346
+ killSent = signalValidationProcessTree(child, "SIGKILL") || killSent;
347
+ };
348
+ const settle = (exitCode, pipesClosed) => {
349
+ const stdout = capturedOutput(stdoutCapture);
350
+ const stderr = capturedOutput(stderrCapture);
351
+ finish({
352
+ exitCode,
353
+ stdout: stdout.output,
354
+ stderr: stderr.output,
355
+ timedOut,
356
+ stdoutTruncated: stdout.truncated,
357
+ stderrTruncated: stderr.truncated,
358
+ }, pipesClosed);
359
+ };
328
360
  const timer = setTimeout(() => {
329
361
  timedOut = true;
362
+ timeoutStartedAt = performance.now();
330
363
  validationMetric("validation-timeout", {
331
364
  id: definition.id,
332
365
  cwd,
333
366
  timeout_ms: definition.timeoutMs,
334
367
  ...testFiles.snapshot(),
335
368
  });
336
- child.kill("SIGTERM");
369
+ signalValidationProcessTree(child, "SIGTERM");
370
+ killTimer = setTimeout(() => {
371
+ forceKill();
372
+ closeTimer = setTimeout(() => {
373
+ // group の外へ出た子孫が pipe を持ち続けても、close を待たずに時間切れとして返す。
374
+ child.stdout.destroy();
375
+ child.stderr.destroy();
376
+ settle(child.exitCode, false);
377
+ }, closeGraceMs);
378
+ }, killGraceMs);
337
379
  }, definition.timeoutMs);
338
- const finish = (result) => {
380
+ const recordStop = (pipesClosed) => {
381
+ if (!timedOut)
382
+ return;
383
+ // 猶予の前に close した場合も、group に残った子孫は pipe を持たなくても止めておく。
384
+ if (survivorsAfterTerm === undefined && hasValidationProcessTreeSurvivors(child))
385
+ forceKill();
386
+ validationMetric("validation-timeout-stop", {
387
+ id: definition.id,
388
+ cwd,
389
+ process_group: VALIDATION_USES_PROCESS_GROUP && child.pid !== undefined,
390
+ survivors_after_term: survivorsAfterTerm === true,
391
+ kill_sent: killSent,
392
+ pipes_closed: pipesClosed,
393
+ stop_ms: performance.now() - timeoutStartedAt,
394
+ });
395
+ };
396
+ const finish = (result, pipesClosed = true) => {
339
397
  if (settled)
340
398
  return;
341
399
  settled = true;
342
400
  clearTimeout(timer);
401
+ clearTimeout(killTimer);
402
+ clearTimeout(closeTimer);
403
+ recordStop(pipesClosed);
404
+ untrack();
343
405
  resolve(result);
344
406
  };
345
407
  child.on("error", (error) => {
@@ -355,18 +417,7 @@ async function invokeParentValidation(definition, cwd) {
355
417
  stderrTruncated: stderr.truncated,
356
418
  });
357
419
  });
358
- child.on("close", (exitCode) => {
359
- const stdout = capturedOutput(stdoutCapture);
360
- const stderr = capturedOutput(stderrCapture);
361
- finish({
362
- exitCode,
363
- stdout: stdout.output,
364
- stderr: stderr.output,
365
- timedOut,
366
- stdoutTruncated: stdout.truncated,
367
- stderrTruncated: stderr.truncated,
368
- });
369
- });
420
+ child.on("close", (exitCode) => settle(exitCode, true));
370
421
  });
371
422
  }
372
423
  function validationSummary(result) {
@@ -24,6 +24,7 @@ export function createPipelineState(input) {
24
24
  },
25
25
  ...(input.artifacts ? { artifacts: input.artifacts } : {}),
26
26
  ...(input.integrationBranches ? { integration_branches: input.integrationBranches } : {}),
27
+ ...(input.resumeNotes?.length ? { resume_notes: input.resumeNotes } : {}),
27
28
  };
28
29
  }
29
30
  function executionRelative(repoRoot, executionPath) {
@@ -109,6 +110,19 @@ function isIntegrationBranches(value) {
109
110
  !Array.isArray(value) &&
110
111
  Object.entries(value).every(([repo, branch]) => /^[a-z0-9-]+$/.test(repo) && typeof branch === "string" && !!branch));
111
112
  }
113
+ function isResumeNotes(value) {
114
+ return (Array.isArray(value) &&
115
+ value.every((entry) => {
116
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
117
+ return false;
118
+ const record = entry;
119
+ return (typeof record.at === "string" &&
120
+ !!record.at &&
121
+ Array.isArray(record.notes) &&
122
+ record.notes.length > 0 &&
123
+ record.notes.every((note) => typeof note === "string" && !!note.trim()));
124
+ }));
125
+ }
112
126
  export function isPipelineState(value) {
113
127
  if (!value || typeof value !== "object" || Array.isArray(value))
114
128
  return false;
@@ -129,6 +143,8 @@ export function isPipelineState(value) {
129
143
  if (state.integration_branches !== undefined &&
130
144
  !isIntegrationBranches(state.integration_branches))
131
145
  return false;
146
+ if (state.resume_notes !== undefined && !isResumeNotes(state.resume_notes))
147
+ return false;
132
148
  const stages = state.stages;
133
149
  if (stages.integrate !== undefined && !isIntegrateStageState(stages.integrate))
134
150
  return false;
@@ -183,6 +183,10 @@ export function selectRegisterRunArtifactResidue(paths) {
183
183
  }
184
184
  return [...residue].sort();
185
185
  }
186
+ /** Register values that may name a product target as `<repo>:<path>` (PJR-QQRH). */
187
+ export function registerProductTargetHints(item) {
188
+ return [item.targetPath, ...(item.targets ?? [])].filter((value) => typeof value === "string" && value.length > 0);
189
+ }
186
190
  export function resolveRegisterRunTarget(projectId, pjrId) {
187
191
  const registerPaths = resolveRegisterPaths({ project: projectId });
188
192
  if (!existsSync(registerPaths.projectRegisterPath)) {
@@ -7,7 +7,8 @@ import { mechanicalEditReporterOutput } from "../mechanical-result.js";
7
7
  import { readResultFrontmatterSnapshot, renderReporterResult } from "../results.js";
8
8
  import { isRunRecordPath, recordStem, snapshotRunAttempt } from "../run-records.js";
9
9
  import { randomHex } from "../shared.js";
10
- import { withProductRepoPrompt } from "../task-repos.js";
10
+ import { executorOutcomeFailure, targetedProductRepos } from "../executor-outcome-checks.js";
11
+ import { productHasPendingWork, withProductRepoPrompt } from "../task-repos.js";
11
12
  import { worktreeStatusPaths } from "../worktree-ops.js";
12
13
  import { agentEnvironment, appendParentValidationsToExecutorEvidence, buildExecutorPrompt, extractBlockReason, resumedTargetCoverageFailure, runConfiguredParentValidationBatch, runWithRetry, } from "./agent.js";
13
14
  export async function refreshParentValidationsForReporterResume(params) {
@@ -192,6 +193,23 @@ export async function runReporterStage(params) {
192
193
  const runResult = exitCode === 0 ? "success" : reporter.result === "rate_limit" ? "rate_limit" : "failure";
193
194
  return { exitCode, runResult, blockReason, state };
194
195
  }
196
+ function editOutcomeFailure(params) {
197
+ if (params.mode !== "edit")
198
+ return undefined;
199
+ const targeted = targetedProductRepos({
200
+ productNames: params.productWorktrees.map((product) => product.name),
201
+ plan: params.plan,
202
+ hints: params.hints,
203
+ });
204
+ const unchanged = params.productWorktrees
205
+ .filter((product) => targeted.includes(product.name) && !productHasPendingWork(product))
206
+ .map((product) => product.name);
207
+ return executorOutcomeFailure({
208
+ output: params.output,
209
+ unchangedTargetedRepos: unchanged,
210
+ resumeHint: params.resumeHint,
211
+ });
212
+ }
195
213
  // 1件の plan/result を executor→reporter の2段階で実行する。register 項目と Job Run の
196
214
  // 双方が使い、in-place(cwd: repoRoot)・worktree(cwd: worktree.path)から共有する。
197
215
  // evidence・pipeline-state の記録先は
@@ -229,6 +247,9 @@ export async function runAgentPipeline(params) {
229
247
  ...(params.integrationBranchOverrides
230
248
  ? { integrationBranches: { ...params.integrationBranchOverrides } }
231
249
  : {}),
250
+ ...(params.resumeNotes?.length
251
+ ? { resumeNotes: params.resumeNotes.map((entry) => ({ ...entry, notes: [...entry.notes] })) }
252
+ : {}),
232
253
  });
233
254
  state = updatePipelineStage(state, "executor", { status: "running", started_at: startedAt }, startedAt);
234
255
  writePipelineState(stateLocation.path, state);
@@ -279,13 +300,32 @@ export async function runAgentPipeline(params) {
279
300
  initialChangeTargets: params.initialChangeTargets,
280
301
  })
281
302
  : undefined;
282
- const executorResult = completionFailure || coverageFailure ? "failure" : outcome.result;
303
+ // PJR-QQRH: a complete report cannot override tool-permission denials in the output or a
304
+ // targeted product repository left unchanged. The evidence is marked incomplete so resume
305
+ // selects the executor stage, as with the approach contract.
306
+ const outcomeFailure = outcome.result === "success" && !completionFailure && !coverageFailure
307
+ ? editOutcomeFailure({
308
+ mode: params.mode ?? "edit",
309
+ output: `${outcome.stdout}\n${outcome.stderr}`,
310
+ plan: planPrompt,
311
+ productWorktrees: params.productWorktrees ?? [],
312
+ hints: params.productTargetHints ?? [],
313
+ resumeHint: params.executorResumeHint ?? DEFAULT_EXECUTOR_RESUME_HINT,
314
+ })
315
+ : undefined;
316
+ if (outcomeFailure) {
317
+ recorded.evidence.completion_status = "incomplete";
318
+ recorded.evidence.block_reason = outcomeFailure;
319
+ writeExecutorEvidence(recorded.evidencePath, recorded.evidence);
320
+ process.stdout.write(` Warning: ${outcomeFailure}\n`);
321
+ }
322
+ const executorResult = completionFailure || coverageFailure || outcomeFailure ? "failure" : outcome.result;
283
323
  const evidenceRef = relative(cwd, recorded.evidencePath).split(sep).join("/");
284
324
  const executorCompletedAt = new Date().toISOString();
285
325
  state = updatePipelineStage(state, "executor", {
286
326
  status: executorResult === "success"
287
327
  ? "succeeded"
288
- : outcome.protectionBlock || completionFailure
328
+ : outcome.protectionBlock || completionFailure || outcomeFailure
289
329
  ? "blocked"
290
330
  : executorResult === "rate_limit"
291
331
  ? "rate_limited"
@@ -301,6 +341,7 @@ export async function runAgentPipeline(params) {
301
341
  if (executorResult !== "success") {
302
342
  const blockReason = completionFailure ??
303
343
  coverageFailure ??
344
+ outcomeFailure ??
304
345
  (executorResult === "rate_limit"
305
346
  ? "executor rate limit reached"
306
347
  : extractBlockReason(outcome.stderr));
@@ -8,6 +8,7 @@ import { runJobWithProjectLock } from "./job-lock.js";
8
8
  import { spawnRefresh, spawnValidate } from "./mode-shared.js";
9
9
  import { resolveRegisterPipelineCommand } from "./register-core.js";
10
10
  import { runRegisterMode } from "./register-mode.js";
11
+ import { resumeNoteOptionError } from "./resume-notes.js";
11
12
  import { runBatchMode, runManualMode } from "./schedule-mode.js";
12
13
  import { EXCLUSIVE_EXEC_RUN, parseParallel, resolveExecDefaultsPath, resolveRegisterWorktree, withProjectExecRunLock, } from "./shared.js";
13
14
  import { withTrailingRunRecords } from "./trailing-records.js";
@@ -38,6 +39,7 @@ export function registerRunCommand(exec) {
38
39
  rcmd.option("--on-failure <mode>", "With --register: stop|continue remaining items after a failure (default: stop)");
39
40
  rcmd.option("--resume", "With register worktree mode: resume the stage where a run stopped (executor, reporter, or integration), reusing the existing worktree and checkpoints", false);
40
41
  rcmd.option("--resume-from <stage>", "With --resume: resume a reporter-stage run from executor instead (accepted value: executor)");
42
+ rcmd.option("--resume-note <text>", "With --resume --resume-from executor: add an instruction to the run's plan before the common conventions (repeatable; recorded in pipeline-state.json)", (value, previous = []) => [...previous, value]);
41
43
  rcmd.option("--force-restart", "With register worktree mode: re-run the whole item even when a resumable executor result exists (discards the worktree and its uncommitted changes)", false);
42
44
  rcmd.option("--worktree", "Use a git worktree and integrate back (requires --task, --register, or --job; Job runs are committed and reviewed before merge)", false);
43
45
  rcmd.option("--in-place", "Run a register item in the current working tree (overrides run.register_execution; cannot be combined with --worktree)", false);
@@ -110,6 +112,13 @@ export function registerRunCommand(exec) {
110
112
  process.exitCode = 1;
111
113
  return;
112
114
  }
115
+ // worktree の plan を書き換えるため、project の解決や lock より前に組み合わせを確かめる。
116
+ const resumeNoteError = resumeNoteOptionError(opts);
117
+ if (resumeNoteError) {
118
+ process.stdout.write(`${resumeNoteError}\n`);
119
+ process.exitCode = 1;
120
+ return;
121
+ }
113
122
  if (opts.worktree && opts.inPlace) {
114
123
  process.stdout.write("Specify either --worktree or --in-place, not both.\n");
115
124
  process.exitCode = 1;
@@ -8,7 +8,7 @@ import { displayIdFromTicketFilename } from "../../register/item.js";
8
8
  import { resolveAgentMember, } from "../../shared/specdojo-config.js";
9
9
  import { resolveMemberCommand, } from "../agent-config.js";
10
10
  import { buildInPlaceStem } from "../plans.js";
11
- import { generateRegisterPlan, normalizePjrId, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, selectRegisterCommitPaths, selectRegisterRunArtifactResidue, ticketPathFromItem, } from "../register.js";
11
+ import { generateRegisterPlan, normalizePjrId, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, selectRegisterCommitPaths, selectRegisterRunArtifactResidue, registerProductTargetHints, ticketPathFromItem, } from "../register.js";
12
12
  import { isResultUnfilled, readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus, } from "../results.js";
13
13
  import { recordRef } from "../run-records.js";
14
14
  import { configuredProductCheckouts } from "../task-repos.js";
@@ -339,6 +339,7 @@ export async function runSingleRegisterItem(context, opts, pjrId) {
339
339
  resultPath,
340
340
  registerPaths: registerReporterManagedPaths(registerPaths),
341
341
  execDefaults: context.execDefaults,
342
+ productTargetHints: registerProductTargetHints(item),
342
343
  productWorktrees: configuredProductCheckouts(schedulePath),
343
344
  providerConcurrencyGate: context.providerConcurrencyGate,
344
345
  executorRateLimitOptions: opts.executorBy
@@ -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")
@@ -308,6 +308,12 @@ export function pendingProductWorktreeChanges(worktree) {
308
308
  }
309
309
  return pending;
310
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
+ }
311
317
  export function assertNoPendingProductChanges(worktree) {
312
318
  const pending = pendingProductWorktreeChanges(worktree);
313
319
  if (pending.length === 0)
@@ -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
+ }
@@ -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)