specdojo 0.4.1 → 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 (30) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/commands/init.js +16 -0
  3. package/dist/dashboard/timeline-build.js +4 -151
  4. package/dist/exec/events.js +17 -6
  5. package/dist/exec/plans-core.js +16 -5
  6. package/dist/exec/plans-storage.js +11 -3
  7. package/dist/kata/kata.js +1 -1
  8. package/dist/register/core.js +3 -2
  9. package/dist/register/cross-project.js +134 -0
  10. package/dist/register/derivation.js +28 -7
  11. package/dist/register/item.js +26 -5
  12. package/dist/register/register.js +45 -28
  13. package/dist/schedule/strategy-generate-scope.js +2 -1
  14. package/dist/shared/catalog-files.js +31 -0
  15. package/dist/shared/lefthook-scaffold.js +177 -0
  16. package/dist/shared/specdojo-config.js +21 -4
  17. package/dist/shared/timeline-index.js +125 -0
  18. package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +4 -2
  19. package/docs/ja/specdojo/guides/quick-start-guide.md +23 -1
  20. package/docs/ja/specdojo/guides/register-operation-guide.md +12 -0
  21. package/docs/ja/specdojo/references/command-reference.md +39 -10
  22. package/docs/ja/specdojo/references/specdojo-config-reference.md +8 -5
  23. package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +5 -0
  24. package/package.json +1 -1
  25. package/templates/init-agent-members.yaml +3 -3
  26. package/templates/lefthook/tools/install-lefthook.mjs +46 -0
  27. package/templates/lefthook/tools/specdojo-pre-commit.mjs +207 -0
  28. package/templates/opencode/README.md +6 -1
  29. package/templates/opencode/agents/specdojo-orchestrator.md +1 -1
  30. /package/dist/{shared → kata}/yaml-schema-modeline.js +0 -0
package/CHANGELOG.md CHANGED
@@ -2,6 +2,28 @@
2
2
 
3
3
  SpecDojo の利用者に影響する変更を記録します。
4
4
 
5
+ ## [0.4.2] - 2026-10-22
6
+
7
+ ### 追加機能
8
+
9
+ - `specdojo init --lefthook` と `specdojo config scaffold --lefthook` で、利用リポジトリ向けの `lefthook.yml`、SpecDojo 文書向けの markdownlint 設定と agent 定義の除外、依存なしの入口スクリプトを生成できるようにしました。pre-commit は staged の Markdown・YAML に対する Prettier、Markdown に対する markdownlint、設定済みパスの変更に対する `register build`・`catalog validate` を実行します。既存ファイル・npm script・依存は上書きせず、package への追加内容を先に表示します(PJR-7H7N)。
10
+ - 別 project の作業ツリーから `register add --project <project-id> --commit` を実行し、対象 project の統合ブランチへ直接起票できるようにしました。統合ブランチは project の `integration_branch` で指定でき、省略時は `project/<project-id>/develop` です。project 修飾した `--from` は参照先 project の統合ブランチから存在を確認します(PJR-W93C)。
11
+
12
+ ### 変更
13
+
14
+ - ドキュメントサイトでは exec の plan / result をページ生成の対象から外し、実行記録一覧などからのリンクを GitHub 上の正本へ置き換えるようにしました。元の実行記録と dead link 検査は維持したまま、ページ数とビルド時のメモリ使用量を削減します(PJR-98P8)。
15
+ - `templates/init-agent-members.yaml` で配布する OpenCode の `gemma-reporter` の既定モデルを 26b(`ollama-local/gemma4:26b`)にし、`gemma-executor`・`gemma-review-executor` および対話型オーケストレーターのモデル名からローカル固有のタグ(`-mlx-work-64k`)を除いて利用者が `ollama pull` で取得できるタグ名(`ollama-local/gemma4:31b`)に改めました。また `templates/opencode/README.md` に文脈長拡張のための Modelfile 手順と既存名簿の書き換え案内を追記しました(PJR-2ASZ)。
16
+
17
+ ### 不具合修正
18
+
19
+ - plan / result の stem、アーカイブ済み plan、実行 event の乱数部分を2バイトから4バイトへ広げ、同じ slug・UTC秒・乱数が重複した場合は連番で別名にするようにしました。event は排他的な新規作成で既存履歴を上書きせず、旧形式の plan 名も引き続き読み取れます(PJR-CNNT)。
20
+ - `templates/lefthook/tools/specdojo-pre-commit.mjs` で、commit したファイルが `.markdownlintignore` や `.prettierignore` で除外されて検査対象がなくなった場合に、markdownlint や Prettier を呼ばずに成功で終えるようにしました。除外ファイルのみを commit したときに markdownlint の使い方の説明(Usage)が出力される問題を解消します(PJR-62T2)。
21
+ - `register build` が生成する登録簿一覧・派生ビュー・PM ログで、自由記述セルのアスタリスクとアンダースコアをエスケープするようにしました。既存のコードスパンとエスケープ済みの記号は保持し、`orch:*` のような記述が複数ある場合も markdownlint(MD037)で止まりません(PJR-6SQH)。
22
+
23
+ ### 文書
24
+
25
+ - `templates/opencode/README.md` に、Mac の Apple シリコン向けに Ollama の公式 mlx 版(`gemma4:26b-mlx`・`gemma4:31b-mlx`)を利用する場合の指定方法と Modelfile での文脈拡張の案内を追記しました(PJR-STB4)。
26
+
5
27
  ## [0.4.1] - 2026-10-21
6
28
 
7
29
  ### 追加機能
@@ -5,6 +5,7 @@ import { dump, load } from "../shared/yaml.js";
5
5
  import { runScaffold } from "../catalog/scaffold.js";
6
6
  import { runDevcontainerScaffold } from "../devcontainer/scaffold.js";
7
7
  import { runProviderScaffold } from "../shared/provider-scaffold.js";
8
+ import { runLefthookScaffold } from "../shared/lefthook-scaffold.js";
8
9
  import { generateDerivedViewFiles } from "../register/register.js";
9
10
  import { defaultWorktreeBase, projectGitignoreLayout, specdojoRootDir, } from "../shared/specdojo-config.js";
10
11
  import { ensureGitignore, formatGitignoreReport, gitignorePatternsForLayouts, } from "../shared/specdojo-gitignore.js";
@@ -142,6 +143,7 @@ export async function collectInitAnswers(options, prompter) {
142
143
  exec: !!options.exec,
143
144
  catalog: parseCatalog(options.catalog),
144
145
  devcontainer,
146
+ lefthook: !!options.lefthook,
145
147
  ...(devcontainerPreset ? { devcontainerPreset } : {}),
146
148
  });
147
149
  for (const [label, used] of [
@@ -154,6 +156,7 @@ export async function collectInitAnswers(options, prompter) {
154
156
  ["exec=no", !options.exec],
155
157
  ["catalog=none", !options.catalog],
156
158
  ["devcontainer=no", !options.devcontainer],
159
+ ["lefthook=no", !options.lefthook],
157
160
  ["devcontainer-preset=recommended", devcontainer && options.devcontainerPreset === undefined],
158
161
  ]) {
159
162
  if (used)
@@ -170,6 +173,7 @@ export async function collectInitAnswers(options, prompter) {
170
173
  const providerDefault = options.provider?.trim() || DEFAULTS.providers.join(",");
171
174
  const execDefault = !!options.exec;
172
175
  const devcontainerDefault = !!options.devcontainer;
176
+ const lefthookDefault = !!options.lefthook;
173
177
  const explicitDevcontainerPreset = parseDevcontainerPreset(options.devcontainerPreset);
174
178
  const providerPrompt = `Orchestrator providers (${PROVIDERS.join(", ")}) [${providerDefault}]: `;
175
179
  const projectId = await promptUntilValid(prompter, `Project ID [${projectDefault}]: `, (answer) => validateProjectId(answer.trim() || projectDefault));
@@ -188,6 +192,7 @@ export async function collectInitAnswers(options, prompter) {
188
192
  const devcontainerPreset = devcontainer && options.devcontainerPreset === undefined
189
193
  ? await promptUntilValid(prompter, "Add the recommended Dev Container settings? [Y/n]: ", (answer) => (parseBoolean(answer, true) ? "recommended" : undefined))
190
194
  : explicitDevcontainerPreset;
195
+ const lefthook = await promptUntilValid(prompter, `Create Git hooks with lefthook? [${lefthookDefault ? "Y/n" : "y/N"}]: `, (answer) => parseBoolean(answer, lefthookDefault));
191
196
  return validateAnswers({
192
197
  projectId,
193
198
  projectName,
@@ -198,6 +203,7 @@ export async function collectInitAnswers(options, prompter) {
198
203
  exec,
199
204
  catalog,
200
205
  devcontainer,
206
+ lefthook,
201
207
  ...(devcontainerPreset ? { devcontainerPreset } : {}),
202
208
  });
203
209
  }
@@ -517,6 +523,15 @@ export async function runInit(options, deps) {
517
523
  dryRun,
518
524
  });
519
525
  }
526
+ if (answers.lefthook) {
527
+ await runLefthookScaffold({
528
+ packageRoot,
529
+ repoRoot,
530
+ config,
531
+ force: false,
532
+ dryRun,
533
+ });
534
+ }
520
535
  const firstProvider = answers.providers[0];
521
536
  const script = firstProvider === "claude"
522
537
  ? "orch:opus"
@@ -551,6 +566,7 @@ export function registerInitCommand(program) {
551
566
  .option("--exec", "Configure executor and reporter agents", false)
552
567
  .option("--catalog <size>", "Create a deliverables catalog (small|medium|large)")
553
568
  .option("--devcontainer", "Create a Dev Container for the selected providers", false)
569
+ .option("--lefthook", "Create pre-commit hooks for SpecDojo repositories", false)
554
570
  .option("--devcontainer-preset <name>", "Apply a Dev Container preset when creating it (recommended|none)")
555
571
  .option("--workspace-name <name>", "Override the Dev Container workspace parent name used under /workspaces")
556
572
  .option("--dry-run", "Show planned files and changes without writing", false)
@@ -1,130 +1,8 @@
1
- import { existsSync, readdirSync } from "node:fs";
1
+ import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { readYaml } from "../shared/fs.js";
4
- import { normalizeDateOnly } from "../shared/time.js";
5
- const CATALOG_STATUSES = ["not_started", "draft", "primary"];
6
- function isRecord(value) {
7
- return typeof value === "object" && value !== null && !Array.isArray(value);
8
- }
9
- function readStringArray(value, field, errors) {
10
- if (value === undefined)
11
- return [];
12
- if (!Array.isArray(value)) {
13
- errors.push(`${field}: must be an array of strings`);
14
- return [];
15
- }
16
- const result = [];
17
- for (const item of value) {
18
- if (typeof item !== "string" || item.trim().length === 0) {
19
- errors.push(`${field}: must contain non-empty strings only`);
20
- continue;
21
- }
22
- result.push(item);
23
- }
24
- return result;
25
- }
26
- function parseTrack(raw, index, errors) {
27
- const where = `tracks[${index}]`;
28
- if (!isRecord(raw)) {
29
- errors.push(`${where}: must be an object`);
30
- return null;
31
- }
32
- const track = raw.track;
33
- if (typeof track !== "string" || track.trim().length === 0) {
34
- errors.push(`${where}.track: required non-empty string`);
35
- return null;
36
- }
37
- const domains = readStringArray(raw.domains, `${where}.domains`, errors);
38
- if (domains.length === 0)
39
- errors.push(`${where}.domains: required non-empty array`);
40
- const catalogStatus = raw.catalog_status;
41
- if (typeof catalogStatus !== "string" ||
42
- !CATALOG_STATUSES.includes(catalogStatus)) {
43
- errors.push(`${where}.catalog_status: must be one of ${CATALOG_STATUSES.join(" | ")}`);
44
- return null;
45
- }
46
- const order = raw.order;
47
- if (typeof order !== "number" || !Number.isInteger(order) || order < 1) {
48
- errors.push(`${where}.order: must be an integer >= 1`);
49
- return null;
50
- }
51
- if (raw.depends_on === undefined) {
52
- errors.push(`${where}.depends_on: required (use [] when there is no prerequisite)`);
53
- }
54
- const dependsOn = readStringArray(raw.depends_on, `${where}.depends_on`, errors);
55
- const estimate = raw.catalog_duration_estimate_days;
56
- if (estimate !== undefined && (typeof estimate !== "number" || estimate <= 0)) {
57
- errors.push(`${where}.catalog_duration_estimate_days: must be a number > 0`);
58
- }
59
- const parallelGroup = raw.parallel_group;
60
- if (parallelGroup !== undefined && typeof parallelGroup !== "string") {
61
- errors.push(`${where}.parallel_group: must be a string`);
62
- }
63
- const note = raw.note;
64
- if (note !== undefined && typeof note !== "string") {
65
- errors.push(`${where}.note: must be a string`);
66
- }
67
- return {
68
- track,
69
- domains,
70
- catalog_status: catalogStatus,
71
- ...(typeof estimate === "number" ? { catalog_duration_estimate_days: estimate } : {}),
72
- order,
73
- ...(typeof parallelGroup === "string" ? { parallel_group: parallelGroup } : {}),
74
- depends_on: dependsOn,
75
- ...(typeof note === "string" ? { note } : {}),
76
- };
77
- }
78
- export function loadTimelineIndex(filePath) {
79
- const errors = [];
80
- const parsed = readYaml(filePath);
81
- if (!isRecord(parsed)) {
82
- throw new Error(`${filePath}: invalid or empty YAML`);
83
- }
84
- const projectId = parsed.project_id;
85
- if (typeof projectId !== "string" || projectId.trim().length === 0) {
86
- errors.push(`project_id: required non-empty string`);
87
- }
88
- if (!Array.isArray(parsed.tracks) || parsed.tracks.length === 0) {
89
- errors.push(`tracks: required non-empty array`);
90
- return {
91
- index: {
92
- id: typeof parsed.id === "string" ? parsed.id : "",
93
- project_id: typeof projectId === "string" ? projectId : "",
94
- status: typeof parsed.status === "string" ? parsed.status : "",
95
- tracks: [],
96
- },
97
- errors,
98
- };
99
- }
100
- const tracks = [];
101
- parsed.tracks.forEach((raw, index) => {
102
- const track = parseTrack(raw, index, errors);
103
- if (track)
104
- tracks.push(track);
105
- });
106
- // 計画開始日は YYYY-MM-DD に正規化する。不正な値はエラーとして報告し、未設定とみなす。
107
- let plannedStartDate;
108
- if (parsed.planned_start_date !== undefined && parsed.planned_start_date !== null) {
109
- const normalized = normalizeDateOnly(parsed.planned_start_date);
110
- if (!normalized) {
111
- errors.push("planned_start_date: must be a YYYY-MM-DD date");
112
- }
113
- else {
114
- plannedStartDate = normalized;
115
- }
116
- }
117
- return {
118
- index: {
119
- id: typeof parsed.id === "string" ? parsed.id : "",
120
- project_id: typeof projectId === "string" ? projectId : "",
121
- status: typeof parsed.status === "string" ? parsed.status : "",
122
- tracks,
123
- ...(plannedStartDate !== undefined ? { planned_start_date: plannedStartDate } : {}),
124
- },
125
- errors,
126
- };
127
- }
3
+ import { collectCatalogFilesByDomain } from "../shared/catalog-files.js";
4
+ import { loadTimelineIndex, } from "../shared/timeline-index.js";
5
+ export { collectCatalogFilesByDomain, loadTimelineIndex };
128
6
  // depends_on の未定義参照・循環・order との矛盾を検出する。
129
7
  export function validateTimelineTracks(tracks) {
130
8
  const errors = [];
@@ -193,31 +71,6 @@ export function buildTimelineWaves(tracks) {
193
71
  tracks: [...group].sort((a, b) => a.track.localeCompare(b.track)),
194
72
  }));
195
73
  }
196
- // 1 ドメインが dct-<domain>-<sub>.yaml のように複数ファイルへ分割されることがあるため、
197
- // ファイル名ではなく各カタログの domain 値で突き合わせる。
198
- export function collectCatalogFilesByDomain(catalogPath) {
199
- const byDomain = new Map();
200
- if (!existsSync(catalogPath))
201
- return byDomain;
202
- const files = readdirSync(catalogPath)
203
- .filter((file) => /^dct-.+\.ya?ml$/.test(file))
204
- .sort();
205
- for (const file of files) {
206
- const fullPath = join(catalogPath, file);
207
- const parsed = readYaml(fullPath);
208
- if (!isRecord(parsed))
209
- continue;
210
- const domain = parsed.domain;
211
- if (typeof domain !== "string" || domain.trim().length === 0)
212
- continue;
213
- const group = byDomain.get(domain);
214
- if (group)
215
- group.push(fullPath);
216
- else
217
- byDomain.set(domain, [fullPath]);
218
- }
219
- return byDomain;
220
- }
221
74
  // catalog_status と実カタログの有無から catalog scaffold の対象を決める。
222
75
  export function buildCatalogScaffoldPlans(tracks, catalogPath) {
223
76
  const scaffolds = [];
@@ -112,17 +112,28 @@ export function buildEvent(type, o) {
112
112
  e.meta = meta;
113
113
  return e;
114
114
  }
115
- export function writeEventFile(projectPath, event) {
115
+ export function writeEventFile(projectPath, event, dependencies = {}) {
116
116
  const execDir = eventsDirForProject(projectPath);
117
117
  ensureDir(execDir);
118
118
  const tsPart = tsForFilenameUtc(event.ts);
119
119
  const byPart = safeSlug(event.by);
120
120
  const idPart = safeSlug(event.task_id);
121
- const rand = randomHex(2);
122
- const filename = `${tsPart}_${byPart}_${idPart}_${event.type}_${rand}.json`;
123
- const fullpath = join(execDir, filename);
124
- writeFileSync(fullpath, JSON.stringify(event, null, 2) + "\n", "utf8");
125
- return fullpath;
121
+ const makeRandomHex = dependencies.randomHex ?? randomHex;
122
+ const base = `${tsPart}_${byPart}_${idPart}_${event.type}_${makeRandomHex(4)}`;
123
+ const contents = JSON.stringify(event, null, 2) + "\n";
124
+ for (let sequence = 0;; sequence += 1) {
125
+ const filename = `${base}${sequence === 0 ? "" : `-${sequence}`}.json`;
126
+ const fullpath = join(execDir, filename);
127
+ try {
128
+ // `wx` preserves the append-only event contract even if another writer wins the name.
129
+ writeFileSync(fullpath, contents, { encoding: "utf8", flag: "wx" });
130
+ return fullpath;
131
+ }
132
+ catch (error) {
133
+ if (error.code !== "EEXIST")
134
+ throw error;
135
+ }
136
+ }
126
137
  }
127
138
  export function foldEventsToState(events, schedule, projectPath, initialTasks) {
128
139
  const tasks = initialTasks ? { ...initialTasks } : {};
@@ -17,11 +17,22 @@ export function execDocId(projectId, prefix, localBase) {
17
17
  const localId = `${prefix}-${localBase.toLowerCase()}`;
18
18
  return projectId ? `${projectId}:${localId}` : localId;
19
19
  }
20
- // In-place plan/result share one unique stem (`<slug>-<UTC>-<rand>`) so each run keeps a
21
- // distinct file and id (no doc-index collision) and the result name is derivable from the
22
- // plan. Mirrors the done/ archive naming convention (tsForFilenameUtc + randomHex).
23
- export function buildInPlaceStem(slug) {
24
- return `${slug}-${tsForFilenameUtc(nowUtcIsoSeconds())}-${randomHex(2)}`;
20
+ const issuedInPlaceStems = new Set();
21
+ // In-place plan/result share one unique stem (`<slug>-<UTC>-<rand>[-<sequence>]`) so each
22
+ // run keeps a distinct file and id (no doc-index collision) and the result name is derivable
23
+ // from the plan. The sequence is only used if the random source repeats within this process.
24
+ export function buildInPlaceStem(slug, dependencies = {}) {
25
+ const now = dependencies.now ?? nowUtcIsoSeconds;
26
+ const makeRandomHex = dependencies.randomHex ?? randomHex;
27
+ const base = `${slug}-${tsForFilenameUtc(now())}-${makeRandomHex(4)}`;
28
+ let stem = base;
29
+ let sequence = 1;
30
+ while (issuedInPlaceStems.has(stem)) {
31
+ stem = `${base}-${sequence}`;
32
+ sequence += 1;
33
+ }
34
+ issuedInPlaceStems.add(stem);
35
+ return stem;
25
36
  }
26
37
  // Recover the shared stem from a plan path: `.../exec/plans/<stem>-plan.md` → `<stem>`.
27
38
  // Used when re-running `--plan <path>` so the tied result is overwritten in place.
@@ -5,7 +5,7 @@ import { nowUtcIsoSeconds, randomHex, tsForFilenameUtc } from "./shared.js";
5
5
  import { readSpecdojoNamespace } from "../docs/frontmatter-namespace.js";
6
6
  import { gradeFindingDisplayMessage, gradeResultPathForDocument, readGradeResultForDocument, } from "../shared/grade-result.js";
7
7
  import { lookupDocIndex } from "../docs/doc-index.js";
8
- export function archivePlan(opts) {
8
+ export function archivePlan(opts, dependencies = {}) {
9
9
  const plansDir = join(opts.executionPath, "exec", "plans");
10
10
  const from = join(plansDir, `${opts.slug}-plan.md`);
11
11
  if (!existsSync(from))
@@ -16,8 +16,16 @@ export function archivePlan(opts) {
16
16
  }
17
17
  const doneDir = join(plansDir, "done");
18
18
  mkdirSync(doneDir, { recursive: true });
19
- const stamp = tsForFilenameUtc(nowUtcIsoSeconds());
20
- const to = join(doneDir, `${opts.slug}-${stamp}-${randomHex(2)}-plan.md`);
19
+ const now = dependencies.now ?? nowUtcIsoSeconds;
20
+ const makeRandomHex = dependencies.randomHex ?? randomHex;
21
+ const stamp = tsForFilenameUtc(now());
22
+ const base = `${opts.slug}-${stamp}-${makeRandomHex(4)}`;
23
+ let sequence = 0;
24
+ let to = join(doneDir, `${base}-plan.md`);
25
+ while (existsSync(to)) {
26
+ sequence += 1;
27
+ to = join(doneDir, `${base}-${sequence}-plan.md`);
28
+ }
21
29
  renameSync(from, to);
22
30
  return { from, to, deleted: false };
23
31
  }
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_";
@@ -241,8 +241,9 @@ export function generatePjrId(existingIds, nextCandidate = defaultPjrCandidate,
241
241
  }
242
242
  export function formatTableRow(item) {
243
243
  // frontmatter・本文由来を問わず、表へ展開する全セルを同じ規則で無害化する。
244
- // 列区切りの `|` と改行をエスケープし、山括弧プレースホルダをインラインコード化する。
245
- // 既存コードスパンは変換処理が保持するため、再生成しても二重に囲まれない。
244
+ // 列区切りの `|`、強調記号、改行をエスケープし、山括弧プレースホルダを
245
+ // インラインコード化する。既存コードスパンは変換処理が保持するため、再生成しても
246
+ // 二重に囲まれない。
246
247
  const cells = [
247
248
  item.id,
248
249
  item.status,
@@ -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)) {
@@ -96,16 +96,37 @@ export function displayIdFromTicketFilename(filename) {
96
96
  export function ticketRefCell(filename) {
97
97
  return `[${filename.replace(/\.md$/, "")}](./${filename})`;
98
98
  }
99
- // 表セルへ埋め込むために1行化し、列区切りの `|` をエスケープする。
100
- // すでにエスケープ済みの `\|` は再エスケープせず、複数回の呼び出しに対して冪等にする。
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
+ // 対して冪等にする。
101
121
  export function toCell(text) {
102
122
  if (typeof text !== "string")
103
123
  return "";
104
- return text
124
+ const normalized = text
105
125
  .replace(/\r?\n/g, " ")
106
126
  .replace(/\s+/g, " ")
107
127
  .replace(/(?<!\\)((\\\\)*)\|/g, "$1\\|")
108
128
  .trim();
129
+ return escapeTableCellEmphasis(normalized);
109
130
  }
110
131
  // H1(`# PJR-XXXX タイトル`)からタイトルを導出する。表示 ID の接頭辞は取り除く。
111
132
  export function titleFromBody(body, id) {
@@ -140,10 +161,10 @@ export function descriptionFromBody(body) {
140
161
  }
141
162
  if (paragraph.length === 0)
142
163
  return CELL_TODO;
143
- const text = toCell(paragraph.join(" "));
164
+ const text = paragraph.join(" ");
144
165
  if (text.startsWith(CELL_TODO))
145
166
  return CELL_TODO;
146
- return text;
167
+ return toCell(text);
147
168
  }
148
169
  // ================================
149
170
  // Reading