specdojo 0.3.0 → 0.3.1

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 (104) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/catalog-build-references.js +144 -0
  3. package/dist/catalog-build-render.js +144 -0
  4. package/dist/catalog-build.js +13 -290
  5. package/dist/catalog-generate.js +6 -9
  6. package/dist/catalog-plan-generate.js +2 -2
  7. package/dist/catalog-plan.js +6 -6
  8. package/dist/catalog-scaffold.js +4 -4
  9. package/dist/catalog.js +2 -2
  10. package/dist/dashboard-exec-records.js +105 -0
  11. package/dist/dashboard-routines.js +255 -0
  12. package/dist/dashboard-shared.js +14 -0
  13. package/dist/dashboard-timeline.js +175 -0
  14. package/dist/dashboard.js +10 -544
  15. package/dist/deliverable-trash.js +3 -3
  16. package/dist/doc-index.js +3 -3
  17. package/dist/exec-commands.js +557 -0
  18. package/dist/exec-core.js +457 -0
  19. package/dist/exec-plans-core.js +693 -0
  20. package/dist/exec-plans-generation.js +206 -0
  21. package/dist/exec-plans-storage.js +131 -0
  22. package/dist/exec-plans.js +3 -1018
  23. package/dist/exec-repo-integration-git.js +23 -0
  24. package/dist/exec-repo-integration-sync.js +264 -0
  25. package/dist/exec-repo-integration.js +4 -281
  26. package/dist/exec-reporter-output.js +206 -0
  27. package/dist/exec-reporter.js +2 -206
  28. package/dist/exec-results.js +22 -15
  29. package/dist/exec-run-agent-pipeline.js +256 -0
  30. package/dist/exec-run-agent.js +531 -0
  31. package/dist/exec-run-in-place.js +541 -0
  32. package/dist/exec-run-job.js +717 -0
  33. package/dist/exec-run-lifecycle-commands.js +522 -0
  34. package/dist/exec-run-mode-shared.js +140 -0
  35. package/dist/exec-run-register-command.js +244 -0
  36. package/dist/exec-run-register-core.js +386 -0
  37. package/dist/exec-run-register-mode.js +206 -0
  38. package/dist/exec-run-register-resume.js +393 -0
  39. package/dist/exec-run-register-state.js +322 -0
  40. package/dist/exec-run-register-worktree.js +509 -0
  41. package/dist/exec-run-schedule-mode.js +294 -0
  42. package/dist/exec-run-schedule-prepare.js +353 -0
  43. package/dist/exec-run-schedule-task.js +572 -0
  44. package/dist/exec-run-shared.js +399 -0
  45. package/dist/exec-run.js +11 -6182
  46. package/dist/exec-shared.js +2 -2
  47. package/dist/exec-trial-commands.js +558 -0
  48. package/dist/exec-trial-core.js +371 -0
  49. package/dist/exec-trial.js +2 -921
  50. package/dist/exec-worktree-ops-commit.js +707 -0
  51. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  52. package/dist/exec-worktree-ops-merge.js +303 -0
  53. package/dist/exec-worktree-ops.js +3 -1292
  54. package/dist/exec-worktree.js +32 -4
  55. package/dist/exec.js +2 -1006
  56. package/dist/frontmatter-namespace.js +2 -2
  57. package/dist/grade-apply.js +734 -0
  58. package/dist/grade-command-apply.js +250 -0
  59. package/dist/grade-command-inspect.js +138 -0
  60. package/dist/grade-command-plan.js +101 -0
  61. package/dist/grade-command-shared.js +68 -0
  62. package/dist/grade-core.js +307 -0
  63. package/dist/grade-markdown.js +274 -0
  64. package/dist/grade-pipeline-state.js +184 -0
  65. package/dist/grade-plan.js +507 -0
  66. package/dist/grade-result.js +5 -5
  67. package/dist/grade-target-discovery.js +265 -0
  68. package/dist/grade-targets.js +432 -0
  69. package/dist/grade.js +14 -3188
  70. package/dist/init-command.js +7 -7
  71. package/dist/job-definition.js +670 -0
  72. package/dist/job.js +9 -673
  73. package/dist/kata-command.js +2 -2
  74. package/dist/register-command-types.js +1 -0
  75. package/dist/register-core.js +363 -0
  76. package/dist/register-create-commands.js +245 -0
  77. package/dist/register-events.js +4 -4
  78. package/dist/register-item.js +6 -6
  79. package/dist/register-maintenance-commands.js +187 -0
  80. package/dist/register-migration.js +268 -0
  81. package/dist/register-renumber.js +314 -0
  82. package/dist/register-transition-commands.js +248 -0
  83. package/dist/register-update.js +230 -0
  84. package/dist/register-views.js +256 -0
  85. package/dist/register.js +61 -2069
  86. package/dist/review-plan.js +3 -3
  87. package/dist/routine-definition.js +401 -0
  88. package/dist/routine.js +6 -402
  89. package/dist/schedule-approach.js +2 -2
  90. package/dist/schedule-strategy-generate-document.js +273 -0
  91. package/dist/schedule-strategy-generate-scope.js +199 -0
  92. package/dist/schedule-strategy-generate.js +9 -473
  93. package/dist/schedule.js +4 -4
  94. package/dist/specdojo-config.js +3 -4
  95. package/dist/viewpoint-document-kinds-check.js +3 -3
  96. package/dist/yaml-pages.js +4 -4
  97. package/dist/yaml.js +28 -0
  98. package/docs/ja/specdojo/guides/exec-config-guide.md +6 -6
  99. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +20 -18
  100. package/docs/ja/specdojo/guides/routine-operation-guide.md +1 -1
  101. package/package.json +4 -5
  102. package/templates/antigravity/README.md +3 -3
  103. package/templates/antigravity/exec-defaults-snippet.yaml +6 -4
  104. package/templates/init-exec-defaults.yaml +3 -1
@@ -0,0 +1,244 @@
1
+ import { loadExecDefaultsConfig } from "./exec-agent-config.js";
2
+ import { resolveProjectPaths } from "./exec-project.js";
3
+ import { isRegisterFailureMode } from "./exec-register.js";
4
+ import { EXCLUSIVE_EXEC_RUN, parseParallel, resolveExecDefaultsPath, resolveRegisterWorktree, withProjectExecRunLock, } from "./exec-run-shared.js";
5
+ import { runBatchMode, runManualMode } from "./exec-run-schedule-mode.js";
6
+ import { runInPlaceMode } from "./exec-run-in-place.js";
7
+ import { runJobMode } from "./exec-run-job.js";
8
+ import { spawnRefresh, spawnValidate } from "./exec-run-mode-shared.js";
9
+ import { resolveRegisterPipelineCommand } from "./exec-run-register-core.js";
10
+ import { runRegisterMode } from "./exec-run-register-mode.js";
11
+ export function registerRunCommand(exec) {
12
+ const rcmd = exec
13
+ .command("run")
14
+ .description("Run AI agent for a ready task (--auto selects next by strategy)");
15
+ rcmd.option("--project <projectId>", "Project id in .specdojo/specdojo.config.json");
16
+ rcmd.option("--by <nickname>", "Select an agent-members.yaml agent for a manual target");
17
+ rcmd.option("--auto", "Automatically select and run next ready task", false);
18
+ rcmd.option("--task <taskId>", "Task ID to run (manual selection)");
19
+ rcmd.option("--deliverable <localId>", "Catalog deliverable local_id target (unique project-wide)");
20
+ rcmd.option("--plan <path>", "Run an existing plan file (in-place; no generation)");
21
+ rcmd.option("--register <pjrIds...>", "One or more project register item IDs (PJR-XXXX) to run; execution location defaults to run.register_execution in exec-defaults (in-place when unset)");
22
+ rcmd.option("--register-filter", "Select register items deterministically with --register-types/--register-priorities/--register-statuses/--register-limit", false);
23
+ rcmd.option("--register-types <types>", "Comma-separated register item types");
24
+ rcmd.option("--register-priorities <priorities>", "Comma-separated register priorities");
25
+ rcmd.option("--register-statuses <statuses>", "Comma-separated register statuses");
26
+ rcmd.option("--register-limit <n>", "Maximum selected register items");
27
+ rcmd.option("--job <jobId>", "Materialize and run a reusable job definition");
28
+ rcmd.option("--input <key=value...>", "Job input values (repeat or provide multiple key=value pairs)");
29
+ rcmd.option("--scheduled-at <dateTime>", "Scheduled occurrence time for a Job Run");
30
+ rcmd.option("--job-trigger <source>", "Job trigger source: manual|routine|ci", "manual");
31
+ rcmd.option("--register-commit", "With in-place --register: commit each successful item's changes as a separate commit (default: leave changes in the working tree). Ignored in worktree mode, which always commits", false);
32
+ rcmd.option("--on-failure <mode>", "With --register: stop|continue remaining items after a failure (default: stop)");
33
+ 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);
34
+ rcmd.option("--resume-from <stage>", "With --resume: resume a reporter-stage run from executor instead (accepted value: executor)");
35
+ 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);
36
+ rcmd.option("--worktree", "Use a git worktree and integrate back (requires --task, --register, or --job; Job runs are committed and reviewed before merge)", false);
37
+ rcmd.option("--in-place", "Run a register item in the current working tree (overrides run.register_execution; cannot be combined with --worktree)", false);
38
+ rcmd.option("--track-state", "Record claim/complete events (requires --task; --by optional, actor auto-derived from the resolved agent)", false);
39
+ rcmd.option("--archive-on-success", "Archive the generated plan to exec/plans/done/ after a successful in-place run", false);
40
+ rcmd.option("--parallel <n>", "Number of worktree instances to run in parallel", "1");
41
+ rcmd.option("--worktree-base <path>", "Override worktree base directory");
42
+ rcmd.option("--strategy <s>", "Task selection strategy: critical-first|fifo (default: critical-first)");
43
+ rcmd.option("--loop", "Repeat rounds until no ready tasks remain, rebuilding doc-index and running exec refresh between rounds", false);
44
+ rcmd.option("--max-rounds <n>", "Maximum number of rounds when using --loop (ignored without --loop)");
45
+ rcmd.option("--if-busy <policy>", "When another exec is running for the project: skip|wait|fail (default: fail)", "fail");
46
+ rcmd.option("--join", "With register worktree mode: run next to a running register worktree exec instead of waiting for it, sharing its provider caps, lifecycle serialization, and parent-validation slots (up to run.max_concurrent_runs; --if-busy applies when all join slots are taken)", false);
47
+ rcmd.option("--exec-defaults <path>", "Path to exec-defaults.yaml global config (default: .specdojo/exec-defaults.yaml)");
48
+ rcmd.option("--agent-config <path>", "Deprecated alias for --exec-defaults");
49
+ rcmd.option("--edit-by <nickname>", "agent-members.yaml nickname for edit-mode tasks in --auto batch runs");
50
+ rcmd.option("--review-by <nickname>", "agent-members.yaml nickname for review-mode tasks in --auto batch runs");
51
+ rcmd.option("--executor-by <nickname>", "Executor nickname; with --register, also accepts PJR-ID=nickname assignments separated by commas. With --plan / --deliverable, runs the executor/reporter pipeline");
52
+ rcmd.option("--reporter-by <nickname>", "agent-members.yaml reporter nickname for agent_pipeline tasks (with --plan / --deliverable, runs the executor/reporter pipeline)");
53
+ rcmd.option("--dry-run", "Print resolved command without executing", false);
54
+ rcmd.action(async (opts) => {
55
+ try {
56
+ const isAuto = !!opts.auto;
57
+ const hasTask = !!opts.task;
58
+ const hasDeliverable = !!opts.deliverable;
59
+ const hasPlan = !!opts.plan;
60
+ const hasRegisterIds = !!opts.register;
61
+ const hasRegisterFilter = !!opts.registerFilter;
62
+ const hasRegister = hasRegisterIds || hasRegisterFilter;
63
+ const hasJob = !!opts.job;
64
+ const isManual = hasTask || hasDeliverable || hasPlan || hasRegister || hasJob;
65
+ const isBatch = isAuto;
66
+ if (hasRegisterIds && hasRegisterFilter) {
67
+ process.stdout.write("Specify either --register or --register-filter, not both.\n");
68
+ process.exitCode = 1;
69
+ return;
70
+ }
71
+ if ((opts.registerTypes ||
72
+ opts.registerPriorities ||
73
+ opts.registerStatuses ||
74
+ opts.registerLimit) &&
75
+ !hasRegisterFilter) {
76
+ process.stdout.write("--register-types, --register-priorities, --register-statuses, and --register-limit require --register-filter.\n");
77
+ process.exitCode = 1;
78
+ return;
79
+ }
80
+ if (!isAuto && !isManual) {
81
+ process.stdout.write("Specify --auto, --by (with a manual target), --task, --deliverable, --plan, --register, or --job.\n");
82
+ process.exitCode = 1;
83
+ return;
84
+ }
85
+ if ([hasTask, hasDeliverable, hasPlan, hasRegister, hasJob].filter(Boolean).length > 1) {
86
+ process.stdout.write("Specify at most one of --task, --deliverable, --plan, --register, --job.\n");
87
+ process.exitCode = 1;
88
+ return;
89
+ }
90
+ if (hasRegister && opts.trackState) {
91
+ process.stdout.write("--track-state cannot be used with --register (state is tracked in the register itself).\n");
92
+ process.exitCode = 1;
93
+ return;
94
+ }
95
+ if (opts.worktree && opts.inPlace) {
96
+ process.stdout.write("Specify either --worktree or --in-place, not both.\n");
97
+ process.exitCode = 1;
98
+ return;
99
+ }
100
+ if (opts.inPlace && !hasRegister) {
101
+ process.stdout.write("--in-place requires --register or --register-filter.\n");
102
+ process.exitCode = 1;
103
+ return;
104
+ }
105
+ if (hasRegister) {
106
+ const { schedulePath, executionPath } = resolveProjectPaths({ project: opts.project });
107
+ const execDefaults = loadExecDefaultsConfig(resolveExecDefaultsPath(opts, schedulePath), executionPath);
108
+ opts.worktree = resolveRegisterWorktree(opts, execDefaults);
109
+ }
110
+ if (hasRegister && !opts.worktree && parseParallel(opts.parallel) !== 1) {
111
+ process.stdout.write("--parallel with --register requires worktree mode; use --worktree or configure run.register_execution: worktree.\n");
112
+ process.exitCode = 1;
113
+ return;
114
+ }
115
+ if (opts.join && !(hasRegister && opts.worktree)) {
116
+ process.stdout.write("--join requires --register (or --register-filter) in worktree mode.\n");
117
+ process.exitCode = 1;
118
+ return;
119
+ }
120
+ if (hasRegister && opts.worktree && opts.registerCommit) {
121
+ process.stdout.write("Note: --register-commit is ignored in worktree mode; worktree runs always commit (checkpoint + merge back).\n");
122
+ }
123
+ if ((opts.registerCommit || opts.onFailure) && !hasRegister) {
124
+ process.stdout.write("--register-commit and --on-failure require --register.\n");
125
+ process.exitCode = 1;
126
+ return;
127
+ }
128
+ if ((opts.resume || opts.forceRestart) && !hasRegister) {
129
+ process.stdout.write("--resume and --force-restart require --register.\n");
130
+ process.exitCode = 1;
131
+ return;
132
+ }
133
+ if (opts.resumeFrom && !opts.resume) {
134
+ process.stdout.write("--resume-from requires --resume.\n");
135
+ process.exitCode = 1;
136
+ return;
137
+ }
138
+ if (opts.resumeFrom && opts.resumeFrom !== "executor") {
139
+ process.stdout.write('--resume-from must be "executor".\n');
140
+ process.exitCode = 1;
141
+ return;
142
+ }
143
+ // 再開は既存 worktree の成果を再利用する操作のため、worktree 実行に限る。in-place 実行は
144
+ // executor の変更が作業ツリーに残り、再開時のID単位 commit が対象を判別できない。
145
+ if ((opts.resume || opts.forceRestart) && !opts.worktree) {
146
+ process.stdout.write("--resume and --force-restart require register worktree mode; use --worktree or configure run.register_execution: worktree.\n");
147
+ process.exitCode = 1;
148
+ return;
149
+ }
150
+ if (opts.resume && opts.forceRestart) {
151
+ process.stdout.write("Specify either --resume or --force-restart, not both.\n");
152
+ process.exitCode = 1;
153
+ return;
154
+ }
155
+ if ((opts.input || opts.scheduledAt) && !hasJob) {
156
+ process.stdout.write("--input and --scheduled-at require --job.\n");
157
+ process.exitCode = 1;
158
+ return;
159
+ }
160
+ if (opts.jobTrigger && !["manual", "routine", "ci"].includes(opts.jobTrigger)) {
161
+ process.stdout.write("--job-trigger must be manual, routine, or ci.\n");
162
+ process.exitCode = 1;
163
+ return;
164
+ }
165
+ if (opts.onFailure && !isRegisterFailureMode(opts.onFailure)) {
166
+ process.stdout.write(`--on-failure must be "stop" or "continue": ${opts.onFailure}\n`);
167
+ process.exitCode = 1;
168
+ return;
169
+ }
170
+ if (isAuto && isManual) {
171
+ process.stdout.write("Specify either --auto or a manual target, not both.\n");
172
+ process.exitCode = 1;
173
+ return;
174
+ }
175
+ if (isAuto && opts.by) {
176
+ process.stdout.write("--by requires a manual target; use --edit-by / --review-by with --auto.\n");
177
+ process.exitCode = 1;
178
+ return;
179
+ }
180
+ if (opts.by && opts.executorBy) {
181
+ process.stdout.write("Specify either --by or --executor-by, not both.\n");
182
+ process.exitCode = 1;
183
+ return;
184
+ }
185
+ if (opts.worktree && !hasTask && !hasRegister && !hasJob) {
186
+ process.stdout.write("--worktree requires --task, --register, or --job.\n");
187
+ process.exitCode = 1;
188
+ return;
189
+ }
190
+ // --parallel is allowed for register worktree runs (handled above); reject it for other
191
+ // manual targets, which run a single instance.
192
+ if (isManual && !hasRegister && parseParallel(opts.parallel) !== 1) {
193
+ process.stdout.write("--parallel cannot be used with a manual target.\n");
194
+ process.exitCode = 1;
195
+ return;
196
+ }
197
+ // register worktree 実行だけが共有資源をプロセス横断で統制するため、後から --join する
198
+ // run を受け入れる。それ以外の run は従来どおり project 全体を排他する。
199
+ const registerWorktreeLockSharing = hasRegister && opts.worktree ? { shareable: true, join: !!opts.join } : EXCLUSIVE_EXEC_RUN;
200
+ await withProjectExecRunLock(opts, "run", async () => {
201
+ // Register-item run: use the configured location or an explicit CLI override, with state tracked
202
+ // via register transitions (start → review / waiting) instead of exec events.
203
+ if (hasRegister) {
204
+ await runRegisterMode(opts);
205
+ return;
206
+ }
207
+ if (hasJob) {
208
+ await runJobMode(opts, resolveRegisterPipelineCommand);
209
+ return;
210
+ }
211
+ // In-place manual run (default): generate the plan on demand and run in the
212
+ // current repository. No validate/refresh pass — that is orchestration only.
213
+ if (isManual && !opts.worktree) {
214
+ await runInPlaceMode(opts);
215
+ return;
216
+ }
217
+ process.stdout.write("[run] validate...\n");
218
+ if (!spawnValidate(opts.project)) {
219
+ process.stdout.write("[run] validate failed — exit\n");
220
+ process.exitCode = 1;
221
+ return;
222
+ }
223
+ process.stdout.write("[run] validate: ok\n[run] refresh...\n");
224
+ if (!spawnRefresh(opts.project)) {
225
+ process.stdout.write("[run] refresh failed — exit\n");
226
+ process.exitCode = 1;
227
+ return;
228
+ }
229
+ process.stdout.write("[run] refresh: ok\n");
230
+ if (isBatch) {
231
+ await runBatchMode(opts);
232
+ }
233
+ else {
234
+ await runManualMode(opts);
235
+ }
236
+ }, registerWorktreeLockSharing);
237
+ }
238
+ catch (error) {
239
+ const message = error instanceof Error ? error.message : String(error);
240
+ process.stdout.write(message + "\n");
241
+ process.exitCode = 1;
242
+ }
243
+ });
244
+ }
@@ -0,0 +1,386 @@
1
+ import { existsSync, readFileSync } from "node:fs";
2
+ import { basename } from "node:path";
3
+ import { resolveMemberCommand, } from "./exec-agent-config.js";
4
+ import { buildInPlaceStem } from "./exec-plans.js";
5
+ import { generateRegisterPlan, normalizePjrId, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, selectRegisterCommitPaths, selectRegisterRunArtifactResidue, ticketPathFromItem, } from "./exec-register.js";
6
+ import { registerEventFilePath } from "./register-events.js";
7
+ import { displayIdFromTicketFilename } from "./register-item.js";
8
+ import { isResultUnfilled, readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus, } from "./exec-results.js";
9
+ import { gitOutput, gitResult } from "./exec-worktree.js";
10
+ import { stabilizeCommitTargets, stageCommitTargets, unstageCommitTargets, worktreeStatusPaths, } from "./exec-worktree-ops.js";
11
+ import { resolveAgentOverride, selectCandidates, } from "./exec-run-shared.js";
12
+ import { expandPromptRefs } from "./exec-run-agent.js";
13
+ import { runAgentPipeline } from "./exec-run-agent-pipeline.js";
14
+ import { spawnAgentInPlace } from "./exec-run-in-place.js";
15
+ import { commitSubject, repoRelativePath, spawnSelf } from "./exec-run-mode-shared.js";
16
+ // --register の単一 agent 実行(--by 指定時)の agent を解決する。owner(Role code)や
17
+ // role からの自動選択は行わない(PJR-ADZ6)。agent は全員 stage_role を持つ pipeline
18
+ // メンバーであり、owner・role から選ぶと pipeline 用でない agent(翻訳専用など)や
19
+ // result を書かない executor が単独で選ばれてしまうため。--by が無い場合の agent は
20
+ // resolveRegisterPipelineCommand が stage_role から選ぶ。
21
+ export function resolveRegisterCommand(item, roster, opts, execDefaults = {}) {
22
+ const by = opts.by?.trim();
23
+ if (!by) {
24
+ throw new Error(`No agent specified for register item ${item.id} (owner: ${item.owner || "-"}). ` +
25
+ "Specify --by <nickname>, or --executor-by <nickname> --reporter-by <nickname>.");
26
+ }
27
+ const member = roster?.members.find((m) => m.nickname === by && m.type === "agent");
28
+ const command = member ? resolveMemberCommand(execDefaults, member) : undefined;
29
+ if (!command)
30
+ throw new Error(`Agent command not found for actor: ${by}`);
31
+ return { command, actor: by };
32
+ }
33
+ // --register を executor/reporter パイプラインで実行するかを判定する。--executor-by /
34
+ // --reporter-by の指定があれば pipeline、どちらも無く --by も無い場合も stage_role からの
35
+ // 自動選択で pipeline にする。--by だけを指定した場合に限り、従来の単一 agent 実行
36
+ // (resolveRegisterCommand)を使う。両者は互いに排他である。
37
+ export function isRegisterPipelineRequested(opts) {
38
+ if (opts.executorBy || opts.reporterBy)
39
+ return true;
40
+ return !opts.by?.trim();
41
+ }
42
+ // `--executor-by` keeps its original single-nickname form and additionally accepts a complete
43
+ // PJR-ID-to-nickname map. Requiring complete coverage makes an omitted item an input error instead
44
+ // of silently falling back to a different executor, while rejecting extra IDs catches typos and
45
+ // stale invocations before any register transition or worktree setup occurs.
46
+ export function parseRegisterExecutorSelection(raw, selectedIds) {
47
+ if (raw === undefined)
48
+ return { kind: "none" };
49
+ const value = raw.trim();
50
+ if (!value)
51
+ throw new Error("--executor-by must not be empty.");
52
+ if (!value.includes("="))
53
+ return { kind: "shared", executor: value };
54
+ const executors = new Map();
55
+ for (const entry of value.split(",")) {
56
+ const parts = entry.split("=");
57
+ if (parts.length !== 2) {
58
+ throw new Error(`Invalid --executor-by item assignment: ${entry}. Use PJR-ID=nickname separated by commas.`);
59
+ }
60
+ const id = normalizePjrId(parts[0]);
61
+ const executor = parts[1].trim();
62
+ if (!executor) {
63
+ throw new Error(`Invalid --executor-by item assignment for ${id}: nickname is empty.`);
64
+ }
65
+ if (executors.has(id)) {
66
+ throw new Error(`Duplicate --executor-by item assignment: ${id}.`);
67
+ }
68
+ executors.set(id, executor);
69
+ }
70
+ const selected = new Set(selectedIds);
71
+ const outsideTarget = [...executors.keys()].filter((id) => !selected.has(id));
72
+ if (outsideTarget.length > 0) {
73
+ throw new Error(`--executor-by item assignments include IDs outside the register execution target: ${outsideTarget.join(", ")}.`);
74
+ }
75
+ const missing = selectedIds.filter((id) => !executors.has(id));
76
+ if (missing.length > 0) {
77
+ throw new Error(`--executor-by item assignments must cover every selected register item; missing: ${missing.join(", ")}.`);
78
+ }
79
+ return { kind: "per-item", executors };
80
+ }
81
+ export function selectedRegisterExecutor(selection, itemId) {
82
+ if (selection.kind === "none")
83
+ return undefined;
84
+ return selection.kind === "shared" ? selection.executor : selection.executors.get(itemId);
85
+ }
86
+ // --register 向けの executor/reporter 解決。Schedule タスクの agent_pipeline と異なり、
87
+ // register 項目には per-item のパイプライン宣言が無いため、owner/role からの自動選択は行わない。
88
+ // --executor-by / --reporter-by は両方そろえて明示する。どちらも無い場合は stage_role:
89
+ // executor(mode: edit)と stage_role: reporter の agent から priority 順に自動選択する。
90
+ // stage_role を持たない agent(翻訳専用など)は候補に入らない(PJR-ADZ6)。
91
+ export function resolveRegisterPipelineCommand(roster, opts, execDefaults = {}) {
92
+ if (!opts.executorBy && !opts.reporterBy) {
93
+ return autoSelectRegisterPipelineAgents(roster, execDefaults);
94
+ }
95
+ if (!opts.executorBy || !opts.reporterBy) {
96
+ throw new Error("--register pipeline execution requires both --executor-by and --reporter-by.");
97
+ }
98
+ const executorResolution = resolveAgentOverride("edit", opts.executorBy, {}, roster, execDefaults, "executor");
99
+ if (executorResolution.kind === "error") {
100
+ throw new Error(executorResolution.message.replace(/^--by/, "--executor-by"));
101
+ }
102
+ if (executorResolution.kind !== "command") {
103
+ throw new Error(`--executor-by agent not found in agent-members.yaml: ${opts.executorBy}`);
104
+ }
105
+ const reporterResolution = resolveAgentOverride("edit", opts.reporterBy, {}, roster, execDefaults, "reporter");
106
+ if (reporterResolution.kind === "error") {
107
+ throw new Error(reporterResolution.message.replace(/^--by/, "--reporter-by"));
108
+ }
109
+ if (reporterResolution.kind !== "command") {
110
+ throw new Error(`--reporter-by agent not found in agent-members.yaml: ${opts.reporterBy}`);
111
+ }
112
+ return {
113
+ executor: {
114
+ command: executorResolution.command,
115
+ actor: executorResolution.actor ?? opts.executorBy,
116
+ provider: executorResolution.provider,
117
+ },
118
+ reporterCandidates: [
119
+ {
120
+ command: reporterResolution.command,
121
+ actor: reporterResolution.actor ?? opts.reporterBy,
122
+ provider: reporterResolution.provider,
123
+ },
124
+ ],
125
+ };
126
+ }
127
+ // --executor-by / --reporter-by も --by も無い --register 実行の agent を stage_role から選ぶ。
128
+ // executor は mode: edit の executor(mode 未指定を含む)、reporter は mode を問わない
129
+ // reporter を priority 順に候補とする。stage_role を持たない agent は selectCandidates の
130
+ // 段指定によって除外される。どちらかの段に候補が無い場合は明示指定を求めるエラーにする。
131
+ export function autoSelectRegisterPipelineAgents(roster, execDefaults) {
132
+ const toCandidates = (members) => members.flatMap((member) => {
133
+ const command = resolveMemberCommand(execDefaults, member);
134
+ return command ? [{ command, actor: member.nickname, provider: member.provider }] : [];
135
+ });
136
+ const executor = toCandidates(selectCandidates({ capabilities: [], stage_role: "executor" }, roster, "edit", undefined, execDefaults))[0];
137
+ const reporterCandidates = toCandidates(selectCandidates({ capabilities: [], stage_role: "reporter" }, roster, undefined, undefined, execDefaults));
138
+ if (!executor || reporterCandidates.length === 0) {
139
+ const missing = [
140
+ ...(executor ? [] : ["stage_role: executor (mode: edit)"]),
141
+ ...(reporterCandidates.length > 0 ? [] : ["stage_role: reporter"]),
142
+ ];
143
+ throw new Error(`No agent found for --register pipeline stage (${missing.join(", ")}). ` +
144
+ "Specify --executor-by <nickname> --reporter-by <nickname>, or --by <nickname>.");
145
+ }
146
+ return { executor, reporterCandidates };
147
+ }
148
+ // register の状態遷移を CLI 経由で実行する。register 側のガード(終端状態の拒否)と
149
+ // 派生ビュー再生成を一元的に通すため、直接ファイルを書き換えず自プロセスを spawn する。
150
+ export function spawnRegisterTransition(projectId, args, cwd) {
151
+ const fullArgs = ["register", ...args];
152
+ if (projectId)
153
+ fullArgs.push("--project", projectId);
154
+ return spawnSelf(fullArgs, cwd);
155
+ }
156
+ // 成功したIDの実行によって生じた変更だけを1コミットにまとめる。開始前スナップショット
157
+ // (preexisting)に無いパスと runnerManaged を対象にし、利用者の既存変更は除外する。
158
+ // commit 後は hook が変更した対象を amend し、対象差分が消えるまで収束を検証する。
159
+ export function commitRegisterItemChanges(repoRoot, item, preexisting, runnerManaged = []) {
160
+ const remainingPaths = () => selectRegisterCommitPaths(preexisting, worktreeStatusPaths(repoRoot), runnerManaged);
161
+ const paths = remainingPaths();
162
+ if (paths.length === 0)
163
+ return { committed: false };
164
+ try {
165
+ stageCommitTargets(repoRoot, paths);
166
+ const staged = gitResult(repoRoot, ["diff", "--cached", "--quiet", "--", ...paths]);
167
+ if (staged.status === 0)
168
+ return { committed: false };
169
+ if (staged.status !== 1)
170
+ throw new Error("Failed to inspect staged register changes.");
171
+ const subject = commitSubject(`exec(register ${item.id}): `, item.title);
172
+ gitOutput(repoRoot, ["commit", "-m", subject, "--", ...paths]);
173
+ stabilizeCommitTargets(repoRoot, remainingPaths);
174
+ const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
175
+ return { committed: true, sha };
176
+ }
177
+ catch (error) {
178
+ unstageCommitTargets(repoRoot, [...paths, ...remainingPaths()]);
179
+ throw error;
180
+ }
181
+ }
182
+ export function registerEventPathForTicket(registerPaths, ticketPath) {
183
+ if (!ticketPath)
184
+ return undefined;
185
+ const displayId = displayIdFromTicketFilename(basename(ticketPath));
186
+ return displayId
187
+ ? registerEventFilePath(registerPaths.projectRegisterPath, displayId)
188
+ : undefined;
189
+ }
190
+ export function registerRunnerManagedPaths(repoRoot, registerPaths, planPath, resultPath, currentPaths, ticketPath, additionalManagedPaths = []) {
191
+ // 状態遷移の書き込み先は個票(正本)。pjr-index と派生ビューは生成物として同時に更新される。
192
+ // 移行完了後の pjr-index.md は非追跡の生成物になり存在しないため、存在する場合のみ対象に含める
193
+ // (存在しないパスを git add すると pathspec エラーになる)。
194
+ const managed = [planPath, resultPath, ...additionalManagedPaths];
195
+ if (existsSync(registerPaths.pjrIndexPath))
196
+ managed.push(registerPaths.pjrIndexPath);
197
+ if (ticketPath)
198
+ managed.push(ticketPath);
199
+ const eventPath = registerEventPathForTicket(registerPaths, ticketPath);
200
+ if (eventPath)
201
+ managed.push(eventPath);
202
+ const exact = new Set(managed.map((path) => repoRelativePath(repoRoot, path)));
203
+ const prefixes = [registerPaths.generatedPath, registerPaths.controlsGeneratedPath].map((path) => `${repoRelativePath(repoRoot, path)}/`);
204
+ for (const path of currentPaths) {
205
+ const normalized = path.replaceAll("\\", "/");
206
+ if (prefixes.some((prefix) => normalized.startsWith(prefix)))
207
+ exact.add(path);
208
+ }
209
+ return [...exact];
210
+ }
211
+ export function registerReporterManagedPaths(registerPaths) {
212
+ return [
213
+ registerPaths.projectRegisterPath,
214
+ registerPaths.generatedPath,
215
+ registerPaths.controlsGeneratedPath,
216
+ ];
217
+ }
218
+ // register 項目1件の in-place 実行。plan 生成 → `register start` → agent 実行 → 成否を
219
+ // register の状態遷移(成功: review / 失敗: waiting)と result に反映し、成功かつ
220
+ // registerCommit 有効なら当該IDの変更だけを commit する。ID別の結果を要約で返す。
221
+ // schedule のタスクではないため exec の claim/complete イベントは記録しない。
222
+ export async function runSingleRegisterItem(context, opts, pjrId) {
223
+ const { projectId, schedulePath, executionPath, repoRoot } = context;
224
+ const { registerPaths, item } = resolveRegisterRunTarget(projectId, pjrId);
225
+ // 状態遷移の書き込み先(登録項目の正本)。commit 対象に必ず含める。
226
+ const ticketPath = ticketPathFromItem(item, registerPaths.projectRegisterPath);
227
+ requireRunnableRegisterItem(item);
228
+ const pipelineMode = isRegisterPipelineRequested(opts);
229
+ const pipelineAgents = pipelineMode
230
+ ? resolveRegisterPipelineCommand(context.roster, opts, context.execDefaults)
231
+ : undefined;
232
+ // agent(result frontmatter へ記録する actor)は executor 側にする。Schedule の
233
+ // agent_pipeline(scaffoldResult 呼び出し時に executor の actor を渡す)と揃える。
234
+ const { command, actor } = pipelineAgents
235
+ ? { command: pipelineAgents.executor.command, actor: pipelineAgents.executor.actor }
236
+ : resolveRegisterCommand(item, context.roster, opts, context.execDefaults);
237
+ const stem = buildInPlaceStem(pjrId.toLowerCase());
238
+ // ID単位 commit のため、この項目が変更を生じる前の作業ツリー状態を記録する。
239
+ const preexisting = context.registerCommit ? worktreeStatusPaths(repoRoot) : [];
240
+ const residue = context.registerCommit ? selectRegisterRunArtifactResidue(preexisting) : [];
241
+ if (residue.length > 0) {
242
+ process.stderr.write(`Warning: pre-existing uncommitted register plan/result files detected before ${item.id}; ` +
243
+ `left out of this item's commit:\n${residue.map((path) => ` ${path}`).join("\n")}\n`);
244
+ }
245
+ const { planPath } = await generateRegisterPlan({
246
+ executionPath,
247
+ projectId,
248
+ registerPaths,
249
+ item,
250
+ stem,
251
+ });
252
+ const prompt = expandPromptRefs(readFileSync(planPath, "utf8"));
253
+ const { resultPath, supersededPaths } = await scaffoldResult({
254
+ executionPath,
255
+ taskId: item.id,
256
+ mode: "edit",
257
+ projectId,
258
+ origin: "register",
259
+ planRef: `exec/plans/${stem}-plan.md`,
260
+ agent: actor,
261
+ startedAt: new Date().toISOString(),
262
+ stem,
263
+ ...(item.targets && item.targets.length > 0 ? { targets: item.targets } : {}),
264
+ });
265
+ const resultScaffold = readResultFrontmatterSnapshot(resultPath);
266
+ process.stdout.write(`Register item: ${item.id} — ${item.title} [${item.type}]\n`);
267
+ process.stdout.write(` Agent: ${actor}${pipelineAgents ? " (executor)" : ""}\n`);
268
+ if (pipelineAgents) {
269
+ process.stdout.write(` Agent: ${pipelineAgents.reporterCandidates[0]?.actor} (reporter)\n`);
270
+ }
271
+ if (!spawnRegisterTransition(projectId, ["start", "--id", item.id, "--by", actor])) {
272
+ throw new Error(`register start failed: ${item.id}`);
273
+ }
274
+ let exitCode;
275
+ let pipelineBlockReason;
276
+ if (pipelineAgents) {
277
+ process.stdout.write(`Running ${item.id} in place (executor/reporter pipeline)\n`);
278
+ const pipelineOutcome = await runAgentPipeline({
279
+ repoRoot,
280
+ cwd: repoRoot,
281
+ schedulePath,
282
+ executionPath,
283
+ taskId: item.id,
284
+ executor: pipelineAgents.executor,
285
+ reporterCandidates: pipelineAgents.reporterCandidates,
286
+ planPath,
287
+ planPrompt: prompt,
288
+ resultPath,
289
+ registerPaths: registerReporterManagedPaths(registerPaths),
290
+ execDefaults: context.execDefaults,
291
+ providerConcurrencyGate: context.providerConcurrencyGate,
292
+ });
293
+ exitCode = pipelineOutcome.exitCode;
294
+ pipelineBlockReason = pipelineOutcome.blockReason;
295
+ if (pipelineOutcome.exitCode !== 0) {
296
+ process.stdout.write(`run blocked: ${item.id} (${pipelineOutcome.blockReason ?? "pipeline failed"})\n`);
297
+ }
298
+ }
299
+ else {
300
+ process.stdout.write(`Running ${item.id} in place: ${command}\n`);
301
+ exitCode = await spawnAgentInPlace(command, prompt, repoRoot, schedulePath, executionPath, resultPath);
302
+ }
303
+ // in-place 実行と同じ補助判定: agent が result 必須節を埋めずに終了コード 0 で
304
+ // 終わった場合は block として扱う(runInPlaceMode と同じ理由)。pipeline モードでは
305
+ // reporter が renderReporterResult で本文を埋めるため通常は該当しないが、
306
+ // フォーマット不整合等の防御として同じチェックを維持する。
307
+ let effectiveExit = exitCode;
308
+ let blockReason = pipelineBlockReason;
309
+ if (exitCode === 0 && isResultUnfilled(resultPath, "edit", resultScaffold)) {
310
+ effectiveExit = 1;
311
+ blockReason =
312
+ "agent exited 0 but result is incomplete or its frontmatter differs from the scaffold (treated as blocked)";
313
+ process.stdout.write(`run blocked: ${item.id} (result incomplete or frontmatter changed despite exit 0)\n`);
314
+ }
315
+ await updateResultStatus(resultPath, effectiveExit === 0 ? "complete" : "blocked", new Date().toISOString(), blockReason);
316
+ if (effectiveExit === 0) {
317
+ let transition = "review";
318
+ let reason;
319
+ if (!spawnRegisterTransition(projectId, ["review", "--id", item.id, "--by", actor])) {
320
+ process.stderr.write(`register review transition failed: ${item.id}\n`);
321
+ transition = "none";
322
+ reason = "register review transition failed";
323
+ }
324
+ let commit = context.registerCommit ? "no-changes" : "off";
325
+ if (context.registerCommit) {
326
+ const currentPaths = worktreeStatusPaths(repoRoot);
327
+ const runnerManaged = registerRunnerManagedPaths(repoRoot, registerPaths, planPath, resultPath, currentPaths, ticketPath, supersededPaths);
328
+ try {
329
+ const result = commitRegisterItemChanges(repoRoot, item, preexisting, runnerManaged);
330
+ if (result.committed)
331
+ commit = `committed ${result.sha}`;
332
+ }
333
+ catch (error) {
334
+ const detail = error instanceof Error ? error.message : String(error);
335
+ const commitReason = sanitizeRegisterConclusion(`register commit incomplete: ${detail}`);
336
+ process.stderr.write(`run commit failed: ${item.id}: ${detail}\n`);
337
+ if (spawnRegisterTransition(projectId, [
338
+ "wait",
339
+ "--id",
340
+ item.id,
341
+ "--reason",
342
+ commitReason,
343
+ "--by",
344
+ actor,
345
+ ])) {
346
+ transition = "waiting";
347
+ }
348
+ else {
349
+ process.stderr.write(`register wait transition failed: ${item.id}\n`);
350
+ transition = "none";
351
+ }
352
+ return {
353
+ id: item.id,
354
+ title: item.title,
355
+ outcome: "failure",
356
+ transition,
357
+ commit: "incomplete",
358
+ reason: commitReason,
359
+ };
360
+ }
361
+ }
362
+ process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
363
+ return { id: item.id, title: item.title, outcome: "success", transition, commit, reason };
364
+ }
365
+ const waitingReason = sanitizeRegisterConclusion(blockReason ?? `agent exited with non-zero code (exit ${exitCode})`);
366
+ if (!spawnRegisterTransition(projectId, [
367
+ "wait",
368
+ "--id",
369
+ item.id,
370
+ "--reason",
371
+ waitingReason,
372
+ "--by",
373
+ actor,
374
+ ])) {
375
+ process.stderr.write(`register wait transition failed: ${item.id}\n`);
376
+ }
377
+ process.stdout.write(`run failed: ${item.id} (exit ${effectiveExit}; status: waiting)\n`);
378
+ return {
379
+ id: item.id,
380
+ title: item.title,
381
+ outcome: "failure",
382
+ transition: "waiting",
383
+ commit: context.registerCommit ? "skipped" : "off",
384
+ reason: waitingReason,
385
+ };
386
+ }