specdojo 0.4.0 → 0.4.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 (93) hide show
  1. package/.github/agents/specdojo-orchestrator.md +61 -2
  2. package/CHANGELOG.md +65 -0
  3. package/README.md +8 -7
  4. package/dist/commands/init.js +88 -15
  5. package/dist/commands/night-orchestrator.js +287 -0
  6. package/dist/commands/orchestrator.js +10 -3
  7. package/dist/dashboard/timeline-build.js +4 -151
  8. package/dist/devcontainer/command.js +3 -1
  9. package/dist/devcontainer/scaffold.js +166 -5
  10. package/dist/exec/agent-config.js +60 -2
  11. package/dist/exec/events.js +17 -6
  12. package/dist/exec/parent-validation.js +14 -0
  13. package/dist/exec/pipeline-state.js +13 -0
  14. package/dist/exec/plans-core.js +16 -5
  15. package/dist/exec/plans-storage.js +11 -3
  16. package/dist/exec/register.js +23 -1
  17. package/dist/exec/repo-integration.js +1 -1
  18. package/dist/exec/reporter.js +113 -13
  19. package/dist/exec/results.js +36 -14
  20. package/dist/exec/run/agent-pipeline.js +3 -0
  21. package/dist/exec/run/agent.js +40 -5
  22. package/dist/exec/run/job.js +2 -2
  23. package/dist/exec/run/lifecycle-commands.js +2 -2
  24. package/dist/exec/run/register-command.js +23 -4
  25. package/dist/exec/run/register-core.js +17 -0
  26. package/dist/exec/run/register-mode.js +39 -16
  27. package/dist/exec/run/register-post-review.js +420 -0
  28. package/dist/exec/run/register-resume.js +27 -11
  29. package/dist/exec/run/register-worktree.js +66 -2
  30. package/dist/exec/run/run.js +1 -1
  31. package/dist/exec/run/shared.js +22 -24
  32. package/dist/exec/task-repos.js +102 -15
  33. package/dist/kata/kata.js +1 -1
  34. package/dist/register/core.js +17 -4
  35. package/dist/register/create-commands.js +62 -6
  36. package/dist/register/cross-project.js +134 -0
  37. package/dist/register/derivation.js +28 -7
  38. package/dist/register/event-merge.js +13 -1
  39. package/dist/register/events.js +4 -0
  40. package/dist/register/item.js +35 -5
  41. package/dist/register/migration.js +1 -0
  42. package/dist/register/register.js +47 -30
  43. package/dist/schedule/strategy-generate-scope.js +2 -1
  44. package/dist/shared/catalog-files.js +31 -0
  45. package/dist/shared/git.js +45 -15
  46. package/dist/shared/lefthook-scaffold.js +177 -0
  47. package/dist/shared/provider-scaffold.js +3 -2
  48. package/dist/shared/specdojo-config.js +87 -17
  49. package/dist/shared/text.js +4 -1
  50. package/dist/shared/timeline-index.js +125 -0
  51. package/dist/shared/workspace-scaffold.js +69 -0
  52. package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +2 -1
  53. package/docs/ja/specdojo/exec-templates/xep-register-template.md +2 -0
  54. package/docs/ja/specdojo/exec-templates/xrp-register-post-run-template.md +46 -0
  55. package/docs/ja/specdojo/guides/branch-workflow-guide.md +34 -1
  56. package/docs/ja/specdojo/guides/docs-structure-guide.md +2 -0
  57. package/docs/ja/specdojo/guides/exec-config-guide.md +79 -11
  58. package/docs/ja/specdojo/guides/exec-operation-guide.md +39 -1
  59. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +9 -3
  60. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +4 -2
  61. package/docs/ja/specdojo/guides/quick-start-guide.md +31 -6
  62. package/docs/ja/specdojo/guides/register-operation-guide.md +54 -0
  63. package/docs/ja/specdojo/guides/remote-host-development-guide.md +52 -6
  64. package/docs/ja/specdojo/guides/specdojo-overview-guide.md +1 -1
  65. package/docs/ja/specdojo/guides/waza-guide.md +1 -1
  66. package/docs/ja/specdojo/references/command-reference.md +138 -64
  67. package/docs/ja/specdojo/references/specdojo-config-reference.md +41 -12
  68. package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +5 -2
  69. package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +92 -18
  70. package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +6 -1
  71. package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +12 -0
  72. package/docs/specdojo/schemas/v1/register-events.schema.yaml +2 -0
  73. package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +21 -0
  74. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +40 -0
  75. package/package.json +17 -17
  76. package/templates/antigravity/README.md +1 -1
  77. package/templates/antigravity/orchestrator.md +61 -2
  78. package/templates/claude/agents/specdojo-orchestrator.md +61 -2
  79. package/templates/codex/README.md +17 -0
  80. package/templates/codex/agents/specdojo-orchestrator.toml +61 -2
  81. package/templates/codex/orchestrator.md +61 -2
  82. package/templates/devcontainer/devcontainer.json +3 -0
  83. package/templates/devcontainer/post-create.sh +15 -7
  84. package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +38 -5
  85. package/templates/devcontainer/remote-host/ssh-config.sample +3 -0
  86. package/templates/devcontainer/vim/vimrc +37 -0
  87. package/templates/init-agent-members.yaml +6 -6
  88. package/templates/init-exec-defaults.yaml +20 -1
  89. package/templates/lefthook/tools/install-lefthook.mjs +46 -0
  90. package/templates/lefthook/tools/specdojo-pre-commit.mjs +207 -0
  91. package/templates/opencode/README.md +6 -1
  92. package/templates/opencode/agents/specdojo-orchestrator.md +62 -3
  93. /package/dist/{shared → kata}/yaml-schema-modeline.js +0 -0
@@ -6,7 +6,7 @@ import { buildInPlaceStem } from "../plans.js";
6
6
  import { generateRegisterPlan, requireRunnableRegisterItem, resolveRegisterRunTarget, sanitizeRegisterConclusion, ticketPathFromItem, } from "../register.js";
7
7
  import { readResultFrontmatterSnapshot, scaffoldResult, updateResultStatus } from "../results.js";
8
8
  import { findExecWorktree, gitOutput } from "../worktree.js";
9
- import { configuredProductRepos, withProductRepoPrompt } from "../task-repos.js";
9
+ import { configuredProductRepos, integrationBranchOverrideRecord, withProductRepoPrompt, } from "../task-repos.js";
10
10
  import { checkpointAndEnsureWorktree, commitTargetPaths, commitWorktreeChanges, discardStaleExecWorktree, isExecBranchMergedIntoCurrent, mergeWorktreeIntoCurrent, removeWorktree, taskTargetsAtHead, WorktreeRemovedBranchDeletionError, worktreeStatusPaths, } from "../worktree-ops.js";
11
11
  import { commitProductWorktrees, integrateTaskRepositories, projectMergeBlockers, PROJECT_REPO_NAME, RepoIntegrationError, } from "../repo-integration.js";
12
12
  import { productIntegrationTrace, recordResultTrace, refsTrailer, registerProjectMergeMessage, traceKey, withCommitTrailers, } from "../repo-trace.js";
@@ -19,6 +19,7 @@ import { downgradeUnfilledResult } from "./schedule-prepare.js";
19
19
  import { commitSubject, integrateLogPath, recordIntegrateStage, recordRepoIntegration, repoRelativePath, } from "./mode-shared.js";
20
20
  import { resolveRegisterCommand, isRegisterPipelineRequested, resolveRegisterPipelineCommand, spawnRegisterTransition, registerRunnerManagedPaths, registerReporterManagedPaths, } from "./register-core.js";
21
21
  import { commitRegisterState, registerPathsInsideWorktree, rebuildRootRegisterViews, registerWaitSummary, } from "./register-state.js";
22
+ import { runRegisterPostReview } from "./register-post-review.js";
22
23
  // 全体再実行が既存 run の未統合成果を破棄しないための保護。既存 worktree に再開可能な run
23
24
  // (executor 成功済みで reporter か統合が未完了)が残っている場合だけ理由を返し、呼び出し側が
24
25
  // 破壊的操作(discardStaleExecWorktree)の手前で中断できるようにする。--force-restart で無効化できる。
@@ -46,6 +47,26 @@ export function protectResumableRegisterWorktree(context, opts, taskId, worktree
46
47
  `its changes are still unintegrated in ${worktree.path}. ` +
47
48
  `Resume the ${stage} stage with --resume, or discard the worktree with --force-restart.`);
48
49
  }
50
+ // cleanup の再開までに別項目の commit が積まれても、対象 exec branch を最初に取り込んだ
51
+ // first-parent commit(runner が作った merge commit)だけを post-review の差分範囲にする。
52
+ function integratedRegisterCommitRange(repoRoot, branch) {
53
+ const tip = gitOutput(repoRoot, ["rev-parse", "--verify", `${branch}^{commit}`]).trim();
54
+ const outputCommit = gitOutput(repoRoot, [
55
+ "rev-list",
56
+ "--first-parent",
57
+ "--ancestry-path",
58
+ `${tip}..HEAD`,
59
+ ])
60
+ .split("\n")
61
+ .map((line) => line.trim())
62
+ .filter(Boolean)
63
+ .at(-1);
64
+ if (!outputCommit) {
65
+ throw new Error(`could not locate integrated commit for register branch: ${branch}`);
66
+ }
67
+ const baseCommit = gitOutput(repoRoot, ["rev-parse", `${outputCommit}^1`]).trim();
68
+ return { baseCommit, outputCommit };
69
+ }
49
70
  // register worktree 実行の Phase 3(成果物統合と状態遷移)。成功なら worktree の成果物を
50
71
  // commit → worktree 側で register review → 統合ブランチへ merge commit 1件 → worktree 撤去、
51
72
  // 失敗なら worktree を保持したまま waiting へ戻す(wait commit 1件)。通常実行・reporter 再開・
@@ -70,6 +91,36 @@ export async function finalizeRegisterWorktreeRun(params) {
70
91
  worktree,
71
92
  bookkeepingPaths: params.bookkeepingPaths,
72
93
  });
94
+ const postReview = async (baseCommit, outputCommit) => {
95
+ if (!context.postReview)
96
+ return undefined;
97
+ if (!ticketPath) {
98
+ throw new Error(`register post-review requires an item ticket: ${item.id}`);
99
+ }
100
+ const reviewed = await runRegisterPostReview({
101
+ context,
102
+ opts: params.opts,
103
+ registerPaths,
104
+ item,
105
+ ticketPath,
106
+ stem,
107
+ editPlanPath: resolve(context.executionPath, "exec", "plans", `${stem}-plan.md`),
108
+ editResultPath: resolve(repoRoot, repoRelativePath(worktree.path, params.worktreeResultPath)),
109
+ baseCommit,
110
+ outputCommit,
111
+ worktreePath: worktree.path,
112
+ editPipelineStatePath: params.pipelineStatePath,
113
+ });
114
+ process.stdout.write(`post-review done: ${item.id} (verdict transition: ${reviewed.transition})\n`);
115
+ return {
116
+ id: item.id,
117
+ title: item.title,
118
+ outcome: reviewed.outcome,
119
+ transition: reviewed.transition,
120
+ commit: reviewed.commit ?? `committed ${outputCommit.slice(0, 12)}`,
121
+ reason: reviewed.reason,
122
+ };
123
+ };
73
124
  const completedAt = new Date().toISOString();
74
125
  const worktreeResultPath = params.worktreeResultPath;
75
126
  const { result: effectiveResult, unfilledBlock } = downgradeUnfilledResult(agentResult, worktreeResultPath, "edit", params.resultScaffold);
@@ -80,6 +131,7 @@ export async function finalizeRegisterWorktreeRun(params) {
80
131
  // exec branch here would force a second merge commit for the same task.
81
132
  if (params.resumedIntegration &&
82
133
  isExecBranchMergedIntoCurrent({ context: wtContext, worktree })) {
134
+ const { baseCommit, outputCommit } = integratedRegisterCommitRange(repoRoot, worktree.branch);
83
135
  try {
84
136
  const lifecyclePaths = new Set([worktreeResultPath, params.pipelineStatePath]
85
137
  .filter((path) => !!path)
@@ -125,6 +177,9 @@ export async function finalizeRegisterWorktreeRun(params) {
125
177
  }
126
178
  }
127
179
  rebuildRootRegisterViews(projectId, item.id);
180
+ const reviewed = await postReview(baseCommit, outputCommit);
181
+ if (reviewed)
182
+ return reviewed;
128
183
  const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
129
184
  process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
130
185
  return {
@@ -136,6 +191,7 @@ export async function finalizeRegisterWorktreeRun(params) {
136
191
  };
137
192
  }
138
193
  await updateResultStatus(worktreeResultPath, "complete", completedAt);
194
+ const baseCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
139
195
  const subject = commitSubject(`exec(register ${item.id}): `, item.title);
140
196
  // PJR-30SW: プロダクト側の commit と merge commit、プロジェクト側の merge commit に
141
197
  // `Refs: <project-id>:<item-id>` を付ける(PJR-1SXK)。
@@ -301,6 +357,10 @@ export async function finalizeRegisterWorktreeRun(params) {
301
357
  }
302
358
  // review は merge で root の個票に入る。非追跡の派生ビューだけ root で作り直す。
303
359
  rebuildRootRegisterViews(projectId, item.id);
360
+ const outputCommit = gitOutput(repoRoot, ["rev-parse", "HEAD"]).trim();
361
+ const reviewed = await postReview(baseCommit, outputCommit);
362
+ if (reviewed)
363
+ return reviewed;
304
364
  const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
305
365
  process.stdout.write(`run done: ${item.id} (status: review — confirm and close with "register close")\n`);
306
366
  return {
@@ -358,7 +418,9 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
358
418
  ? `${new Date().toISOString().replace(/[-:.]/g, "")}-${randomHex(4)}`
359
419
  : undefined;
360
420
  // PJR-98G4: repos を宣言した project では、プロダクトの worktree も同じタスクの下に作る。
361
- const products = configuredProductRepos(schedulePath);
421
+ // PJR-XRAB: --integration-branch は設定の integration_branch より優先する。
422
+ const products = configuredProductRepos(schedulePath, opts.integrationBranch);
423
+ const integrationBranchOverrides = integrationBranchOverrideRecord(opts.integrationBranch);
362
424
  // Phase 1: plan/result 生成 → register start → checkpoint → worktree 作成(root で直列化)。
363
425
  const setup = async () => {
364
426
  // executor が成功した run の worktree を、全体再実行が破棄しないよう保護する。
@@ -494,6 +556,7 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
494
556
  execDefaults: context.execDefaults,
495
557
  providerConcurrencyGate: context.providerConcurrencyGate,
496
558
  productWorktrees: worktree.repos,
559
+ ...(integrationBranchOverrides ? { integrationBranchOverrides } : {}),
497
560
  runId: pipelineRunId,
498
561
  executorRateLimitOptions: opts.executorBy
499
562
  ? resolvePinnedRateLimitRunOptions(opts, context.execDefaults, context.roster, "executor", pipelineAgents.executor)
@@ -522,6 +585,7 @@ export async function runSingleRegisterItemWorktree(context, opts, pjrId, lifecy
522
585
  // Phase 3: 成果物統合と状態遷移(root で直列化)。通常実行と再開経路で共通化する。
523
586
  const finalize = async () => finalizeRegisterWorktreeRun({
524
587
  context,
588
+ opts,
525
589
  registerPaths,
526
590
  item,
527
591
  ticketPath,
@@ -4,7 +4,7 @@ export { checkCompletionBeforeIntegration, downgradeUnfilledResult } from "./sch
4
4
  export { rebuildStaleGeneratedTracksForCycle, resolveClaimingActor } from "./schedule-mode.js";
5
5
  export { resolveInPlaceAgentPipeline, resolveInPlaceCommand } from "./in-place.js";
6
6
  export { commitSubject, pipelineRecoveryMeta } from "./mode-shared.js";
7
- export { commitRegisterItemChanges, isRegisterPipelineRequested, parseRegisterExecutorSelection, resolveRegisterCommand, resolveRegisterPipelineCommand, } from "./register-core.js";
7
+ export { applyRegisterDifficultyRouting, commitRegisterItemChanges, isRegisterPipelineRequested, parseRegisterExecutorSelection, resolveRegisterCommand, resolveRegisterPipelineCommand, } from "./register-core.js";
8
8
  export { registerStatePaths } from "./register-state.js";
9
9
  export { resolveRegisterResumeExecutor, resolveRegisterResumeReporter } from "./register-resume.js";
10
10
  export { registerRunCommand } from "./register-command.js";
@@ -13,16 +13,18 @@ export function rateLimitRecoveryReason(events) {
13
13
  return events
14
14
  .map((event) => event.action === "wait"
15
15
  ? `rate limit wait: ${event.to_actor} resumed at ${event.resumed_at}`
16
- : `rate limit fallback: ${event.from_actor} -> ${event.to_actor} at ${event.resumed_at}`)
16
+ : event.trigger === "connection_error"
17
+ ? `connection error fallback: ${event.from_actor} -> ${event.to_actor} at ${event.resumed_at}`
18
+ : `rate limit fallback: ${event.from_actor} -> ${event.to_actor} at ${event.resumed_at}`)
17
19
  .join("; ");
18
20
  }
19
21
  export function isPinnedRateLimitAction(value) {
20
22
  return value === "stop" || value === "wait" || value === "fallback";
21
23
  }
22
24
  /**
23
- * Resolve CLI-over-config recovery for one pinned pipeline stage. A fallback action without a
24
- * fallback nickname intentionally degrades to stop, preserving the historical non-switching
25
- * behaviour instead of choosing an arbitrary agent.
25
+ * Resolve CLI-over-config recovery for one pinned pipeline stage. A fallback nickname is resolved
26
+ * independently of --on-rate-limit because the same candidate also handles configured connection
27
+ * failures. A rate-limit fallback action without a nickname still degrades to stop.
26
28
  */
27
29
  export function resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, stageRole, primary) {
28
30
  const configured = resolvePinnedRateLimitPolicy(execDefaults, primary.provider);
@@ -34,7 +36,7 @@ export function resolvePinnedRateLimitRunOptions(opts, execDefaults, roster, sta
34
36
  const nickname = stageRole === "executor"
35
37
  ? (opts.fallbackExecutorBy ?? configured.fallbackExecutorBy)
36
38
  : (opts.fallbackReporterBy ?? configured.fallbackReporterBy);
37
- if (action !== "fallback" || !nickname) {
39
+ if (!nickname) {
38
40
  return {
39
41
  action: action === "fallback" ? "stop" : action,
40
42
  maxWaitSeconds: configured.maxWaitSeconds,
@@ -302,30 +304,26 @@ export function collectBusyActors(schedulePath) {
302
304
  return busy;
303
305
  }
304
306
  export function isRateLimitError(exitCode, output, detection) {
307
+ // `output` is combined stdout+stderr because some CLIs print failures to stdout. Successful
308
+ // output is ignored by default so quoted configuration/examples do not become false positives.
309
+ return isConfiguredAgentError(exitCode, output, detection);
310
+ }
311
+ export function isConnectionError(exitCode, output, detection) {
312
+ return isConfiguredAgentError(exitCode, output, detection);
313
+ }
314
+ function isConfiguredAgentError(exitCode, output, detection) {
305
315
  if (!detection)
306
316
  return false;
307
- // exit_codes is a standalone signal: an exact configured code identifies a rate limit
308
- // on its own. Keep this list minimal (see exec-defaults.yaml) since generic codes like 1
309
- // also mean ordinary failure.
310
317
  if (detection.exit_codes && exitCode !== null && detection.exit_codes.includes(exitCode)) {
311
318
  return true;
312
319
  }
313
- if (detection.stderr_patterns) {
314
- // `output` is the agent's combined stdout+stderr: some CLIs print the limit notice to
315
- // stdout, not stderr (e.g. claude's "You've hit your session limit"), so scanning stderr
316
- // alone misses it. By default a pattern only counts when the process also failed (non-zero
317
- // or null exit). A successful run (exit 0) that merely echoes the phrase — e.g. an agent
318
- // editing a file containing the literal text "rate limit" — is not a rate limit.
319
- const requireNonzeroExit = detection.stderr_requires_nonzero_exit ?? true;
320
- if (!requireNonzeroExit || exitCode !== 0) {
321
- const lower = output.toLowerCase();
322
- for (const pattern of detection.stderr_patterns) {
323
- if (lower.includes(pattern.toLowerCase()))
324
- return true;
325
- }
326
- }
327
- }
328
- return false;
320
+ if (!detection.stderr_patterns)
321
+ return false;
322
+ const requireNonzeroExit = detection.stderr_requires_nonzero_exit ?? true;
323
+ if (requireNonzeroExit && exitCode === 0)
324
+ return false;
325
+ const lower = output.toLowerCase();
326
+ return detection.stderr_patterns.some((pattern) => lower.includes(pattern.toLowerCase()));
329
327
  }
330
328
  export function resolveExecDefaultsPath(opts, schedulePath) {
331
329
  if (opts.execDefaults)
@@ -6,30 +6,117 @@ import { ensureExecWorktree, execBranchExists, execWorktreePath, findExecWorktre
6
6
  // 変更する場合の worktree を扱う。`repos` を持たない project では、ここの関数はどれも空の結果を
7
7
  // 返し、既存の 1 リポジトリ・`<worktree_base>/<task-id>/` 直下の配置を変えない。
8
8
  export { PROJECT_REPO_WORKTREE_DIRNAME };
9
- export function resolveProductRepos(rootDir, project) {
10
- return getProjectRepos(project).map((repo) => ({
11
- name: repo.name,
12
- repoRoot: resolveRepoRoot(rootDir, repo),
13
- ...(repo.integration_branch?.trim()
14
- ? { integrationBranch: repo.integration_branch.trim() }
15
- : {}),
16
- install: repo.setup?.install ?? true,
17
- build: repo.setup?.build ?? true,
18
- }));
9
+ /** Parse repeatable `<repo>=<branch>` values used by `exec run --integration-branch`. */
10
+ export function parseIntegrationBranchOverrides(values) {
11
+ const entries = values === undefined ? [] : typeof values === "string" ? [values] : values;
12
+ const overrides = new Map();
13
+ for (const entry of entries) {
14
+ const separator = entry.indexOf("=");
15
+ const repo = separator > 0 ? entry.slice(0, separator).trim() : "";
16
+ const branch = separator > 0 ? entry.slice(separator + 1).trim() : "";
17
+ if (!repo || !branch) {
18
+ throw new Error(`--integration-branch must use <repo>=<branch> with non-empty values: ${entry}`);
19
+ }
20
+ if (overrides.has(repo)) {
21
+ throw new Error(`--integration-branch specifies repository "${repo}" more than once`);
22
+ }
23
+ overrides.set(repo, branch);
24
+ }
25
+ return overrides;
26
+ }
27
+ function isIntegrationBranchOverrides(value) {
28
+ return value instanceof Map;
29
+ }
30
+ function toIntegrationBranchOverrides(value) {
31
+ return isIntegrationBranchOverrides(value) ? value : parseIntegrationBranchOverrides(value);
32
+ }
33
+ function assertLocalIntegrationBranch(product, branch) {
34
+ if (!existsSync(product.repoRoot)) {
35
+ throw new Error(`Product repository "${product.name}" does not exist: ${product.repoRoot} (check repos[].path)`);
36
+ }
37
+ const validName = gitResult(product.repoRoot, ["check-ref-format", "--branch", branch]);
38
+ if (validName.status !== 0) {
39
+ throw new Error(`--integration-branch for repository "${product.name}" is not a valid branch name: ${branch}`);
40
+ }
41
+ const exists = gitResult(product.repoRoot, [
42
+ "show-ref",
43
+ "--verify",
44
+ "--quiet",
45
+ `refs/heads/${branch}`,
46
+ ]);
47
+ if (exists.status !== 0) {
48
+ throw new Error(`--integration-branch for repository "${product.name}" is not a local branch: ${branch}`);
49
+ }
50
+ }
51
+ /** Resolve the configured target; undefined deliberately means "use the current branch". */
52
+ export function resolveProductIntegrationBranch(repo, overrides) {
53
+ const configuredBranch = repo.integration_branch?.trim();
54
+ return overrides.get(repo.name) ?? (configuredBranch || undefined);
55
+ }
56
+ export function resolveProductRepos(rootDir, project, integrationBranches) {
57
+ const overrides = toIntegrationBranchOverrides(integrationBranches);
58
+ // Priority: run-scoped override → repos[].integration_branch → current branch (at use time).
59
+ const configured = getProjectRepos(project);
60
+ const configuredNames = new Set(configured.map((repo) => repo.name));
61
+ const unknown = [...overrides.keys()].filter((name) => !configuredNames.has(name));
62
+ if (unknown.length > 0) {
63
+ throw new Error(`--integration-branch references undeclared product repositories: ${unknown.join(", ")}`);
64
+ }
65
+ return configured.map((repo) => {
66
+ const override = overrides.get(repo.name);
67
+ const integrationBranch = resolveProductIntegrationBranch(repo, overrides);
68
+ const product = {
69
+ name: repo.name,
70
+ repoRoot: resolveRepoRoot(rootDir, repo),
71
+ ...(integrationBranch ? { integrationBranch } : {}),
72
+ install: repo.setup?.install ?? true,
73
+ build: repo.setup?.build ?? true,
74
+ };
75
+ if (override)
76
+ assertLocalIntegrationBranch(product, override);
77
+ return product;
78
+ });
19
79
  }
20
80
  /** Product repositories of the project whose schedule path is `schedulePath` ([] when none). */
21
- export function configuredProductRepos(schedulePath) {
81
+ export function configuredProductRepos(schedulePath, integrationBranches) {
82
+ const overrides = toIntegrationBranchOverrides(integrationBranches);
22
83
  const { config } = loadConfig();
23
- if (!config)
24
- return [];
25
84
  const rootDir = specdojoRootDir();
26
- for (const project of Object.values(config.projects)) {
85
+ for (const project of Object.values(config?.projects ?? {})) {
27
86
  if (resolve(rootDir, getProjectSchedulePath(project)) === resolve(schedulePath)) {
28
- return resolveProductRepos(rootDir, project);
87
+ return resolveProductRepos(rootDir, project, overrides);
29
88
  }
30
89
  }
90
+ if (overrides.size > 0) {
91
+ throw new Error(`--integration-branch references undeclared product repositories: ${[...overrides.keys()].join(", ")}`);
92
+ }
31
93
  return [];
32
94
  }
95
+ /**
96
+ * Run-scoped `--integration-branch` values recorded in the run checkpoint (`integration_branches`).
97
+ * Only explicit overrides are recorded, so a run without the option keeps resolving its targets
98
+ * from `repos[].integration_branch` or the current branch exactly as before.
99
+ */
100
+ export function integrationBranchOverrideRecord(values) {
101
+ const overrides = parseIntegrationBranchOverrides(values);
102
+ return overrides.size > 0 ? Object.fromEntries(overrides) : undefined;
103
+ }
104
+ /**
105
+ * Integration branch overrides for a resumed run. The checkpoint's overrides are reused so the
106
+ * option does not have to be repeated; an explicit value must match the checkpoint, because a
107
+ * run cannot change or add its integration target midway through execution.
108
+ */
109
+ export function resumeIntegrationBranches(persisted, requested) {
110
+ const requestedOverrides = parseIntegrationBranchOverrides(requested);
111
+ for (const [repo, branch] of requestedOverrides) {
112
+ const original = persisted?.[repo];
113
+ if (original !== branch) {
114
+ throw new Error(`--integration-branch cannot change the resumed run target for "${repo}" ` +
115
+ `(checkpoint: ${original ?? "not specified"}, requested: ${branch})`);
116
+ }
117
+ }
118
+ return new Map(Object.entries(persisted ?? {}));
119
+ }
33
120
  /** Product repositories of the project `projectId` ([] when none or unknown). */
34
121
  export function configuredProductReposForProject(projectId) {
35
122
  if (!projectId)
package/dist/kata/kata.js CHANGED
@@ -3,7 +3,7 @@ import { specdojoRootDir } from "../shared/specdojo-config.js";
3
3
  import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
4
4
  import { practiceLocalId } from "../shared/practice-id.js";
5
5
  import { resolveSpecdojoPathIfExists, resolveSpecdojoReferencePathIfExists, specdojoResourceCandidates, } from "../docs/template-resolution.js";
6
- import { readYamlSchemaModelineRef } from "../shared/yaml-schema-modeline.js";
6
+ import { readYamlSchemaModelineRef } from "./yaml-schema-modeline.js";
7
7
  // 実践の型(rulebook / recipe / sample / template)の解決を 1 か所に集約する。
8
8
  // plan 生成(明示パスの注入)と validate(参照先の存在確認)の両方から使う。
9
9
  const MISSING = "_MISSING_";
@@ -5,10 +5,21 @@ import { inlineCodeAnglePlaceholders } from "../shared/text.js";
5
5
  import { appendRegisterEvent, registerEventFilePath } from "./events.js";
6
6
  import { REGISTER_TIMESTAMP_RE, resolveRegisterDateTimeZone, timestampFromDateInTimeZone, } from "./date.js";
7
7
  import { applyRegisterItemFields, CELL_NONE, CELL_TODO, isPlaceholderCell, PJR_ID_ALPHABET, PJR_ID_RE, registerItemFieldsFromItem, setRegisterItemDescription, toCell, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
8
- import { getProjectExecutionPath, getProjectRegisterPath, loadConfig, loadEnv, specdojoRootDir, } from "../shared/specdojo-config.js";
8
+ import { getProjectExecutionPath, getProjectRegisterPath, loadConfig, loadEnv, loadMemberRoster, resolveRegisterActor, specdojoRootDir, } from "../shared/specdojo-config.js";
9
9
  import { flattenTemplateFrontmatter } from "../docs/template-frontmatter.js";
10
10
  export function registerEventActor(opts) {
11
- return opts.by?.trim() || process.env.SPECDOJO_ACTOR?.trim() || "manual";
11
+ const actor = opts.by?.trim() || process.env.SPECDOJO_ACTOR?.trim() || "SpecDojo";
12
+ const { config } = loadConfig();
13
+ if (!config)
14
+ throw new Error("register commands require specdojo.config.json");
15
+ const projectId = opts.project?.trim() ||
16
+ process.env.SPECDOJO_PROJECT?.trim() ||
17
+ Object.keys(config.projects)[0] ||
18
+ "";
19
+ const project = config.projects[projectId];
20
+ if (!project)
21
+ throw new Error(`Unknown project: ${projectId}`);
22
+ return resolveRegisterActor(actor, loadMemberRoster(specdojoRootDir(), project));
12
23
  }
13
24
  export function atomicWriteFile(path, content) {
14
25
  mkdirSync(dirname(path), { recursive: true });
@@ -230,8 +241,9 @@ export function generatePjrId(existingIds, nextCandidate = defaultPjrCandidate,
230
241
  }
231
242
  export function formatTableRow(item) {
232
243
  // frontmatter・本文由来を問わず、表へ展開する全セルを同じ規則で無害化する。
233
- // 列区切りの `|` と改行をエスケープし、山括弧プレースホルダをインラインコード化する。
234
- // 既存コードスパンは変換処理が保持するため、再生成しても二重に囲まれない。
244
+ // 列区切りの `|`、強調記号、改行をエスケープし、山括弧プレースホルダを
245
+ // インラインコード化する。既存コードスパンは変換処理が保持するため、再生成しても
246
+ // 二重に囲まれない。
235
247
  const cells = [
236
248
  item.id,
237
249
  item.status,
@@ -356,6 +368,7 @@ export function buildRegisterItemContent(opts) {
356
368
  description: opts.fields.description,
357
369
  type: opts.fields.type,
358
370
  priority: opts.fields.priority,
371
+ ...(opts.fields.difficulty ? { difficulty: opts.fields.difficulty } : {}),
359
372
  owner: opts.fields.owner,
360
373
  registeredAt: opts.fields.registeredAt,
361
374
  due: opts.fields.due,
@@ -4,7 +4,7 @@ import { inlineCodeAnglePlaceholders } from "../shared/text.js";
4
4
  import { APPROACHES } from "../shared/agent-types.js";
5
5
  import { appendRegisterEvent, buildRegisterEvent, registerEventFilePath } from "./events.js";
6
6
  import { nowUtcTimestamp } from "./date.js";
7
- import { CELL_NONE, CELL_TODO, REMOVE_REGISTER_ITEM_FIELD, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
7
+ import { CELL_NONE, CELL_TODO, REMOVE_REGISTER_ITEM_FIELD, VALID_PRIORITIES, VALID_DIFFICULTIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
8
8
  import { resolveSpecdojoTemplatePath } from "../docs/template-resolution.js";
9
9
  import { validateRegisterApproachTargetsForProject } from "./approach.js";
10
10
  import { normalizeDerivedFrom, validateDerivedFrom } from "./derivation.js";
@@ -58,6 +58,7 @@ export function registerCreateCommands(reg, dependencies) {
58
58
  addCmd.requiredOption("--title <title>", "Short title for the item");
59
59
  addCmd.option("--description <text>", "Description shown in the list", "_TODO_");
60
60
  addCmd.option("--priority <priority>", `Priority: ${VALID_PRIORITIES.join(" | ")}`, "medium");
61
+ addCmd.option("--difficulty <difficulty>", `Difficulty: ${VALID_DIFFICULTIES.join(" | ")}`);
61
62
  addCmd.option("--status <status>", `Status: ${VALID_STATUSES.join(" | ")}`, "open");
62
63
  addCmd.option("--owner <owner>", "Owner or role", "_TODO_");
63
64
  addCmd.option("--registered <datetime>", "Registration date-time (RFC 3339 with time zone, or _TODO_; defaults to now in UTC)");
@@ -84,6 +85,10 @@ export function registerCreateCommands(reg, dependencies) {
84
85
  }
85
86
  const registeredAt = parseRegisterTimestampOption(opts.registered, "registered", CELL_TODO);
86
87
  const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE);
88
+ if (opts.difficulty !== undefined &&
89
+ !VALID_DIFFICULTIES.includes(opts.difficulty)) {
90
+ throw new Error(`Invalid difficulty: "${opts.difficulty}". Must be one of: ${VALID_DIFFICULTIES.join(", ")}`);
91
+ }
87
92
  if (opts.target?.some((target) => target.trim() === "-")) {
88
93
  throw new Error("--target - is only valid with register update");
89
94
  }
@@ -99,6 +104,7 @@ export function registerCreateCommands(reg, dependencies) {
99
104
  title: opts.title,
100
105
  description: opts.description,
101
106
  priority: opts.priority,
107
+ ...(opts.difficulty !== undefined ? { difficulty: opts.difficulty } : {}),
102
108
  status: opts.status,
103
109
  owner: opts.owner,
104
110
  registeredAt: registeredAt ?? nowUtcTimestamp(),
@@ -182,10 +188,12 @@ export function registerUpdateCommand(reg, dependencies) {
182
188
  updateCmd.option("--title <title>", "Update title");
183
189
  updateCmd.option("--description <text>", "Update description");
184
190
  updateCmd.option("--priority <priority>", `Update priority: ${VALID_PRIORITIES.join(" | ")}`);
191
+ updateCmd.option("--difficulty <difficulty>", `Update difficulty: ${VALID_DIFFICULTIES.join(" | ")}; use - to remove`);
185
192
  updateCmd.option("--owner <owner>", "Update owner or role");
186
193
  updateCmd.option("--due <date>", "Update due date (YYYY-MM-DD, -, or _TODO_)");
187
194
  updateCmd.option("--conclusion <text>", "Update conclusion or use - to remove it");
188
195
  updateCmd.option("--block-reason <text>", "Update the waiting reason or use - to remove it");
196
+ updateCmd.option("--autopilot <approval>", "Night orchestrator approval: approved, or - to revoke");
189
197
  updateCmd.option("--approach <approach>", `Update execution approach (${APPROACHES.join(" | ")}; use - to remove)`);
190
198
  updateCmd.option("--target <doc-id>", "Replace target document ids (repeatable; use - to remove)", collectTarget);
191
199
  updateCmd.option("--from <item-id>", "Replace source register item IDs (repeatable; use - to remove)", collectTarget);
@@ -203,22 +211,29 @@ export function registerUpdateCommand(reg, dependencies) {
203
211
  "title",
204
212
  "description",
205
213
  "priority",
214
+ "difficulty",
206
215
  "owner",
207
216
  "due",
208
217
  "conclusion",
209
218
  "blockReason",
219
+ "autopilot",
210
220
  "approach",
211
221
  "target",
212
222
  "from",
213
223
  "topic",
214
224
  ].some((key) => opts[key] !== undefined);
215
225
  if (!hasUpdates) {
216
- throw new Error("At least one field option must be specified (--title, --description, --priority, --owner, --due, --conclusion, --block-reason, --approach, --target, --from, --topic)");
226
+ throw new Error("At least one field option must be specified (--title, --description, --priority, --difficulty, --owner, --due, --conclusion, --block-reason, --autopilot, --approach, --target, --from, --topic)");
217
227
  }
218
228
  if (opts.priority !== undefined &&
219
229
  !VALID_PRIORITIES.includes(opts.priority)) {
220
230
  throw new Error(`Invalid priority: "${opts.priority}". Must be one of: ${VALID_PRIORITIES.join(", ")}`);
221
231
  }
232
+ if (opts.difficulty !== undefined &&
233
+ opts.difficulty !== "-" &&
234
+ !VALID_DIFFICULTIES.includes(opts.difficulty)) {
235
+ throw new Error(`Invalid difficulty: "${opts.difficulty}". Must be one of: ${VALID_DIFFICULTIES.join(", ")}, -`);
236
+ }
222
237
  if (opts.due !== undefined && !/^(\d{4}-\d{2}-\d{2}|-|_TODO_)$/.test(opts.due)) {
223
238
  throw new Error(`Invalid due: "${opts.due}". Must be YYYY-MM-DD, -, or _TODO_`);
224
239
  }
@@ -240,6 +255,17 @@ export function registerUpdateCommand(reg, dependencies) {
240
255
  ? REMOVE_REGISTER_ITEM_FIELD
241
256
  : inlineCodeAnglePlaceholders(blockReason),
242
257
  };
258
+ if (opts.autopilot !== undefined && !["approved", "-"].includes(opts.autopilot)) {
259
+ throw new Error('Invalid autopilot approval. Use "approved" or "-".');
260
+ }
261
+ if (opts.autopilot === "approved" && item.type !== "todo" && item.type !== "issue") {
262
+ throw new Error(`Cannot approve ${item.id} for night autopilot: type is "${item.type}" (expected todo or issue).`);
263
+ }
264
+ const autopilotUpdates = opts.autopilot === undefined
265
+ ? undefined
266
+ : {
267
+ autopilot: opts.autopilot === "-" ? REMOVE_REGISTER_ITEM_FIELD : "approved",
268
+ };
243
269
  const nextApproach = opts.approach === undefined
244
270
  ? item.approach
245
271
  : opts.approach.trim() === "-"
@@ -261,6 +287,11 @@ export function registerUpdateCommand(reg, dependencies) {
261
287
  validateTargetsWithoutApproach: opts.target !== undefined,
262
288
  });
263
289
  const approachTargetUpdates = {
290
+ ...(opts.difficulty !== undefined
291
+ ? {
292
+ difficulty: opts.difficulty === "-" ? REMOVE_REGISTER_ITEM_FIELD : opts.difficulty,
293
+ }
294
+ : {}),
264
295
  ...(opts.approach !== undefined
265
296
  ? {
266
297
  approach: nextApproach === undefined ? REMOVE_REGISTER_ITEM_FIELD : nextApproach,
@@ -282,10 +313,21 @@ export function registerUpdateCommand(reg, dependencies) {
282
313
  ...(opts.title !== undefined ? { title: opts.title } : {}),
283
314
  ...(opts.description !== undefined ? { description: opts.description } : {}),
284
315
  ...(opts.priority !== undefined ? { priority: opts.priority } : {}),
316
+ ...(opts.difficulty !== undefined && opts.difficulty !== "-"
317
+ ? { difficulty: opts.difficulty }
318
+ : {}),
285
319
  ...(opts.owner !== undefined ? { owner: opts.owner } : {}),
286
320
  ...(opts.due !== undefined ? { due: opts.due } : {}),
287
321
  ...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
288
322
  };
323
+ if (opts.difficulty === "-")
324
+ delete updated.difficulty;
325
+ if (opts.autopilot !== undefined) {
326
+ if (opts.autopilot === "-")
327
+ delete updated.autopilot;
328
+ else
329
+ updated.autopilot = "approved";
330
+ }
289
331
  if (opts.approach !== undefined) {
290
332
  if (nextApproach === undefined)
291
333
  delete updated.approach;
@@ -320,8 +362,16 @@ export function registerUpdateCommand(reg, dependencies) {
320
362
  topic,
321
363
  updated,
322
364
  dryRun: opts.dryRun,
323
- ...(blockReasonUpdates || Object.keys(approachTargetUpdates).length > 0
324
- ? { fieldUpdates: { ...blockReasonUpdates, ...approachTargetUpdates } }
365
+ ...(blockReasonUpdates ||
366
+ autopilotUpdates ||
367
+ Object.keys(approachTargetUpdates).length > 0
368
+ ? {
369
+ fieldUpdates: {
370
+ ...blockReasonUpdates,
371
+ ...autopilotUpdates,
372
+ ...approachTargetUpdates,
373
+ },
374
+ }
325
375
  : {}),
326
376
  ...(opts.title !== undefined ? { title: opts.title } : {}),
327
377
  ...(opts.description !== undefined ? { description: opts.description } : {}),
@@ -339,8 +389,14 @@ export function registerUpdateCommand(reg, dependencies) {
339
389
  action: "fields updated",
340
390
  ...(opts.title !== undefined ? { title: opts.title } : {}),
341
391
  ...(opts.description !== undefined ? { description: opts.description } : {}),
342
- ...(blockReasonUpdates || Object.keys(approachTargetUpdates).length > 0
343
- ? { fieldUpdates: { ...blockReasonUpdates, ...approachTargetUpdates } }
392
+ ...(blockReasonUpdates || autopilotUpdates || Object.keys(approachTargetUpdates).length > 0
393
+ ? {
394
+ fieldUpdates: {
395
+ ...blockReasonUpdates,
396
+ ...autopilotUpdates,
397
+ ...approachTargetUpdates,
398
+ },
399
+ }
344
400
  : {}),
345
401
  eventAction: "update",
346
402
  eventActor: registerEventActor(opts),