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
@@ -0,0 +1,134 @@
1
+ import { mkdtempSync, rmSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { gitOutput, gitResult, worktreeStatusPaths } from "../shared/git.js";
5
+ import { loadConfig, specdojoRootDir, } from "../shared/specdojo-config.js";
6
+ const CROSS_PROJECT_TRANSITIONS = new Set([
7
+ "start",
8
+ "wait",
9
+ "review",
10
+ "close",
11
+ "reject",
12
+ "defer",
13
+ "reopen",
14
+ ]);
15
+ export function resolveProjectIntegrationBranch(projectId, project) {
16
+ return project.integration_branch?.trim() || `project/${projectId}/develop`;
17
+ }
18
+ function currentBranch(repoRoot) {
19
+ const result = gitResult(repoRoot, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
20
+ // register の既存単体利用は Git 初期化前でも許している。branch を読めない場所では
21
+ // current_project へフォールバックし、別 project の記帳を選んだときだけ Git を必須にする。
22
+ if (result.status !== 0)
23
+ return undefined;
24
+ return typeof result.stdout === "string" ? result.stdout.trim() : undefined;
25
+ }
26
+ function worktreeForBranch(repoRoot, branch) {
27
+ const output = gitOutput(repoRoot, ["worktree", "list", "--porcelain"]);
28
+ let path;
29
+ for (const line of output.split(/\r?\n/)) {
30
+ if (line.startsWith("worktree ")) {
31
+ path = resolve(line.slice("worktree ".length));
32
+ }
33
+ else if (line === `branch refs/heads/${branch}`) {
34
+ return path;
35
+ }
36
+ else if (line === "") {
37
+ path = undefined;
38
+ }
39
+ }
40
+ return undefined;
41
+ }
42
+ function requireLocalBranch(repoRoot, projectId, branch) {
43
+ const result = gitResult(repoRoot, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]);
44
+ if (result.status === 0)
45
+ return;
46
+ if (result.status === 1) {
47
+ throw new Error(`Integration branch for project ${projectId} does not exist locally: ${branch}`);
48
+ }
49
+ throw new Error(`Failed to inspect integration branch for project ${projectId}: ${branch}`);
50
+ }
51
+ function configuredCurrentProject(config, branch) {
52
+ const projectIds = Object.keys(config.projects).sort((left, right) => right.length - left.length);
53
+ if (branch) {
54
+ const exact = projectIds.find((projectId) => resolveProjectIntegrationBranch(projectId, config.projects[projectId]) === branch);
55
+ if (exact)
56
+ return exact;
57
+ const named = projectIds.find((projectId) => branch.startsWith(`feature/${projectId}/`) || branch.startsWith(`exec/${projectId}-`));
58
+ if (named)
59
+ return named;
60
+ }
61
+ return config.current_project?.trim() || projectIds[0];
62
+ }
63
+ export function assertCrossProjectMutationAllowed(command, projectId, commit) {
64
+ if (command !== "add") {
65
+ if (CROSS_PROJECT_TRANSITIONS.has(command)) {
66
+ throw new Error(`Cross-project register ${command} is not supported for ${projectId}. ` +
67
+ `Run the command in the worktree for project ${projectId}.`);
68
+ }
69
+ throw new Error(`Cross-project register ${command} is not supported for ${projectId}. ` +
70
+ `Only register add --project ${projectId} --commit can write to another project.`);
71
+ }
72
+ if (!commit) {
73
+ throw new Error(`Cross-project register add requires --commit so the item is not left in another worktree.`);
74
+ }
75
+ }
76
+ export function resolveCrossProjectMutationTarget(command, opts) {
77
+ const projectId = opts.project?.trim();
78
+ if (!projectId)
79
+ return undefined;
80
+ const repoRoot = specdojoRootDir();
81
+ const { config, configPath } = loadConfig(repoRoot);
82
+ if (!config)
83
+ throw new Error(`register commands require specdojo.config.json (${configPath})`);
84
+ const project = config.projects[projectId];
85
+ if (!project)
86
+ throw new Error(`Unknown project: ${projectId} (check ${configPath})`);
87
+ const branch = resolveProjectIntegrationBranch(projectId, project);
88
+ const branchNow = currentBranch(repoRoot);
89
+ if (branchNow === branch)
90
+ return undefined;
91
+ if (configuredCurrentProject(config, branchNow) === projectId)
92
+ return undefined;
93
+ assertCrossProjectMutationAllowed(command, projectId, opts.commit);
94
+ requireLocalBranch(repoRoot, projectId, branch);
95
+ return { projectId, branch };
96
+ }
97
+ function removeTemporaryWorktree(repoRoot, path, parent) {
98
+ gitOutput(repoRoot, ["worktree", "remove", path]);
99
+ rmSync(parent, { recursive: true, force: true });
100
+ }
101
+ export async function inCrossProjectWorktree(target, operation) {
102
+ const repoRoot = specdojoRootDir();
103
+ const existing = worktreeForBranch(repoRoot, target.branch);
104
+ const temporaryParent = existing
105
+ ? undefined
106
+ : mkdtempSync(join(tmpdir(), `specdojo-register-${target.projectId}-`));
107
+ const worktreePath = existing ?? join(temporaryParent, "worktree");
108
+ if (!existing) {
109
+ try {
110
+ gitOutput(repoRoot, ["worktree", "add", worktreePath, target.branch]);
111
+ }
112
+ catch (error) {
113
+ rmSync(temporaryParent, { recursive: true, force: true });
114
+ throw error;
115
+ }
116
+ }
117
+ const originalDirectory = process.cwd();
118
+ let succeeded = false;
119
+ try {
120
+ process.chdir(worktreePath);
121
+ const result = await operation();
122
+ succeeded = true;
123
+ return result;
124
+ }
125
+ finally {
126
+ process.chdir(originalDirectory);
127
+ if (temporaryParent && succeeded) {
128
+ removeTemporaryWorktree(repoRoot, worktreePath, temporaryParent);
129
+ }
130
+ else if (temporaryParent && worktreeStatusPaths(worktreePath).length === 0) {
131
+ removeTemporaryWorktree(repoRoot, worktreePath, temporaryParent);
132
+ }
133
+ }
134
+ }
@@ -1,7 +1,9 @@
1
1
  import { existsSync } from "node:fs";
2
- import { resolve } from "node:path";
2
+ import { basename, resolve } from "node:path";
3
+ import { gitOutput, gitResult } from "../shared/git.js";
3
4
  import { getProjectRegisterPath, loadConfig, specdojoRootDir, } from "../shared/specdojo-config.js";
4
- import { loadRegisterItemDocs, PJR_ID_RE } from "./item.js";
5
+ import { displayIdFromTicketFilename, loadRegisterItemDocs, PJR_ID_RE, } from "./item.js";
6
+ import { resolveProjectIntegrationBranch } from "./cross-project.js";
5
7
  const QUALIFIED_REGISTER_ITEM_REF_RE = /^([a-z][a-z0-9-]*):(PJR-[0-9ABCDEFGHJKMNPQRSTVWXYZ]{4})$/;
6
8
  export function parseRegisterItemRef(value, currentProjectId) {
7
9
  if (PJR_ID_RE.test(value))
@@ -24,14 +26,35 @@ export function normalizeDerivedFrom(values, options) {
24
26
  throw new Error("--from must contain a register item ID");
25
27
  return refs;
26
28
  }
27
- function configuredItemIds(config, projectId) {
29
+ function configuredItemIds(config, projectId, currentProjectId) {
28
30
  const project = config.projects[projectId];
29
31
  if (!project)
30
- return undefined;
32
+ throw new Error(`Cannot verify derived_from item: unknown project ${projectId}`);
31
33
  const registerPath = getProjectRegisterPath(project);
32
34
  if (!registerPath) {
33
35
  throw new Error(`Cannot verify derived_from item in configured project ${projectId}: project_register_path is not set`);
34
36
  }
37
+ if (projectId !== currentProjectId) {
38
+ const repoRoot = specdojoRootDir();
39
+ const branch = resolveProjectIntegrationBranch(projectId, project);
40
+ const exists = gitResult(repoRoot, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]);
41
+ if (exists.status !== 0) {
42
+ throw new Error(`Cannot verify derived_from item in project ${projectId}: ` +
43
+ `integration branch does not exist locally: ${branch}`);
44
+ }
45
+ const files = gitOutput(repoRoot, [
46
+ "ls-tree",
47
+ "-r",
48
+ "--name-only",
49
+ branch,
50
+ "--",
51
+ registerPath.replaceAll("\\", "/"),
52
+ ]);
53
+ return new Set(files
54
+ .split(/\r?\n/)
55
+ .map((path) => displayIdFromTicketFilename(basename(path)))
56
+ .filter((id) => id !== undefined));
57
+ }
35
58
  const absolutePath = resolve(specdojoRootDir(), registerPath);
36
59
  return new Set(loadRegisterItemDocs(absolutePath).map((doc) => doc.id));
37
60
  }
@@ -44,11 +67,9 @@ function validateDerivedFromWithConfig(opts, config, idsByProject) {
44
67
  if (parsed.projectId === opts.projectId && parsed.itemId === opts.itemId) {
45
68
  throw new Error(`Item ${opts.itemId} cannot derive from itself`);
46
69
  }
47
- if (!config.projects[parsed.projectId])
48
- continue;
49
70
  let ids = idsByProject.get(parsed.projectId);
50
71
  if (!idsByProject.has(parsed.projectId)) {
51
- ids = configuredItemIds(config, parsed.projectId);
72
+ ids = configuredItemIds(config, parsed.projectId, opts.projectId);
52
73
  idsByProject.set(parsed.projectId, ids);
53
74
  }
54
75
  if (!ids?.has(parsed.itemId)) {
@@ -1,7 +1,7 @@
1
1
  // 統合 merge で登録簿の記帳ファイルが競合したときの解決処理。イベントファイルは追記型の記録なので、
2
2
  // 両側のイベントの和集合(同一 id は 1 件)を時刻順に並べ、`previous_event_id` の連鎖を張り直す。
3
3
  // 個票は exec branch 側を基準にし、統合先だけにあるイベントが変えたフィールドのうち、frontmatter の
4
- // 単純な値へ写せるもの(type / priority / owner / due / approach / targets /
4
+ // 単純な値へ写せるもの(type / priority / difficulty / owner / due / approach / targets /
5
5
  // derived_from)だけを再構築する。
6
6
  import { readRegisterEventsFromContent, serializeRegisterEvents, } from "./events.js";
7
7
  import { applyRegisterItemFields, CELL_NONE, CELL_TODO, REMOVE_REGISTER_ITEM_FIELD, } from "./item.js";
@@ -127,6 +127,12 @@ function fieldUpdateFromChange(change) {
127
127
  return isUnset ? undefined : { item_type: value };
128
128
  case "priority":
129
129
  return isUnset ? undefined : { priority: value };
130
+ case "difficulty":
131
+ return isUnset
132
+ ? { difficulty: REMOVE_REGISTER_ITEM_FIELD }
133
+ : ["hard", "medium", "easy"].includes(value)
134
+ ? { difficulty: value }
135
+ : undefined;
130
136
  case "owner":
131
137
  return { owner: isUnset ? null : value };
132
138
  case "due":
@@ -165,6 +171,12 @@ function fieldUpdateFromChange(change) {
165
171
  return undefined;
166
172
  }
167
173
  }
174
+ case "autopilot":
175
+ return isUnset
176
+ ? { autopilot: REMOVE_REGISTER_ITEM_FIELD }
177
+ : value === "approved"
178
+ ? { autopilot: "approved" }
179
+ : undefined;
168
180
  default:
169
181
  return undefined;
170
182
  }
@@ -14,6 +14,7 @@ export const REGISTER_EVENT_FIELDS = [
14
14
  "description",
15
15
  "type",
16
16
  "priority",
17
+ "difficulty",
17
18
  "owner",
18
19
  "registered",
19
20
  "due",
@@ -23,6 +24,7 @@ export const REGISTER_EVENT_FIELDS = [
23
24
  "approach",
24
25
  "targets",
25
26
  "derived_from",
27
+ "autopilot",
26
28
  ];
27
29
  export const REGISTER_EVENT_ACTIONS = [
28
30
  "add",
@@ -65,6 +67,7 @@ export function registerEventFieldValues(content, filename, timeZone) {
65
67
  description: item.description,
66
68
  type: item.type,
67
69
  priority: item.priority,
70
+ difficulty: item.difficulty ?? CELL_NONE,
68
71
  owner: item.owner,
69
72
  registered: item.registered,
70
73
  due: item.due,
@@ -74,6 +77,7 @@ export function registerEventFieldValues(content, filename, timeZone) {
74
77
  approach: item.approach ?? CELL_NONE,
75
78
  targets: item.targets ? JSON.stringify(item.targets) : CELL_NONE,
76
79
  derived_from: item.derivedFrom ? JSON.stringify(item.derivedFrom) : CELL_NONE,
80
+ autopilot: item.autopilot ?? CELL_NONE,
77
81
  };
78
82
  }
79
83
  function isUnsetFieldValue(value) {
@@ -28,6 +28,7 @@ export const VALID_TYPES = [
28
28
  "note",
29
29
  ];
30
30
  export const VALID_PRIORITIES = ["high", "medium", "low"];
31
+ export const VALID_DIFFICULTIES = ["hard", "medium", "easy"];
31
32
  export const TERMINAL_STATUSES_SET = new Set(["done", "decided", "rejected", "deferred"]);
32
33
  // PJR-ID の乱数部分に使う 32 文字セット。曖昧文字(`I` / `L` / `O` / `U`)を除いた
33
34
  // 英大文字(単一ケース)と数字で構成し、目視・手入力時の誤読を避ける。
@@ -58,6 +59,7 @@ const SPECDOJO_KEY_ORDER = [
58
59
  "item_type",
59
60
  "item_status",
60
61
  "priority",
62
+ "difficulty",
61
63
  "owner",
62
64
  "registered_at",
63
65
  "due_on",
@@ -65,6 +67,7 @@ const SPECDOJO_KEY_ORDER = [
65
67
  "block_reason",
66
68
  "conclusion",
67
69
  "derived_from",
70
+ "autopilot",
68
71
  "approach",
69
72
  "targets",
70
73
  ];
@@ -93,16 +96,37 @@ export function displayIdFromTicketFilename(filename) {
93
96
  export function ticketRefCell(filename) {
94
97
  return `[${filename.replace(/\.md$/, "")}](./${filename})`;
95
98
  }
96
- // 表セルへ埋め込むために1行化し、列区切りの `|` をエスケープする。
97
- // すでにエスケープ済みの `\|` は再エスケープせず、複数回の呼び出しに対して冪等にする。
99
+ // Markdown のコードスパン。コードとして明示された内容は、表セルでも著者の記法を保持する。
100
+ const MARKDOWN_CODE_SPAN = /(`+)[\s\S]*?\1/g;
101
+ // コードスパン外の未エスケープな強調記号をエスケープする。
102
+ // 記号の直前に偶数個のバックスラッシュがある場合は Markdown 上で未エスケープなので、
103
+ // バックスラッシュを 1 個加える。奇数個なら既にエスケープ済みとして保持する。
104
+ function escapeTableCellEmphasis(text) {
105
+ const escapeSegment = (segment) => segment.replace(/(?<!\\)((?:\\\\)*)[*_]/g, (match) => {
106
+ return `${match.slice(0, -1)}\\${match.slice(-1)}`;
107
+ });
108
+ let result = "";
109
+ let lastIndex = 0;
110
+ for (const match of text.matchAll(MARKDOWN_CODE_SPAN)) {
111
+ const start = match.index ?? 0;
112
+ result += escapeSegment(text.slice(lastIndex, start));
113
+ result += match[0];
114
+ lastIndex = start + match[0].length;
115
+ }
116
+ return result + escapeSegment(text.slice(lastIndex));
117
+ }
118
+ // 表セルへ埋め込むために1行化し、列区切りの `|` と強調記号の `*` / `_` を
119
+ // エスケープする。既存コードスパンとエスケープ済みの記号は保持し、複数回の呼び出しに
120
+ // 対して冪等にする。
98
121
  export function toCell(text) {
99
122
  if (typeof text !== "string")
100
123
  return "";
101
- return text
124
+ const normalized = text
102
125
  .replace(/\r?\n/g, " ")
103
126
  .replace(/\s+/g, " ")
104
127
  .replace(/(?<!\\)((\\\\)*)\|/g, "$1\\|")
105
128
  .trim();
129
+ return escapeTableCellEmphasis(normalized);
106
130
  }
107
131
  // H1(`# PJR-XXXX タイトル`)からタイトルを導出する。表示 ID の接頭辞は取り除く。
108
132
  export function titleFromBody(body, id) {
@@ -137,10 +161,10 @@ export function descriptionFromBody(body) {
137
161
  }
138
162
  if (paragraph.length === 0)
139
163
  return CELL_TODO;
140
- const text = toCell(paragraph.join(" "));
164
+ const text = paragraph.join(" ");
141
165
  if (text.startsWith(CELL_TODO))
142
166
  return CELL_TODO;
143
- return text;
167
+ return toCell(text);
144
168
  }
145
169
  // ================================
146
170
  // Reading
@@ -172,6 +196,8 @@ export function readRegisterItemContent(content, filename) {
172
196
  const derivedFrom = Array.isArray(fields.derived_from)
173
197
  ? fields.derived_from.filter((entry) => typeof entry === "string" && entry.trim() !== "")
174
198
  : undefined;
199
+ const autopilot = fields.autopilot === "approved" ? "approved" : undefined;
200
+ const difficulty = asString(fields.difficulty);
175
201
  const item = {
176
202
  id,
177
203
  status: asString(fields.item_status) ?? "open",
@@ -179,6 +205,7 @@ export function readRegisterItemContent(content, filename) {
179
205
  description: descriptionFromBody(body),
180
206
  type: asString(fields.item_type) ?? CELL_TODO,
181
207
  priority: asString(fields.priority) ?? "medium",
208
+ ...(difficulty ? { difficulty } : {}),
182
209
  owner: asString(fields.owner) ?? CELL_TODO,
183
210
  registeredAt: asString(fields.registered_at) ?? CELL_TODO,
184
211
  due: fields.due_on === null
@@ -191,6 +218,7 @@ export function readRegisterItemContent(content, filename) {
191
218
  ...(approach ? { approach } : {}),
192
219
  ...(targets && targets.length > 0 ? { targets } : {}),
193
220
  ...(derivedFrom && derivedFrom.length > 0 ? { derivedFrom } : {}),
221
+ ...(autopilot ? { autopilot } : {}),
194
222
  };
195
223
  return {
196
224
  id,
@@ -299,6 +327,7 @@ export function registerItemFieldsFromItem(item) {
299
327
  item_type: item.type,
300
328
  item_status: item.status,
301
329
  priority: item.priority,
330
+ ...(item.difficulty ? { difficulty: item.difficulty } : {}),
302
331
  owner: isPlaceholderCell(item.owner) ? null : item.owner.trim(),
303
332
  registered_at: isPlaceholderCell(item.registeredAt) ? null : item.registeredAt.trim(),
304
333
  due_on: item.due.trim() === CELL_TODO
@@ -313,6 +342,7 @@ export function registerItemFieldsFromItem(item) {
313
342
  ...(item.approach ? { approach: item.approach } : {}),
314
343
  ...(item.targets && item.targets.length > 0 ? { targets: item.targets } : {}),
315
344
  ...(item.derivedFrom && item.derivedFrom.length > 0 ? { derived_from: item.derivedFrom } : {}),
345
+ ...(item.autopilot ? { autopilot: item.autopilot } : {}),
316
346
  };
317
347
  }
318
348
  function orderSpecdojoKeys(fields) {
@@ -144,6 +144,7 @@ export function planRegisterMigration(paths) {
144
144
  title: tableCellToBody(source.item.title),
145
145
  description: tableCellToBody(source.item.description),
146
146
  priority: source.item.priority,
147
+ ...(source.item.difficulty ? { difficulty: source.item.difficulty } : {}),
147
148
  status: source.item.status,
148
149
  owner: source.item.owner,
149
150
  registeredAt: source.item.registeredAt,
@@ -9,7 +9,7 @@ import { normalizeRegisterTimestamp } from "./date.js";
9
9
  import { validateDerivedFromDocs } from "./derivation.js";
10
10
  import { appendRegisterEvent, deterministicRegisterEventId, readEmbeddedRegisterEvents, readRegisterEventsFromContent, registerEventFilePath, removeEmbeddedRegisterEvents, serializeRegisterEvents, validateRegisterEventDocs, } from "./events.js";
11
11
  import { collectRegisterHistoryEvents } from "./history.js";
12
- import { loadRegisterItemDocs, PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, toCell, validateRegisterItemDocs, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
12
+ import { loadRegisterItemDocs, PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, toCell, validateRegisterItemDocs, VALID_PRIORITIES, VALID_DIFFICULTIES, VALID_STATUSES, VALID_TYPES, } from "./item.js";
13
13
  import { registerMaintenanceCommands } from "./maintenance-commands.js";
14
14
  import { applyRegisterMigrationPlan, planRegisterMigration } from "./migration.js";
15
15
  import { planRenumber, planRetopic, renumberPjrItem, retopicPjrItem, ticketTopicFromFilename, } from "./renumber.js";
@@ -18,7 +18,8 @@ import { applyItemUpdate, assertTerminalOperationAllowed, loadItemForUpdate, upd
18
18
  import { generateDerivedViewFiles, loadRegisterItems, VALID_BUILD_SCOPES, writeDerivedViews, } from "./views.js";
19
19
  import { specdojoRootDir } from "../shared/specdojo-config.js";
20
20
  import { registerLifecyclePoolPath } from "./lifecycle-lock.js";
21
- export { PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, toCell, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, };
21
+ import { inCrossProjectWorktree, resolveCrossProjectMutationTarget } from "./cross-project.js";
22
+ export { PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, toCell, VALID_PRIORITIES, VALID_DIFFICULTIES, VALID_STATUSES, VALID_TYPES, };
22
23
  export { REGISTER_TOPIC_RE, VALID_TICKET_STATUSES, buildRegisterItemContent, extractTableHeading, findMarkdownReferenceFiles, generatePjrId, injectRegisterRows, parsePjrIndex, resolveRegisterPaths, } from "./core.js";
23
24
  export { applyRegisterMigrationPlan, planRegisterMigration, } from "./migration.js";
24
25
  export { findItemById, findRegisterItem, generateDerivedViewFiles, injectViewSlots, loadRegisterItems, sortByRegisteredDesc, } from "./views.js";
@@ -135,38 +136,54 @@ function commitRegisterMutation(repoRoot, paths, command, result, preexisting, m
135
136
  throw new Error(`Register commit incomplete: target paths remained dirty after hook stabilization:\n` +
136
137
  remaining.map((path) => ` ${path}`).join("\n"));
137
138
  }
139
+ async function runRegisterMutationInCurrentWorktree(command, opts, mutate, requireCleanRegister) {
140
+ const paths = resolveRegisterPaths(opts);
141
+ if (!opts.commit || opts.dryRun) {
142
+ mutate({ paths, assertCommitTargetsClean: () => undefined });
143
+ return;
144
+ }
145
+ const repoRoot = specdojoRootDir();
146
+ if (!paths.executionPath) {
147
+ throw new Error(`Execution path is not configured for project ${paths.projectId}`);
148
+ }
149
+ const mutex = new CrossProcessMutex(registerLifecyclePoolPath(paths.executionPath), {
150
+ actor: registerEventActor(opts),
151
+ label: `register ${command}`,
152
+ }, {
153
+ onWait: () => process.stdout.write("Waiting for the register lifecycle lock held by another operation\n"),
154
+ });
155
+ await mutex.runExclusive(() => {
156
+ const preexisting = new Set(worktreeStatusPaths(repoRoot));
157
+ if (requireCleanRegister) {
158
+ const registerPrefix = `${repoRelative(repoRoot, paths.projectRegisterPath)}/`;
159
+ const dirtyRegisterPaths = [...preexisting].filter((path) => path === registerPrefix.slice(0, -1) || path.startsWith(registerPrefix));
160
+ if (dirtyRegisterPaths.length > 0) {
161
+ throw new Error(`Cannot add to project ${paths.projectId} because its register has uncommitted changes:\n` +
162
+ dirtyRegisterPaths.map((path) => ` ${path}`).join("\n"));
163
+ }
164
+ }
165
+ const assertCommitTargetsClean = (targets) => {
166
+ const overlapping = targets
167
+ .map((target) => repoRelative(repoRoot, target))
168
+ .filter((target) => preexisting.has(target));
169
+ if (overlapping.length === 0)
170
+ return;
171
+ throw new Error(`Cannot use --commit because register targets already have uncommitted changes:\n` +
172
+ overlapping.map((path) => ` ${path}`).join("\n"));
173
+ };
174
+ const result = mutate({ paths, assertCommitTargetsClean });
175
+ rebuildRegisterViews(paths);
176
+ commitRegisterMutation(repoRoot, paths, command, result, preexisting, opts.message);
177
+ });
178
+ }
138
179
  async function runRegisterMutation(command, opts, mutate) {
139
180
  try {
140
- const paths = resolveRegisterPaths(opts);
141
- if (!opts.commit || opts.dryRun) {
142
- mutate({ paths, assertCommitTargetsClean: () => undefined });
181
+ const crossProjectTarget = resolveCrossProjectMutationTarget(command, opts);
182
+ if (crossProjectTarget) {
183
+ await inCrossProjectWorktree(crossProjectTarget, () => runRegisterMutationInCurrentWorktree(command, opts, mutate, true));
143
184
  return;
144
185
  }
145
- const repoRoot = specdojoRootDir();
146
- if (!paths.executionPath) {
147
- throw new Error(`Execution path is not configured for project ${paths.projectId}`);
148
- }
149
- const mutex = new CrossProcessMutex(registerLifecyclePoolPath(paths.executionPath), {
150
- actor: registerEventActor(opts),
151
- label: `register ${command}`,
152
- }, {
153
- onWait: () => process.stdout.write("Waiting for the register lifecycle lock held by another operation\n"),
154
- });
155
- await mutex.runExclusive(() => {
156
- const preexisting = new Set(worktreeStatusPaths(repoRoot));
157
- const assertCommitTargetsClean = (targets) => {
158
- const overlapping = targets
159
- .map((target) => repoRelative(repoRoot, target))
160
- .filter((target) => preexisting.has(target));
161
- if (overlapping.length === 0)
162
- return;
163
- throw new Error(`Cannot use --commit because register targets already have uncommitted changes:\n` +
164
- overlapping.map((path) => ` ${path}`).join("\n"));
165
- };
166
- const result = mutate({ paths, assertCommitTargetsClean });
167
- rebuildRegisterViews(paths);
168
- commitRegisterMutation(repoRoot, paths, command, result, preexisting, opts.message);
169
- });
186
+ await runRegisterMutationInCurrentWorktree(command, opts, mutate, false);
170
187
  }
171
188
  catch (error) {
172
189
  printCommandError(error);
@@ -2,8 +2,9 @@ import { existsSync } from "node:fs";
2
2
  import { basename, join, relative, resolve } from "node:path";
3
3
  import { collectResolvedDeliverables } from "../catalog/build.js";
4
4
  import { resolveBasePath } from "../catalog/paths.js";
5
+ import { collectCatalogFilesByDomain } from "../shared/catalog-files.js";
5
6
  import { readYaml } from "../shared/fs.js";
6
- import { collectCatalogFilesByDomain, loadTimelineIndex } from "../dashboard/timeline-build.js";
7
+ import { loadTimelineIndex } from "../shared/timeline-index.js";
7
8
  export function isRecord(value) {
8
9
  return typeof value === "object" && value !== null && !Array.isArray(value);
9
10
  }
@@ -0,0 +1,31 @@
1
+ import { existsSync, readdirSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { readYaml } from "./fs.js";
4
+ function isRecord(value) {
5
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6
+ }
7
+ // 1 ドメインが dct-<domain>-<sub>.yaml のように複数ファイルへ分割されることがあるため、
8
+ // ファイル名ではなく各カタログの domain 値で突き合わせる。
9
+ export function collectCatalogFilesByDomain(catalogPath) {
10
+ const byDomain = new Map();
11
+ if (!existsSync(catalogPath))
12
+ return byDomain;
13
+ const files = readdirSync(catalogPath)
14
+ .filter((file) => /^dct-.+\.ya?ml$/.test(file))
15
+ .sort();
16
+ for (const file of files) {
17
+ const fullPath = join(catalogPath, file);
18
+ const parsed = readYaml(fullPath);
19
+ if (!isRecord(parsed))
20
+ continue;
21
+ const domain = parsed.domain;
22
+ if (typeof domain !== "string" || domain.trim().length === 0)
23
+ continue;
24
+ const group = byDomain.get(domain);
25
+ if (group)
26
+ group.push(fullPath);
27
+ else
28
+ byDomain.set(domain, [fullPath]);
29
+ }
30
+ return byDomain;
31
+ }
@@ -9,14 +9,24 @@ export { GIT_LOCAL_ENV_VARS, gitEnvironment } from "./git-environment.js";
9
9
  // concurrent worktree commits (each firing lefthook pre-commit hooks that invoke git) contend
10
10
  // for that lock, surfacing as "Unable to create '.../index.lock'". A failed lock acquisition
11
11
  // happens before git mutates anything, so retrying the same command is safe and idempotent.
12
- const INDEX_LOCK_RETRY_ATTEMPTS = 5;
13
- const INDEX_LOCK_RETRY_BASE_MS = 50;
12
+ // 並行の run の統合や記帳と重なると、ロックは数百ミリ秒より長く保持される(PJR-G90K)。
13
+ // 1.5 秒間隔で 10 回までやり直し、ロックのファイルは消さない(実際に動いている git がありうる)。
14
+ export const INDEX_LOCK_RETRY_ATTEMPTS = 10;
15
+ export const INDEX_LOCK_RETRY_WAIT_MS = 1500;
14
16
  // dubious ownership と、`.git` がある cwd での not-a-repository は一時的に起き、すぐの
15
17
  // 再試行では収まらないことがある(並行実行中の統合段で確認した)。両方で上限を共有する。
16
18
  const TRANSIENT_GIT_RETRY_DELAYS_MS = [2000, 5000, 10000];
19
+ // 英語の `Unable to create '<path>/index.lock': File exists.` に加え、翻訳された git の
20
+ // メッセージ(日本語など)でも引用符で囲まれた index.lock のパスが出るため、それも拾う。
21
+ const INDEX_LOCK_QUOTED_PATH = /['"‘’“「]([^'"‘’“”「」\r\n]*index\.lock)['"’”」]/u;
22
+ export function gitIndexLockPath(stderr) {
23
+ return INDEX_LOCK_QUOTED_PATH.exec(stderr)?.[1];
24
+ }
17
25
  export function isGitIndexLockContention(stderr) {
18
26
  return (/Unable to create '[^']*index\.lock'/.test(stderr) ||
19
- /Another git process seems to be running/.test(stderr));
27
+ /Another git process seems to be running/.test(stderr) ||
28
+ /別の\s*git\s*プロセス/iu.test(stderr) ||
29
+ gitIndexLockPath(stderr) !== undefined);
20
30
  }
21
31
  export function isGitDubiousOwnership(stderr) {
22
32
  return /fatal:\s+detected dubious ownership in repository\b/i.test(stderr);
@@ -75,7 +85,13 @@ export function runGitWithTransientRetry(run, onTransientFailureRetry = () => un
75
85
  }
76
86
  if (indexLockRetries < INDEX_LOCK_RETRY_ATTEMPTS && isGitIndexLockContention(stderr)) {
77
87
  indexLockRetries += 1;
78
- sleep(INDEX_LOCK_RETRY_BASE_MS * indexLockRetries); // 50, 100, 150, 200, 250 ms
88
+ onTransientFailureRetry({
89
+ attempt: indexLockRetries,
90
+ maxAttempts: INDEX_LOCK_RETRY_ATTEMPTS,
91
+ waitMilliseconds: INDEX_LOCK_RETRY_WAIT_MS,
92
+ reason: "index.lock contention",
93
+ });
94
+ sleep(INDEX_LOCK_RETRY_WAIT_MS);
79
95
  result = run();
80
96
  continue;
81
97
  }
@@ -175,7 +191,11 @@ export function formatGitCommandFailure(args, stderr, processFailure = "") {
175
191
  ? args
176
192
  : [...args.slice(0, subcommandIndex), ...args.slice(subcommandIndex + 1)]);
177
193
  const detail = summary ? ` (args: ${summary})` : "";
178
- const cause = [processFailure.trim(), summarizeGitStderr(stderr)]
194
+ // gitResult は index.lock の取り合いをやり直したうえで失敗を返す。どのロックが残っていたかを
195
+ // 要約の切り詰めに左右されず先頭に残す(ロックは runner が消さないため、人が確かめる手掛かり)。
196
+ const lockPath = isGitIndexLockContention(stderr) ? gitIndexLockPath(stderr) : undefined;
197
+ const lockNotice = lockPath ? `index.lock is still held (lock: ${lockPath})` : "";
198
+ const cause = [processFailure.trim(), lockNotice, summarizeGitStderr(stderr)]
179
199
  .filter((part) => part !== "")
180
200
  .join(" / ");
181
201
  return cause ? `${label} failed: ${cause}${detail}` : `${label} failed${detail}`;
@@ -203,21 +223,31 @@ export function summarizeGitHookFailure(output) {
203
223
  .filter(Boolean);
204
224
  if (lines.length === 0)
205
225
  return "unknown hook failure";
206
- let step = "";
207
- let stepIndex = -1;
226
+ const stepHeaders = [];
208
227
  for (const [index, line] of lines.entries()) {
209
228
  const match = line.match(/^(.+?)\s*[❯▶]\s*$/u);
210
- if (!match)
211
- continue;
212
- step = match[1].trim();
213
- stepIndex = index;
214
- break;
229
+ if (match)
230
+ stepHeaders.push({ step: match[1].trim(), index });
215
231
  }
232
+ // parallel: true の lefthook は成功した step の出力も並べるため、最初の step 見出しが
233
+ // 失敗した step とは限らない。末尾の summary で失敗印(🥊 など)が付いた step を優先する。
234
+ const failedSteps = lines
235
+ .map((line) => line.match(/^(?:🥊|✗|✘|✕|❌)️?\s*([^\s(]+)/u)?.[1])
236
+ .filter((name) => name !== undefined && name !== "lefthook");
237
+ const selected = stepHeaders.find((header) => failedSteps.includes(header.step)) ?? stepHeaders[0];
238
+ const step = selected?.step ?? failedSteps[0] ?? "";
239
+ const stepIndex = selected?.index ?? -1;
240
+ const sectionEnd = selected === undefined
241
+ ? lines.length
242
+ : (stepHeaders.find((header) => header.index > selected.index)?.index ?? lines.length);
216
243
  const isDecoration = (line) => /^(?:hook output|summary:|exit status\b|failed steps?:|skip(?:ped)?\b)/i.test(line) ||
217
244
  /^[✓✔✗✘✕❯▶]+$/u.test(line);
218
- const errorLine = lines
219
- .slice(stepIndex >= 0 ? stepIndex + 1 : 0)
220
- .find((line) => line !== step && !isDecoration(line) && !/[❯▶]\s*$/u.test(line));
245
+ const isCandidate = (line) => line !== step && !isDecoration(line) && !/[❯▶]\s*$/u.test(line);
246
+ const sectionLines = lines.slice(stepIndex + 1, sectionEnd).filter(isCandidate);
247
+ // 整形ツールが出す "(unchanged)" などの進捗行より、error を含む行を最初のエラーとして選ぶ。
248
+ const errorLine = sectionLines.find((line) => /\berror\b/i.test(line)) ??
249
+ sectionLines[0] ??
250
+ lines.slice(stepIndex + 1).find(isCandidate);
221
251
  const primary = step && errorLine
222
252
  ? `${step}: ${errorLine}`
223
253
  : step ||