specdojo 0.2.1 → 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.
- package/.github/agents/specdojo-orchestrator.md +165 -0
- package/CHANGELOG.md +298 -0
- package/README.md +92 -42
- package/dist/agent-response.js +20 -0
- package/dist/agent.js +4 -4
- package/dist/build-command.js +28 -8
- package/dist/catalog-build-references.js +144 -0
- package/dist/catalog-build-render.js +144 -0
- package/dist/catalog-build.js +13 -290
- package/dist/catalog-generate.js +6 -9
- package/dist/catalog-plan-generate.js +2 -2
- package/dist/catalog-plan.js +6 -6
- package/dist/catalog-scaffold.js +4 -4
- package/dist/catalog.js +2 -2
- package/dist/dashboard-exec-records.js +105 -0
- package/dist/dashboard-routines.js +255 -0
- package/dist/dashboard-shared.js +14 -0
- package/dist/dashboard-timeline.js +175 -0
- package/dist/dashboard.js +31 -444
- package/dist/deliverable-trash.js +3 -3
- package/dist/devcontainer-command.js +43 -0
- package/dist/devcontainer-scaffold.js +165 -0
- package/dist/doc-index.js +3 -3
- package/dist/exec-agent-config.js +107 -9
- package/dist/exec-agent-git-state.js +18 -0
- package/dist/exec-agent-protected-config.js +46 -8
- package/dist/exec-commands.js +557 -0
- package/dist/exec-core.js +457 -0
- package/dist/exec-evidence.js +254 -11
- package/dist/exec-handoff.js +336 -0
- package/dist/exec-parent-validation.js +317 -43
- package/dist/exec-pipeline-state.js +74 -9
- package/dist/exec-plans-core.js +693 -0
- package/dist/exec-plans-generation.js +206 -0
- package/dist/exec-plans-storage.js +131 -0
- package/dist/exec-plans.js +3 -1016
- package/dist/exec-protection-handoff.js +43 -2
- package/dist/exec-provider-scaffold.js +247 -15
- package/dist/exec-register-resume.js +65 -19
- package/dist/exec-register.js +9 -3
- package/dist/exec-repo-integration-git.js +23 -0
- package/dist/exec-repo-integration-sync.js +264 -0
- package/dist/exec-repo-integration.js +534 -0
- package/dist/exec-repo-trace.js +182 -0
- package/dist/exec-reporter-output.js +206 -0
- package/dist/exec-reporter.js +525 -248
- package/dist/exec-results.js +103 -71
- package/dist/exec-run-agent-pipeline.js +256 -0
- package/dist/exec-run-agent.js +531 -0
- package/dist/exec-run-in-place.js +541 -0
- package/dist/exec-run-job.js +717 -0
- package/dist/exec-run-lifecycle-commands.js +522 -0
- package/dist/exec-run-lock.js +110 -107
- package/dist/exec-run-mode-shared.js +140 -0
- package/dist/exec-run-register-command.js +244 -0
- package/dist/exec-run-register-core.js +386 -0
- package/dist/exec-run-register-mode.js +206 -0
- package/dist/exec-run-register-resume.js +393 -0
- package/dist/exec-run-register-state.js +322 -0
- package/dist/exec-run-register-worktree.js +509 -0
- package/dist/exec-run-schedule-mode.js +294 -0
- package/dist/exec-run-schedule-prepare.js +353 -0
- package/dist/exec-run-schedule-task.js +572 -0
- package/dist/exec-run-shared.js +399 -0
- package/dist/exec-run.js +11 -4953
- package/dist/exec-shared.js +9 -2
- package/dist/exec-slot-lock.js +242 -0
- package/dist/exec-task-repos.js +415 -0
- package/dist/exec-trial-commands.js +558 -0
- package/dist/exec-trial-core.js +371 -0
- package/dist/exec-trial.js +2 -895
- package/dist/exec-worktree-command.js +87 -43
- package/dist/exec-worktree-ops-commit.js +707 -0
- package/dist/exec-worktree-ops-lifecycle.js +292 -0
- package/dist/exec-worktree-ops-merge.js +303 -0
- package/dist/exec-worktree-ops.js +3 -847
- package/dist/exec-worktree.js +146 -31
- package/dist/exec.js +2 -999
- package/dist/frontmatter-namespace.js +2 -2
- package/dist/grade-apply.js +734 -0
- package/dist/grade-command-apply.js +250 -0
- package/dist/grade-command-inspect.js +138 -0
- package/dist/grade-command-plan.js +101 -0
- package/dist/grade-command-shared.js +68 -0
- package/dist/grade-core.js +307 -0
- package/dist/grade-markdown.js +274 -0
- package/dist/grade-pipeline-state.js +184 -0
- package/dist/grade-plan.js +507 -0
- package/dist/grade-result.js +133 -5
- package/dist/grade-target-discovery.js +265 -0
- package/dist/grade-targets.js +432 -0
- package/dist/grade.js +14 -2451
- package/dist/init-command.js +443 -0
- package/dist/job-definition.js +670 -0
- package/dist/job.js +64 -578
- package/dist/kata-command.js +2 -2
- package/dist/orchestrator.js +213 -0
- package/dist/register-command-types.js +1 -0
- package/dist/register-core.js +363 -0
- package/dist/register-create-commands.js +245 -0
- package/dist/register-event-merge.js +169 -0
- package/dist/register-events.js +4 -4
- package/dist/register-item.js +13 -7
- package/dist/register-maintenance-commands.js +187 -0
- package/dist/register-migration.js +268 -0
- package/dist/register-renumber.js +314 -0
- package/dist/register-transition-commands.js +248 -0
- package/dist/register-update.js +230 -0
- package/dist/register-views.js +256 -0
- package/dist/register.js +175 -1975
- package/dist/review-grade.js +252 -0
- package/dist/review-plan.js +114 -4
- package/dist/review-types.js +40 -1
- package/dist/routine-definition.js +401 -0
- package/dist/routine.js +73 -402
- package/dist/schedule-approach.js +2 -2
- package/dist/schedule-build.js +2 -2
- package/dist/schedule-strategy-generate-document.js +273 -0
- package/dist/schedule-strategy-generate-scope.js +199 -0
- package/dist/schedule-strategy-generate.js +9 -473
- package/dist/schedule.js +19 -6
- package/dist/specdojo-config.js +465 -20
- package/dist/specdojo-gitignore.js +135 -0
- package/dist/specdojo.js +6 -0
- package/dist/viewpoint-document-kinds-check.js +128 -0
- package/dist/yaml-pages.js +4 -4
- package/dist/yaml.js +28 -0
- package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +348 -90
- package/docs/ja/specdojo/exec-templates/xep-common-conventions-template.md +51 -17
- package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +7 -5
- package/docs/ja/specdojo/exec-templates/xrp-freeform-template.md +29 -31
- package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +34 -55
- package/docs/ja/specdojo/exec-templates/xrp-job-template.md +54 -0
- package/docs/ja/specdojo/exec-templates/xrp-recipe-guided-template.md +28 -37
- package/docs/ja/specdojo/exec-templates/xrp-recipe-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-retrofit-template.md +30 -30
- package/docs/ja/specdojo/exec-templates/xrp-rulebook-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-sample-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template-maintenance-template.md +29 -34
- package/docs/ja/specdojo/exec-templates/xrp-template.md +29 -28
- package/docs/ja/specdojo/exec-templates/xrr-template.md +11 -9
- package/docs/ja/specdojo/guides/docs-editing-guide.md +20 -0
- package/docs/ja/specdojo/guides/docs-structure-guide.md +103 -70
- package/docs/ja/specdojo/guides/exec-config-guide.md +93 -49
- package/docs/ja/specdojo/guides/exec-operation-guide.md +124 -27
- package/docs/ja/specdojo/guides/exec-worktree-guide.md +40 -11
- package/docs/ja/specdojo/guides/kata-guide.md +4 -4
- package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +45 -22
- package/docs/ja/specdojo/guides/plan-result-lifecycle-guide.md +1 -1
- package/docs/ja/specdojo/guides/practice-system-composition-guide.md +13 -13
- package/docs/ja/specdojo/guides/quick-start-guide.md +260 -30
- package/docs/ja/specdojo/guides/register-operation-guide.md +31 -14
- package/docs/ja/specdojo/guides/release-v0-3-0-migration-guide.md +264 -0
- package/docs/ja/specdojo/guides/remote-host-development-guide.md +22 -1
- package/docs/ja/specdojo/guides/review-guide.md +195 -158
- package/docs/ja/specdojo/guides/routine-operation-guide.md +75 -10
- package/docs/ja/specdojo/guides/ryu-guide.md +32 -30
- package/docs/ja/specdojo/guides/schedule-design-guide.md +10 -10
- package/docs/ja/specdojo/guides/schedule-operation-guide.md +1 -1
- package/docs/ja/specdojo/guides/specdojo-overview-guide.md +58 -33
- package/docs/ja/specdojo/guides/use-case-guide.md +3 -3
- package/docs/ja/specdojo/guides/waza-guide.md +15 -2
- package/docs/ja/specdojo/index.md +2 -2
- package/docs/ja/specdojo/philosophy/specdojo-philosophy.md +5 -5
- package/docs/ja/specdojo/recipes/bps-recipe.md +213 -0
- package/docs/ja/specdojo/recipes/pm-members-recipe.md +52 -117
- package/docs/ja/specdojo/references/command-reference.md +335 -92
- package/docs/ja/specdojo/references/deliverables-reference.md +1 -1
- package/docs/ja/specdojo/references/directory-layout-reference.md +13 -9
- package/docs/ja/specdojo/references/specdojo-config-reference.md +107 -24
- package/docs/ja/specdojo/rulebooks/bps-rulebook.md +132 -220
- package/docs/ja/specdojo/rulebooks/br-rulebook.md +6 -44
- package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +2 -0
- package/docs/ja/specdojo/rulebooks/dmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/gl-rulebook.md +61 -39
- package/docs/ja/specdojo/rulebooks/ifx-cmd-rulebook.md +0 -87
- package/docs/ja/specdojo/rulebooks/ifx-index-rulebook.md +1 -33
- package/docs/ja/specdojo/rulebooks/opd-rulebook.md +0 -137
- package/docs/ja/specdojo/rulebooks/opr-rulebook.md +0 -247
- package/docs/ja/specdojo/rulebooks/otp-rulebook.md +0 -83
- package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -2
- package/docs/ja/specdojo/rulebooks/pm-members-rulebook.md +78 -150
- package/docs/ja/specdojo/rulebooks/pm-roles-rulebook.md +5 -4
- package/docs/ja/specdojo/rulebooks/sch-rulebook.md +1 -1
- package/docs/ja/specdojo/rulebooks/stsd-mermaid-rulebook.md +0 -11
- package/docs/ja/specdojo/rulebooks/stsd-rulebook.md +0 -61
- package/docs/ja/specdojo/rulebooks/tml-rulebook.md +2 -47
- package/docs/ja/specdojo/samples/bps-sample.md +74 -21
- package/docs/ja/specdojo/samples/gl-sample.yaml +17 -1
- package/docs/ja/specdojo/samples/ifx-index-sample.yaml +28 -0
- package/docs/ja/specdojo/samples/pm-members-sample.yaml +2 -67
- package/docs/ja/specdojo/samples/pm-organization-sample.md +8 -7
- package/docs/ja/specdojo/samples/pm-raci-sample.md +1 -1
- package/docs/ja/specdojo/samples/tml-sample.yaml +40 -0
- package/docs/ja/specdojo/standards/document-metadata-standard.md +21 -16
- package/docs/ja/specdojo/standards/id-and-file-naming-standard.md +14 -14
- package/docs/ja/specdojo/standards/job-definition-standard.md +37 -17
- package/docs/ja/specdojo/standards/people-and-organization-definition-standard.md +37 -32
- package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -1
- package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +21 -11
- package/docs/ja/specdojo/templates/agent-members-template.yaml +25 -0
- package/docs/ja/specdojo/templates/bps-template.md +91 -0
- package/docs/ja/specdojo/templates/pm-members-template.yaml +2 -59
- package/docs/specdojo/schemas/v1/agent-members.schema.yaml +76 -0
- package/docs/specdojo/schemas/v1/exec-common.schema.yaml +4 -2
- package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +55 -2
- package/docs/specdojo/schemas/v1/exec-evidence.schema.yaml +93 -6
- package/docs/specdojo/schemas/v1/exec-reporter-output.schema.yaml +27 -78
- package/docs/specdojo/schemas/v1/gl.schema.yaml +87 -0
- package/docs/specdojo/schemas/v1/grade-result.schema.yaml +33 -0
- package/docs/specdojo/schemas/v1/job-run.schema.yaml +27 -0
- package/docs/specdojo/schemas/v1/job.schema.yaml +25 -0
- package/docs/specdojo/schemas/v1/pipeline-state.schema.yaml +49 -1
- package/docs/specdojo/schemas/v1/pm-members.schema.yaml +9 -169
- package/docs/specdojo/schemas/v1/pm-review-viewpoints.schema.yaml +100 -10
- package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +13 -0
- package/docs/specdojo/schemas/v1/routine-run.schema.yaml +3 -0
- package/docs/specdojo/schemas/v1/routine.schema.yaml +7 -0
- package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +110 -0
- package/package.json +17 -12
- package/templates/antigravity/README.md +29 -4
- package/templates/antigravity/{pm-members-snippet.yaml → agent-members-snippet.yaml} +8 -2
- package/templates/antigravity/exec-defaults-snippet.yaml +10 -7
- package/templates/antigravity/orchestrator.md +18 -7
- package/templates/antigravity/settings.global.json +55 -0
- package/templates/claude/agents/claude-executor.md +14 -0
- package/templates/claude/agents/claude-reporter.md +16 -0
- package/templates/claude/agents/specdojo-orchestrator.md +18 -7
- package/templates/claude/settings.edit.json +27 -1
- package/templates/codex/README.md +5 -4
- package/templates/codex/agents/specdojo-orchestrator.toml +18 -7
- package/templates/codex/orchestrator.md +18 -7
- package/templates/copilot/README.md +7 -5
- package/templates/copilot/{pm-members-snippet.yaml → agent-members-snippet.yaml} +4 -2
- package/templates/devcontainer/devcontainer.json +27 -0
- package/templates/devcontainer/emacs/init.el +88 -0
- package/templates/devcontainer/post-create.sh +62 -0
- package/templates/init-agent-members.yaml +200 -0
- package/templates/init-exec-defaults.yaml +74 -0
- package/templates/opencode/agents/specdojo-orchestrator.md +18 -7
- package/docs/ja/specdojo/exec-templates/xrp-viewpoint-detail-template.md +0 -7
- package/docs/ja/specdojo/exec-templates/xrr-viewpoint-detail-template.md +0 -7
package/dist/register.js
CHANGED
|
@@ -1,1359 +1,29 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import
|
|
5
|
-
import { getProjectRegisterPath, loadConfig, loadEnv, specdojoRootDir } from "./specdojo-config.js";
|
|
6
|
-
import { normalizeRegisterTimestamp, nowUtcTimestamp, REGISTER_TIMESTAMP_RE, resolveRegisterDateTimeZone, timestampFromDateInTimeZone, } from "./register-date.js";
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { relative, sep } from "node:path";
|
|
3
|
+
import { execLifecyclePoolPath } from "./exec-run-lock.js";
|
|
4
|
+
import { CrossProcessMutex } from "./exec-slot-lock.js";
|
|
7
5
|
import { inlineCodeAnglePlaceholders } from "./exec-shared.js";
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import { appendRegisterEvent,
|
|
14
|
-
import {
|
|
15
|
-
|
|
16
|
-
|
|
6
|
+
import { repoRelative, stageCommitTargets, worktreeStatusPaths } from "./exec-worktree-ops.js";
|
|
7
|
+
import { gitOutput, gitResult } from "./exec-worktree.js";
|
|
8
|
+
import { atomicWriteFile, buildRegisterItemContent, derivedTopicNeedsWarning, generatePjrId, printDerivedTopicWarning, registerEventActor, REGISTER_TOPIC_RE, resolveRegisterPaths, slugify, validateFields, } from "./register-core.js";
|
|
9
|
+
import { registerCreateCommands, registerUpdateCommand } from "./register-create-commands.js";
|
|
10
|
+
import { normalizeRegisterTimestamp } from "./register-date.js";
|
|
11
|
+
import { appendRegisterEvent, deterministicRegisterEventId, readEmbeddedRegisterEvents, readRegisterEventsFromContent, registerEventFilePath, removeEmbeddedRegisterEvents, serializeRegisterEvents, validateRegisterEventDocs, } from "./register-events.js";
|
|
12
|
+
import { collectRegisterHistoryEvents } from "./register-history.js";
|
|
13
|
+
import { loadRegisterItemDocs, PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, validateRegisterItemDocs, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, } from "./register-item.js";
|
|
14
|
+
import { registerMaintenanceCommands } from "./register-maintenance-commands.js";
|
|
15
|
+
import { applyRegisterMigrationPlan, planRegisterMigration } from "./register-migration.js";
|
|
16
|
+
import { planRenumber, planRetopic, renumberPjrItem, retopicPjrItem, ticketTopicFromFilename, } from "./register-renumber.js";
|
|
17
|
+
import { registerTransitionCommands } from "./register-transition-commands.js";
|
|
18
|
+
import { applyItemUpdate, assertTerminalOperationAllowed, loadItemForUpdate, updateTicketStatusForItem, } from "./register-update.js";
|
|
19
|
+
import { generateDerivedViewFiles, loadRegisterItems, VALID_BUILD_SCOPES, writeDerivedViews, } from "./register-views.js";
|
|
20
|
+
import { specdojoRootDir } from "./specdojo-config.js";
|
|
17
21
|
export { PJR_ID_ALPHABET, PJR_ID_RE, TERMINAL_STATUSES_SET, VALID_PRIORITIES, VALID_STATUSES, VALID_TYPES, };
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
const temporary = join(dirname(path), `.${basename(path)}.${randomUUID()}.tmp`);
|
|
24
|
-
try {
|
|
25
|
-
writeFileSync(temporary, content, { encoding: "utf8", flag: "wx" });
|
|
26
|
-
renameSync(temporary, path);
|
|
27
|
-
}
|
|
28
|
-
finally {
|
|
29
|
-
if (existsSync(temporary))
|
|
30
|
-
unlinkSync(temporary);
|
|
31
|
-
}
|
|
32
|
-
}
|
|
33
|
-
function prepareRegisterEventFile(projectRegisterPath, displayId, event) {
|
|
34
|
-
const eventPath = registerEventFilePath(projectRegisterPath, displayId);
|
|
35
|
-
const content = existsSync(eventPath) ? readFileSync(eventPath, "utf8") : undefined;
|
|
36
|
-
return { path: eventPath, content: appendRegisterEvent(content, event) };
|
|
37
|
-
}
|
|
38
|
-
// ================================
|
|
39
|
-
// Constants
|
|
40
|
-
// ================================
|
|
41
|
-
// PJR-ID の乱数部分の桁数。
|
|
42
|
-
const PJR_ID_LENGTH = 4;
|
|
43
|
-
// 個票ファイル名・文書 ID の論点部分。先頭・末尾や連続ハイフンを許さない。
|
|
44
|
-
export const REGISTER_TOPIC_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
|
45
|
-
// 生成した ID が偶然含みうる不適切語の簡易ブロックリスト(4 文字, 大文字, 曖昧文字除外後)。
|
|
46
|
-
// 一致した候補は採用せず再抽選する。曖昧文字(I/L/O/U)を含む語は生成されえないため載せない。
|
|
47
|
-
const PJR_ID_BLOCKLIST = new Set(["CRAP", "DAMN", "TWAT", "WANK", "SHAG", "FART"]);
|
|
48
|
-
// 個票 Frontmatter の文書成熟度(specdojo:pjr-rulebook「個票 status の遷移基準」)。
|
|
49
|
-
// pjr-index の処理状態(VALID_STATUSES)とは別の状態軸として扱う。
|
|
50
|
-
export const VALID_TICKET_STATUSES = ["draft", "ready", "deprecated"];
|
|
51
|
-
// 登録項目一覧テーブルは specdojo:pjr-rulebook「本文構成」で章 1 に固定される。
|
|
52
|
-
// 見出し文言(言語依存)ではなく章番号でセクションを特定し、i18n 非依存にする。
|
|
53
|
-
const REGISTER_SECTION_RE = /^## 1\.\s/;
|
|
54
|
-
// 登録項目一覧(pjr-index)の生成 template。外枠(H1・注記・章見出し)と章 1 の
|
|
55
|
-
// 列見出しを所有し、生成処理は行だけを差し込む。列名を定数として持たないことで、
|
|
56
|
-
// 一覧の言語は template 側の差し替えだけで切り替えられる。
|
|
57
|
-
const REGISTER_INDEX_TEMPLATE = "pjr-index-template.md";
|
|
58
|
-
// ================================
|
|
59
|
-
// Path Resolution
|
|
60
|
-
// ================================
|
|
61
|
-
export function resolveRegisterPaths(opts) {
|
|
62
|
-
loadEnv();
|
|
63
|
-
const { config, configPath } = loadConfig();
|
|
64
|
-
const baseDir = specdojoRootDir();
|
|
65
|
-
const projectId = opts.project?.trim() ||
|
|
66
|
-
process.env.SPECDOJO_PROJECT?.trim() ||
|
|
67
|
-
(config ? Object.keys(config.projects)[0] : "");
|
|
68
|
-
if (!config) {
|
|
69
|
-
throw new Error(`register commands require specdojo.config.json.\nRun: specdojo config init`);
|
|
70
|
-
}
|
|
71
|
-
if (!projectId) {
|
|
72
|
-
throw new Error(`No project specified. Use --project <id> or SPECDOJO_PROJECT.`);
|
|
73
|
-
}
|
|
74
|
-
const project = config.projects[projectId];
|
|
75
|
-
if (!project) {
|
|
76
|
-
throw new Error(`Unknown project: ${projectId} (check ${configPath})`);
|
|
77
|
-
}
|
|
78
|
-
const registerPath = getProjectRegisterPath(project);
|
|
79
|
-
if (!registerPath) {
|
|
80
|
-
throw new Error(`project_register_path not set for project '${projectId}' in ${configPath}.\n` +
|
|
81
|
-
`Add "project_register_path": "<path>" to the project config.`);
|
|
82
|
-
}
|
|
83
|
-
const absRegisterPath = resolve(baseDir, registerPath);
|
|
84
|
-
return {
|
|
85
|
-
projectId,
|
|
86
|
-
projectRegisterPath: absRegisterPath,
|
|
87
|
-
pjrIndexPath: join(absRegisterPath, "pjr-index.md"),
|
|
88
|
-
generatedPath: join(absRegisterPath, "generated"),
|
|
89
|
-
controlsGeneratedPath: join(dirname(absRegisterPath), "generated"),
|
|
90
|
-
registerDateTimeZone: resolveRegisterDateTimeZone(config, projectId),
|
|
91
|
-
};
|
|
92
|
-
}
|
|
93
|
-
// ================================
|
|
94
|
-
// Markdown Table Parsing
|
|
95
|
-
// ================================
|
|
96
|
-
function parseTableCells(line) {
|
|
97
|
-
// Replace escaped pipes with placeholder before splitting
|
|
98
|
-
const PIPE = "\x01";
|
|
99
|
-
const normalized = line.replace(/\\\|/g, PIPE);
|
|
100
|
-
const cells = normalized.split("|").map((c) => c.replace(new RegExp(PIPE, "g"), "\\|").trim());
|
|
101
|
-
// Remove first and last empty elements (line starts and ends with |)
|
|
102
|
-
return cells.slice(1, cells.length - 1);
|
|
103
|
-
}
|
|
104
|
-
function isTableSeparator(line) {
|
|
105
|
-
return line.startsWith("|") && /\|\s*---+\s*\|/.test(line);
|
|
106
|
-
}
|
|
107
|
-
function locateRegisterTable(lines) {
|
|
108
|
-
let inSection = false;
|
|
109
|
-
let header;
|
|
110
|
-
for (let index = 0; index < lines.length; index++) {
|
|
111
|
-
const line = lines[index];
|
|
112
|
-
if (REGISTER_SECTION_RE.test(line)) {
|
|
113
|
-
inSection = true;
|
|
114
|
-
continue;
|
|
115
|
-
}
|
|
116
|
-
if (inSection && /^## /.test(line))
|
|
117
|
-
break;
|
|
118
|
-
if (!inSection || !line.startsWith("|"))
|
|
119
|
-
continue;
|
|
120
|
-
if (isTableSeparator(line)) {
|
|
121
|
-
if (header === undefined) {
|
|
122
|
-
throw new Error("Register table header row not found before the separator in the register list source");
|
|
123
|
-
}
|
|
124
|
-
return {
|
|
125
|
-
heading: { header: header.trim(), separator: line.trim() },
|
|
126
|
-
separatorIndex: index,
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
if (header === undefined)
|
|
130
|
-
header = line;
|
|
131
|
-
}
|
|
132
|
-
return undefined;
|
|
133
|
-
}
|
|
134
|
-
export function extractTableHeading(content) {
|
|
135
|
-
const located = locateRegisterTable(content.split("\n"));
|
|
136
|
-
if (!located) {
|
|
137
|
-
throw new Error("Register table header row not found in the register list source");
|
|
138
|
-
}
|
|
139
|
-
return located.heading;
|
|
140
|
-
}
|
|
141
|
-
// 章 1 の登録項目一覧テーブルの区切り行直後へ、生成した行を差し込む。
|
|
142
|
-
// テーブルの列見出しは template が所有するため、生成処理は行だけを注入する。
|
|
143
|
-
export function injectRegisterRows(content, rows) {
|
|
144
|
-
const lines = content.split("\n");
|
|
145
|
-
const located = locateRegisterTable(lines);
|
|
146
|
-
if (!located) {
|
|
147
|
-
throw new Error(`Register table not found in template: ${REGISTER_INDEX_TEMPLATE}`);
|
|
148
|
-
}
|
|
149
|
-
lines.splice(located.separatorIndex + 1, 0, ...rows);
|
|
150
|
-
return lines.join("\n");
|
|
151
|
-
}
|
|
152
|
-
// 旧一覧(追跡対象だった頃の pjr-index.md)の表を読む互換経路。日付セルは暦日しか持たない
|
|
153
|
-
// ため、移行と同じ規則でプロジェクトタイムゾーンの 21:00 を補って日時へ変換する。
|
|
154
|
-
export function parsePjrIndex(content, timeZone) {
|
|
155
|
-
const lines = content.split("\n");
|
|
156
|
-
const items = [];
|
|
157
|
-
let inSection = false;
|
|
158
|
-
const toTimestamp = (cell) => isPlaceholderCell(cell) ? cell.trim() : timestampFromDateInTimeZone(cell.trim(), timeZone);
|
|
159
|
-
for (const line of lines) {
|
|
160
|
-
if (REGISTER_SECTION_RE.test(line)) {
|
|
161
|
-
inSection = true;
|
|
162
|
-
continue;
|
|
163
|
-
}
|
|
164
|
-
if (inSection && /^## /.test(line))
|
|
165
|
-
break;
|
|
166
|
-
if (!inSection)
|
|
167
|
-
continue;
|
|
168
|
-
if (!line.startsWith("|") || isTableSeparator(line))
|
|
169
|
-
continue;
|
|
170
|
-
const cells = parseTableCells(line);
|
|
171
|
-
if (cells.length < 12)
|
|
172
|
-
continue;
|
|
173
|
-
if (!PJR_ID_RE.test(cells[0]))
|
|
174
|
-
continue;
|
|
175
|
-
items.push({
|
|
176
|
-
id: cells[0],
|
|
177
|
-
status: cells[1],
|
|
178
|
-
title: cells[2],
|
|
179
|
-
description: cells[3],
|
|
180
|
-
type: cells[4],
|
|
181
|
-
priority: cells[5],
|
|
182
|
-
owner: cells[6],
|
|
183
|
-
registeredAt: toTimestamp(cells[7]),
|
|
184
|
-
due: cells[8],
|
|
185
|
-
completedAt: toTimestamp(cells[9]),
|
|
186
|
-
conclusion: cells[10],
|
|
187
|
-
ticket: cells[11],
|
|
188
|
-
});
|
|
189
|
-
}
|
|
190
|
-
return items;
|
|
191
|
-
}
|
|
192
|
-
// 32 文字セットから一様乱択した 4 文字を持つ PJR-ID 候補を 1 件生成する。
|
|
193
|
-
function defaultPjrCandidate() {
|
|
194
|
-
let suffix = "";
|
|
195
|
-
for (let i = 0; i < PJR_ID_LENGTH; i++) {
|
|
196
|
-
suffix += PJR_ID_ALPHABET[randomInt(0, PJR_ID_ALPHABET.length)];
|
|
197
|
-
}
|
|
198
|
-
return `PJR-${suffix}`;
|
|
199
|
-
}
|
|
200
|
-
// 既存 ID・不適切語ブロックリストと衝突しない PJR-ID をランダムに採番する。
|
|
201
|
-
// 生成候補が既存 ID かブロックリストに一致した場合は再抽選する。nextCandidate は
|
|
202
|
-
// テストで抽選列を差し込むための注入点で、既定は 32 文字セットからの一様乱択。
|
|
203
|
-
export function generatePjrId(existingIds, nextCandidate = defaultPjrCandidate, maxAttempts = 256) {
|
|
204
|
-
const existing = new Set(existingIds);
|
|
205
|
-
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
206
|
-
const id = nextCandidate();
|
|
207
|
-
if (!PJR_ID_RE.test(id))
|
|
208
|
-
continue;
|
|
209
|
-
if (existing.has(id))
|
|
210
|
-
continue;
|
|
211
|
-
if (PJR_ID_BLOCKLIST.has(id.slice("PJR-".length)))
|
|
212
|
-
continue;
|
|
213
|
-
return id;
|
|
214
|
-
}
|
|
215
|
-
throw new Error(`Failed to generate an unused PJR-ID after ${maxAttempts} attempts`);
|
|
216
|
-
}
|
|
217
|
-
function formatTableRow(item) {
|
|
218
|
-
// frontmatter・本文由来を問わず、表へ展開する全セルを同じ規則で無害化する。
|
|
219
|
-
// 既存コードスパンは変換処理が保持するため、再生成しても二重に囲まれない。
|
|
220
|
-
const cells = [
|
|
221
|
-
item.id,
|
|
222
|
-
item.status,
|
|
223
|
-
item.title,
|
|
224
|
-
item.description,
|
|
225
|
-
item.type,
|
|
226
|
-
item.priority,
|
|
227
|
-
item.owner,
|
|
228
|
-
item.registered,
|
|
229
|
-
item.due,
|
|
230
|
-
item.completed,
|
|
231
|
-
item.conclusion,
|
|
232
|
-
item.ticket,
|
|
233
|
-
].map(inlineCodeAnglePlaceholders);
|
|
234
|
-
return `| ${cells.join(" | ")} |`;
|
|
235
|
-
}
|
|
236
|
-
// ================================
|
|
237
|
-
// Validation
|
|
238
|
-
// ================================
|
|
239
|
-
function validateFields(opts) {
|
|
240
|
-
const errors = [];
|
|
241
|
-
if (!VALID_STATUSES.includes(opts.status)) {
|
|
242
|
-
errors.push(`Invalid status: "${opts.status}". Must be one of: ${VALID_STATUSES.join(", ")}`);
|
|
243
|
-
}
|
|
244
|
-
if (!VALID_TYPES.includes(opts.type)) {
|
|
245
|
-
errors.push(`Invalid type: "${opts.type}". Must be one of: ${VALID_TYPES.join(", ")}`);
|
|
246
|
-
}
|
|
247
|
-
if (!VALID_PRIORITIES.includes(opts.priority)) {
|
|
248
|
-
errors.push(`Invalid priority: "${opts.priority}". Must be one of: ${VALID_PRIORITIES.join(", ")}`);
|
|
249
|
-
}
|
|
250
|
-
if (opts.id && !PJR_ID_RE.test(opts.id)) {
|
|
251
|
-
errors.push(`Invalid ID: "${opts.id}". Must match PJR-XXXX (e.g., PJR-0001)`);
|
|
252
|
-
}
|
|
253
|
-
if (opts.registeredAt !== CELL_TODO && !REGISTER_TIMESTAMP_RE.test(opts.registeredAt)) {
|
|
254
|
-
errors.push(`Invalid registered: "${opts.registeredAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or _TODO_`);
|
|
255
|
-
}
|
|
256
|
-
if (!/^(\d{4}-\d{2}-\d{2}|-|_TODO_)$/.test(opts.due)) {
|
|
257
|
-
errors.push(`Invalid due: "${opts.due}". Must be YYYY-MM-DD, -, or _TODO_`);
|
|
258
|
-
}
|
|
259
|
-
if (opts.completedAt !== CELL_NONE && !REGISTER_TIMESTAMP_RE.test(opts.completedAt)) {
|
|
260
|
-
errors.push(`Invalid completed: "${opts.completedAt}". Must be an RFC 3339 UTC date-time (YYYY-MM-DDTHH:MM:SSZ) or -`);
|
|
261
|
-
}
|
|
262
|
-
if (errors.length > 0) {
|
|
263
|
-
throw new Error(errors.join("\n"));
|
|
264
|
-
}
|
|
265
|
-
}
|
|
266
|
-
// ================================
|
|
267
|
-
// Slug
|
|
268
|
-
// ================================
|
|
269
|
-
function slugify(text) {
|
|
270
|
-
return (text
|
|
271
|
-
.toLowerCase()
|
|
272
|
-
.replace(/[^a-z0-9\s-]/g, " ")
|
|
273
|
-
.trim()
|
|
274
|
-
.replace(/[\s_]+/g, "-")
|
|
275
|
-
.replace(/-+/g, "-")
|
|
276
|
-
.replace(/^-|-$/g, "") || "item");
|
|
277
|
-
}
|
|
278
|
-
// ================================
|
|
279
|
-
// Ticket Generation
|
|
280
|
-
// ================================
|
|
281
|
-
function getTitlePlaceholder(type) {
|
|
282
|
-
return `_${type.toUpperCase().replace(/-/g, "_")}_TITLE_`;
|
|
283
|
-
}
|
|
284
|
-
function generateTicket(opts) {
|
|
285
|
-
if (!existsSync(opts.templatePath)) {
|
|
286
|
-
throw new Error(`Template not found: ${opts.templatePath}`);
|
|
287
|
-
}
|
|
288
|
-
let content = readFileSync(opts.templatePath, "utf8");
|
|
289
|
-
content = flattenTemplateFrontmatter(content);
|
|
290
|
-
const pjrLower = opts.displayId.toLowerCase();
|
|
291
|
-
// Keep the canonical document ID aligned with the ticket filename.
|
|
292
|
-
content = content.replace(/_PJR_DOCUMENT_ID_/g, `${opts.projectId}:${pjrLower}-${opts.topic}`);
|
|
293
|
-
// Replace remaining project id placeholder
|
|
294
|
-
content = content.replace(/_PROJECT_ID_/g, opts.projectId);
|
|
295
|
-
// Replace display id placeholder with uppercase
|
|
296
|
-
content = content.replace(/_PJR-XXXX_/g, opts.displayId);
|
|
297
|
-
// Replace type-specific title placeholder
|
|
298
|
-
const titlePh = getTitlePlaceholder(opts.type);
|
|
299
|
-
content = content.replace(new RegExp(titlePh.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "g"), opts.title);
|
|
300
|
-
return content;
|
|
301
|
-
}
|
|
302
|
-
// 個票の完成形(テンプレート展開 + 説明の反映 + 登録項目 frontmatter)を組み立てる。
|
|
303
|
-
// 登録項目の構造化フィールドは frontmatter、タイトルは H1、説明は概要段落が正本になる。
|
|
304
|
-
export function buildRegisterItemContent(opts) {
|
|
305
|
-
let content = generateTicket({
|
|
306
|
-
projectId: opts.projectId,
|
|
307
|
-
displayId: opts.displayId,
|
|
308
|
-
topic: opts.topic,
|
|
309
|
-
type: opts.fields.type,
|
|
310
|
-
title: opts.fields.title,
|
|
311
|
-
templatePath: opts.templatePath,
|
|
312
|
-
});
|
|
313
|
-
if (!isPlaceholderCell(opts.fields.description)) {
|
|
314
|
-
content = setRegisterItemDescription(content, opts.fields.description);
|
|
315
|
-
}
|
|
316
|
-
return applyRegisterItemFields(content, registerItemFieldsFromItem({
|
|
317
|
-
id: opts.displayId,
|
|
318
|
-
status: opts.fields.status,
|
|
319
|
-
title: opts.fields.title,
|
|
320
|
-
description: opts.fields.description,
|
|
321
|
-
type: opts.fields.type,
|
|
322
|
-
priority: opts.fields.priority,
|
|
323
|
-
owner: opts.fields.owner,
|
|
324
|
-
registeredAt: opts.fields.registeredAt,
|
|
325
|
-
due: opts.fields.due,
|
|
326
|
-
completedAt: opts.fields.completedAt,
|
|
327
|
-
conclusion: opts.fields.conclusion,
|
|
328
|
-
ticket: "-",
|
|
329
|
-
}));
|
|
330
|
-
}
|
|
331
|
-
const REGISTER_ITEM_VALUE_KEYS = [
|
|
332
|
-
"id",
|
|
333
|
-
"status",
|
|
334
|
-
"title",
|
|
335
|
-
"description",
|
|
336
|
-
"type",
|
|
337
|
-
"priority",
|
|
338
|
-
"owner",
|
|
339
|
-
"registeredAt",
|
|
340
|
-
"due",
|
|
341
|
-
"completedAt",
|
|
342
|
-
"conclusion",
|
|
343
|
-
];
|
|
344
|
-
// pjr-index の表セルだけで必要だった pipe のエスケープを本文へ持ち込まない。
|
|
345
|
-
function tableCellToBody(value) {
|
|
346
|
-
return value.replace(/\\\|/g, "|");
|
|
347
|
-
}
|
|
348
|
-
function migrationTopic(title) {
|
|
349
|
-
return slugify(tableCellToBody(title)).slice(0, 64).replace(/-+$/g, "") || "item";
|
|
350
|
-
}
|
|
351
|
-
function assertMigratedItemMatches(source, content, filename) {
|
|
352
|
-
const migrated = readRegisterItemContent(content, filename)?.item;
|
|
353
|
-
if (!migrated) {
|
|
354
|
-
throw new Error(`Failed to read planned register item: ${filename}`);
|
|
355
|
-
}
|
|
356
|
-
const mismatches = REGISTER_ITEM_VALUE_KEYS.filter((key) => migrated[key] !== source[key]);
|
|
357
|
-
if (mismatches.length > 0) {
|
|
358
|
-
const detail = mismatches
|
|
359
|
-
.map((key) => `${key}: ${JSON.stringify(source[key])} -> ${JSON.stringify(migrated[key])}`)
|
|
360
|
-
.join(", ");
|
|
361
|
-
throw new Error(`Migration verification failed for ${source.id}: ${detail}`);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
// 追跡対象の旧 pjr-index と、すでに frontmatter 正本へ移った個票を統合して移行計画を作る。
|
|
365
|
-
// この段階では書き込みを行わず、全件の変換結果が元の項目値と一致してから計画を返す。
|
|
366
|
-
export function planRegisterMigration(paths) {
|
|
367
|
-
const docs = loadRegisterItemDocs(paths.projectRegisterPath);
|
|
368
|
-
const duplicateDocIds = docs
|
|
369
|
-
.map((doc) => doc.id)
|
|
370
|
-
.filter((id, index, ids) => ids.indexOf(id) !== index);
|
|
371
|
-
if (duplicateDocIds.length > 0) {
|
|
372
|
-
throw new Error(`Duplicate register item ticket IDs: ${[...new Set(duplicateDocIds)].join(", ")}`);
|
|
373
|
-
}
|
|
374
|
-
if (!existsSync(paths.pjrIndexPath)) {
|
|
375
|
-
const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
|
|
376
|
-
if (notMigrated.length > 0) {
|
|
377
|
-
throw new Error(`Legacy pjr-index.md is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
|
|
378
|
-
notMigrated.map((doc) => doc.id).join(", "));
|
|
379
|
-
}
|
|
380
|
-
return {
|
|
381
|
-
sourceCount: docs.length,
|
|
382
|
-
createdCount: 0,
|
|
383
|
-
updatedCount: 0,
|
|
384
|
-
unchangedCount: docs.length,
|
|
385
|
-
files: [],
|
|
386
|
-
};
|
|
387
|
-
}
|
|
388
|
-
const sourceIndexContent = readFileSync(paths.pjrIndexPath, "utf8");
|
|
389
|
-
const timeZone = paths.registerDateTimeZone;
|
|
390
|
-
// 旧構成の pjr-index.md が一覧テーブルを持たない参照案内だった場合もある。
|
|
391
|
-
// その案内ページは、旧一覧が存在しない場合と同じ no-op として扱う。
|
|
392
|
-
if (!locateRegisterTable(sourceIndexContent.split("\n"))) {
|
|
393
|
-
const notMigrated = docs.filter((doc) => !doc.hasRegisterFields);
|
|
394
|
-
if (notMigrated.length > 0) {
|
|
395
|
-
throw new Error(`Legacy pjr-index table is missing, but ${notMigrated.length} ticket(s) have no register item fields: ` +
|
|
396
|
-
notMigrated.map((doc) => doc.id).join(", "));
|
|
397
|
-
}
|
|
398
|
-
return {
|
|
399
|
-
sourceCount: docs.length,
|
|
400
|
-
createdCount: 0,
|
|
401
|
-
updatedCount: 0,
|
|
402
|
-
unchangedCount: docs.length,
|
|
403
|
-
files: [],
|
|
404
|
-
};
|
|
405
|
-
}
|
|
406
|
-
const indexItems = parsePjrIndex(sourceIndexContent, timeZone);
|
|
407
|
-
const duplicateIndexIds = indexItems
|
|
408
|
-
.map((item) => item.id)
|
|
409
|
-
.filter((id, index, ids) => ids.indexOf(id) !== index);
|
|
410
|
-
if (duplicateIndexIds.length > 0) {
|
|
411
|
-
throw new Error(`Duplicate pjr-index IDs: ${[...new Set(duplicateIndexIds)].join(", ")}`);
|
|
412
|
-
}
|
|
413
|
-
// loadRegisterItems は移行済み個票を優先し、未移行項目だけ旧一覧を読む。これにより、
|
|
414
|
-
// runner がすでに遷移させた item_status を古い一覧行で巻き戻さない。
|
|
415
|
-
const sources = loadRegisterItems(paths);
|
|
416
|
-
if (sources.length !== indexItems.length) {
|
|
417
|
-
throw new Error(`Register item count mismatch before migration: index=${indexItems.length}, resolved=${sources.length}`);
|
|
418
|
-
}
|
|
419
|
-
const docsById = new Map(docs.map((doc) => [doc.id, doc]));
|
|
420
|
-
const files = [];
|
|
421
|
-
let createdCount = 0;
|
|
422
|
-
let updatedCount = 0;
|
|
423
|
-
let unchangedCount = 0;
|
|
424
|
-
for (const source of sources) {
|
|
425
|
-
validateFields({
|
|
426
|
-
type: source.item.type,
|
|
427
|
-
priority: source.item.priority,
|
|
428
|
-
status: source.item.status,
|
|
429
|
-
registeredAt: source.item.registeredAt,
|
|
430
|
-
due: source.item.due,
|
|
431
|
-
completedAt: source.item.completedAt,
|
|
432
|
-
});
|
|
433
|
-
const existing = docsById.get(source.id);
|
|
434
|
-
let filename;
|
|
435
|
-
let path;
|
|
436
|
-
let originalContent;
|
|
437
|
-
let content;
|
|
438
|
-
if (existing) {
|
|
439
|
-
filename = existing.filename;
|
|
440
|
-
path = existing.path;
|
|
441
|
-
originalContent = readFileSync(path, "utf8");
|
|
442
|
-
content = originalContent;
|
|
443
|
-
if (source.source === "index") {
|
|
444
|
-
if (existing.item.title !== source.item.title) {
|
|
445
|
-
content = setRegisterItemTitle(content, tableCellToBody(source.item.title));
|
|
446
|
-
}
|
|
447
|
-
if (existing.item.description !== source.item.description) {
|
|
448
|
-
content = prependRegisterItemDescription(content, tableCellToBody(source.item.description));
|
|
449
|
-
}
|
|
450
|
-
content = applyRegisterItemFields(content, registerItemFieldsFromItem(source.item));
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
else {
|
|
454
|
-
const topic = migrationTopic(source.item.title);
|
|
455
|
-
filename = `pjr-${source.id.slice("PJR-".length).toLowerCase()}-${topic}.md`;
|
|
456
|
-
path = join(paths.projectRegisterPath, filename);
|
|
457
|
-
if (existsSync(path)) {
|
|
458
|
-
throw new Error(`Migration target already exists: ${path}`);
|
|
459
|
-
}
|
|
460
|
-
const templatePath = resolveSpecdojoTemplatePath(`pjr-${source.item.type}-template.md`);
|
|
461
|
-
content = buildRegisterItemContent({
|
|
462
|
-
projectId: paths.projectId,
|
|
463
|
-
displayId: source.item.id,
|
|
464
|
-
topic,
|
|
465
|
-
fields: {
|
|
466
|
-
type: source.item.type,
|
|
467
|
-
title: tableCellToBody(source.item.title),
|
|
468
|
-
description: tableCellToBody(source.item.description),
|
|
469
|
-
priority: source.item.priority,
|
|
470
|
-
status: source.item.status,
|
|
471
|
-
owner: source.item.owner,
|
|
472
|
-
registeredAt: source.item.registeredAt,
|
|
473
|
-
due: source.item.due,
|
|
474
|
-
completedAt: source.item.completedAt,
|
|
475
|
-
conclusion: source.item.conclusion,
|
|
476
|
-
},
|
|
477
|
-
templatePath,
|
|
478
|
-
});
|
|
479
|
-
// 旧一覧のセルでは問題にならなかった `_CAPITAL_CASE_` などを本文へ移すと、
|
|
480
|
-
// markdownlint が underscore emphasis と解釈する。表示値を変えずに規則だけ抑止する。
|
|
481
|
-
if (/_[A-Z][A-Z0-9_]*_/.test(`${source.item.title}\n${source.item.description}`)) {
|
|
482
|
-
content = content.replace(/^(---\r?\n[\s\S]*?\r?\n---\r?\n)/, "$1\n<!-- markdownlint-disable MD049 -->\n");
|
|
483
|
-
}
|
|
484
|
-
}
|
|
485
|
-
assertMigratedItemMatches(source.item, content, filename);
|
|
486
|
-
if (content === originalContent) {
|
|
487
|
-
unchangedCount++;
|
|
488
|
-
}
|
|
489
|
-
else {
|
|
490
|
-
files.push({ path, content, originalContent });
|
|
491
|
-
if (originalContent === undefined)
|
|
492
|
-
createdCount++;
|
|
493
|
-
else
|
|
494
|
-
updatedCount++;
|
|
495
|
-
}
|
|
496
|
-
}
|
|
497
|
-
return {
|
|
498
|
-
sourceCount: sources.length,
|
|
499
|
-
createdCount,
|
|
500
|
-
updatedCount,
|
|
501
|
-
unchangedCount,
|
|
502
|
-
files,
|
|
503
|
-
sourceIndexPath: paths.pjrIndexPath,
|
|
504
|
-
sourceIndexContent,
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
// 全出力を同一ディレクトリ内の一時ファイルへ書いてから切り替える。切り替え途中で失敗した
|
|
508
|
-
// 場合は既存ファイルと旧一覧を戻し、作成途中の個票を除去して部分適用を残さない。
|
|
509
|
-
export function applyRegisterMigrationPlan(plan) {
|
|
510
|
-
if (plan.files.length === 0 && !plan.sourceIndexPath)
|
|
511
|
-
return;
|
|
512
|
-
if (plan.sourceIndexPath) {
|
|
513
|
-
if (!existsSync(plan.sourceIndexPath)) {
|
|
514
|
-
throw new Error(`Migration source changed after planning: missing ${plan.sourceIndexPath}`);
|
|
515
|
-
}
|
|
516
|
-
if (readFileSync(plan.sourceIndexPath, "utf8") !== plan.sourceIndexContent) {
|
|
517
|
-
throw new Error(`Migration source changed after planning: ${plan.sourceIndexPath}`);
|
|
518
|
-
}
|
|
519
|
-
}
|
|
520
|
-
for (const file of plan.files) {
|
|
521
|
-
if (file.originalContent === undefined) {
|
|
522
|
-
if (existsSync(file.path)) {
|
|
523
|
-
throw new Error(`Migration target appeared after planning: ${file.path}`);
|
|
524
|
-
}
|
|
525
|
-
}
|
|
526
|
-
else if (!existsSync(file.path) || readFileSync(file.path, "utf8") !== file.originalContent) {
|
|
527
|
-
throw new Error(`Migration target changed after planning: ${file.path}`);
|
|
528
|
-
}
|
|
529
|
-
}
|
|
530
|
-
const transactionId = randomUUID();
|
|
531
|
-
const staged = [];
|
|
532
|
-
let indexBackupPath;
|
|
533
|
-
try {
|
|
534
|
-
for (const file of plan.files) {
|
|
535
|
-
const stagedPath = join(dirname(file.path), `.specdojo-migrate-${transactionId}-${basename(file.path)}`);
|
|
536
|
-
staged.push({ ...file, stagedPath });
|
|
537
|
-
writeFileSync(stagedPath, file.content, { encoding: "utf8", flag: "wx" });
|
|
538
|
-
}
|
|
539
|
-
for (const file of staged) {
|
|
540
|
-
if (file.originalContent !== undefined) {
|
|
541
|
-
file.backupPath = `${file.stagedPath}.backup`;
|
|
542
|
-
renameSync(file.path, file.backupPath);
|
|
543
|
-
}
|
|
544
|
-
renameSync(file.stagedPath, file.path);
|
|
545
|
-
}
|
|
546
|
-
if (plan.sourceIndexPath) {
|
|
547
|
-
indexBackupPath = join(dirname(plan.sourceIndexPath), `.specdojo-migrate-${transactionId}-${basename(plan.sourceIndexPath)}.backup`);
|
|
548
|
-
renameSync(plan.sourceIndexPath, indexBackupPath);
|
|
549
|
-
}
|
|
550
|
-
}
|
|
551
|
-
catch (error) {
|
|
552
|
-
if (indexBackupPath && existsSync(indexBackupPath) && plan.sourceIndexPath) {
|
|
553
|
-
if (existsSync(plan.sourceIndexPath))
|
|
554
|
-
unlinkSync(plan.sourceIndexPath);
|
|
555
|
-
renameSync(indexBackupPath, plan.sourceIndexPath);
|
|
556
|
-
}
|
|
557
|
-
for (const file of [...staged].reverse()) {
|
|
558
|
-
if (existsSync(file.stagedPath))
|
|
559
|
-
unlinkSync(file.stagedPath);
|
|
560
|
-
if (file.backupPath && existsSync(file.backupPath)) {
|
|
561
|
-
if (existsSync(file.path))
|
|
562
|
-
unlinkSync(file.path);
|
|
563
|
-
renameSync(file.backupPath, file.path);
|
|
564
|
-
}
|
|
565
|
-
else if (file.originalContent === undefined && existsSync(file.path)) {
|
|
566
|
-
unlinkSync(file.path);
|
|
567
|
-
}
|
|
568
|
-
}
|
|
569
|
-
throw error;
|
|
570
|
-
}
|
|
571
|
-
// バックアップ除去は切り替え完了後に行う。ここで一時ファイルの除去に失敗しても、
|
|
572
|
-
// 正本の切り替え自体は完了しているため migration を巻き戻さない。
|
|
573
|
-
for (const file of staged) {
|
|
574
|
-
if (file.backupPath && existsSync(file.backupPath)) {
|
|
575
|
-
try {
|
|
576
|
-
unlinkSync(file.backupPath);
|
|
577
|
-
}
|
|
578
|
-
catch {
|
|
579
|
-
// 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
}
|
|
583
|
-
if (indexBackupPath && existsSync(indexBackupPath)) {
|
|
584
|
-
try {
|
|
585
|
-
unlinkSync(indexBackupPath);
|
|
586
|
-
}
|
|
587
|
-
catch {
|
|
588
|
-
// 正本は切り替え済み。一時バックアップは次回の手動清掃対象として残す。
|
|
589
|
-
}
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
// ================================
|
|
593
|
-
// Derived View Generation
|
|
594
|
-
// ================================
|
|
595
|
-
function adjustTicketLink(ticket, prefix) {
|
|
596
|
-
if (ticket === "-")
|
|
597
|
-
return ticket;
|
|
598
|
-
return ticket.replace(/\]\(\.\//g, `](${prefix}`);
|
|
599
|
-
}
|
|
600
|
-
function rebaseItems(items, prefix) {
|
|
601
|
-
return items.map((it) => ({ ...it, ticket: adjustTicketLink(it.ticket, prefix) }));
|
|
602
|
-
}
|
|
603
|
-
function makeTable(items, heading) {
|
|
604
|
-
const rows = items.map(formatTableRow);
|
|
605
|
-
return [heading.header, heading.separator, ...rows].join("\n");
|
|
606
|
-
}
|
|
607
|
-
// 派生ビューの外枠(H1・note・章見出し・frontmatter)は template が所有する。
|
|
608
|
-
// template をロードして生成物形へ平坦化し、`_PROJECT_ID_` を実プロジェクト ID へ置換する。
|
|
609
|
-
function loadViewTemplate(templateFileName, projectId) {
|
|
610
|
-
const templatePath = resolveSpecdojoTemplatePath(templateFileName);
|
|
611
|
-
const raw = readFileSync(templatePath, "utf8");
|
|
612
|
-
return flattenTemplateFrontmatter(raw).replace(/_PROJECT_ID_/g, projectId);
|
|
613
|
-
}
|
|
614
|
-
// template 本文中の `<!-- specdojo:view-slot=<key> -->` 行を生成テーブルへ置換する。
|
|
615
|
-
// slot と提供テーブルは相互に過不足がないことを検証し、template の不整合を早期に検出する。
|
|
616
|
-
export function injectViewSlots(content, slots) {
|
|
617
|
-
const used = new Set();
|
|
618
|
-
const injected = content.replace(/^<!-- specdojo:view-slot=([a-z-]+) -->$/gm, (_match, key) => {
|
|
619
|
-
if (!(key in slots)) {
|
|
620
|
-
throw new Error(`Unknown view-slot in template: ${key}`);
|
|
621
|
-
}
|
|
622
|
-
used.add(key);
|
|
623
|
-
return slots[key];
|
|
624
|
-
});
|
|
625
|
-
const missing = Object.keys(slots).filter((key) => !used.has(key));
|
|
626
|
-
if (missing.length > 0) {
|
|
627
|
-
throw new Error(`View-slot not found in template: ${missing.join(", ")}`);
|
|
628
|
-
}
|
|
629
|
-
return injected;
|
|
630
|
-
}
|
|
631
|
-
// グループ(状態別・優先度別・担当者別など)を `### <chapter>.<n>. <label>` 見出し付きの
|
|
632
|
-
// テーブル群へ整形する。章見出しラベルは template 側が持つため、ここでは番号と値のみ扱う。
|
|
633
|
-
function renderGroupedTables(groups, chapter, heading) {
|
|
634
|
-
return groups
|
|
635
|
-
.map((group, index) => [
|
|
636
|
-
`### ${chapter}.${index + 1}. ${group.label}`,
|
|
637
|
-
"",
|
|
638
|
-
"<!-- prettier-ignore -->",
|
|
639
|
-
makeTable(group.items, heading),
|
|
640
|
-
].join("\n"))
|
|
641
|
-
.join("\n\n");
|
|
642
|
-
}
|
|
643
|
-
// ビューの行順に使う起票時刻を解決する。`registered` は移行前の項目で `_TODO_` になるため、
|
|
644
|
-
// 追記型イベントの `add` の `ts` で補う。表示 ID はランダムな 4 文字で、ID 順には時系列の意味が
|
|
645
|
-
// ないため、並びの根拠は時刻に置く。
|
|
646
|
-
function resolveRegisteredOrder(item, paths, cache) {
|
|
647
|
-
const cached = cache.get(item.id);
|
|
648
|
-
if (cached !== undefined)
|
|
649
|
-
return cached;
|
|
650
|
-
let value = "";
|
|
651
|
-
if (item.registered && item.registered !== "_TODO_" && item.registered !== "-") {
|
|
652
|
-
value = item.registered;
|
|
653
|
-
}
|
|
654
|
-
else {
|
|
655
|
-
const eventPath = registerEventFilePath(paths.projectRegisterPath, item.id);
|
|
656
|
-
if (existsSync(eventPath)) {
|
|
657
|
-
const events = readRegisterEventsFromContent(readFileSync(eventPath, "utf8"), eventPath);
|
|
658
|
-
const added = events.find((event) => event.action === "add");
|
|
659
|
-
if (added?.ts)
|
|
660
|
-
value = added.ts;
|
|
661
|
-
}
|
|
662
|
-
}
|
|
663
|
-
cache.set(item.id, value);
|
|
664
|
-
return value;
|
|
665
|
-
}
|
|
666
|
-
// 新しい起票を先頭へ置く。時刻が並ぶ場合と時刻を解決できない場合は ID で安定させる。
|
|
667
|
-
// 時刻を解決できない項目は末尾へ送り、解決できた項目の並びを乱さない。
|
|
668
|
-
export function sortByRegisteredDesc(items, paths) {
|
|
669
|
-
const cache = new Map();
|
|
670
|
-
return [...items].sort((a, b) => {
|
|
671
|
-
const left = resolveRegisteredOrder(a, paths, cache);
|
|
672
|
-
const right = resolveRegisteredOrder(b, paths, cache);
|
|
673
|
-
if (left !== right) {
|
|
674
|
-
if (!left)
|
|
675
|
-
return 1;
|
|
676
|
-
if (!right)
|
|
677
|
-
return -1;
|
|
678
|
-
return left < right ? 1 : -1;
|
|
679
|
-
}
|
|
680
|
-
return compareRegisterItemIds(a.id, b.id);
|
|
681
|
-
});
|
|
682
|
-
}
|
|
683
|
-
function groupByOwner(items) {
|
|
684
|
-
const grouped = new Map();
|
|
685
|
-
for (const item of items) {
|
|
686
|
-
const key = item.owner || "-";
|
|
687
|
-
if (!grouped.has(key))
|
|
688
|
-
grouped.set(key, []);
|
|
689
|
-
grouped.get(key).push(item);
|
|
690
|
-
}
|
|
691
|
-
return [...grouped.keys()].sort().map((owner) => ({ label: owner, items: grouped.get(owner) }));
|
|
692
|
-
}
|
|
693
|
-
// 登録項目一覧(pjr-index)本体を生成する。行は ID 昇順で、列見出しと外枠は template が持つ。
|
|
694
|
-
function generateIndexView(items, projectId) {
|
|
695
|
-
const template = loadViewTemplate(REGISTER_INDEX_TEMPLATE, projectId);
|
|
696
|
-
return injectRegisterRows(template, items.map(formatTableRow));
|
|
697
|
-
}
|
|
698
|
-
// 状態別・優先度別・担当者別のビューは、非追跡の生成物になったことで単一ファイルへ
|
|
699
|
-
// まとめる理由(共有編集時の git 差分・マージ競合の回避)が無くなったため、
|
|
700
|
-
// 軸ごとに別ファイルへ分割する(見やすさを優先する)。
|
|
701
|
-
function generateViewsByStatusFile(items, projectId, heading) {
|
|
702
|
-
const statusGroups = VALID_STATUSES.map((status) => ({
|
|
703
|
-
label: status,
|
|
704
|
-
items: items.filter((it) => it.status === status),
|
|
705
|
-
})).filter((group) => group.items.length > 0);
|
|
706
|
-
const template = loadViewTemplate("pjr-views-by-status-template.md", projectId);
|
|
707
|
-
return injectViewSlots(template, {
|
|
708
|
-
"by-status": renderGroupedTables(statusGroups, 1, heading),
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
function generateViewsByPriorityFile(items, projectId, heading) {
|
|
712
|
-
const priorityGroups = VALID_PRIORITIES.map((priority) => ({
|
|
713
|
-
label: priority,
|
|
714
|
-
items: items.filter((it) => it.priority === priority),
|
|
715
|
-
}));
|
|
716
|
-
const template = loadViewTemplate("pjr-views-by-priority-template.md", projectId);
|
|
717
|
-
return injectViewSlots(template, {
|
|
718
|
-
"by-priority": renderGroupedTables(priorityGroups, 1, heading),
|
|
719
|
-
});
|
|
720
|
-
}
|
|
721
|
-
function generateViewsByOwnerFile(items, projectId, heading) {
|
|
722
|
-
const template = loadViewTemplate("pjr-views-by-owner-template.md", projectId);
|
|
723
|
-
return injectViewSlots(template, {
|
|
724
|
-
"by-owner": renderGroupedTables(groupByOwner(items), 1, heading),
|
|
725
|
-
});
|
|
726
|
-
}
|
|
727
|
-
function generateTypeFilterView(items, type, templateFileName, projectId, heading) {
|
|
728
|
-
const filtered = items.filter((it) => it.type === type);
|
|
729
|
-
const template = loadViewTemplate(templateFileName, projectId);
|
|
730
|
-
return injectViewSlots(template, {
|
|
731
|
-
table: ["<!-- prettier-ignore -->", makeTable(filtered, heading)].join("\n"),
|
|
732
|
-
});
|
|
733
|
-
}
|
|
734
|
-
const VALID_BUILD_SCOPES = ["register", "controls", "all"];
|
|
735
|
-
export function generateDerivedViewFiles(paths, scope) {
|
|
736
|
-
// 項目の値は個票 frontmatter(正本)から集める。列見出しは template から採用するため、
|
|
737
|
-
// 生成処理は作業ツリーの pjr-index.md を入力にしない。
|
|
738
|
-
// 「登録日」「完了日」は保存された日時をプロジェクトの登録日タイムゾーンへ変換して導出する。
|
|
739
|
-
const items = loadRegisterItems(paths).map((view) => toDisplayItem(view.item, paths.registerDateTimeZone));
|
|
740
|
-
const heading = extractTableHeading(loadViewTemplate(REGISTER_INDEX_TEMPLATE, paths.projectId));
|
|
741
|
-
// 個票セルのリンクは project-register/ 起点の `./` 表記で作られる。
|
|
742
|
-
// 各 generated/ ディレクトリから辿れるよう相対パスを付け替える。
|
|
743
|
-
const pjrDirName = basename(paths.projectRegisterPath);
|
|
744
|
-
const regItems = rebaseItems(items, "../");
|
|
745
|
-
const ctrlItems = rebaseItems(items, `../${pjrDirName}/`);
|
|
746
|
-
const registerViews = [];
|
|
747
|
-
const controlsViews = [];
|
|
748
|
-
if (scope === "register" || scope === "all") {
|
|
749
|
-
// 本体(pjr-index)は ID で引く用途があるため ID 昇順を保つ。軸別ビューは状況の把握が目的で、
|
|
750
|
-
// 新しい起票を先頭へ置く。
|
|
751
|
-
const viewItems = sortByRegisteredDesc(regItems, paths);
|
|
752
|
-
registerViews.push({
|
|
753
|
-
path: join(paths.generatedPath, "pjr-index.md"),
|
|
754
|
-
content: generateIndexView(regItems, paths.projectId),
|
|
755
|
-
}, {
|
|
756
|
-
path: join(paths.generatedPath, "pjr-views-by-status.md"),
|
|
757
|
-
content: generateViewsByStatusFile(viewItems, paths.projectId, heading),
|
|
758
|
-
}, {
|
|
759
|
-
path: join(paths.generatedPath, "pjr-views-by-priority.md"),
|
|
760
|
-
content: generateViewsByPriorityFile(viewItems, paths.projectId, heading),
|
|
761
|
-
}, {
|
|
762
|
-
path: join(paths.generatedPath, "pjr-views-by-owner.md"),
|
|
763
|
-
content: generateViewsByOwnerFile(viewItems, paths.projectId, heading),
|
|
764
|
-
});
|
|
765
|
-
}
|
|
766
|
-
if (scope === "controls" || scope === "all") {
|
|
767
|
-
controlsViews.push({
|
|
768
|
-
path: join(paths.controlsGeneratedPath, "pm-risk-register.md"),
|
|
769
|
-
content: generateTypeFilterView(ctrlItems, "risk", "pm-risk-register-template.md", paths.projectId, heading),
|
|
770
|
-
}, {
|
|
771
|
-
path: join(paths.controlsGeneratedPath, "pm-issue-log.md"),
|
|
772
|
-
content: generateTypeFilterView(ctrlItems, "issue", "pm-issue-log-template.md", paths.projectId, heading),
|
|
773
|
-
}, {
|
|
774
|
-
path: join(paths.controlsGeneratedPath, "pm-change-request-log.md"),
|
|
775
|
-
content: generateTypeFilterView(ctrlItems, "change-request", "pm-change-request-log-template.md", paths.projectId, heading),
|
|
776
|
-
}, {
|
|
777
|
-
path: join(paths.controlsGeneratedPath, "pm-decision-log.md"),
|
|
778
|
-
content: generateTypeFilterView(ctrlItems, "decision", "pm-decision-log-template.md", paths.projectId, heading),
|
|
779
|
-
});
|
|
780
|
-
}
|
|
781
|
-
return [...registerViews, ...controlsViews];
|
|
782
|
-
}
|
|
783
|
-
function writeDerivedViews(paths, scope) {
|
|
784
|
-
const views = generateDerivedViewFiles(paths, scope);
|
|
785
|
-
const hasRegisterViews = views.some((view) => dirname(view.path) === paths.generatedPath);
|
|
786
|
-
const hasControlsViews = views.some((view) => dirname(view.path) === paths.controlsGeneratedPath);
|
|
787
|
-
if (hasRegisterViews) {
|
|
788
|
-
mkdirSync(paths.generatedPath, { recursive: true });
|
|
789
|
-
}
|
|
790
|
-
if (hasControlsViews) {
|
|
791
|
-
mkdirSync(paths.controlsGeneratedPath, { recursive: true });
|
|
792
|
-
}
|
|
793
|
-
for (const view of views) {
|
|
794
|
-
writeFileSync(view.path, view.content, "utf8");
|
|
795
|
-
}
|
|
796
|
-
return views;
|
|
797
|
-
}
|
|
798
|
-
// ================================
|
|
799
|
-
// Item Update Helpers
|
|
800
|
-
// ================================
|
|
801
|
-
export function findItemById(items, id) {
|
|
802
|
-
return items.find((it) => it.id === id);
|
|
803
|
-
}
|
|
804
|
-
// 登録項目を全件解決する。正本は個票 frontmatter で、登録項目フィールドを持つ個票を
|
|
805
|
-
// 最優先で採用する。まだ個票へ移行していない項目は pjr-index の行から読み取り(互換)、
|
|
806
|
-
// 個票ファイルがある場合はそのパスを保持して、次回の更新時に frontmatter へ移す。
|
|
807
|
-
export function loadRegisterItems(paths) {
|
|
808
|
-
const docs = loadRegisterItemDocs(paths.projectRegisterPath);
|
|
809
|
-
const docById = new Map(docs.map((doc) => [doc.id, doc]));
|
|
810
|
-
const views = new Map();
|
|
811
|
-
for (const doc of docs) {
|
|
812
|
-
if (!doc.hasRegisterFields)
|
|
813
|
-
continue;
|
|
814
|
-
views.set(doc.id, {
|
|
815
|
-
id: doc.id,
|
|
816
|
-
item: doc.item,
|
|
817
|
-
ticketPath: doc.path,
|
|
818
|
-
ticketFilename: doc.filename,
|
|
819
|
-
source: "ticket",
|
|
820
|
-
});
|
|
821
|
-
}
|
|
822
|
-
if (existsSync(paths.pjrIndexPath)) {
|
|
823
|
-
for (const item of parsePjrIndex(readFileSync(paths.pjrIndexPath, "utf8"), paths.registerDateTimeZone)) {
|
|
824
|
-
if (views.has(item.id))
|
|
825
|
-
continue;
|
|
826
|
-
const doc = docById.get(item.id);
|
|
827
|
-
views.set(item.id, {
|
|
828
|
-
id: item.id,
|
|
829
|
-
item: doc ? { ...item, ticket: ticketRefCell(doc.filename) } : item,
|
|
830
|
-
ticketPath: doc?.path,
|
|
831
|
-
ticketFilename: doc?.filename,
|
|
832
|
-
source: "index",
|
|
833
|
-
});
|
|
834
|
-
}
|
|
835
|
-
}
|
|
836
|
-
return [...views.values()].sort((a, b) => compareRegisterItemIds(a.id, b.id));
|
|
837
|
-
}
|
|
838
|
-
export function findRegisterItem(views, id) {
|
|
839
|
-
return views.find((view) => view.id === id);
|
|
840
|
-
}
|
|
841
|
-
// 更新対象の登録項目を解決する。個票ファイルが無い項目は、書き込み先(正本)が無いため
|
|
842
|
-
// 更新できない。移行が済んでいない旧項目に当たった場合は、個票化を促して中断する。
|
|
843
|
-
function loadItemForUpdate(paths, id, guard) {
|
|
844
|
-
if (!PJR_ID_RE.test(id)) {
|
|
845
|
-
throw new Error(`Invalid ID: "${id}". Must match PJR-XXXX (e.g., PJR-0001)`);
|
|
846
|
-
}
|
|
847
|
-
const view = findRegisterItem(loadRegisterItems(paths), id);
|
|
848
|
-
if (!view) {
|
|
849
|
-
throw new Error(`Item not found: ${id} (searched ${paths.projectRegisterPath})`);
|
|
850
|
-
}
|
|
851
|
-
if (!view.ticketPath) {
|
|
852
|
-
throw new Error(`Item ${id} has no ticket file under ${paths.projectRegisterPath}.\n` +
|
|
853
|
-
`The register item frontmatter is the source of truth; create the ticket file ` +
|
|
854
|
-
`(pjr-${id.slice("PJR-".length).toLowerCase()}-<topic>.md) before updating the item.`);
|
|
855
|
-
}
|
|
856
|
-
if (guard === "require-active" && TERMINAL_STATUSES_SET.has(view.item.status)) {
|
|
857
|
-
throw new Error(`Cannot change ${id}: status is "${view.item.status}" (terminal). Use "register reopen" first.`);
|
|
858
|
-
}
|
|
859
|
-
if (guard === "require-terminal" && !TERMINAL_STATUSES_SET.has(view.item.status)) {
|
|
860
|
-
throw new Error(`Cannot reopen ${id}: status is "${view.item.status}" (already active).`);
|
|
861
|
-
}
|
|
862
|
-
return view;
|
|
863
|
-
}
|
|
864
|
-
// 更新後の項目値を個票 frontmatter へ書き戻す。未移行(source: index)の項目は、
|
|
865
|
-
// 行から読んだ値も含めて全フィールドを書き込み、その場で個票正本へ移行する。
|
|
866
|
-
// タイトル・説明は frontmatter に持たないため、H1 と概要段落を書き換える。
|
|
867
|
-
function applyItemUpdate(opts) {
|
|
868
|
-
const ticketPath = opts.view.ticketPath;
|
|
869
|
-
if (!ticketPath) {
|
|
870
|
-
throw new Error(`Item ${opts.view.id} has no ticket file to update`);
|
|
871
|
-
}
|
|
872
|
-
const label = opts.action ?? `→ ${opts.updated.status}`;
|
|
873
|
-
const updates = {
|
|
874
|
-
...registerItemFieldsFromItem(opts.updated),
|
|
875
|
-
...opts.fieldUpdates,
|
|
876
|
-
};
|
|
877
|
-
if (opts.dryRun) {
|
|
878
|
-
const lines = [`Would update ${ticketPath} (${opts.updated.id} ${label}):`];
|
|
879
|
-
if (opts.title !== undefined)
|
|
880
|
-
lines.push(` title: ${opts.title}`);
|
|
881
|
-
if (opts.description !== undefined)
|
|
882
|
-
lines.push(` description: ${opts.description}`);
|
|
883
|
-
lines.push(formatRegisterItemFields(updates));
|
|
884
|
-
process.stdout.write(`${lines.join("\n")}\n`);
|
|
885
|
-
return;
|
|
886
|
-
}
|
|
887
|
-
const beforeContent = readFileSync(ticketPath, "utf8");
|
|
888
|
-
let content = beforeContent;
|
|
889
|
-
if (opts.title !== undefined)
|
|
890
|
-
content = setRegisterItemTitle(content, opts.title);
|
|
891
|
-
if (opts.description !== undefined) {
|
|
892
|
-
content = setRegisterItemDescription(content, opts.description);
|
|
893
|
-
}
|
|
894
|
-
content = applyRegisterItemFields(content, updates);
|
|
895
|
-
const event = buildRegisterEvent({
|
|
896
|
-
beforeContent,
|
|
897
|
-
afterContent: content,
|
|
898
|
-
filename: basename(ticketPath),
|
|
899
|
-
timeZone: opts.paths.registerDateTimeZone,
|
|
900
|
-
action: opts.eventAction,
|
|
901
|
-
actor: opts.eventActor,
|
|
902
|
-
reason: opts.eventReason,
|
|
903
|
-
});
|
|
904
|
-
if (!event) {
|
|
905
|
-
process.stdout.write(`Unchanged: ${ticketPath} (${opts.updated.id})\n`);
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
const eventWrite = prepareRegisterEventFile(opts.paths.projectRegisterPath, opts.updated.id, event);
|
|
909
|
-
atomicWriteFile(ticketPath, content);
|
|
910
|
-
atomicWriteFile(eventWrite.path, eventWrite.content);
|
|
911
|
-
process.stdout.write(`Updated: ${ticketPath} (${opts.updated.id} ${label})\n`);
|
|
912
|
-
process.stdout.write(`Updated: ${eventWrite.path}\n`);
|
|
913
|
-
for (const view of writeDerivedViews(opts.paths, "all")) {
|
|
914
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
915
|
-
}
|
|
916
|
-
}
|
|
917
|
-
// ================================
|
|
918
|
-
// Ticket Frontmatter Status
|
|
919
|
-
// ================================
|
|
920
|
-
const FRONTMATTER_BLOCK_RE = /^---\r?\n([\s\S]*?)\r?\n---/;
|
|
921
|
-
// pjr-index の「個票」セル(例: `[pjr-0001-topic](./pjr-0001-topic.md)`)から
|
|
922
|
-
// project-register ディレクトリ相対のファイル名を取り出す。個票なし(`-`)は undefined。
|
|
923
|
-
export function parseTicketFilename(ticketCell) {
|
|
924
|
-
if (ticketCell === "-" || ticketCell.trim() === "")
|
|
925
|
-
return undefined;
|
|
926
|
-
const match = ticketCell.match(/\]\(\.\/([^)]+\.md)\)/);
|
|
927
|
-
return match ? match[1] : undefined;
|
|
928
|
-
}
|
|
929
|
-
function stripFencedCode(markdown) {
|
|
930
|
-
let fence;
|
|
931
|
-
return markdown
|
|
932
|
-
.split(/(?<=\n)/)
|
|
933
|
-
.map((lineWithEnding) => {
|
|
934
|
-
const line = lineWithEnding.replace(/\r?\n$/, "");
|
|
935
|
-
const lineEnding = lineWithEnding.slice(line.length);
|
|
936
|
-
if (fence) {
|
|
937
|
-
const closing = line.match(/^ {0,3}(`+|~+)[ \t]*$/);
|
|
938
|
-
if (closing && closing[1][0] === fence.marker && closing[1].length >= fence.length) {
|
|
939
|
-
fence = undefined;
|
|
940
|
-
}
|
|
941
|
-
return lineEnding;
|
|
942
|
-
}
|
|
943
|
-
const opening = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/);
|
|
944
|
-
if (opening && !(opening[1][0] === "`" && opening[2].includes("`"))) {
|
|
945
|
-
fence = { marker: opening[1][0], length: opening[1].length };
|
|
946
|
-
return lineEnding;
|
|
947
|
-
}
|
|
948
|
-
return lineWithEnding;
|
|
949
|
-
})
|
|
950
|
-
.join("");
|
|
951
|
-
}
|
|
952
|
-
function isEscapedMarkdownCharacter(markdown, index) {
|
|
953
|
-
let backslashes = 0;
|
|
954
|
-
for (let cursor = index - 1; cursor >= 0 && markdown[cursor] === "\\"; cursor--) {
|
|
955
|
-
backslashes++;
|
|
956
|
-
}
|
|
957
|
-
return backslashes % 2 === 1;
|
|
958
|
-
}
|
|
959
|
-
function findClosingBacktickRun(markdown, start, length) {
|
|
960
|
-
for (let cursor = start; cursor < markdown.length;) {
|
|
961
|
-
if (markdown[cursor] !== "`") {
|
|
962
|
-
cursor++;
|
|
963
|
-
continue;
|
|
964
|
-
}
|
|
965
|
-
const runStart = cursor;
|
|
966
|
-
while (markdown[cursor] === "`")
|
|
967
|
-
cursor++;
|
|
968
|
-
if (cursor - runStart === length && !isEscapedMarkdownCharacter(markdown, runStart)) {
|
|
969
|
-
return runStart;
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
return -1;
|
|
973
|
-
}
|
|
974
|
-
function stripInlineCode(markdown) {
|
|
975
|
-
let result = "";
|
|
976
|
-
for (let cursor = 0; cursor < markdown.length;) {
|
|
977
|
-
if (markdown[cursor] !== "`" || isEscapedMarkdownCharacter(markdown, cursor)) {
|
|
978
|
-
result += markdown[cursor];
|
|
979
|
-
cursor++;
|
|
980
|
-
continue;
|
|
981
|
-
}
|
|
982
|
-
const runStart = cursor;
|
|
983
|
-
while (markdown[cursor] === "`")
|
|
984
|
-
cursor++;
|
|
985
|
-
const runLength = cursor - runStart;
|
|
986
|
-
const closing = findClosingBacktickRun(markdown, cursor, runLength);
|
|
987
|
-
if (closing === -1) {
|
|
988
|
-
result += markdown.slice(runStart, cursor);
|
|
989
|
-
continue;
|
|
990
|
-
}
|
|
991
|
-
cursor = closing + runLength;
|
|
992
|
-
}
|
|
993
|
-
return result;
|
|
994
|
-
}
|
|
995
|
-
// type 固有の必須節が固まっているかの判定。見出し文言(言語依存)に依存せず、
|
|
996
|
-
// Markdown のコード範囲を除く本文に記入プレースホルダ `_TODO_` が残っていれば
|
|
997
|
-
// 「未確定」とみなす。コード範囲は記法の説明や例示に使えるため判定対象外とする。
|
|
998
|
-
function ticketBodyHasTodo(content) {
|
|
999
|
-
const { body } = parseSpecdojoDocument(content);
|
|
1000
|
-
return stripInlineCode(stripFencedCode(body)).includes("_TODO_");
|
|
1001
|
-
}
|
|
1002
|
-
// 個票 Frontmatter(specdojo 名前空間)内の `status:` 行を targetStatus へ書き換える。
|
|
1003
|
-
// 既に目的の値なら changed=false を返し、内容を変えない(冪等)。
|
|
1004
|
-
export function updateTicketFrontmatterStatus(content, targetStatus) {
|
|
1005
|
-
const block = content.match(FRONTMATTER_BLOCK_RE);
|
|
1006
|
-
if (!block) {
|
|
1007
|
-
throw new Error("frontmatter not found in ticket file");
|
|
1008
|
-
}
|
|
1009
|
-
const statusLineRe = /^(\s*status:[ \t]*)(\S+)(.*)$/m;
|
|
1010
|
-
const statusLine = block[1].match(statusLineRe);
|
|
1011
|
-
if (!statusLine) {
|
|
1012
|
-
throw new Error("status field not found in ticket frontmatter");
|
|
1013
|
-
}
|
|
1014
|
-
if (statusLine[2] === targetStatus) {
|
|
1015
|
-
return { content, changed: false };
|
|
1016
|
-
}
|
|
1017
|
-
const newFrontmatter = block[1].replace(statusLineRe, (_m, prefix, _old, suffix) => `${prefix}${targetStatus}${suffix}`);
|
|
1018
|
-
const newContent = content.replace(block[1], () => newFrontmatter);
|
|
1019
|
-
return { content: newContent, changed: true };
|
|
1020
|
-
}
|
|
1021
|
-
// close / reject に伴い、対象個票の Frontmatter `status` を昇格・廃止する。
|
|
1022
|
-
// - 個票なし(個票列が `-`)や個票ファイル不在は、エラーにせず処理状態のみで完了する。
|
|
1023
|
-
// - `ready` への昇格は必須節に `_TODO_` が残っていないことを条件とし、残る場合は警告して据え置く。
|
|
1024
|
-
export function updateTicketStatusForItem(opts) {
|
|
1025
|
-
const filename = parseTicketFilename(opts.item.ticket);
|
|
1026
|
-
if (!filename)
|
|
1027
|
-
return;
|
|
1028
|
-
const ticketPath = join(opts.paths.projectRegisterPath, filename);
|
|
1029
|
-
if (!existsSync(ticketPath)) {
|
|
1030
|
-
process.stdout.write(`Warning: ticket file not found; skipped status update for ${opts.item.id}: ${ticketPath}\n`);
|
|
1031
|
-
return;
|
|
1032
|
-
}
|
|
1033
|
-
const content = readFileSync(ticketPath, "utf8");
|
|
1034
|
-
if (opts.targetStatus === "ready" && ticketBodyHasTodo(content)) {
|
|
1035
|
-
process.stdout.write(`Warning: ${opts.item.id} ticket has unresolved _TODO_; kept as draft (not promoted to ready): ${ticketPath}\n`);
|
|
1036
|
-
return;
|
|
1037
|
-
}
|
|
1038
|
-
const { content: updated, changed } = updateTicketFrontmatterStatus(content, opts.targetStatus);
|
|
1039
|
-
if (!changed) {
|
|
1040
|
-
if (opts.dryRun) {
|
|
1041
|
-
process.stdout.write(`Ticket already ${opts.targetStatus}: ${ticketPath}\n`);
|
|
1042
|
-
}
|
|
1043
|
-
return;
|
|
1044
|
-
}
|
|
1045
|
-
if (opts.dryRun) {
|
|
1046
|
-
process.stdout.write(`Would update ticket status → ${opts.targetStatus}: ${ticketPath}\n`);
|
|
1047
|
-
return;
|
|
1048
|
-
}
|
|
1049
|
-
atomicWriteFile(ticketPath, updated);
|
|
1050
|
-
process.stdout.write(`Updated ticket status → ${opts.targetStatus}: ${ticketPath}\n`);
|
|
1051
|
-
}
|
|
1052
|
-
// ================================
|
|
1053
|
-
// Renumber (duplicate ID recovery)
|
|
1054
|
-
// ================================
|
|
1055
|
-
function escapeRegExp(text) {
|
|
1056
|
-
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1057
|
-
}
|
|
1058
|
-
// 個票ファイル名 `pjr-XXXX-<topic>.md` から topic を取り出す。
|
|
1059
|
-
// ID 接頭辞(`pjr-xxxx-`)と一致しない場合は undefined。
|
|
1060
|
-
export function ticketTopicFromFilename(id, filename) {
|
|
1061
|
-
const prefix = `${id.toLowerCase()}-`;
|
|
1062
|
-
const base = filename.replace(/\.md$/, "");
|
|
1063
|
-
if (!base.startsWith(prefix))
|
|
1064
|
-
return undefined;
|
|
1065
|
-
const topic = base.slice(prefix.length);
|
|
1066
|
-
return topic.length > 0 ? topic : undefined;
|
|
1067
|
-
}
|
|
1068
|
-
// pjr-index の登録項目一覧テーブルで fromId の行を updated へ差し替える。
|
|
1069
|
-
// replaceRowInContent は「同一 ID を書き戻す」用途で updated.id と一致する行を探すため、
|
|
1070
|
-
// ID を変える再採番には fromId で行を特定する専用処理を使う。
|
|
1071
|
-
function renumberRowInContent(content, fromId, updated) {
|
|
1072
|
-
const newRow = formatTableRow(updated);
|
|
1073
|
-
const lines = content.split("\n");
|
|
1074
|
-
let inSection = false;
|
|
1075
|
-
for (let i = 0; i < lines.length; i++) {
|
|
1076
|
-
const line = lines[i];
|
|
1077
|
-
if (REGISTER_SECTION_RE.test(line)) {
|
|
1078
|
-
inSection = true;
|
|
1079
|
-
continue;
|
|
1080
|
-
}
|
|
1081
|
-
if (inSection && /^## /.test(line))
|
|
1082
|
-
break;
|
|
1083
|
-
if (!inSection)
|
|
1084
|
-
continue;
|
|
1085
|
-
if (!line.startsWith("|") || isTableSeparator(line))
|
|
1086
|
-
continue;
|
|
1087
|
-
const cells = parseTableCells(line);
|
|
1088
|
-
if (cells.length >= 1 && cells[0] === fromId) {
|
|
1089
|
-
lines[i] = newRow;
|
|
1090
|
-
return lines.join("\n");
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
throw new Error(`Item ${fromId} not found in table`);
|
|
1094
|
-
}
|
|
1095
|
-
// 個票本文の再採番。frontmatter の doc id 断片(`:pjr-XXXX-<topic>`)と
|
|
1096
|
-
// H1 の表示 ID(`# PJR-XXXX ...`)を新しい ID へ更新する。
|
|
1097
|
-
export function renumberTicketContent(content, fromId, toId, topic) {
|
|
1098
|
-
const fromFragment = `:${fromId.toLowerCase()}-${topic}`;
|
|
1099
|
-
const toFragment = `:${toId.toLowerCase()}-${topic}`;
|
|
1100
|
-
let updated = content.split(fromFragment).join(toFragment);
|
|
1101
|
-
updated = updated.replace(new RegExp(`^(#\\s+)${escapeRegExp(fromId)}(\\s|$)`, "m"), (_m, prefix, tail) => `${prefix}${toId}${tail}`);
|
|
1102
|
-
return updated;
|
|
1103
|
-
}
|
|
1104
|
-
// 他文書からの参照リンク(wikilink `[[<docId>|...]]`)と
|
|
1105
|
-
// exec plan / result の `targets` に含まれる doc id を新しい doc id へ置き換える。
|
|
1106
|
-
export function renumberReferences(content, fromDocId, toDocId) {
|
|
1107
|
-
if (!content.includes(fromDocId))
|
|
1108
|
-
return { content, changed: false };
|
|
1109
|
-
return { content: content.split(fromDocId).join(toDocId), changed: true };
|
|
1110
|
-
}
|
|
1111
|
-
// topic 変更で書き換える全ファイルを事前に算出する。参照の更新範囲は renumber と
|
|
1112
|
-
// 同じく docs/ja 配下(生成物を除く)とし、文書 ID を含む wikilink / targets を
|
|
1113
|
-
// 付け替える。衝突や個票 ID の不整合は、書き込み前に検出する。
|
|
1114
|
-
export function planRetopic(paths, id, topic) {
|
|
1115
|
-
if (!PJR_ID_RE.test(id)) {
|
|
1116
|
-
throw new Error(`Invalid ID: "${id}". Must match PJR-XXXX (e.g., PJR-0001)`);
|
|
1117
|
-
}
|
|
1118
|
-
if (!REGISTER_TOPIC_RE.test(topic)) {
|
|
1119
|
-
throw new Error(`Invalid topic: "${topic}". Must use lowercase letters, numbers, and single hyphens`);
|
|
1120
|
-
}
|
|
1121
|
-
const view = loadItemForUpdate(paths, id);
|
|
1122
|
-
const oldFilename = view.ticketFilename;
|
|
1123
|
-
if (!oldFilename || !view.ticketPath) {
|
|
1124
|
-
throw new Error(`Item ${id} has no ticket file to change topic`);
|
|
1125
|
-
}
|
|
1126
|
-
const fromTopic = ticketTopicFromFilename(id, oldFilename);
|
|
1127
|
-
if (!fromTopic) {
|
|
1128
|
-
throw new Error(`Ticket filename "${oldFilename}" does not match ID "${id}"; fix it before changing topic.`);
|
|
1129
|
-
}
|
|
1130
|
-
const fromDocId = `${paths.projectId}:${oldFilename.replace(/\.md$/, "")}`;
|
|
1131
|
-
const newFilename = `${id.toLowerCase()}-${topic}.md`;
|
|
1132
|
-
const toDocId = `${paths.projectId}:${newFilename.replace(/\.md$/, "")}`;
|
|
1133
|
-
const newTicketPath = join(paths.projectRegisterPath, newFilename);
|
|
1134
|
-
const ticketContent = readFileSync(view.ticketPath, "utf8");
|
|
1135
|
-
const currentDocId = parseSpecdojoDocument(ticketContent).data.id;
|
|
1136
|
-
if (currentDocId !== fromDocId) {
|
|
1137
|
-
throw new Error(`Ticket ${oldFilename} must have frontmatter id "${fromDocId}" before changing topic`);
|
|
1138
|
-
}
|
|
1139
|
-
if (existsSync(newTicketPath)) {
|
|
1140
|
-
throw new Error(`Target ticket file already exists: ${newTicketPath}`);
|
|
1141
|
-
}
|
|
1142
|
-
const writes = [
|
|
1143
|
-
{
|
|
1144
|
-
path: newTicketPath,
|
|
1145
|
-
content: renumberReferences(ticketContent, fromDocId, toDocId).content,
|
|
1146
|
-
},
|
|
1147
|
-
];
|
|
1148
|
-
const root = specdojoRootDir();
|
|
1149
|
-
const referenceFiles = fg
|
|
1150
|
-
.sync("docs/ja/**/*.md", { cwd: root, absolute: true, ignore: ["**/generated/**"] })
|
|
1151
|
-
.sort((a, b) => a.localeCompare(b));
|
|
1152
|
-
for (const absPath of referenceFiles) {
|
|
1153
|
-
if (absPath === view.ticketPath)
|
|
1154
|
-
continue;
|
|
1155
|
-
const content = readFileSync(absPath, "utf8");
|
|
1156
|
-
const referenceUpdate = renumberReferences(content, fromDocId, toDocId);
|
|
1157
|
-
// 旧構成の pjr-index に登録項目行が残っている場合は、文書 ID だけでなく個票リンクの
|
|
1158
|
-
// ファイル名も追随させる。現行の generated ビューは適用後に再生成する。
|
|
1159
|
-
const replaced = absPath === paths.pjrIndexPath
|
|
1160
|
-
? referenceUpdate.content.split(oldFilename).join(newFilename)
|
|
1161
|
-
: referenceUpdate.content;
|
|
1162
|
-
if (referenceUpdate.changed || replaced !== content) {
|
|
1163
|
-
writes.push({ path: absPath, content: replaced });
|
|
1164
|
-
}
|
|
1165
|
-
}
|
|
1166
|
-
return {
|
|
1167
|
-
writes,
|
|
1168
|
-
ticketRename: { from: view.ticketPath, to: newTicketPath },
|
|
1169
|
-
fromTopic,
|
|
1170
|
-
fromDocId,
|
|
1171
|
-
toDocId,
|
|
1172
|
-
};
|
|
1173
|
-
}
|
|
1174
|
-
export function retopicPjrItem(opts) {
|
|
1175
|
-
const plan = planRetopic(opts.paths, opts.id, opts.topic);
|
|
1176
|
-
const ticketWrite = plan.writes.find((write) => write.path === plan.ticketRename.to);
|
|
1177
|
-
if (!ticketWrite)
|
|
1178
|
-
throw new Error(`Retopiced ticket content not found: ${plan.ticketRename.to}`);
|
|
1179
|
-
if (opts.title !== undefined)
|
|
1180
|
-
ticketWrite.content = setRegisterItemTitle(ticketWrite.content, opts.title);
|
|
1181
|
-
if (opts.description !== undefined) {
|
|
1182
|
-
ticketWrite.content = setRegisterItemDescription(ticketWrite.content, opts.description);
|
|
1183
|
-
}
|
|
1184
|
-
ticketWrite.content = applyRegisterItemFields(ticketWrite.content, registerItemFieldsFromItem(opts.updated));
|
|
1185
|
-
if (opts.dryRun) {
|
|
1186
|
-
process.stdout.write(`Would change topic for ${opts.id}: ${plan.fromTopic} → ${opts.topic}\n`);
|
|
1187
|
-
process.stdout.write(` Rename: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
|
|
1188
|
-
for (const write of plan.writes)
|
|
1189
|
-
process.stdout.write(` Update: ${write.path}\n`);
|
|
1190
|
-
return;
|
|
1191
|
-
}
|
|
1192
|
-
const beforeContent = readFileSync(plan.ticketRename.from, "utf8");
|
|
1193
|
-
const event = buildRegisterEvent({
|
|
1194
|
-
beforeContent,
|
|
1195
|
-
afterContent: ticketWrite.content,
|
|
1196
|
-
filename: basename(plan.ticketRename.to),
|
|
1197
|
-
timeZone: opts.paths.registerDateTimeZone,
|
|
1198
|
-
action: "update",
|
|
1199
|
-
actor: opts.actor?.trim() || "manual",
|
|
1200
|
-
reason: opts.reason?.trim() || `topic changed from ${plan.fromTopic} to ${opts.topic}`,
|
|
1201
|
-
extraChanges: [{ field: "id", from: plan.fromDocId, to: plan.toDocId }],
|
|
1202
|
-
});
|
|
1203
|
-
if (!event)
|
|
1204
|
-
throw new Error(`Failed to build topic update event for ${opts.id}`);
|
|
1205
|
-
const eventWrite = prepareRegisterEventFile(opts.paths.projectRegisterPath, opts.id, event);
|
|
1206
|
-
for (const write of plan.writes) {
|
|
1207
|
-
atomicWriteFile(write.path, write.content);
|
|
1208
|
-
process.stdout.write(`Updated: ${write.path}\n`);
|
|
1209
|
-
}
|
|
1210
|
-
unlinkSync(plan.ticketRename.from);
|
|
1211
|
-
process.stdout.write(`Renamed: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
|
|
1212
|
-
atomicWriteFile(eventWrite.path, eventWrite.content);
|
|
1213
|
-
process.stdout.write(`Updated: ${eventWrite.path}\n`);
|
|
1214
|
-
for (const view of writeDerivedViews(opts.paths, "all")) {
|
|
1215
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
1216
|
-
}
|
|
1217
|
-
}
|
|
1218
|
-
// 再採番で書き換える全ファイルを事前に算出する。
|
|
1219
|
-
// 途中で衝突・不整合を検出したら例外を投げ、部分適用が起きないようにする。
|
|
1220
|
-
export function planRenumber(paths, fromId, toId) {
|
|
1221
|
-
const views = loadRegisterItems(paths);
|
|
1222
|
-
const fromView = findRegisterItem(views, fromId);
|
|
1223
|
-
if (!fromView) {
|
|
1224
|
-
throw new Error(`Item not found: ${fromId}`);
|
|
1225
|
-
}
|
|
1226
|
-
if (findRegisterItem(views, toId)) {
|
|
1227
|
-
throw new Error(`Target ID already exists: ${toId}`);
|
|
1228
|
-
}
|
|
1229
|
-
const fromItem = fromView.item;
|
|
1230
|
-
const writes = [];
|
|
1231
|
-
let ticketRename;
|
|
1232
|
-
// pjr-index に旧 ID の行が残っている場合だけ、その行も新しい ID へ差し替える。
|
|
1233
|
-
const hasIndexRow = existsSync(paths.pjrIndexPath) &&
|
|
1234
|
-
parsePjrIndex(readFileSync(paths.pjrIndexPath, "utf8"), paths.registerDateTimeZone).some((it) => it.id === fromId);
|
|
1235
|
-
let newIndexContent = hasIndexRow ? readFileSync(paths.pjrIndexPath, "utf8") : "";
|
|
1236
|
-
const oldFilename = fromView.ticketFilename;
|
|
1237
|
-
let fromDocId;
|
|
1238
|
-
let toDocId;
|
|
1239
|
-
if (oldFilename) {
|
|
1240
|
-
const topic = ticketTopicFromFilename(fromId, oldFilename);
|
|
1241
|
-
if (!topic) {
|
|
1242
|
-
throw new Error(`Ticket filename "${oldFilename}" does not match ID "${fromId}"; ` +
|
|
1243
|
-
`fix the ticket link before renumbering.`);
|
|
1244
|
-
}
|
|
1245
|
-
const newFilename = `${toId.toLowerCase()}-${topic}.md`;
|
|
1246
|
-
const oldTicketPath = join(paths.projectRegisterPath, oldFilename);
|
|
1247
|
-
const newTicketPath = join(paths.projectRegisterPath, newFilename);
|
|
1248
|
-
if (!existsSync(oldTicketPath)) {
|
|
1249
|
-
throw new Error(`Ticket file not found: ${oldTicketPath}`);
|
|
1250
|
-
}
|
|
1251
|
-
if (existsSync(newTicketPath)) {
|
|
1252
|
-
throw new Error(`Target ticket file already exists: ${newTicketPath}`);
|
|
1253
|
-
}
|
|
1254
|
-
fromDocId = `${paths.projectId}:${oldFilename.replace(/\.md$/, "")}`;
|
|
1255
|
-
toDocId = `${paths.projectId}:${newFilename.replace(/\.md$/, "")}`;
|
|
1256
|
-
const ticketContent = readFileSync(oldTicketPath, "utf8");
|
|
1257
|
-
writes.push({
|
|
1258
|
-
path: newTicketPath,
|
|
1259
|
-
content: renumberTicketContent(ticketContent, fromId, toId, topic),
|
|
1260
|
-
});
|
|
1261
|
-
ticketRename = { from: oldTicketPath, to: newTicketPath };
|
|
1262
|
-
if (hasIndexRow) {
|
|
1263
|
-
const updated = { ...fromItem, id: toId, ticket: ticketRefCell(newFilename) };
|
|
1264
|
-
newIndexContent = renumberRowInContent(newIndexContent, fromId, toDisplayItem(updated, paths.registerDateTimeZone));
|
|
1265
|
-
}
|
|
1266
|
-
}
|
|
1267
|
-
else if (hasIndexRow) {
|
|
1268
|
-
const updated = { ...fromItem, id: toId };
|
|
1269
|
-
newIndexContent = renumberRowInContent(newIndexContent, fromId, toDisplayItem(updated, paths.registerDateTimeZone));
|
|
1270
|
-
}
|
|
1271
|
-
if (hasIndexRow) {
|
|
1272
|
-
writes.push({ path: paths.pjrIndexPath, content: newIndexContent });
|
|
1273
|
-
}
|
|
1274
|
-
// 参照リンク・targets の付け替え(doc id を持つ個票がある場合のみ)。
|
|
1275
|
-
if (fromDocId && toDocId) {
|
|
1276
|
-
const root = specdojoRootDir();
|
|
1277
|
-
const referenceFiles = fg
|
|
1278
|
-
.sync("docs/ja/**/*.md", { cwd: root, absolute: true, ignore: ["**/generated/**"] })
|
|
1279
|
-
.sort((a, b) => a.localeCompare(b));
|
|
1280
|
-
for (const absPath of referenceFiles) {
|
|
1281
|
-
if (absPath === paths.pjrIndexPath)
|
|
1282
|
-
continue;
|
|
1283
|
-
if (ticketRename && absPath === ticketRename.from)
|
|
1284
|
-
continue;
|
|
1285
|
-
const content = readFileSync(absPath, "utf8");
|
|
1286
|
-
const { content: replaced, changed } = renumberReferences(content, fromDocId, toDocId);
|
|
1287
|
-
if (changed)
|
|
1288
|
-
writes.push({ path: absPath, content: replaced });
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
|
-
return { writes, ticketRename };
|
|
1292
|
-
}
|
|
1293
|
-
export function renumberPjrItem(opts) {
|
|
1294
|
-
const { paths, fromId, toId, dryRun } = opts;
|
|
1295
|
-
for (const id of [fromId, toId]) {
|
|
1296
|
-
if (!PJR_ID_RE.test(id)) {
|
|
1297
|
-
throw new Error(`Invalid ID: "${id}". Must match PJR-XXXX (e.g., PJR-0001)`);
|
|
1298
|
-
}
|
|
1299
|
-
}
|
|
1300
|
-
if (fromId === toId) {
|
|
1301
|
-
throw new Error(`--id and --to must differ (both are ${fromId})`);
|
|
1302
|
-
}
|
|
1303
|
-
const plan = planRenumber(paths, fromId, toId);
|
|
1304
|
-
if (!dryRun && plan.ticketRename) {
|
|
1305
|
-
const ticketWrite = plan.writes.find((write) => write.path === plan.ticketRename?.to);
|
|
1306
|
-
if (!ticketWrite)
|
|
1307
|
-
throw new Error(`Renumbered ticket content not found: ${plan.ticketRename.to}`);
|
|
1308
|
-
const beforeContent = readFileSync(plan.ticketRename.from, "utf8");
|
|
1309
|
-
const event = buildRegisterEvent({
|
|
1310
|
-
beforeContent,
|
|
1311
|
-
afterContent: ticketWrite.content,
|
|
1312
|
-
filename: basename(plan.ticketRename.to),
|
|
1313
|
-
timeZone: paths.registerDateTimeZone,
|
|
1314
|
-
action: "renumber",
|
|
1315
|
-
actor: opts.actor?.trim() || "manual",
|
|
1316
|
-
reason: opts.reason?.trim() || `renumbered ${fromId} to ${toId}`,
|
|
1317
|
-
extraChanges: [{ field: "id", from: fromId, to: toId }],
|
|
1318
|
-
});
|
|
1319
|
-
if (!event)
|
|
1320
|
-
throw new Error(`Failed to build renumber event for ${fromId}`);
|
|
1321
|
-
const oldEventPath = registerEventFilePath(paths.projectRegisterPath, fromId);
|
|
1322
|
-
const newEventPath = registerEventFilePath(paths.projectRegisterPath, toId);
|
|
1323
|
-
if (!existsSync(oldEventPath)) {
|
|
1324
|
-
throw new Error(`Register event file not found: ${oldEventPath}`);
|
|
1325
|
-
}
|
|
1326
|
-
if (existsSync(newEventPath)) {
|
|
1327
|
-
throw new Error(`Target register event file already exists: ${newEventPath}`);
|
|
1328
|
-
}
|
|
1329
|
-
const eventContent = appendRegisterEvent(readFileSync(oldEventPath, "utf8"), event);
|
|
1330
|
-
plan.writes.push({ path: newEventPath, content: eventContent });
|
|
1331
|
-
}
|
|
1332
|
-
if (dryRun) {
|
|
1333
|
-
process.stdout.write(`Would renumber ${fromId} → ${toId}:\n`);
|
|
1334
|
-
if (plan.ticketRename) {
|
|
1335
|
-
process.stdout.write(` Rename: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
|
|
1336
|
-
}
|
|
1337
|
-
for (const write of plan.writes) {
|
|
1338
|
-
process.stdout.write(` Update: ${write.path}\n`);
|
|
1339
|
-
}
|
|
1340
|
-
return;
|
|
1341
|
-
}
|
|
1342
|
-
for (const write of plan.writes) {
|
|
1343
|
-
atomicWriteFile(write.path, write.content);
|
|
1344
|
-
process.stdout.write(`Updated: ${write.path}\n`);
|
|
1345
|
-
}
|
|
1346
|
-
if (plan.ticketRename) {
|
|
1347
|
-
unlinkSync(plan.ticketRename.from);
|
|
1348
|
-
process.stdout.write(`Renamed: ${plan.ticketRename.from} → ${plan.ticketRename.to}\n`);
|
|
1349
|
-
const oldEventPath = registerEventFilePath(paths.projectRegisterPath, fromId);
|
|
1350
|
-
unlinkSync(oldEventPath);
|
|
1351
|
-
process.stdout.write(`Renamed: ${oldEventPath} → ${registerEventFilePath(paths.projectRegisterPath, toId)}\n`);
|
|
1352
|
-
}
|
|
1353
|
-
for (const view of writeDerivedViews(paths, "all")) {
|
|
1354
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
1355
|
-
}
|
|
1356
|
-
}
|
|
22
|
+
export { REGISTER_TOPIC_RE, VALID_TICKET_STATUSES, buildRegisterItemContent, extractTableHeading, findMarkdownReferenceFiles, generatePjrId, injectRegisterRows, parsePjrIndex, resolveRegisterPaths, } from "./register-core.js";
|
|
23
|
+
export { applyRegisterMigrationPlan, planRegisterMigration, } from "./register-migration.js";
|
|
24
|
+
export { findItemById, findRegisterItem, generateDerivedViewFiles, injectViewSlots, loadRegisterItems, sortByRegisteredDesc, } from "./register-views.js";
|
|
25
|
+
export { parseTicketFilename, updateTicketFrontmatterStatus, updateTicketStatusForItem, } from "./register-update.js";
|
|
26
|
+
export { planRenumber, planRetopic, renumberPjrItem, renumberReferences, renumberTicketContent, retopicPjrItem, ticketTopicFromFilename, } from "./register-renumber.js";
|
|
1357
27
|
// 作成する個票ファイル名と割り当て ID を算出する純粋関数。I/O を持たず、
|
|
1358
28
|
// フィールド検証と ID 衝突検知だけを行う。ID を省略するとランダムに採番する。
|
|
1359
29
|
export function planRegisterItem(opts) {
|
|
@@ -1386,6 +56,117 @@ export function printCommandError(error) {
|
|
|
1386
56
|
function addProjectOption(cmd) {
|
|
1387
57
|
return cmd.option("--project <projectId>", "Project id in specdojo.config.json");
|
|
1388
58
|
}
|
|
59
|
+
function assertRegisterItemCommitTargetsClean(context, view) {
|
|
60
|
+
if (!view.ticketPath)
|
|
61
|
+
return;
|
|
62
|
+
context.assertCommitTargetsClean([
|
|
63
|
+
view.ticketPath,
|
|
64
|
+
registerEventFilePath(context.paths.projectRegisterPath, view.id),
|
|
65
|
+
]);
|
|
66
|
+
}
|
|
67
|
+
function addRegisterCommitOptions(cmd) {
|
|
68
|
+
return cmd
|
|
69
|
+
.option("--commit", "Take the register lifecycle lock, rebuild views, and commit only this command's changes", false)
|
|
70
|
+
.option("-m, --message <message>", "Override the register commit message");
|
|
71
|
+
}
|
|
72
|
+
const REGISTER_COMMIT_SUBJECT_MAX_LENGTH = 100;
|
|
73
|
+
const REGISTER_COMMIT_STABILIZATION_ATTEMPTS = 3;
|
|
74
|
+
function defaultRegisterCommitMessage(command, result) {
|
|
75
|
+
const prefix = `docs(register ${result.id}): ${command} `;
|
|
76
|
+
const flatTitle = result.title.replace(/\s+/g, " ").trim();
|
|
77
|
+
const subject = `${prefix}${flatTitle}`;
|
|
78
|
+
if (subject.length <= REGISTER_COMMIT_SUBJECT_MAX_LENGTH)
|
|
79
|
+
return subject;
|
|
80
|
+
return `${subject.slice(0, REGISTER_COMMIT_SUBJECT_MAX_LENGTH - 1)}…`;
|
|
81
|
+
}
|
|
82
|
+
function rebuildRegisterViews(paths) {
|
|
83
|
+
const validation = validateRegisterItemDocs(paths.projectRegisterPath);
|
|
84
|
+
const eventErrors = validateRegisterEventDocs(paths.projectRegisterPath, paths.registerDateTimeZone);
|
|
85
|
+
if (validation.errors.length > 0 || eventErrors.length > 0) {
|
|
86
|
+
throw new Error(`Invalid register item files:\n${[...validation.errors, ...eventErrors].join("\n")}`);
|
|
87
|
+
}
|
|
88
|
+
writeDerivedViews(paths, "all");
|
|
89
|
+
}
|
|
90
|
+
function isGeneratedRegisterPath(repoRoot, paths, path) {
|
|
91
|
+
const normalized = path.replaceAll("\\", "/");
|
|
92
|
+
const generatedPrefixes = [paths.generatedPath, paths.controlsGeneratedPath].map((target) => `${repoRelative(repoRoot, target)}/`);
|
|
93
|
+
return (normalized === ".specdojo/doc-index.json" ||
|
|
94
|
+
generatedPrefixes.some((prefix) => normalized.startsWith(prefix)));
|
|
95
|
+
}
|
|
96
|
+
function commitRegisterMutation(repoRoot, paths, command, result, preexisting, message) {
|
|
97
|
+
const changed = worktreeStatusPaths(repoRoot).filter((path) => !preexisting.has(path) && !isGeneratedRegisterPath(repoRoot, paths, path));
|
|
98
|
+
if (changed.length === 0) {
|
|
99
|
+
process.stdout.write(`No register changes to commit for ${result.id}.\n`);
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
stageCommitTargets(repoRoot, changed);
|
|
103
|
+
const staged = gitResult(repoRoot, ["diff", "--cached", "--quiet", "--", ...changed]);
|
|
104
|
+
if (staged.status === 0) {
|
|
105
|
+
process.stdout.write(`No register changes to commit for ${result.id}.\n`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
if (staged.status !== 1)
|
|
109
|
+
throw new Error("Failed to inspect staged register changes.");
|
|
110
|
+
const commitMessage = message?.trim() || defaultRegisterCommitMessage(command, result);
|
|
111
|
+
if (commitMessage === "")
|
|
112
|
+
throw new Error("Register commit message must not be empty");
|
|
113
|
+
gitOutput(repoRoot, ["commit", "-m", commitMessage, "--", ...changed]);
|
|
114
|
+
for (let attempt = 0; attempt < REGISTER_COMMIT_STABILIZATION_ATTEMPTS; attempt++) {
|
|
115
|
+
const remaining = worktreeStatusPaths(repoRoot).filter((path) => changed.includes(path));
|
|
116
|
+
if (remaining.length === 0) {
|
|
117
|
+
const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
|
|
118
|
+
process.stdout.write(`Committed: ${sha} (${result.id})\n`);
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
stageCommitTargets(repoRoot, remaining);
|
|
122
|
+
gitOutput(repoRoot, ["commit", "--amend", "--no-edit", "--", ...remaining]);
|
|
123
|
+
}
|
|
124
|
+
const remaining = worktreeStatusPaths(repoRoot).filter((path) => changed.includes(path));
|
|
125
|
+
if (remaining.length === 0) {
|
|
126
|
+
const sha = gitOutput(repoRoot, ["rev-parse", "--short", "HEAD"]).trim();
|
|
127
|
+
process.stdout.write(`Committed: ${sha} (${result.id})\n`);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
throw new Error(`Register commit incomplete: target paths remained dirty after hook stabilization:\n` +
|
|
131
|
+
remaining.map((path) => ` ${path}`).join("\n"));
|
|
132
|
+
}
|
|
133
|
+
async function runRegisterMutation(command, opts, mutate) {
|
|
134
|
+
try {
|
|
135
|
+
const paths = resolveRegisterPaths(opts);
|
|
136
|
+
if (!opts.commit || opts.dryRun) {
|
|
137
|
+
mutate({ paths, assertCommitTargetsClean: () => undefined });
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
const repoRoot = specdojoRootDir();
|
|
141
|
+
if (!paths.executionPath) {
|
|
142
|
+
throw new Error(`Execution path is not configured for project ${paths.projectId}`);
|
|
143
|
+
}
|
|
144
|
+
const mutex = new CrossProcessMutex(execLifecyclePoolPath(paths.executionPath), {
|
|
145
|
+
actor: registerEventActor(opts),
|
|
146
|
+
label: `register ${command}`,
|
|
147
|
+
}, {
|
|
148
|
+
onWait: () => process.stdout.write("Waiting for the register lifecycle lock held by another operation\n"),
|
|
149
|
+
});
|
|
150
|
+
await mutex.runExclusive(() => {
|
|
151
|
+
const preexisting = new Set(worktreeStatusPaths(repoRoot));
|
|
152
|
+
const assertCommitTargetsClean = (targets) => {
|
|
153
|
+
const overlapping = targets
|
|
154
|
+
.map((target) => repoRelative(repoRoot, target))
|
|
155
|
+
.filter((target) => preexisting.has(target));
|
|
156
|
+
if (overlapping.length === 0)
|
|
157
|
+
return;
|
|
158
|
+
throw new Error(`Cannot use --commit because register targets already have uncommitted changes:\n` +
|
|
159
|
+
overlapping.map((path) => ` ${path}`).join("\n"));
|
|
160
|
+
};
|
|
161
|
+
const result = mutate({ paths, assertCommitTargetsClean });
|
|
162
|
+
rebuildRegisterViews(paths);
|
|
163
|
+
commitRegisterMutation(repoRoot, paths, command, result, preexisting, opts.message);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
catch (error) {
|
|
167
|
+
printCommandError(error);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
1389
170
|
// CLI で明示された日時オプションを UTC の秒精度へ正規化する。未指定は undefined を返し、
|
|
1390
171
|
// 呼び出し側の既定値(実行時刻・プレースホルダ)へ委ねる。
|
|
1391
172
|
function parseRegisterTimestampOption(value, label, placeholder) {
|
|
@@ -1573,627 +354,46 @@ function migrateRegisterEventsFromGit(paths, dryRun) {
|
|
|
1573
354
|
// ================================
|
|
1574
355
|
// Command Registration
|
|
1575
356
|
// ================================
|
|
357
|
+
const REGISTER_COMMAND_DEPENDENCIES = {
|
|
358
|
+
registerTopicPattern: REGISTER_TOPIC_RE,
|
|
359
|
+
validBuildScopes: VALID_BUILD_SCOPES,
|
|
360
|
+
addProjectOption,
|
|
361
|
+
addRegisterCommitOptions,
|
|
362
|
+
applyItemUpdate,
|
|
363
|
+
applyRegisterMigrationPlan,
|
|
364
|
+
assertRegisterItemCommitTargetsClean,
|
|
365
|
+
assertTerminalOperationAllowed,
|
|
366
|
+
atomicWriteFile,
|
|
367
|
+
buildRegisterItemContent,
|
|
368
|
+
derivedTopicNeedsWarning,
|
|
369
|
+
generateDerivedViewFiles,
|
|
370
|
+
loadItemForUpdate,
|
|
371
|
+
loadRegisterItems,
|
|
372
|
+
migrateEmbeddedRegisterEvents,
|
|
373
|
+
migrateRegisterEventsFromGit,
|
|
374
|
+
parseHistoryIds,
|
|
375
|
+
parseRegisterTimestampOption,
|
|
376
|
+
planRegisterItem,
|
|
377
|
+
planRegisterMigration,
|
|
378
|
+
planRenumber,
|
|
379
|
+
planRetopic,
|
|
380
|
+
printCommandError,
|
|
381
|
+
printDerivedTopicWarning,
|
|
382
|
+
registerEventActor,
|
|
383
|
+
renumberPjrItem,
|
|
384
|
+
repoRelativePathspec,
|
|
385
|
+
resolveRegisterPaths,
|
|
386
|
+
retopicPjrItem,
|
|
387
|
+
runRegisterMutation,
|
|
388
|
+
slugify,
|
|
389
|
+
ticketTopicFromFilename,
|
|
390
|
+
updateTicketStatusForItem,
|
|
391
|
+
writeDerivedViews,
|
|
392
|
+
};
|
|
1576
393
|
export function registerRegisterCommands(program) {
|
|
1577
394
|
const reg = program.command("register").description("Project register (pjr-index.md) commands");
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
.command("scaffold")
|
|
1583
|
-
.description("Initialize the register directory and generate its views");
|
|
1584
|
-
addProjectOption(scaffoldCmd);
|
|
1585
|
-
scaffoldCmd.option("--dry-run", "Print generated content to stdout without writing", false);
|
|
1586
|
-
scaffoldCmd.action((opts) => {
|
|
1587
|
-
try {
|
|
1588
|
-
const paths = resolveRegisterPaths(opts);
|
|
1589
|
-
if (opts.dryRun) {
|
|
1590
|
-
for (const view of generateDerivedViewFiles(paths, "all")) {
|
|
1591
|
-
process.stdout.write(`=== ${view.path} ===\n${view.content}\n\n`);
|
|
1592
|
-
}
|
|
1593
|
-
return;
|
|
1594
|
-
}
|
|
1595
|
-
mkdirSync(paths.projectRegisterPath, { recursive: true });
|
|
1596
|
-
process.stdout.write(`Created: ${paths.projectRegisterPath}/\n`);
|
|
1597
|
-
for (const view of writeDerivedViews(paths, "all")) {
|
|
1598
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
1599
|
-
}
|
|
1600
|
-
}
|
|
1601
|
-
catch (error) {
|
|
1602
|
-
printCommandError(error);
|
|
1603
|
-
}
|
|
1604
|
-
});
|
|
1605
|
-
// --- add ---
|
|
1606
|
-
const addCmd = reg.command("add").description("Add a new item to pjr-index.md");
|
|
1607
|
-
addProjectOption(addCmd);
|
|
1608
|
-
addCmd.requiredOption("--type <type>", `Item type: ${VALID_TYPES.join(" | ")}`);
|
|
1609
|
-
addCmd.requiredOption("--title <title>", "Short title for the item");
|
|
1610
|
-
addCmd.option("--description <text>", "Description shown in the list", "_TODO_");
|
|
1611
|
-
addCmd.option("--priority <priority>", `Priority: ${VALID_PRIORITIES.join(" | ")}`, "medium");
|
|
1612
|
-
addCmd.option("--status <status>", `Status: ${VALID_STATUSES.join(" | ")}`, "open");
|
|
1613
|
-
addCmd.option("--owner <owner>", "Owner or role", "_TODO_");
|
|
1614
|
-
addCmd.option("--registered <datetime>", "Registration date-time (RFC 3339 with time zone, or _TODO_; defaults to now in UTC)");
|
|
1615
|
-
addCmd.option("--due <date>", "Due date (YYYY-MM-DD, -, or _TODO_)", "_TODO_");
|
|
1616
|
-
addCmd.option("--completed <datetime>", "Completion date-time (RFC 3339 with time zone, or -)", "-");
|
|
1617
|
-
addCmd.option("--conclusion <text>", "Conclusion or resolution summary", "-");
|
|
1618
|
-
addCmd.option("--id <id>", "Display ID (e.g., PJR-0061); auto-incremented if omitted");
|
|
1619
|
-
addCmd.option("--topic <topic>", "Topic slug for ticket filename; derived from --title if omitted");
|
|
1620
|
-
addCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1621
|
-
addCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1622
|
-
addCmd.option("--force", "Overwrite existing ticket file", false);
|
|
1623
|
-
addCmd.option("--dry-run", "Print the generated item file without writing", false);
|
|
1624
|
-
addCmd.action((opts) => {
|
|
1625
|
-
try {
|
|
1626
|
-
const paths = resolveRegisterPaths(opts);
|
|
1627
|
-
const topic = opts.topic?.trim() || slugify(opts.title);
|
|
1628
|
-
if (!REGISTER_TOPIC_RE.test(topic)) {
|
|
1629
|
-
throw new Error(`Invalid topic: "${topic}". Must use lowercase letters, numbers, and single hyphens`);
|
|
1630
|
-
}
|
|
1631
|
-
// 起票日時は明示指定が無ければ実行時刻を採る。明示された場合はタイムゾーン付きの
|
|
1632
|
-
// RFC 3339 を受け付け、UTC の秒精度へ正規化してから保存する。
|
|
1633
|
-
const registeredAt = parseRegisterTimestampOption(opts.registered, "registered", CELL_TODO);
|
|
1634
|
-
const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE);
|
|
1635
|
-
const fields = {
|
|
1636
|
-
type: opts.type,
|
|
1637
|
-
title: opts.title,
|
|
1638
|
-
description: opts.description,
|
|
1639
|
-
priority: opts.priority,
|
|
1640
|
-
status: opts.status,
|
|
1641
|
-
owner: opts.owner,
|
|
1642
|
-
registeredAt: registeredAt ?? nowUtcTimestamp(),
|
|
1643
|
-
due: opts.due,
|
|
1644
|
-
completedAt: completedAt ?? CELL_NONE,
|
|
1645
|
-
conclusion: opts.conclusion,
|
|
1646
|
-
};
|
|
1647
|
-
const templatePath = resolveSpecdojoTemplatePath(`pjr-${opts.type}-template.md`);
|
|
1648
|
-
const { assignedId: displayId, ticketFilename } = planRegisterItem({
|
|
1649
|
-
existingIds: loadRegisterItems(paths).map((view) => view.id),
|
|
1650
|
-
explicitId: opts.id?.trim() || undefined,
|
|
1651
|
-
fields,
|
|
1652
|
-
topic,
|
|
1653
|
-
});
|
|
1654
|
-
const ticketPath = join(paths.projectRegisterPath, ticketFilename);
|
|
1655
|
-
const content = buildRegisterItemContent({
|
|
1656
|
-
projectId: paths.projectId,
|
|
1657
|
-
displayId,
|
|
1658
|
-
topic,
|
|
1659
|
-
fields,
|
|
1660
|
-
templatePath,
|
|
1661
|
-
});
|
|
1662
|
-
const addEvent = buildRegisterEvent({
|
|
1663
|
-
afterContent: content,
|
|
1664
|
-
filename: ticketFilename,
|
|
1665
|
-
timeZone: paths.registerDateTimeZone,
|
|
1666
|
-
action: "add",
|
|
1667
|
-
actor: registerEventActor(opts),
|
|
1668
|
-
reason: opts.reason?.trim() || "item added",
|
|
1669
|
-
});
|
|
1670
|
-
if (!addEvent)
|
|
1671
|
-
throw new Error(`Failed to build add event for ${displayId}`);
|
|
1672
|
-
if (opts.dryRun) {
|
|
1673
|
-
process.stdout.write(`Would create ${ticketPath}:\n${content}\n`);
|
|
1674
|
-
process.stdout.write(`Would create ${registerEventFilePath(paths.projectRegisterPath, displayId)}:\n` +
|
|
1675
|
-
`${appendRegisterEvent(undefined, addEvent)}\n`);
|
|
1676
|
-
return;
|
|
1677
|
-
}
|
|
1678
|
-
if (!opts.force && existsSync(ticketPath)) {
|
|
1679
|
-
throw new Error(`Item file already exists (use --force to overwrite): ${ticketPath}`);
|
|
1680
|
-
}
|
|
1681
|
-
const eventPath = registerEventFilePath(paths.projectRegisterPath, displayId);
|
|
1682
|
-
if (!opts.force && existsSync(eventPath)) {
|
|
1683
|
-
throw new Error(`Register event file already exists (use --force to overwrite): ${eventPath}`);
|
|
1684
|
-
}
|
|
1685
|
-
mkdirSync(paths.projectRegisterPath, { recursive: true });
|
|
1686
|
-
atomicWriteFile(ticketPath, content);
|
|
1687
|
-
atomicWriteFile(eventPath, appendRegisterEvent(undefined, addEvent));
|
|
1688
|
-
process.stdout.write(`Created: ${ticketPath} (added ${displayId})\n`);
|
|
1689
|
-
process.stdout.write(`Created: ${eventPath}\n`);
|
|
1690
|
-
if (existsSync(paths.pjrIndexPath)) {
|
|
1691
|
-
for (const view of writeDerivedViews(paths, "all")) {
|
|
1692
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
1693
|
-
}
|
|
1694
|
-
}
|
|
1695
|
-
}
|
|
1696
|
-
catch (error) {
|
|
1697
|
-
printCommandError(error);
|
|
1698
|
-
}
|
|
1699
|
-
});
|
|
1700
|
-
// --- close ---
|
|
1701
|
-
const closeCmd = reg.command("close").description("Set item status to done or decided");
|
|
1702
|
-
addProjectOption(closeCmd);
|
|
1703
|
-
closeCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1704
|
-
closeCmd.option("--status <status>", "done or decided (auto from item type if omitted)");
|
|
1705
|
-
closeCmd.option("--conclusion <text>", "Conclusion or resolution summary");
|
|
1706
|
-
closeCmd.option("--completed <datetime>", "Completion date-time (RFC 3339 with time zone; defaults to now in UTC)");
|
|
1707
|
-
closeCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1708
|
-
closeCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1709
|
-
closeCmd.option("--dry-run", "Print change without writing", false);
|
|
1710
|
-
closeCmd.action((opts) => {
|
|
1711
|
-
try {
|
|
1712
|
-
const paths = resolveRegisterPaths(opts);
|
|
1713
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1714
|
-
const item = view.item;
|
|
1715
|
-
const targetStatus = opts.status ?? (["decision", "question"].includes(item.type) ? "decided" : "done");
|
|
1716
|
-
if (targetStatus !== "done" && targetStatus !== "decided") {
|
|
1717
|
-
throw new Error(`--status must be "done" or "decided" for the close command`);
|
|
1718
|
-
}
|
|
1719
|
-
const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE) ?? nowUtcTimestamp();
|
|
1720
|
-
if (completedAt === CELL_NONE) {
|
|
1721
|
-
throw new Error(`Invalid completed: "${opts.completed}". A completion date-time is required`);
|
|
1722
|
-
}
|
|
1723
|
-
const updated = {
|
|
1724
|
-
...item,
|
|
1725
|
-
status: targetStatus,
|
|
1726
|
-
completedAt,
|
|
1727
|
-
...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
|
|
1728
|
-
};
|
|
1729
|
-
applyItemUpdate({
|
|
1730
|
-
paths,
|
|
1731
|
-
view,
|
|
1732
|
-
updated,
|
|
1733
|
-
dryRun: opts.dryRun,
|
|
1734
|
-
eventAction: "close",
|
|
1735
|
-
eventActor: registerEventActor(opts),
|
|
1736
|
-
eventReason: opts.reason?.trim() || opts.conclusion?.trim() || `closed as ${targetStatus}`,
|
|
1737
|
-
});
|
|
1738
|
-
updateTicketStatusForItem({ paths, item, targetStatus: "ready", dryRun: opts.dryRun });
|
|
1739
|
-
}
|
|
1740
|
-
catch (error) {
|
|
1741
|
-
printCommandError(error);
|
|
1742
|
-
}
|
|
1743
|
-
});
|
|
1744
|
-
// --- reject ---
|
|
1745
|
-
const rejectCmd = reg.command("reject").description("Set item status to rejected");
|
|
1746
|
-
addProjectOption(rejectCmd);
|
|
1747
|
-
rejectCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1748
|
-
rejectCmd.option("--conclusion <text>", "Reason for rejection");
|
|
1749
|
-
rejectCmd.option("--completed <datetime>", "Rejection date-time (RFC 3339 with time zone; defaults to now in UTC)");
|
|
1750
|
-
rejectCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1751
|
-
rejectCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1752
|
-
rejectCmd.option("--dry-run", "Print change without writing", false);
|
|
1753
|
-
rejectCmd.action((opts) => {
|
|
1754
|
-
try {
|
|
1755
|
-
const paths = resolveRegisterPaths(opts);
|
|
1756
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1757
|
-
const item = view.item;
|
|
1758
|
-
const completedAt = parseRegisterTimestampOption(opts.completed, "completed", CELL_NONE) ?? nowUtcTimestamp();
|
|
1759
|
-
if (completedAt === CELL_NONE) {
|
|
1760
|
-
throw new Error(`Invalid completed: "${opts.completed}". A rejection date-time is required`);
|
|
1761
|
-
}
|
|
1762
|
-
const updated = {
|
|
1763
|
-
...item,
|
|
1764
|
-
status: "rejected",
|
|
1765
|
-
completedAt,
|
|
1766
|
-
...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
|
|
1767
|
-
};
|
|
1768
|
-
applyItemUpdate({
|
|
1769
|
-
paths,
|
|
1770
|
-
view,
|
|
1771
|
-
updated,
|
|
1772
|
-
dryRun: opts.dryRun,
|
|
1773
|
-
eventAction: "reject",
|
|
1774
|
-
eventActor: registerEventActor(opts),
|
|
1775
|
-
eventReason: opts.reason?.trim() || opts.conclusion?.trim() || "item rejected",
|
|
1776
|
-
});
|
|
1777
|
-
updateTicketStatusForItem({ paths, item, targetStatus: "deprecated", dryRun: opts.dryRun });
|
|
1778
|
-
}
|
|
1779
|
-
catch (error) {
|
|
1780
|
-
printCommandError(error);
|
|
1781
|
-
}
|
|
1782
|
-
});
|
|
1783
|
-
// --- defer ---
|
|
1784
|
-
const deferCmd = reg.command("defer").description("Set item status to deferred");
|
|
1785
|
-
addProjectOption(deferCmd);
|
|
1786
|
-
deferCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1787
|
-
deferCmd.option("--conclusion <text>", "Reason for deferral");
|
|
1788
|
-
deferCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1789
|
-
deferCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1790
|
-
deferCmd.option("--dry-run", "Print change without writing", false);
|
|
1791
|
-
deferCmd.action((opts) => {
|
|
1792
|
-
try {
|
|
1793
|
-
const paths = resolveRegisterPaths(opts);
|
|
1794
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1795
|
-
const item = view.item;
|
|
1796
|
-
const updated = {
|
|
1797
|
-
...item,
|
|
1798
|
-
status: "deferred",
|
|
1799
|
-
...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
|
|
1800
|
-
};
|
|
1801
|
-
applyItemUpdate({
|
|
1802
|
-
paths,
|
|
1803
|
-
view,
|
|
1804
|
-
updated,
|
|
1805
|
-
dryRun: opts.dryRun,
|
|
1806
|
-
eventAction: "defer",
|
|
1807
|
-
eventActor: registerEventActor(opts),
|
|
1808
|
-
eventReason: opts.reason?.trim() || opts.conclusion?.trim() || "item deferred",
|
|
1809
|
-
});
|
|
1810
|
-
}
|
|
1811
|
-
catch (error) {
|
|
1812
|
-
printCommandError(error);
|
|
1813
|
-
}
|
|
1814
|
-
});
|
|
1815
|
-
// --- reopen ---
|
|
1816
|
-
const reopenCmd = reg.command("reopen").description("Reopen a terminal-status item");
|
|
1817
|
-
addProjectOption(reopenCmd);
|
|
1818
|
-
reopenCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1819
|
-
reopenCmd.option("--status <status>", "Target status: open | in-progress | waiting | review", "open");
|
|
1820
|
-
reopenCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1821
|
-
reopenCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1822
|
-
reopenCmd.option("--dry-run", "Print change without writing", false);
|
|
1823
|
-
reopenCmd.action((opts) => {
|
|
1824
|
-
try {
|
|
1825
|
-
const paths = resolveRegisterPaths(opts);
|
|
1826
|
-
const view = loadItemForUpdate(paths, opts.id, "require-terminal");
|
|
1827
|
-
const item = view.item;
|
|
1828
|
-
const validReopenStatuses = ["open", "in-progress", "waiting", "review"];
|
|
1829
|
-
if (!validReopenStatuses.includes(opts.status)) {
|
|
1830
|
-
throw new Error(`--status must be one of: ${validReopenStatuses.join(", ")}`);
|
|
1831
|
-
}
|
|
1832
|
-
// reopen は完了日時のキーを取り除き、活動中の項目として扱えるようにする。
|
|
1833
|
-
const updated = { ...item, status: opts.status, completedAt: CELL_NONE };
|
|
1834
|
-
applyItemUpdate({
|
|
1835
|
-
paths,
|
|
1836
|
-
view,
|
|
1837
|
-
updated,
|
|
1838
|
-
dryRun: opts.dryRun,
|
|
1839
|
-
eventAction: "reopen",
|
|
1840
|
-
eventActor: registerEventActor(opts),
|
|
1841
|
-
eventReason: opts.reason?.trim() || `reopened as ${opts.status}`,
|
|
1842
|
-
});
|
|
1843
|
-
}
|
|
1844
|
-
catch (error) {
|
|
1845
|
-
printCommandError(error);
|
|
1846
|
-
}
|
|
1847
|
-
});
|
|
1848
|
-
// --- start ---
|
|
1849
|
-
const startCmd = reg.command("start").description("Set item status to in-progress");
|
|
1850
|
-
addProjectOption(startCmd);
|
|
1851
|
-
startCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1852
|
-
startCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1853
|
-
startCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1854
|
-
startCmd.option("--dry-run", "Print change without writing", false);
|
|
1855
|
-
startCmd.action((opts) => {
|
|
1856
|
-
try {
|
|
1857
|
-
const paths = resolveRegisterPaths(opts);
|
|
1858
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1859
|
-
const item = view.item;
|
|
1860
|
-
const updated = { ...item, status: "in-progress" };
|
|
1861
|
-
applyItemUpdate({
|
|
1862
|
-
paths,
|
|
1863
|
-
view,
|
|
1864
|
-
updated,
|
|
1865
|
-
dryRun: opts.dryRun,
|
|
1866
|
-
eventAction: "start",
|
|
1867
|
-
eventActor: registerEventActor(opts),
|
|
1868
|
-
eventReason: opts.reason?.trim() || "work started",
|
|
1869
|
-
});
|
|
1870
|
-
}
|
|
1871
|
-
catch (error) {
|
|
1872
|
-
printCommandError(error);
|
|
1873
|
-
}
|
|
1874
|
-
});
|
|
1875
|
-
// --- wait ---
|
|
1876
|
-
const waitCmd = reg.command("wait").description("Set item status to waiting");
|
|
1877
|
-
addProjectOption(waitCmd);
|
|
1878
|
-
waitCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1879
|
-
waitCmd.option("--reason <text>", "Reason for waiting");
|
|
1880
|
-
waitCmd.option("--conclusion <text>", "Deprecated alias for --reason");
|
|
1881
|
-
waitCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1882
|
-
waitCmd.option("--dry-run", "Print change without writing", false);
|
|
1883
|
-
waitCmd.action((opts) => {
|
|
1884
|
-
try {
|
|
1885
|
-
if (opts.reason !== undefined && opts.conclusion !== undefined) {
|
|
1886
|
-
throw new Error("Specify only one of --reason or --conclusion");
|
|
1887
|
-
}
|
|
1888
|
-
const paths = resolveRegisterPaths(opts);
|
|
1889
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1890
|
-
const item = view.item;
|
|
1891
|
-
const reason = (opts.reason ?? opts.conclusion)?.trim();
|
|
1892
|
-
if (reason !== undefined && reason === "") {
|
|
1893
|
-
throw new Error("Waiting reason must not be empty");
|
|
1894
|
-
}
|
|
1895
|
-
const updated = {
|
|
1896
|
-
...item,
|
|
1897
|
-
status: "waiting",
|
|
1898
|
-
};
|
|
1899
|
-
applyItemUpdate({
|
|
1900
|
-
paths,
|
|
1901
|
-
view,
|
|
1902
|
-
updated,
|
|
1903
|
-
dryRun: opts.dryRun,
|
|
1904
|
-
...(reason !== undefined
|
|
1905
|
-
? { fieldUpdates: { block_reason: inlineCodeAnglePlaceholders(reason) } }
|
|
1906
|
-
: {}),
|
|
1907
|
-
eventAction: "wait",
|
|
1908
|
-
eventActor: registerEventActor(opts),
|
|
1909
|
-
eventReason: reason || "item waiting",
|
|
1910
|
-
});
|
|
1911
|
-
}
|
|
1912
|
-
catch (error) {
|
|
1913
|
-
printCommandError(error);
|
|
1914
|
-
}
|
|
1915
|
-
});
|
|
1916
|
-
// --- review ---
|
|
1917
|
-
const reviewCmd = reg.command("review").description("Set item status to review");
|
|
1918
|
-
addProjectOption(reviewCmd);
|
|
1919
|
-
reviewCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1920
|
-
reviewCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1921
|
-
reviewCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1922
|
-
reviewCmd.option("--dry-run", "Print change without writing", false);
|
|
1923
|
-
reviewCmd.action((opts) => {
|
|
1924
|
-
try {
|
|
1925
|
-
const paths = resolveRegisterPaths(opts);
|
|
1926
|
-
const view = loadItemForUpdate(paths, opts.id, "require-active");
|
|
1927
|
-
const item = view.item;
|
|
1928
|
-
const updated = { ...item, status: "review" };
|
|
1929
|
-
applyItemUpdate({
|
|
1930
|
-
paths,
|
|
1931
|
-
view,
|
|
1932
|
-
updated,
|
|
1933
|
-
dryRun: opts.dryRun,
|
|
1934
|
-
eventAction: "review",
|
|
1935
|
-
eventActor: registerEventActor(opts),
|
|
1936
|
-
eventReason: opts.reason?.trim() || "ready for review",
|
|
1937
|
-
});
|
|
1938
|
-
}
|
|
1939
|
-
catch (error) {
|
|
1940
|
-
printCommandError(error);
|
|
1941
|
-
}
|
|
1942
|
-
});
|
|
1943
|
-
// --- update ---
|
|
1944
|
-
const updateCmd = reg.command("update").description("Update fields of a register item");
|
|
1945
|
-
addProjectOption(updateCmd);
|
|
1946
|
-
updateCmd.requiredOption("--id <id>", "Item ID (PJR-XXXX)");
|
|
1947
|
-
updateCmd.option("--title <title>", "Update title");
|
|
1948
|
-
updateCmd.option("--description <text>", "Update description");
|
|
1949
|
-
updateCmd.option("--priority <priority>", `Update priority: ${VALID_PRIORITIES.join(" | ")}`);
|
|
1950
|
-
updateCmd.option("--owner <owner>", "Update owner or role");
|
|
1951
|
-
updateCmd.option("--due <date>", "Update due date (YYYY-MM-DD, -, or _TODO_)");
|
|
1952
|
-
updateCmd.option("--conclusion <text>", "Update conclusion or use - to remove it");
|
|
1953
|
-
updateCmd.option("--topic <topic>", "Update the topic slug in the ticket filename and document ID");
|
|
1954
|
-
updateCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
1955
|
-
updateCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
1956
|
-
updateCmd.option("--dry-run", "Print change without writing", false);
|
|
1957
|
-
updateCmd.action((opts) => {
|
|
1958
|
-
try {
|
|
1959
|
-
const paths = resolveRegisterPaths(opts);
|
|
1960
|
-
const view = loadItemForUpdate(paths, opts.id);
|
|
1961
|
-
const item = view.item;
|
|
1962
|
-
const hasUpdates = [
|
|
1963
|
-
"title",
|
|
1964
|
-
"description",
|
|
1965
|
-
"priority",
|
|
1966
|
-
"owner",
|
|
1967
|
-
"due",
|
|
1968
|
-
"conclusion",
|
|
1969
|
-
"topic",
|
|
1970
|
-
].some((k) => opts[k] !== undefined);
|
|
1971
|
-
if (!hasUpdates) {
|
|
1972
|
-
throw new Error("At least one field option must be specified (--title, --description, --priority, --owner, --due, --conclusion, --topic)");
|
|
1973
|
-
}
|
|
1974
|
-
if (opts.priority !== undefined &&
|
|
1975
|
-
!VALID_PRIORITIES.includes(opts.priority)) {
|
|
1976
|
-
throw new Error(`Invalid priority: "${opts.priority}". Must be one of: ${VALID_PRIORITIES.join(", ")}`);
|
|
1977
|
-
}
|
|
1978
|
-
if (opts.due !== undefined && !/^(\d{4}-\d{2}-\d{2}|-|_TODO_)$/.test(opts.due)) {
|
|
1979
|
-
throw new Error(`Invalid due: "${opts.due}". Must be YYYY-MM-DD, -, or _TODO_`);
|
|
1980
|
-
}
|
|
1981
|
-
const topic = opts.topic?.trim();
|
|
1982
|
-
if (topic !== undefined && !REGISTER_TOPIC_RE.test(topic)) {
|
|
1983
|
-
throw new Error(`Invalid topic: "${topic}". Must use lowercase letters, numbers, and single hyphens`);
|
|
1984
|
-
}
|
|
1985
|
-
const updated = {
|
|
1986
|
-
...item,
|
|
1987
|
-
...(opts.title !== undefined ? { title: opts.title } : {}),
|
|
1988
|
-
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
1989
|
-
...(opts.priority !== undefined ? { priority: opts.priority } : {}),
|
|
1990
|
-
...(opts.owner !== undefined ? { owner: opts.owner } : {}),
|
|
1991
|
-
...(opts.due !== undefined ? { due: opts.due } : {}),
|
|
1992
|
-
...(opts.conclusion !== undefined ? { conclusion: opts.conclusion } : {}),
|
|
1993
|
-
};
|
|
1994
|
-
const currentTopic = view.ticketFilename
|
|
1995
|
-
? ticketTopicFromFilename(opts.id, view.ticketFilename)
|
|
1996
|
-
: undefined;
|
|
1997
|
-
if (topic !== undefined && topic !== currentTopic) {
|
|
1998
|
-
retopicPjrItem({
|
|
1999
|
-
paths,
|
|
2000
|
-
id: opts.id,
|
|
2001
|
-
topic,
|
|
2002
|
-
updated,
|
|
2003
|
-
dryRun: opts.dryRun,
|
|
2004
|
-
...(opts.title !== undefined ? { title: opts.title } : {}),
|
|
2005
|
-
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
2006
|
-
actor: registerEventActor(opts),
|
|
2007
|
-
reason: opts.reason?.trim() || "",
|
|
2008
|
-
});
|
|
2009
|
-
return;
|
|
2010
|
-
}
|
|
2011
|
-
applyItemUpdate({
|
|
2012
|
-
paths,
|
|
2013
|
-
view,
|
|
2014
|
-
updated,
|
|
2015
|
-
dryRun: opts.dryRun,
|
|
2016
|
-
action: "fields updated",
|
|
2017
|
-
...(opts.title !== undefined ? { title: opts.title } : {}),
|
|
2018
|
-
...(opts.description !== undefined ? { description: opts.description } : {}),
|
|
2019
|
-
eventAction: "update",
|
|
2020
|
-
eventActor: registerEventActor(opts),
|
|
2021
|
-
eventReason: opts.reason?.trim() || "fields updated",
|
|
2022
|
-
});
|
|
2023
|
-
}
|
|
2024
|
-
catch (error) {
|
|
2025
|
-
printCommandError(error);
|
|
2026
|
-
}
|
|
2027
|
-
});
|
|
2028
|
-
// --- migrate ---
|
|
2029
|
-
const migrateCmd = reg
|
|
2030
|
-
.command("migrate")
|
|
2031
|
-
.description("Migrate legacy register data (index rows, dates, and embedded register events)");
|
|
2032
|
-
addProjectOption(migrateCmd);
|
|
2033
|
-
migrateCmd.option("--dry-run", "Validate and print the migration summary without writing", false);
|
|
2034
|
-
migrateCmd.action((opts) => {
|
|
2035
|
-
try {
|
|
2036
|
-
const paths = resolveRegisterPaths(opts);
|
|
2037
|
-
const plan = planRegisterMigration(paths);
|
|
2038
|
-
const summary = `items=${plan.sourceCount}, create=${plan.createdCount}, update=${plan.updatedCount}, ` +
|
|
2039
|
-
`unchanged=${plan.unchangedCount}`;
|
|
2040
|
-
if (opts.dryRun) {
|
|
2041
|
-
process.stdout.write(`Would migrate register items: ${summary}\n`);
|
|
2042
|
-
if (plan.sourceIndexPath) {
|
|
2043
|
-
process.stdout.write(`Would remove legacy index: ${plan.sourceIndexPath}\n`);
|
|
2044
|
-
}
|
|
2045
|
-
}
|
|
2046
|
-
else {
|
|
2047
|
-
applyRegisterMigrationPlan(plan);
|
|
2048
|
-
process.stdout.write(`Migrated register items: ${summary}\n`);
|
|
2049
|
-
if (plan.sourceIndexPath) {
|
|
2050
|
-
process.stdout.write(`Removed legacy index: ${plan.sourceIndexPath}\n`);
|
|
2051
|
-
}
|
|
2052
|
-
}
|
|
2053
|
-
// 旧日付キーの移行は個票が正本になった後の状態を入力にするため、行の個票化より後に行う。
|
|
2054
|
-
const timestampPlan = planRegisterTimestampMigration({
|
|
2055
|
-
projectRegisterPath: paths.projectRegisterPath,
|
|
2056
|
-
timeZone: paths.registerDateTimeZone,
|
|
2057
|
-
resolveGitTimestamps: createGitTimestampResolver(specdojoRootDir()),
|
|
2058
|
-
});
|
|
2059
|
-
const timestampSummary = summarizeTimestampMigration(timestampPlan);
|
|
2060
|
-
if (opts.dryRun) {
|
|
2061
|
-
const embeddedMigration = migrateEmbeddedRegisterEvents(paths, true);
|
|
2062
|
-
const eventMigration = migrateRegisterEventsFromGit(paths, true);
|
|
2063
|
-
const eventSummary = eventMigration.available
|
|
2064
|
-
? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
|
|
2065
|
-
: "unavailable (Git history not found; legacy fallback remains active)";
|
|
2066
|
-
process.stdout.write(`Would migrate register timestamps: ${timestampSummary}\n`);
|
|
2067
|
-
process.stdout.write(`Would separate embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
|
|
2068
|
-
process.stdout.write(`Would migrate register events: ${eventSummary}\n`);
|
|
2069
|
-
return;
|
|
2070
|
-
}
|
|
2071
|
-
for (const file of timestampPlan.files) {
|
|
2072
|
-
writeFileSync(file.path, file.content, "utf8");
|
|
2073
|
-
}
|
|
2074
|
-
process.stdout.write(`Migrated register timestamps: ${timestampSummary}\n`);
|
|
2075
|
-
const embeddedMigration = migrateEmbeddedRegisterEvents(paths, false);
|
|
2076
|
-
process.stdout.write(`Separated embedded register events: items=${embeddedMigration.items}, events=${embeddedMigration.events}\n`);
|
|
2077
|
-
const eventMigration = migrateRegisterEventsFromGit(paths, false);
|
|
2078
|
-
const eventSummary = eventMigration.available
|
|
2079
|
-
? `items=${eventMigration.items}, events=${eventMigration.events}, skipped=${eventMigration.skipped}`
|
|
2080
|
-
: "unavailable (Git history not found; legacy fallback remains active)";
|
|
2081
|
-
process.stdout.write(`Migrated register events: ${eventSummary}\n`);
|
|
2082
|
-
for (const view of writeDerivedViews(paths, "all")) {
|
|
2083
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
2084
|
-
}
|
|
2085
|
-
}
|
|
2086
|
-
catch (error) {
|
|
2087
|
-
printCommandError(error);
|
|
2088
|
-
}
|
|
2089
|
-
});
|
|
2090
|
-
// --- build ---
|
|
2091
|
-
const buildCmd = reg
|
|
2092
|
-
.command("build")
|
|
2093
|
-
.description("Generate the register list and derived views from register item files");
|
|
2094
|
-
addProjectOption(buildCmd);
|
|
2095
|
-
buildCmd.option("--scope <scope>", "Generation scope: register | controls | all", "all");
|
|
2096
|
-
buildCmd.option("--dry-run", "Print generated content without writing", false);
|
|
2097
|
-
buildCmd.action((opts) => {
|
|
2098
|
-
try {
|
|
2099
|
-
const paths = resolveRegisterPaths(opts);
|
|
2100
|
-
if (!existsSync(paths.projectRegisterPath)) {
|
|
2101
|
-
throw new Error(`Project register directory not found: ${paths.projectRegisterPath}\n` +
|
|
2102
|
-
`Run: specdojo register scaffold --project ${opts.project || paths.projectId}`);
|
|
2103
|
-
}
|
|
2104
|
-
const scope = opts.scope;
|
|
2105
|
-
if (!VALID_BUILD_SCOPES.includes(scope)) {
|
|
2106
|
-
throw new Error(`Invalid scope: "${opts.scope}". Must be one of: ${VALID_BUILD_SCOPES.join(", ")}`);
|
|
2107
|
-
}
|
|
2108
|
-
const validation = validateRegisterItemDocs(paths.projectRegisterPath);
|
|
2109
|
-
const eventErrors = validateRegisterEventDocs(paths.projectRegisterPath, paths.registerDateTimeZone);
|
|
2110
|
-
if (validation.errors.length > 0 || eventErrors.length > 0) {
|
|
2111
|
-
throw new Error(`Invalid register item files:\n${[...validation.errors, ...eventErrors].join("\n")}`);
|
|
2112
|
-
}
|
|
2113
|
-
const views = generateDerivedViewFiles(paths, scope);
|
|
2114
|
-
if (opts.dryRun) {
|
|
2115
|
-
for (const view of views) {
|
|
2116
|
-
process.stdout.write(`=== ${view.path} ===\n${view.content}\n\n`);
|
|
2117
|
-
}
|
|
2118
|
-
return;
|
|
2119
|
-
}
|
|
2120
|
-
for (const view of writeDerivedViews(paths, scope)) {
|
|
2121
|
-
process.stdout.write(`Generated: ${view.path}\n`);
|
|
2122
|
-
}
|
|
2123
|
-
}
|
|
2124
|
-
catch (error) {
|
|
2125
|
-
printCommandError(error);
|
|
2126
|
-
}
|
|
2127
|
-
});
|
|
2128
|
-
// --- history ---
|
|
2129
|
-
// 新しい変更は項目別の追記型 event、event 導入前の変更は Git 履歴から再構成する。
|
|
2130
|
-
const historyCmd = reg
|
|
2131
|
-
.command("history")
|
|
2132
|
-
.description("Show register item changes from append-only events and legacy Git history");
|
|
2133
|
-
addProjectOption(historyCmd);
|
|
2134
|
-
historyCmd.option("--since <date>", "Include commits on or after this date (YYYY-MM-DD)");
|
|
2135
|
-
historyCmd.option("--until <date>", "Include commits on or before this date (YYYY-MM-DD)");
|
|
2136
|
-
historyCmd.option("--id <id...>", "Limit output to these item IDs (PJR-XXXX; space/comma separated)");
|
|
2137
|
-
historyCmd.option("--status-only", "Show only additions, removals, and status transitions", false);
|
|
2138
|
-
historyCmd.option("--limit <count>", "Maximum number of commits to inspect");
|
|
2139
|
-
historyCmd.option("--json", "Print events as JSON", false);
|
|
2140
|
-
historyCmd.action((opts) => {
|
|
2141
|
-
try {
|
|
2142
|
-
const paths = resolveRegisterPaths(opts);
|
|
2143
|
-
const ids = parseHistoryIds(opts.id);
|
|
2144
|
-
const limit = opts.limit === undefined ? undefined : Number(opts.limit);
|
|
2145
|
-
const events = collectRegisterHistoryEvents({
|
|
2146
|
-
repoRoot: specdojoRootDir(),
|
|
2147
|
-
registerPathspec: repoRelativePathspec(specdojoRootDir(), paths.projectRegisterPath),
|
|
2148
|
-
since: opts.since?.trim() || undefined,
|
|
2149
|
-
until: opts.until?.trim() || undefined,
|
|
2150
|
-
limit,
|
|
2151
|
-
ids,
|
|
2152
|
-
statusOnly: Boolean(opts.statusOnly),
|
|
2153
|
-
timeZone: paths.registerDateTimeZone,
|
|
2154
|
-
});
|
|
2155
|
-
if (opts.json) {
|
|
2156
|
-
process.stdout.write(`${JSON.stringify(events, null, 2)}\n`);
|
|
2157
|
-
return;
|
|
2158
|
-
}
|
|
2159
|
-
if (events.length === 0) {
|
|
2160
|
-
process.stdout.write("No register item changes found for the given range.\n");
|
|
2161
|
-
return;
|
|
2162
|
-
}
|
|
2163
|
-
process.stdout.write(`${formatRegisterHistoryEvents(events)}\n`);
|
|
2164
|
-
const itemCount = new Set(events.map((event) => event.id)).size;
|
|
2165
|
-
const gitCommitCount = new Set(events.filter((event) => event.source !== "event").map((event) => event.commit)).size;
|
|
2166
|
-
const storedEventCount = events.filter((event) => event.source === "event").length;
|
|
2167
|
-
process.stdout.write(`events=${events.length} items=${itemCount} stored=${storedEventCount} legacy_commits=${gitCommitCount}\n`);
|
|
2168
|
-
}
|
|
2169
|
-
catch (error) {
|
|
2170
|
-
printCommandError(error);
|
|
2171
|
-
}
|
|
2172
|
-
});
|
|
2173
|
-
// --- renumber ---
|
|
2174
|
-
const renumberCmd = reg
|
|
2175
|
-
.command("renumber")
|
|
2176
|
-
.description("Resolve a random PJR-ID collision by moving one item to an unused ID");
|
|
2177
|
-
addProjectOption(renumberCmd);
|
|
2178
|
-
renumberCmd.requiredOption("--id <id>", "Current item ID (PJR-XXXX)");
|
|
2179
|
-
renumberCmd.requiredOption("--to <id>", "Target unused ID (PJR-XXXX)");
|
|
2180
|
-
renumberCmd.option("--by <actor>", "Actor recorded in the append-only register event");
|
|
2181
|
-
renumberCmd.option("--reason <text>", "Reason recorded in the append-only register event");
|
|
2182
|
-
renumberCmd.option("--dry-run", "Print planned changes without writing", false);
|
|
2183
|
-
renumberCmd.action((opts) => {
|
|
2184
|
-
try {
|
|
2185
|
-
const paths = resolveRegisterPaths(opts);
|
|
2186
|
-
renumberPjrItem({
|
|
2187
|
-
paths,
|
|
2188
|
-
fromId: opts.id,
|
|
2189
|
-
toId: opts.to,
|
|
2190
|
-
dryRun: opts.dryRun,
|
|
2191
|
-
actor: registerEventActor(opts),
|
|
2192
|
-
reason: opts.reason,
|
|
2193
|
-
});
|
|
2194
|
-
}
|
|
2195
|
-
catch (error) {
|
|
2196
|
-
printCommandError(error);
|
|
2197
|
-
}
|
|
2198
|
-
});
|
|
395
|
+
registerCreateCommands(reg, REGISTER_COMMAND_DEPENDENCIES);
|
|
396
|
+
registerTransitionCommands(reg, REGISTER_COMMAND_DEPENDENCIES);
|
|
397
|
+
registerUpdateCommand(reg, REGISTER_COMMAND_DEPENDENCIES);
|
|
398
|
+
registerMaintenanceCommands(reg, REGISTER_COMMAND_DEPENDENCIES);
|
|
2199
399
|
}
|