specdojo 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/catalog-build-references.js +144 -0
  3. package/dist/catalog-build-render.js +144 -0
  4. package/dist/catalog-build.js +13 -290
  5. package/dist/catalog-generate.js +6 -9
  6. package/dist/catalog-plan-generate.js +2 -2
  7. package/dist/catalog-plan.js +6 -6
  8. package/dist/catalog-scaffold.js +4 -4
  9. package/dist/catalog.js +2 -2
  10. package/dist/dashboard-exec-records.js +105 -0
  11. package/dist/dashboard-routines.js +255 -0
  12. package/dist/dashboard-shared.js +14 -0
  13. package/dist/dashboard-timeline.js +175 -0
  14. package/dist/dashboard.js +10 -544
  15. package/dist/deliverable-trash.js +3 -3
  16. package/dist/doc-index.js +3 -3
  17. package/dist/exec-commands.js +557 -0
  18. package/dist/exec-core.js +457 -0
  19. package/dist/exec-plans-core.js +693 -0
  20. package/dist/exec-plans-generation.js +206 -0
  21. package/dist/exec-plans-storage.js +131 -0
  22. package/dist/exec-plans.js +3 -1018
  23. package/dist/exec-repo-integration-git.js +23 -0
  24. package/dist/exec-repo-integration-sync.js +264 -0
  25. package/dist/exec-repo-integration.js +4 -281
  26. package/dist/exec-reporter-output.js +206 -0
  27. package/dist/exec-reporter.js +2 -206
  28. package/dist/exec-results.js +22 -15
  29. package/dist/exec-run-agent-pipeline.js +256 -0
  30. package/dist/exec-run-agent.js +531 -0
  31. package/dist/exec-run-in-place.js +541 -0
  32. package/dist/exec-run-job.js +717 -0
  33. package/dist/exec-run-lifecycle-commands.js +522 -0
  34. package/dist/exec-run-mode-shared.js +140 -0
  35. package/dist/exec-run-register-command.js +244 -0
  36. package/dist/exec-run-register-core.js +386 -0
  37. package/dist/exec-run-register-mode.js +206 -0
  38. package/dist/exec-run-register-resume.js +393 -0
  39. package/dist/exec-run-register-state.js +322 -0
  40. package/dist/exec-run-register-worktree.js +509 -0
  41. package/dist/exec-run-schedule-mode.js +294 -0
  42. package/dist/exec-run-schedule-prepare.js +353 -0
  43. package/dist/exec-run-schedule-task.js +572 -0
  44. package/dist/exec-run-shared.js +399 -0
  45. package/dist/exec-run.js +11 -6182
  46. package/dist/exec-shared.js +2 -2
  47. package/dist/exec-trial-commands.js +558 -0
  48. package/dist/exec-trial-core.js +371 -0
  49. package/dist/exec-trial.js +2 -921
  50. package/dist/exec-worktree-ops-commit.js +707 -0
  51. package/dist/exec-worktree-ops-lifecycle.js +292 -0
  52. package/dist/exec-worktree-ops-merge.js +303 -0
  53. package/dist/exec-worktree-ops.js +3 -1292
  54. package/dist/exec-worktree.js +32 -4
  55. package/dist/exec.js +2 -1006
  56. package/dist/frontmatter-namespace.js +2 -2
  57. package/dist/grade-apply.js +734 -0
  58. package/dist/grade-command-apply.js +250 -0
  59. package/dist/grade-command-inspect.js +138 -0
  60. package/dist/grade-command-plan.js +101 -0
  61. package/dist/grade-command-shared.js +68 -0
  62. package/dist/grade-core.js +307 -0
  63. package/dist/grade-markdown.js +274 -0
  64. package/dist/grade-pipeline-state.js +184 -0
  65. package/dist/grade-plan.js +507 -0
  66. package/dist/grade-result.js +5 -5
  67. package/dist/grade-target-discovery.js +265 -0
  68. package/dist/grade-targets.js +432 -0
  69. package/dist/grade.js +14 -3188
  70. package/dist/init-command.js +7 -7
  71. package/dist/job-definition.js +670 -0
  72. package/dist/job.js +9 -673
  73. package/dist/kata-command.js +2 -2
  74. package/dist/register-command-types.js +1 -0
  75. package/dist/register-core.js +363 -0
  76. package/dist/register-create-commands.js +245 -0
  77. package/dist/register-events.js +4 -4
  78. package/dist/register-item.js +6 -6
  79. package/dist/register-maintenance-commands.js +187 -0
  80. package/dist/register-migration.js +268 -0
  81. package/dist/register-renumber.js +314 -0
  82. package/dist/register-transition-commands.js +248 -0
  83. package/dist/register-update.js +230 -0
  84. package/dist/register-views.js +256 -0
  85. package/dist/register.js +61 -2069
  86. package/dist/review-plan.js +3 -3
  87. package/dist/routine-definition.js +401 -0
  88. package/dist/routine.js +6 -402
  89. package/dist/schedule-approach.js +2 -2
  90. package/dist/schedule-strategy-generate-document.js +273 -0
  91. package/dist/schedule-strategy-generate-scope.js +199 -0
  92. package/dist/schedule-strategy-generate.js +9 -473
  93. package/dist/schedule.js +4 -4
  94. package/dist/specdojo-config.js +3 -4
  95. package/dist/viewpoint-document-kinds-check.js +3 -3
  96. package/dist/yaml-pages.js +4 -4
  97. package/dist/yaml.js +28 -0
  98. package/docs/ja/specdojo/guides/exec-config-guide.md +6 -6
  99. package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +20 -18
  100. package/docs/ja/specdojo/guides/routine-operation-guide.md +1 -1
  101. package/package.json +4 -5
  102. package/templates/antigravity/README.md +3 -3
  103. package/templates/antigravity/exec-defaults-snippet.yaml +6 -4
  104. package/templates/init-exec-defaults.yaml +3 -1
@@ -5,7 +5,7 @@
5
5
  // 表示 ID・タイトル・説明は frontmatter に重複させず、`id` / H1 / 本文から導出する。
6
6
  import { existsSync, readdirSync, readFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
- import yaml from "js-yaml";
8
+ import { dump, load } from "./yaml.js";
9
9
  import { inlineCodeAnglePlaceholders } from "./exec-shared.js";
10
10
  import { registerDateFromTimestamp } from "./register-date.js";
11
11
  export const VALID_STATUSES = [
@@ -148,7 +148,7 @@ export function readRegisterItemContent(content, filename) {
148
148
  if (match) {
149
149
  let parsed;
150
150
  try {
151
- parsed = yaml.load(match[1]);
151
+ parsed = load(match[1]);
152
152
  }
153
153
  catch {
154
154
  parsed = undefined;
@@ -244,7 +244,7 @@ export function validateRegisterItemDocs(projectRegisterPath) {
244
244
  let frontmatterId;
245
245
  if (match) {
246
246
  try {
247
- const parsed = yaml.load(match[1]);
247
+ const parsed = load(match[1]);
248
248
  if (isRecord(parsed) && isRecord(parsed.specdojo)) {
249
249
  frontmatterId = asString(parsed.specdojo.id);
250
250
  }
@@ -323,7 +323,7 @@ export function updateSpecdojoFields(content, mutate) {
323
323
  const fields = { ...parsed.specdojo };
324
324
  mutate(fields);
325
325
  const document = { ...parsed, specdojo: orderSpecdojoKeys(fields) };
326
- const dumped = yaml.dump(document, { lineWidth: -1, noRefs: true, quotingType: '"' });
326
+ const dumped = dump(document, { lineWidth: -1, noRefs: true, quoteStyle: "double" });
327
327
  return `---\n${dumped}---\n${match[2] ?? ""}`;
328
328
  }
329
329
  // 個票 frontmatter の `specdojo:` 名前空間を、イベント検証などの読み取り用途へ返す。
@@ -342,7 +342,7 @@ export function readSpecdojoFields(content) {
342
342
  function parseFrontmatterDocument(frontmatter) {
343
343
  let parsed;
344
344
  try {
345
- parsed = yaml.load(frontmatter);
345
+ parsed = load(frontmatter);
346
346
  }
347
347
  catch (error) {
348
348
  const detail = error instanceof Error ? error.message : String(error);
@@ -376,7 +376,7 @@ export function readRegisterItemLegacyDates(content) {
376
376
  return {};
377
377
  let parsed;
378
378
  try {
379
- parsed = yaml.load(match[1]);
379
+ parsed = load(match[1]);
380
380
  }
381
381
  catch {
382
382
  return {};
@@ -0,0 +1,187 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { collectRegisterHistoryEvents, formatRegisterHistoryEvents } from "./register-history.js";
3
+ import { createGitTimestampResolver, planRegisterTimestampMigration, summarizeTimestampMigration, } from "./register-migrate-timestamps.js";
4
+ import { registerEventFilePath, validateRegisterEventDocs } from "./register-events.js";
5
+ import { validateRegisterItemDocs } from "./register-item.js";
6
+ import { specdojoRootDir } from "./specdojo-config.js";
7
+ export function registerMaintenanceCommands(reg, dependencies) {
8
+ const { addProjectOption, addRegisterCommitOptions, applyRegisterMigrationPlan, generateDerivedViewFiles, loadItemForUpdate, migrateEmbeddedRegisterEvents, migrateRegisterEventsFromGit, parseHistoryIds, planRegisterMigration, planRenumber, printCommandError, registerEventActor, renumberPjrItem, repoRelativePathspec, resolveRegisterPaths, runRegisterMutation, validBuildScopes, writeDerivedViews, } = dependencies;
9
+ // --- migrate ---
10
+ const migrateCmd = reg
11
+ .command("migrate")
12
+ .description("Migrate legacy register data (index rows, dates, and embedded register events)");
13
+ addProjectOption(migrateCmd);
14
+ migrateCmd.option("--dry-run", "Validate and print the migration summary without writing", false);
15
+ migrateCmd.action((opts) => {
16
+ try {
17
+ const paths = resolveRegisterPaths(opts);
18
+ const plan = planRegisterMigration(paths);
19
+ const summary = `items=${plan.sourceCount}, create=${plan.createdCount}, update=${plan.updatedCount}, ` +
20
+ `unchanged=${plan.unchangedCount}`;
21
+ if (opts.dryRun) {
22
+ process.stdout.write(`Would migrate register items: ${summary}\n`);
23
+ if (plan.sourceIndexPath) {
24
+ process.stdout.write(`Would remove legacy index: ${plan.sourceIndexPath}\n`);
25
+ }
26
+ }
27
+ else {
28
+ applyRegisterMigrationPlan(plan);
29
+ process.stdout.write(`Migrated register items: ${summary}\n`);
30
+ if (plan.sourceIndexPath) {
31
+ process.stdout.write(`Removed legacy index: ${plan.sourceIndexPath}\n`);
32
+ }
33
+ }
34
+ const timestampPlan = planRegisterTimestampMigration({
35
+ projectRegisterPath: paths.projectRegisterPath,
36
+ timeZone: paths.registerDateTimeZone,
37
+ resolveGitTimestamps: createGitTimestampResolver(specdojoRootDir()),
38
+ });
39
+ const timestampSummary = summarizeTimestampMigration(timestampPlan);
40
+ if (opts.dryRun) {
41
+ const embeddedMigration = migrateEmbeddedRegisterEvents(paths, true);
42
+ const eventMigration = migrateRegisterEventsFromGit(paths, true);
43
+ const eventSummary = eventMigration.available
44
+ ? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
45
+ : "unavailable (Git history not found; legacy fallback remains active)";
46
+ process.stdout.write(`Would migrate register timestamps: ${timestampSummary}\n`);
47
+ process.stdout.write(`Would separate embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
48
+ process.stdout.write(`Would migrate register events: ${eventSummary}\n`);
49
+ return;
50
+ }
51
+ for (const file of timestampPlan.files) {
52
+ writeFileSync(file.path, file.content, "utf8");
53
+ }
54
+ process.stdout.write(`Migrated register timestamps: ${timestampSummary}\n`);
55
+ const embeddedMigration = migrateEmbeddedRegisterEvents(paths, false);
56
+ process.stdout.write(`Separated embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
57
+ const eventMigration = migrateRegisterEventsFromGit(paths, false);
58
+ const eventSummary = eventMigration.available
59
+ ? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
60
+ : "unavailable (Git history not found; legacy fallback remains active)";
61
+ process.stdout.write(`Migrated register events: ${eventSummary}\n`);
62
+ for (const view of writeDerivedViews(paths, "all")) {
63
+ process.stdout.write(`Generated: ${view.path}\n`);
64
+ }
65
+ }
66
+ catch (error) {
67
+ printCommandError(error);
68
+ }
69
+ });
70
+ // --- build ---
71
+ const buildCmd = reg
72
+ .command("build")
73
+ .description("Generate the register list and derived views from register item files");
74
+ addProjectOption(buildCmd);
75
+ buildCmd.option("--scope <scope>", "Generation scope: register | controls | all", "all");
76
+ buildCmd.option("--dry-run", "Print generated content without writing", false);
77
+ buildCmd.action((opts) => {
78
+ try {
79
+ const paths = resolveRegisterPaths(opts);
80
+ if (!existsSync(paths.projectRegisterPath)) {
81
+ throw new Error(`Project register directory not found: ${paths.projectRegisterPath}\n` +
82
+ `Run: specdojo register scaffold --project ${opts.project || paths.projectId}`);
83
+ }
84
+ const scope = opts.scope;
85
+ if (!validBuildScopes.includes(scope)) {
86
+ throw new Error(`Invalid scope: "${opts.scope}". Must be one of: ${validBuildScopes.join(", ")}`);
87
+ }
88
+ const validation = validateRegisterItemDocs(paths.projectRegisterPath);
89
+ const eventErrors = validateRegisterEventDocs(paths.projectRegisterPath, paths.registerDateTimeZone);
90
+ if (validation.errors.length > 0 || eventErrors.length > 0) {
91
+ throw new Error(`Invalid register item files:\n${[...validation.errors, ...eventErrors].join("\n")}`);
92
+ }
93
+ const views = generateDerivedViewFiles(paths, scope);
94
+ if (opts.dryRun) {
95
+ for (const view of views) {
96
+ process.stdout.write(`=== ${view.path} ===\n${view.content}\n\n`);
97
+ }
98
+ return;
99
+ }
100
+ for (const view of writeDerivedViews(paths, scope)) {
101
+ process.stdout.write(`Generated: ${view.path}\n`);
102
+ }
103
+ }
104
+ catch (error) {
105
+ printCommandError(error);
106
+ }
107
+ });
108
+ // --- history ---
109
+ const historyCmd = reg
110
+ .command("history")
111
+ .description("Show register item changes from append-only events and legacy Git history");
112
+ addProjectOption(historyCmd);
113
+ historyCmd.option("--since <date>", "Include commits on or after this date (YYYY-MM-DD)");
114
+ historyCmd.option("--until <date>", "Include commits on or before this date (YYYY-MM-DD)");
115
+ historyCmd.option("--id <id...>", "Limit output to these item IDs (PJR-XXXX; space/comma separated)");
116
+ historyCmd.option("--status-only", "Show only additions, removals, and status transitions", false);
117
+ historyCmd.option("--limit <count>", "Maximum number of commits to inspect");
118
+ historyCmd.option("--json", "Print events as JSON", false);
119
+ historyCmd.action((opts) => {
120
+ try {
121
+ const paths = resolveRegisterPaths(opts);
122
+ const ids = parseHistoryIds(opts.id);
123
+ const limit = opts.limit === undefined ? undefined : Number(opts.limit);
124
+ const events = collectRegisterHistoryEvents({
125
+ repoRoot: specdojoRootDir(),
126
+ registerPathspec: repoRelativePathspec(specdojoRootDir(), paths.projectRegisterPath),
127
+ since: opts.since?.trim() || undefined,
128
+ until: opts.until?.trim() || undefined,
129
+ limit,
130
+ ids,
131
+ statusOnly: Boolean(opts.statusOnly),
132
+ timeZone: paths.registerDateTimeZone,
133
+ });
134
+ if (opts.json) {
135
+ process.stdout.write(`${JSON.stringify(events, null, 2)}\n`);
136
+ return;
137
+ }
138
+ if (events.length === 0) {
139
+ process.stdout.write("No register item changes found for the given range.\n");
140
+ return;
141
+ }
142
+ process.stdout.write(`${formatRegisterHistoryEvents(events)}\n`);
143
+ const itemCount = new Set(events.map((event) => event.id)).size;
144
+ const gitCommitCount = new Set(events.filter((event) => event.source !== "event").map((event) => event.commit)).size;
145
+ const storedEventCount = events.filter((event) => event.source === "event").length;
146
+ process.stdout.write(`events=${events.length} items=${itemCount} stored=${storedEventCount} legacy_commits=${gitCommitCount}\n`);
147
+ }
148
+ catch (error) {
149
+ printCommandError(error);
150
+ }
151
+ });
152
+ // --- renumber ---
153
+ const renumberCmd = reg
154
+ .command("renumber")
155
+ .description("Resolve a random PJR-ID collision by moving one item to an unused ID");
156
+ addProjectOption(renumberCmd);
157
+ renumberCmd.requiredOption("--id <id>", "Current item ID (PJR-XXXX)");
158
+ renumberCmd.requiredOption("--to <id>", "Target unused ID (PJR-XXXX)");
159
+ renumberCmd.option("--by <actor>", "Actor recorded in the append-only register event");
160
+ renumberCmd.option("--reason <text>", "Reason recorded in the append-only register event");
161
+ renumberCmd.option("--dry-run", "Print planned changes without writing", false);
162
+ addRegisterCommitOptions(renumberCmd);
163
+ renumberCmd.action(async (opts) => {
164
+ await runRegisterMutation("renumber", opts, (context) => {
165
+ const { paths } = context;
166
+ const source = loadItemForUpdate(paths, opts.id);
167
+ const renumberPlan = planRenumber(paths, opts.id, opts.to);
168
+ context.assertCommitTargetsClean([
169
+ ...(renumberPlan.ticketRename
170
+ ? [renumberPlan.ticketRename.from, renumberPlan.ticketRename.to]
171
+ : []),
172
+ ...renumberPlan.writes.map((write) => write.path),
173
+ registerEventFilePath(paths.projectRegisterPath, opts.id),
174
+ registerEventFilePath(paths.projectRegisterPath, opts.to),
175
+ ]);
176
+ renumberPjrItem({
177
+ paths,
178
+ fromId: opts.id,
179
+ toId: opts.to,
180
+ dryRun: opts.dryRun,
181
+ actor: registerEventActor(opts),
182
+ reason: opts.reason,
183
+ });
184
+ return { id: opts.to, title: source.item.title };
185
+ });
186
+ });
187
+ }
@@ -0,0 +1,268 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { basename, dirname, join } from "node:path";
4
+ import { buildRegisterItemContent, locateRegisterTable, parsePjrIndex, slugify, validateFields, } from "./register-core.js";
5
+ import { applyRegisterItemFields, loadRegisterItemDocs, prependRegisterItemDescription, readRegisterItemContent, registerItemFieldsFromItem, setRegisterItemTitle, } from "./register-item.js";
6
+ import { resolveSpecdojoTemplatePath } from "./template-resolution.js";
7
+ import { loadRegisterItems } from "./register-views.js";
8
+ const REGISTER_ITEM_VALUE_KEYS = [
9
+ "id",
10
+ "status",
11
+ "title",
12
+ "description",
13
+ "type",
14
+ "priority",
15
+ "owner",
16
+ "registeredAt",
17
+ "due",
18
+ "completedAt",
19
+ "conclusion",
20
+ ];
21
+ // pjr-index の表セルだけで必要だった pipe のエスケープを本文へ持ち込まない。
22
+ function tableCellToBody(value) {
23
+ return value.replace(/\\\|/g, "|");
24
+ }
25
+ function migrationTopic(title) {
26
+ return slugify(tableCellToBody(title)).slice(0, 64).replace(/-+$/g, "") || "item";
27
+ }
28
+ function assertMigratedItemMatches(source, content, filename) {
29
+ const migrated = readRegisterItemContent(content, filename)?.item;
30
+ if (!migrated) {
31
+ throw new Error(`Failed to read planned register item: ${filename}`);
32
+ }
33
+ const mismatches = REGISTER_ITEM_VALUE_KEYS.filter((key) => migrated[key] !== source[key]);
34
+ if (mismatches.length > 0) {
35
+ const detail = mismatches
36
+ .map((key) => `${key}: ${JSON.stringify(source[key])} -> ${JSON.stringify(migrated[key])}`)
37
+ .join(", ");
38
+ throw new Error(`Migration verification failed for ${source.id}: ${detail}`);
39
+ }
40
+ }
41
+ // 追跡対象の旧 pjr-index と、すでに frontmatter 正本へ移った個票を統合して移行計画を作る。
42
+ // この段階では書き込みを行わず、全件の変換結果が元の項目値と一致してから計画を返す。
43
+ export function planRegisterMigration(paths) {
44
+ const docs = loadRegisterItemDocs(paths.projectRegisterPath);
45
+ const duplicateDocIds = docs
46
+ .map((doc) => doc.id)
47
+ .filter((id, index, ids) => ids.indexOf(id) !== index);
48
+ if (duplicateDocIds.length > 0) {
49
+ throw new Error(`Duplicate register item ticket IDs: ${[...new Set(duplicateDocIds)].join(", ")}`);
50
+ }
51
+ if (!existsSync(paths.pjrIndexPath)) {
52
+ const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
53
+ if (notMigrated.length > 0) {
54
+ throw new Error(`Legacy pjr-index.md is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
55
+ notMigrated.map((doc) => doc.id).join(", "));
56
+ }
57
+ return {
58
+ sourceCount: docs.length,
59
+ createdCount: 0,
60
+ updatedCount: 0,
61
+ unchangedCount: docs.length,
62
+ files: [],
63
+ };
64
+ }
65
+ const sourceIndexContent = readFileSync(paths.pjrIndexPath, "utf8");
66
+ const timeZone = paths.registerDateTimeZone;
67
+ // 旧構成の pjr-index.md が一覧テーブルを持たない参照案内だった場合もある。
68
+ // その案内ページは、旧一覧が存在しない場合と同じ no-op として扱う。
69
+ if (!locateRegisterTable(sourceIndexContent.split("\n"))) {
70
+ const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
71
+ if (notMigrated.length > 0) {
72
+ throw new Error(`Legacy pjr-index table is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
73
+ notMigrated.map((doc) => doc.id).join(", "));
74
+ }
75
+ return {
76
+ sourceCount: docs.length,
77
+ createdCount: 0,
78
+ updatedCount: 0,
79
+ unchangedCount: docs.length,
80
+ files: [],
81
+ };
82
+ }
83
+ const indexItems = parsePjrIndex(sourceIndexContent, timeZone);
84
+ const duplicateIndexIds = indexItems
85
+ .map((item) => item.id)
86
+ .filter((id, index, ids) => ids.indexOf(id) !== index);
87
+ if (duplicateIndexIds.length > 0) {
88
+ throw new Error(`Duplicate pjr-index IDs: ${[...new Set(duplicateIndexIds)].join(", ")}`);
89
+ }
90
+ // loadRegisterItems は移行済み個票を優先し、未移行項目だけ旧一覧を読む。これにより、
91
+ // runner がすでに遷移させた item_status を古い一覧行で巻き戻さない。
92
+ const sources = loadRegisterItems(paths);
93
+ if (sources.length !== indexItems.length) {
94
+ throw new Error(`Register item count mismatch before migration: index=${indexItems.length}, resolved=${sources.length}`);
95
+ }
96
+ const docsById = new Map(docs.map((doc) => [doc.id, doc]));
97
+ const files = [];
98
+ let createdCount = 0;
99
+ let updatedCount = 0;
100
+ let unchangedCount = 0;
101
+ for (const source of sources) {
102
+ validateFields({
103
+ type: source.item.type,
104
+ priority: source.item.priority,
105
+ status: source.item.status,
106
+ registeredAt: source.item.registeredAt,
107
+ due: source.item.due,
108
+ completedAt: source.item.completedAt,
109
+ });
110
+ const existing = docsById.get(source.id);
111
+ let filename;
112
+ let path;
113
+ let originalContent;
114
+ let content;
115
+ if (existing) {
116
+ filename = existing.filename;
117
+ path = existing.path;
118
+ originalContent = readFileSync(path, "utf8");
119
+ content = originalContent;
120
+ if (source.source === "index") {
121
+ if (existing.item.title !== source.item.title) {
122
+ content = setRegisterItemTitle(content, tableCellToBody(source.item.title));
123
+ }
124
+ if (existing.item.description !== source.item.description) {
125
+ content = prependRegisterItemDescription(content, tableCellToBody(source.item.description));
126
+ }
127
+ content = applyRegisterItemFields(content, registerItemFieldsFromItem(source.item));
128
+ }
129
+ }
130
+ else {
131
+ const topic = migrationTopic(source.item.title);
132
+ filename = `pjr-${source.id.slice("PJR-".length).toLowerCase()}-${topic}.md`;
133
+ path = join(paths.projectRegisterPath, filename);
134
+ if (existsSync(path)) {
135
+ throw new Error(`Migration target already exists: ${path}`);
136
+ }
137
+ const templatePath = resolveSpecdojoTemplatePath(`pjr-${source.item.type}-template.md`);
138
+ content = buildRegisterItemContent({
139
+ projectId: paths.projectId,
140
+ displayId: source.item.id,
141
+ topic,
142
+ fields: {
143
+ type: source.item.type,
144
+ title: tableCellToBody(source.item.title),
145
+ description: tableCellToBody(source.item.description),
146
+ priority: source.item.priority,
147
+ status: source.item.status,
148
+ owner: source.item.owner,
149
+ registeredAt: source.item.registeredAt,
150
+ due: source.item.due,
151
+ completedAt: source.item.completedAt,
152
+ conclusion: source.item.conclusion,
153
+ },
154
+ templatePath,
155
+ });
156
+ // 旧一覧のセルでは問題にならなかった `_CAPITAL_CASE_` などを本文へ移すと、
157
+ // markdownlint が underscore emphasis と解釈する。表示値を変えずに規則だけ抑止する。
158
+ if (/_[A-Z][A-Z0-9_]*_/.test(`${source.item.title}\n${source.item.description}`)) {
159
+ content = content.replace(/^(---\r?\n[\s\S]*?\r?\n---\r?\n)/, "$1\n<!-- markdownlint-disable MD049 -->\n");
160
+ }
161
+ }
162
+ assertMigratedItemMatches(source.item, content, filename);
163
+ if (content === originalContent) {
164
+ unchangedCount++;
165
+ }
166
+ else {
167
+ files.push({ path, content, originalContent });
168
+ if (originalContent === undefined)
169
+ createdCount++;
170
+ else
171
+ updatedCount++;
172
+ }
173
+ }
174
+ return {
175
+ sourceCount: sources.length,
176
+ createdCount,
177
+ updatedCount,
178
+ unchangedCount,
179
+ files,
180
+ sourceIndexPath: paths.pjrIndexPath,
181
+ sourceIndexContent,
182
+ };
183
+ }
184
+ // 全出力を同一ディレクトリ内の一時ファイルへ書いてから切り替える。切り替え途中で失敗した
185
+ // 場合は既存ファイルと旧一覧を戻し、作成途中の個票を除去して部分適用を残さない。
186
+ export function applyRegisterMigrationPlan(plan) {
187
+ if (plan.files.length === 0 && !plan.sourceIndexPath)
188
+ return;
189
+ if (plan.sourceIndexPath) {
190
+ if (!existsSync(plan.sourceIndexPath)) {
191
+ throw new Error(`Migration source changed after planning: missing ${plan.sourceIndexPath}`);
192
+ }
193
+ if (readFileSync(plan.sourceIndexPath, "utf8") !== plan.sourceIndexContent) {
194
+ throw new Error(`Migration source changed after planning: ${plan.sourceIndexPath}`);
195
+ }
196
+ }
197
+ for (const file of plan.files) {
198
+ if (file.originalContent === undefined) {
199
+ if (existsSync(file.path)) {
200
+ throw new Error(`Migration target appeared after planning: ${file.path}`);
201
+ }
202
+ }
203
+ else if (!existsSync(file.path) || readFileSync(file.path, "utf8") !== file.originalContent) {
204
+ throw new Error(`Migration target changed after planning: ${file.path}`);
205
+ }
206
+ }
207
+ const transactionId = randomUUID();
208
+ const staged = [];
209
+ let indexBackupPath;
210
+ try {
211
+ for (const file of plan.files) {
212
+ const stagedPath = join(dirname(file.path), `.specdojo-migrate-${transactionId}-${basename(file.path)}`);
213
+ staged.push({ ...file, stagedPath });
214
+ writeFileSync(stagedPath, file.content, { encoding: "utf8", flag: "wx" });
215
+ }
216
+ for (const file of staged) {
217
+ if (file.originalContent !== undefined) {
218
+ file.backupPath = `${file.stagedPath}.backup`;
219
+ renameSync(file.path, file.backupPath);
220
+ }
221
+ renameSync(file.stagedPath, file.path);
222
+ }
223
+ if (plan.sourceIndexPath) {
224
+ indexBackupPath = join(dirname(plan.sourceIndexPath), `.specdojo-migrate-${transactionId}-${basename(plan.sourceIndexPath)}.backup`);
225
+ renameSync(plan.sourceIndexPath, indexBackupPath);
226
+ }
227
+ }
228
+ catch (error) {
229
+ if (indexBackupPath && existsSync(indexBackupPath) && plan.sourceIndexPath) {
230
+ if (existsSync(plan.sourceIndexPath))
231
+ unlinkSync(plan.sourceIndexPath);
232
+ renameSync(indexBackupPath, plan.sourceIndexPath);
233
+ }
234
+ for (const file of [...staged].reverse()) {
235
+ if (existsSync(file.stagedPath))
236
+ unlinkSync(file.stagedPath);
237
+ if (file.backupPath && existsSync(file.backupPath)) {
238
+ if (existsSync(file.path))
239
+ unlinkSync(file.path);
240
+ renameSync(file.backupPath, file.path);
241
+ }
242
+ else if (file.originalContent === undefined && existsSync(file.path)) {
243
+ unlinkSync(file.path);
244
+ }
245
+ }
246
+ throw error;
247
+ }
248
+ // バックアップ除去は切り替え完了後に行う。ここで一時ファイルの除去に失敗しても、
249
+ // 正本の切り替え自体は完了しているため migration を巻き戻さない。
250
+ for (const file of staged) {
251
+ if (file.backupPath && existsSync(file.backupPath)) {
252
+ try {
253
+ unlinkSync(file.backupPath);
254
+ }
255
+ catch {
256
+ // 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
257
+ }
258
+ }
259
+ }
260
+ if (indexBackupPath && existsSync(indexBackupPath)) {
261
+ try {
262
+ unlinkSync(indexBackupPath);
263
+ }
264
+ catch {
265
+ // 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
266
+ }
267
+ }
268
+ }