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
@@ -0,0 +1,104 @@
1
+ import { parsePlanTaskIdentity } from "./plans-storage.js";
2
+ import { redactSensitiveText } from "./shared.js";
3
+ // executor が complete と報告しても、runner が観測した事実と食い違う場合は成功として扱わない
4
+ // (PJR-QQRH)。ツールの権限による拒否が出力にある場合と、プロダクトを対象にする計画なのに
5
+ // プロダクトの worktree に変更が無い場合を検出する。
6
+ /** Marker that `exec status` looks for in block reasons. */
7
+ export const NO_PRODUCT_CHANGES_MARKER = "no product changes";
8
+ const MAX_REASON_LENGTH = 1_000;
9
+ const MAX_DENIAL_SAMPLE_LENGTH = 120;
10
+ const REPORT_BLOCK_PATTERN = /<specdojo_executor_evidence>[\s\S]*?<\/specdojo_executor_evidence>/giu;
11
+ // provider のツール権限による拒否の文言。シェルの EACCES など一般的な "Permission denied" は
12
+ // テストの出力などにも現れるため対象にしない。
13
+ const PERMISSION_DENIAL_PATTERNS = [
14
+ // opencode: permission rule の deny(PJR-08EK の実観測)。
15
+ /The user has specified a rule which prevents you from using this specific tool call/iu,
16
+ /"permission"\s*:\s*"[^"]+"\s*,\s*"action"\s*:\s*"deny"/iu,
17
+ // Claude Code: deny rule と未許可の書き込み。
18
+ /Permission to use \S+(?: with [^\n]*)? has been denied/iu,
19
+ /requested permissions? to (?:use|write|edit|read)[^\n]*but you haven't granted it/iu,
20
+ ];
21
+ /** Output lines that show a provider's tool-permission denial, excluding the report envelope. */
22
+ export function toolPermissionDenials(output) {
23
+ const text = output.replace(REPORT_BLOCK_PATTERN, "");
24
+ const seen = new Set();
25
+ for (const line of text.split("\n")) {
26
+ const trimmed = line.trim();
27
+ if (!trimmed)
28
+ continue;
29
+ if (PERMISSION_DENIAL_PATTERNS.some((pattern) => pattern.test(trimmed)))
30
+ seen.add(trimmed);
31
+ }
32
+ return [...seen];
33
+ }
34
+ function escapeRegExp(value) {
35
+ return value.replace(/[.*+?^${}()|[\]\\]/gu, "\\$&");
36
+ }
37
+ /**
38
+ * Product repositories the task targets: a `<repo>:<path>` value in the plan frontmatter
39
+ * `targets` or in `hints` (register `target_path` / `targets`), or a `<repo>:<path>` reference
40
+ * in the plan body. Returned in the order of `productNames`.
41
+ */
42
+ export function targetedProductRepos(params) {
43
+ const identity = parsePlanTaskIdentity(params.plan);
44
+ const declared = [...(identity?.targets ?? []), ...(params.hints ?? [])].map((value) => value.trim());
45
+ return params.productNames.filter((name) => {
46
+ if (declared.some((value) => value.startsWith(`${name}:`) && value.length > name.length + 1)) {
47
+ return true;
48
+ }
49
+ // approach の plan は対象を frontmatter の targets で宣言し、本文の `<repo>:<path>` は
50
+ // 読み取り専用の手本(sources)でもありうるため、本文からは判定しない。
51
+ if (identity?.approach)
52
+ return false;
53
+ // 直前が語の一部でなく、`:` の直後にパスが続く参照だけを数える(`app1: 説明` は数えない)。
54
+ const reference = new RegExp(`(?:^|[^A-Za-z0-9._/:-])${escapeRegExp(name)}:[A-Za-z0-9._/-]`, "mu");
55
+ return reference.test(params.plan);
56
+ });
57
+ }
58
+ function bounded(value, limit) {
59
+ const redacted = redactSensitiveText(value);
60
+ return redacted.length <= limit ? redacted : `${redacted.slice(0, Math.max(0, limit - 1))}…`;
61
+ }
62
+ /**
63
+ * Why an executor that reported complete must not be treated as successful, or undefined.
64
+ * `unchangedTargetedRepos` lists targeted product repositories without uncommitted changes or
65
+ * exec-branch commits.
66
+ */
67
+ export function executorOutcomeFailure(params) {
68
+ // register の block_reason は 200 文字で切られるため、`exec status` が探す目印を先頭に置く。
69
+ const reasons = [];
70
+ if (params.unchangedTargetedRepos.length > 0) {
71
+ reasons.push(`${NO_PRODUCT_CHANGES_MARKER} in ${params.unchangedTargetedRepos.join(", ")} ` +
72
+ "although the plan targets it");
73
+ }
74
+ const denials = toolPermissionDenials(params.output);
75
+ if (denials.length > 0) {
76
+ reasons.push(`${denials.length} tool permission denial(s) in executor output ` +
77
+ `(first: ${bounded(denials[0], MAX_DENIAL_SAMPLE_LENGTH)})`);
78
+ }
79
+ if (reasons.length === 0)
80
+ return undefined;
81
+ return bounded(`${reasons.join("; ")}; executor reported complete; next: ${params.resumeHint}`, MAX_REASON_LENGTH);
82
+ }
83
+ /** Whether a block reason records the missing product changes, for status warnings. */
84
+ export function isNoProductChangesReason(reason) {
85
+ return typeof reason === "string" && reason.includes(NO_PRODUCT_CHANGES_MARKER);
86
+ }
87
+ /**
88
+ * `exec status` warning lines for waiting register items and blocked schedule tasks whose block
89
+ * reason records missing product changes. Sorted by ID.
90
+ */
91
+ export function noProductChangeWarnings(input) {
92
+ const lines = [
93
+ ...input.registerItems
94
+ .filter((item) => item.status === "waiting" && isNoProductChangesReason(item.blockReason))
95
+ .map((item) => ({
96
+ id: item.id,
97
+ line: `${item.id} (register, waiting): ${item.blockReason}`,
98
+ })),
99
+ ...input.tasks
100
+ .filter((task) => task.state === "blocked" && isNoProductChangesReason(task.lastMsg))
101
+ .map((task) => ({ id: task.taskId, line: `${task.taskId} (blocked): ${task.lastMsg}` })),
102
+ ];
103
+ return lines.sort((a, b) => a.id.localeCompare(b.id)).map((entry) => entry.line);
104
+ }
@@ -1,6 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
3
  import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
4
+ import { warnDeprecated } from "../shared/deprecation.js";
4
5
  import { readSpecdojoNamespace } from "../shared/frontmatter-namespace.js";
5
6
  import { listFilesRecursive } from "../shared/fs.js";
6
7
  import { gitEnvironment } from "../shared/git.js";
@@ -229,11 +230,12 @@ export function applyRecordMigration(repoRoot, plan) {
229
230
  export function registerRecordMigrationCommand(exec) {
230
231
  const command = exec
231
232
  .command("migrate-records")
232
- .description("Move tracked legacy run records with git mv");
233
+ .description("Deprecated: legacy run record migration is no longer needed; standard layout is execution/runs/ (will be removed in 0.10.0)");
233
234
  addProjectOptions(command);
234
235
  command.option("--dry-run", "List moves and reference updates without writing", false);
235
236
  command.action((opts) => {
236
237
  try {
238
+ warnDeprecated("exec migrate-records", "Legacy run record migration is no longer needed as execution/runs/ is standard. This command will be removed in 0.10.0.");
237
239
  const { executionPath } = resolveProjectContext(opts);
238
240
  const root = specdojoRootDir();
239
241
  const plan = planRecordMigration(root, executionPath, resolveProjectId(opts));
@@ -0,0 +1,117 @@
1
+ import { relative, resolve } from "node:path";
2
+ /**
3
+ * Runtime permission injection that lets an OpenCode agent edit declared extra roots (product
4
+ * worktrees, external projects). OpenCode merges `OPENCODE_CONFIG_CONTENT` after the
5
+ * `.opencode/agents/<name>.md` definitions, so the override survives the agent frontmatter, while
6
+ * `opencode.json` `agent.<name>.permission` would be overwritten by it.
7
+ *
8
+ * OpenCode matches the two permissions in different forms: `external_directory` by the absolute
9
+ * directory path and `edit` by the path relative to its working directory. The injected patterns
10
+ * follow those forms, and only the given roots are allowed; other external directories stay denied.
11
+ */
12
+ export const OPENCODE_CONFIG_CONTENT_ENV = "OPENCODE_CONFIG_CONTENT";
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function toPosix(path) {
17
+ return path.replaceAll("\\", "/");
18
+ }
19
+ /** `external_directory` pattern: the absolute root path. */
20
+ export function opencodeExternalDirectoryPattern(root) {
21
+ return `${toPosix(resolve(root))}/**`;
22
+ }
23
+ /** `edit` pattern: the root relative to OpenCode's working directory (e.g. `../app1/**`). */
24
+ export function opencodeEditPattern(root, cwd) {
25
+ const relativePath = toPosix(relative(resolve(cwd), resolve(root)));
26
+ return relativePath ? `${relativePath}/**` : "**";
27
+ }
28
+ /**
29
+ * Merge the extra-root permissions for `agentName` into the current `OPENCODE_CONFIG_CONTENT`.
30
+ * Other keys and agents are preserved. Throws when the current value is not a valid config object.
31
+ */
32
+ export function opencodeExtraRootConfig(current, agentName, roots, cwd) {
33
+ let config = {};
34
+ if (current?.trim()) {
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(current);
38
+ }
39
+ catch (error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: ${message}`, { cause: error });
42
+ }
43
+ if (!isRecord(parsed)) {
44
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: top-level value must be an object`);
45
+ }
46
+ config = parsed;
47
+ }
48
+ const agents = config.agent === undefined ? {} : config.agent;
49
+ if (!isRecord(agents)) {
50
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent must be an object`);
51
+ }
52
+ const selectedAgent = agents[agentName] === undefined ? {} : agents[agentName];
53
+ if (!isRecord(selectedAgent)) {
54
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName} must be an object`);
55
+ }
56
+ const permission = selectedAgent.permission === undefined ? {} : selectedAgent.permission;
57
+ if (!isRecord(permission)) {
58
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName}.permission must be an object`);
59
+ }
60
+ const externalDirectory = { "*": "deny" };
61
+ const currentEdit = permission.edit;
62
+ let edit = {};
63
+ if (isRecord(currentEdit)) {
64
+ edit = { ...currentEdit };
65
+ }
66
+ else if (typeof currentEdit === "string") {
67
+ edit = { "*": currentEdit };
68
+ }
69
+ else if (currentEdit !== undefined) {
70
+ throw new Error(`Invalid ${OPENCODE_CONFIG_CONTENT_ENV}: agent.${agentName}.permission.edit must be a string or object`);
71
+ }
72
+ for (const root of roots) {
73
+ externalDirectory[opencodeExternalDirectoryPattern(root)] = "allow";
74
+ edit[opencodeEditPattern(root, cwd)] = "allow";
75
+ }
76
+ return JSON.stringify({
77
+ ...config,
78
+ agent: {
79
+ ...agents,
80
+ [agentName]: {
81
+ ...selectedAgent,
82
+ permission: {
83
+ ...permission,
84
+ external_directory: externalDirectory,
85
+ edit,
86
+ },
87
+ },
88
+ },
89
+ });
90
+ }
91
+ /** Agent name from `--agent <name>` / `--agent=<name>` arguments (the last one wins). */
92
+ export function opencodeAgentNameFromArguments(args) {
93
+ let selected;
94
+ for (let index = 0; index < args.length; index += 1) {
95
+ const arg = args[index];
96
+ if (arg === "--agent") {
97
+ selected = args[index + 1];
98
+ index += 1;
99
+ }
100
+ else if (arg.startsWith("--agent=")) {
101
+ selected = arg.slice("--agent=".length);
102
+ }
103
+ }
104
+ const trimmed = selected?.trim();
105
+ return trimmed ? trimmed : undefined;
106
+ }
107
+ /**
108
+ * Agent name in a resolved shell command such as `opencode run --agent opencode-executor ...`.
109
+ * Single or double quotes around the name are accepted; anything else is split on whitespace.
110
+ */
111
+ export function opencodeAgentNameFromCommand(command) {
112
+ const words = command
113
+ .trim()
114
+ .split(/\s+/)
115
+ .map((word) => word.replace(/^(['"])(.*)\1$/, "$2"));
116
+ return opencodeAgentNameFromArguments(words);
117
+ }
@@ -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;
@@ -1,4 +1,5 @@
1
1
  import { stagedMergeBlocker } from "../shared/git.js";
2
+ import { escapeRegExp } from "../shared/text.js";
2
3
  import { acquireSchedulerLock, releaseSchedulerLock } from "./events.js";
3
4
  import { currentBranch } from "./worktree-ops-commit.js";
4
5
  import { abortMerge } from "./worktree-ops-merge.js";
@@ -12,9 +13,6 @@ import { gitOutput, gitResult, summarizeGitHookFailure } from "./worktree.js";
12
13
  // 後で job の branch を本体へ統合しても、同じ commit を共有して衝突しない。
13
14
  const LOCK_TIMEOUT_MS = 10_000;
14
15
  const LOCK_STALE_MS = 300_000;
15
- function escapeRegExp(value) {
16
- return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
17
- }
18
16
  // exec branch の first-parent 履歴から最新の wait 後の同期 merge を探し、その統合先の commit が
19
17
  // 本体の HEAD に含まれていなければ返す。同期 merge が無い、または含まれている場合は null。
20
18
  export function findForeignWaitRecords(params) {
@@ -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)) {
@@ -1,5 +1,6 @@
1
1
  import { readFileSync, writeFileSync } from "node:fs";
2
2
  import { productMergeState } from "./repo-integration.js";
3
+ import { escapeMarkdownTableCell } from "../shared/text.js";
3
4
  import { productIntegrationTarget } from "./task-repos.js";
4
5
  import { gitOutput, gitResult } from "./worktree.js";
5
6
  // PJR-30SW: プロダクト側の commit と merge commit へ付ける `Refs:` trailer と、統合後に result へ
@@ -96,7 +97,7 @@ function traceRows(key, traces, recordedAt) {
96
97
  ]);
97
98
  }
98
99
  function renderTable(header, rows) {
99
- const escape = (cell) => cell.replace(/\|/g, "\\|");
100
+ const escape = (cell) => escapeMarkdownTableCell(cell);
100
101
  const all = [header.map(escape), ...rows.map((row) => row.map(escape))];
101
102
  const widths = header.map((cell, column) => Math.max(3, cell.length, ...all.map((row) => (row[column] ?? "").length)));
102
103
  const line = (cells) => `| ${cells.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" | ")} |`;
@@ -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));
@@ -425,7 +425,7 @@ export async function runWithRetry(candidates, prompt, execDefaults, cwd, env, r
425
425
  lastActor = candidate.actor;
426
426
  const protectedConfigBefore = captureAgentProtectedConfigAcrossRepos(agentRepos);
427
427
  const gitStateBefore = captureAgentGitStateAcrossRepos(agentRepos);
428
- const attempt = await executeAgent(withAgentExtraRoots(candidate.command, candidate.provider, productRoots.map((root) => root.path)), prompt, detection, candidate.provider, candidatePolicy?.cooldown_seconds, cwd, env, false, stageRole);
428
+ const attempt = await executeAgent(withAgentExtraRoots(candidate.command, candidate.provider, productRoots.map((root) => root.path), { cwd, env }), prompt, detection, candidate.provider, candidatePolicy?.cooldown_seconds, cwd, env, false, stageRole);
429
429
  const protectedConfigChanges = changedAgentProtectedConfigAcrossRepos(protectedConfigBefore);
430
430
  if (protectedConfigChanges.length > 0) {
431
431
  // 利用上限で止まった場合も保護の検査は飛ばさない。止まった理由として利用上限を先に記録する。
@@ -186,11 +186,11 @@ export function inferChangeScope(params) {
186
186
  };
187
187
  for (const match of body.matchAll(/`([^`\n]+)`/g)) {
188
188
  const value = match[1].replace(/#.*$|:\d+(?::\d+)?$/g, "");
189
- if (/^(?:[\w-]+:)?(?:\.?\/?[\w@.-]+\/)+[\w@.*?{}[\]/-]*$/.test(value) ||
189
+ if (/^(?:[\w-]+:)?\.?\/?[\w@.-]+\/[\w@.*?{}[\]/-]*$/.test(value) ||
190
190
  /^[\w.-]+\.[a-z0-9]+$/i.test(value))
191
191
  addTextPath(value);
192
192
  }
193
- for (const match of body.matchAll(/(?:^|[\s`((・])((?:[\w-]+:)?(?:[\w@.-]+\/)+[\w@.*?{}[\]/-]+)/gm)) {
193
+ for (const match of body.matchAll(/(?:^|[\s`((・])((?:[\w-]+:)?[\w@.-]+\/[\w@.*?{}[\]/-]+)/gm)) {
194
194
  const value = match[1];
195
195
  // A slash in prose can also mean alternatives (executor/reporter). Accept filenames,
196
196
  // explicit directory/glob syntax, or an existing repository path rather than every slash.
@@ -111,7 +111,7 @@ export async function spawnAgentInPlace(command, prompt, cwd, schedulePath, exec
111
111
  const protectedConfigBefore = captureAgentProtectedConfigSnapshot(cwd);
112
112
  const gitStateBefore = captureAgentGitStateSnapshot(cwd);
113
113
  const products = configuredProductCheckouts(schedulePath);
114
- const child = spawn(withAgentExtraRoots(command, provider, products.map((product) => product.path)), {
114
+ const child = spawn(withAgentExtraRoots(command, provider, products.map((product) => product.path), { cwd }), {
115
115
  cwd,
116
116
  env: {
117
117
  ...withoutInheritedRepoEnvironment(gitEnvironment()),
@@ -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