specdojo 0.5.0 → 0.7.0
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 +2 -0
- package/CHANGELOG.md +100 -0
- package/README.md +2 -2
- package/dist/catalog/generate.js +144 -13
- package/dist/commands/agent.js +33 -0
- package/dist/commands/init.js +2 -0
- package/dist/commands/orchestrator.js +10 -1
- package/dist/deliverable/deliverable.js +77 -4
- package/dist/devcontainer/command.js +18 -0
- package/dist/devcontainer/host-script.js +21 -0
- package/dist/devcontainer/scaffold.js +4 -3
- package/dist/exec/antigravity-session.js +154 -0
- package/dist/exec/core.js +1 -0
- package/dist/exec/parent-validation.js +14 -0
- package/dist/exec/plan-markdownlint.js +89 -0
- package/dist/exec/plans-core.js +46 -1
- package/dist/exec/plans-generation.js +45 -5
- package/dist/exec/plans-planning.js +1 -1
- package/dist/exec/plans-storage.js +1 -0
- package/dist/exec/product-branch-records.js +105 -0
- package/dist/exec/product-branches.js +52 -0
- package/dist/exec/register-product-message.js +50 -0
- package/dist/exec/register-resume.js +28 -0
- package/dist/exec/register.js +6 -0
- package/dist/exec/repo-integration-sync.js +4 -2
- package/dist/exec/repo-integration.js +41 -4
- package/dist/exec/repo-trace.js +2 -0
- package/dist/exec/results.js +9 -5
- package/dist/exec/run/lifecycle-commands.js +85 -16
- package/dist/exec/run/register-command.js +22 -0
- package/dist/exec/run/register-resume.js +11 -1
- package/dist/exec/run/register-worktree.js +29 -8
- package/dist/exec/run/schedule-mode.js +22 -2
- package/dist/exec/run/schedule-prepare.js +49 -4
- package/dist/exec/run/schedule-task.js +3 -0
- package/dist/exec/strategy.js +2 -1
- package/dist/exec/task-repos.js +78 -16
- package/dist/exec/worktree-command.js +2 -2
- package/dist/exec/worktree-ops-commit.js +1 -13
- package/dist/exec/worktree-ops-lifecycle.js +40 -36
- package/dist/exec/worktree.js +3 -3
- package/dist/register/core.js +5 -0
- package/dist/register/create-commands.js +54 -2
- package/dist/register/deliverable-target.js +24 -17
- package/dist/register/event-merge.js +4 -0
- package/dist/register/events.js +6 -0
- package/dist/register/external-project.js +2 -0
- package/dist/register/input.js +168 -0
- package/dist/register/item.js +61 -0
- package/dist/register/register.js +33 -25
- package/dist/register/renumber.js +4 -0
- package/dist/register/update.js +6 -0
- package/dist/schedule/approach.js +9 -0
- package/dist/schedule/strategy-profiles.js +22 -2
- package/dist/shared/agent-types.js +4 -1
- package/dist/shared/branch-template.js +26 -0
- package/dist/shared/commit-message-template.js +38 -0
- package/dist/shared/commit-types.js +15 -0
- package/dist/shared/git.js +7 -0
- package/dist/shared/provider-scaffold.js +2 -0
- package/dist/shared/specdojo-config.js +35 -4
- package/dist/shared/specdojo-gitignore.js +1 -0
- package/docs/ja/specdojo/defaults/pm-review-viewpoints.yaml +2 -0
- package/docs/ja/specdojo/exec-templates/xep-draft-template.md +93 -0
- package/docs/ja/specdojo/exec-templates/xep-fully-guided-template.md +9 -2
- package/docs/ja/specdojo/exec-templates/xep-register-investigate-template.md +2 -0
- package/docs/ja/specdojo/exec-templates/xep-register-template.md +2 -0
- package/docs/ja/specdojo/exec-templates/xer-human-bootstrap-finalize-template.md +2 -0
- package/docs/ja/specdojo/exec-templates/xer-human-draft-template.md +23 -0
- package/docs/ja/specdojo/exec-templates/xer-human-finalize-template.md +2 -0
- package/docs/ja/specdojo/exec-templates/xrp-fully-guided-template.md +7 -4
- package/docs/ja/specdojo/guides/docs-editing-guide.md +36 -0
- package/docs/ja/specdojo/guides/exec-config-guide.md +16 -12
- package/docs/ja/specdojo/guides/exec-operation-guide.md +116 -10
- package/docs/ja/specdojo/guides/orchestrator-operation-guide.md +4 -2
- package/docs/ja/specdojo/guides/quick-start-guide.md +597 -871
- package/docs/ja/specdojo/guides/register-operation-guide.md +16 -1
- package/docs/ja/specdojo/guides/remote-host-development-guide.md +31 -4
- package/docs/ja/specdojo/guides/ryu-guide.md +114 -23
- package/docs/ja/specdojo/guides/schedule-design-guide.md +31 -4
- package/docs/ja/specdojo/guides/schedule-operation-guide.md +14 -0
- package/docs/ja/specdojo/guides/use-case-guide.md +537 -77
- package/docs/ja/specdojo/recipes/cdfd-overview-recipe.md +88 -86
- package/docs/ja/specdojo/recipes/cdfd-uc-recipe.md +96 -122
- package/docs/ja/specdojo/recipes/exec-human-finalize-recipe.md +1 -0
- package/docs/ja/specdojo/recipes/tsd-recipe.md +20 -12
- package/docs/ja/specdojo/references/command-reference.md +111 -46
- package/docs/ja/specdojo/references/specdojo-config-reference.md +69 -8
- package/docs/ja/specdojo/rulebooks/cdfd-d2-rulebook.md +367 -0
- package/docs/ja/specdojo/rulebooks/cdfd-mermaid-rulebook.md +6 -5
- package/docs/ja/specdojo/rulebooks/cdfd-overview-rulebook.md +96 -100
- package/docs/ja/specdojo/rulebooks/cdfd-rulebook.md +38 -47
- package/docs/ja/specdojo/rulebooks/cdfd-uc-rulebook.md +108 -103
- package/docs/ja/specdojo/rulebooks/dct-rulebook.md +8 -0
- package/docs/ja/specdojo/rulebooks/pjr-rulebook.md +4 -0
- package/docs/ja/specdojo/rulebooks/sch-rulebook.md +3 -1
- package/docs/ja/specdojo/samples/cdfd-overview-sample.md +248 -140
- package/docs/ja/specdojo/samples/cdfd-uc-sample.md +128 -97
- package/docs/ja/specdojo/samples/dct-sample.yaml +5 -1
- package/docs/ja/specdojo/standards/document-metadata-standard.md +16 -0
- package/docs/ja/specdojo/standards/exec-human-finalize-standard.md +1 -0
- package/docs/ja/specdojo/standards/guide-authoring-standard.md +2 -1
- package/docs/ja/specdojo/standards/philosophy-authoring-standard.md +1 -0
- package/docs/ja/specdojo/standards/recipe-authoring-standard.md +2 -1
- package/docs/ja/specdojo/standards/rulebook-authoring-standard.md +2 -1
- package/docs/ja/specdojo/standards/standard-authoring-standard.md +2 -1
- package/docs/ja/specdojo/templates/cdfd-overview-template.md +161 -83
- package/docs/ja/specdojo/templates/cdfd-uc-template.md +127 -90
- package/docs/ja/specdojo/templates/pjr-change-request-template.md +10 -4
- package/docs/ja/specdojo/templates/pjr-issue-template.md +10 -4
- package/docs/ja/specdojo/templates/pjr-question-template.md +11 -5
- package/docs/ja/specdojo/templates/pjr-risk-template.md +10 -4
- package/docs/ja/specdojo/templates/pjr-todo-template.md +10 -4
- package/docs/specdojo/schemas/v1/dct.schema.yaml +9 -0
- package/docs/specdojo/schemas/v1/exec-common.schema.yaml +2 -1
- package/docs/specdojo/schemas/v1/exec-defaults.schema.yaml +2 -0
- package/docs/specdojo/schemas/v1/register-events.schema.yaml +3 -0
- package/docs/specdojo/schemas/v1/register-item-frontmatter.schema.yaml +35 -0
- package/docs/specdojo/schemas/v1/sch-strategy.schema.yaml +1 -0
- package/docs/specdojo/schemas/v1/specdojo-config.schema.yaml +41 -2
- package/package.json +6 -2
- package/templates/antigravity/README.md +19 -46
- package/templates/antigravity/exec-defaults-snippet.yaml +5 -6
- package/templates/antigravity/orchestrator.md +2 -0
- package/templates/antigravity/settings.edit.json +73 -0
- package/templates/antigravity/settings.orchestrator.json +15 -0
- package/templates/antigravity/settings.report.json +7 -0
- package/templates/antigravity/settings.review.json +7 -0
- package/templates/claude/agents/specdojo-orchestrator.md +2 -0
- package/templates/codex/agents/specdojo-orchestrator.toml +2 -0
- package/templates/codex/orchestrator.md +2 -0
- package/templates/devcontainer/remote-host/devcontainer-tmux.sh +217 -0
- package/templates/devcontainer/remote-host/specdojo-tmux.sh.sample +8 -90
- package/templates/devcontainer/remote-host/ssh-config.sample +3 -1
- package/templates/init-agent-members.yaml +1 -0
- package/templates/init-exec-defaults.yaml +1 -1
- package/templates/opencode/agents/specdojo-orchestrator.md +2 -0
|
@@ -130,8 +130,10 @@ export function generateSshConfigSample(ports) {
|
|
|
130
130
|
"",
|
|
131
131
|
"# devcontainer 内の tmux セッションへ直接入る接続用",
|
|
132
132
|
"# RemoteCommand は非対話シェルで動くため、接続先端末の ~/.zshrc などの PATH 設定は読み込まれません。",
|
|
133
|
+
"# 通常の接続(コンテナ稼働中または停止中)では Node.js は不要です(docker のみ使用)。",
|
|
134
|
+
"# コンテナ未作成時のみ Dev Container CLI が自動起動されます。",
|
|
133
135
|
"# 接続元から「ssh <host> 'command -v devcontainer'」を実行して Dev Container CLI が見つかるか確認できます。",
|
|
134
|
-
"#
|
|
136
|
+
"# 見つからない場合は、ホストの環境変数 SPECDOJO_NODE_BIN を設定するか、ログインシェルの PATH を確認してください。",
|
|
135
137
|
"Host <host>-tmux",
|
|
136
138
|
" HostName <host>",
|
|
137
139
|
" User <user>",
|
|
@@ -355,7 +357,7 @@ fi`);
|
|
|
355
357
|
postCreateScript = postCreateScript.replace("npm install", extraScripts.join("\n\n") + "\n\nnpm install");
|
|
356
358
|
}
|
|
357
359
|
const specdojoTmuxTemplatePath = path.join(templateDir, "remote-host", "specdojo-tmux.sh.sample");
|
|
358
|
-
|
|
360
|
+
const specdojoTmuxScript = await readFile(specdojoTmuxTemplatePath, "utf8");
|
|
359
361
|
const remoteUser = typeof devcontainer.remoteUser === "string" && devcontainer.remoteUser.trim()
|
|
360
362
|
? devcontainer.remoteUser.trim()
|
|
361
363
|
: "node";
|
|
@@ -379,7 +381,6 @@ fi`);
|
|
|
379
381
|
...existingRemoteEnv,
|
|
380
382
|
PATH: remotePath,
|
|
381
383
|
};
|
|
382
|
-
specdojoTmuxScript = specdojoTmuxScript.replace('container_user="node"', `container_user="${remoteUser}"`);
|
|
383
384
|
const publishedPorts = extractPublishedPorts(devcontainer);
|
|
384
385
|
const sshConfigScript = generateSshConfigSample(publishedPorts);
|
|
385
386
|
if (dryRun) {
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { existsSync, readFileSync, readdirSync, realpathSync } from "node:fs";
|
|
2
|
+
import { join, resolve } from "node:path";
|
|
3
|
+
import { specdojoPackageRootDir } from "../shared/package-paths.js";
|
|
4
|
+
import { isAgentProtectedConfigPath, PROTECTED_DIRECTORY_PREFIXES, PROTECTED_EXACT_PATHS, } from "./agent-protected-config.js";
|
|
5
|
+
export function antigravityRole(value) {
|
|
6
|
+
if (["edit", "review", "report", "orchestrator"].includes(value)) {
|
|
7
|
+
return value;
|
|
8
|
+
}
|
|
9
|
+
throw new Error(`Invalid Antigravity role: ${value}`);
|
|
10
|
+
}
|
|
11
|
+
function canonicalRoot(root) {
|
|
12
|
+
const absolute = resolve(root);
|
|
13
|
+
const normalized = (existsSync(absolute) ? realpathSync(absolute) : absolute).replaceAll("\\", "/");
|
|
14
|
+
// The permission syntax has no escaping for parentheses or the global wildcard.
|
|
15
|
+
if (/[()*\r\n]/u.test(normalized)) {
|
|
16
|
+
throw new Error(`Unsupported Antigravity workspace path: ${normalized}`);
|
|
17
|
+
}
|
|
18
|
+
return normalized.replace(/\/$/u, "") + "/";
|
|
19
|
+
}
|
|
20
|
+
/** One settings object per launch: never read or modify the user's global settings. */
|
|
21
|
+
export function buildAntigravitySession(options) {
|
|
22
|
+
const { role, cwd } = options;
|
|
23
|
+
const roots = [...new Set([cwd, ...options.repoRoots].map(canonicalRoot))];
|
|
24
|
+
const localProfile = join(cwd, ".specdojo", "antigravity", `settings.${role}.json`);
|
|
25
|
+
const profilePath = existsSync(localProfile)
|
|
26
|
+
? localProfile
|
|
27
|
+
: join(specdojoPackageRootDir(), "templates", "antigravity", `settings.${role}.json`);
|
|
28
|
+
const profile = JSON.parse(readFileSync(profilePath, "utf8"));
|
|
29
|
+
if (!profile || typeof profile !== "object" || Array.isArray(profile)) {
|
|
30
|
+
throw new Error(`Invalid Antigravity settings: ${profilePath}`);
|
|
31
|
+
}
|
|
32
|
+
const settings = profile;
|
|
33
|
+
const permissions = { allow: [], deny: [], ask: [] };
|
|
34
|
+
if (settings.permissions !== undefined) {
|
|
35
|
+
if (!settings.permissions ||
|
|
36
|
+
typeof settings.permissions !== "object" ||
|
|
37
|
+
Array.isArray(settings.permissions)) {
|
|
38
|
+
throw new Error(`Invalid permissions in ${profilePath}`);
|
|
39
|
+
}
|
|
40
|
+
for (const name of ["allow", "deny", "ask"]) {
|
|
41
|
+
const rules = settings.permissions[name] ?? [];
|
|
42
|
+
if (!Array.isArray(rules) || rules.some((rule) => typeof rule !== "string")) {
|
|
43
|
+
throw new Error(`Invalid permissions.${name} in ${profilePath}`);
|
|
44
|
+
}
|
|
45
|
+
permissions[name] = [...rules];
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
for (const root of roots) {
|
|
49
|
+
permissions.allow.push(`read_file(${root})`);
|
|
50
|
+
if (role === "edit" || role === "orchestrator")
|
|
51
|
+
permissions.allow.push(`write_file(${root})`);
|
|
52
|
+
for (const secret of [
|
|
53
|
+
".env",
|
|
54
|
+
".env.local",
|
|
55
|
+
".env.development",
|
|
56
|
+
".env.production",
|
|
57
|
+
".env.test",
|
|
58
|
+
".env.staging",
|
|
59
|
+
".envrc",
|
|
60
|
+
"secrets/",
|
|
61
|
+
".ssh/",
|
|
62
|
+
".aws/",
|
|
63
|
+
".gemini/",
|
|
64
|
+
]) {
|
|
65
|
+
permissions.deny.push(`read_file(${root}${secret})`);
|
|
66
|
+
}
|
|
67
|
+
permissions.deny.push(`write_file(${root}.git)`);
|
|
68
|
+
if (role !== "orchestrator") {
|
|
69
|
+
const discovered = existsSync(root)
|
|
70
|
+
? readdirSync(root).filter(isAgentProtectedConfigPath)
|
|
71
|
+
: [];
|
|
72
|
+
for (const protectedPath of new Set([
|
|
73
|
+
...PROTECTED_DIRECTORY_PREFIXES,
|
|
74
|
+
...PROTECTED_EXACT_PATHS,
|
|
75
|
+
...discovered,
|
|
76
|
+
])) {
|
|
77
|
+
if (/[()*\r\n]/u.test(protectedPath)) {
|
|
78
|
+
throw new Error(`Unsupported Antigravity protected path: ${protectedPath}`);
|
|
79
|
+
}
|
|
80
|
+
permissions.deny.push(`write_file(${root}${protectedPath})`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (role === "review" || role === "report") {
|
|
85
|
+
// A command or MCP tool can write independently of write_file permissions.
|
|
86
|
+
permissions.deny.push("write_file(*)", "command(*)", "unsandboxed(*)", "mcp(*)", "execute_url(*)");
|
|
87
|
+
}
|
|
88
|
+
permissions.deny.push("command(sudo)", "command(rm -rf)");
|
|
89
|
+
for (const bin of ["", "/usr/bin/", "/usr/local/bin/"]) {
|
|
90
|
+
permissions.deny.push(`command(${bin}git push)`, `command(${bin}gh)`);
|
|
91
|
+
if (role !== "orchestrator") {
|
|
92
|
+
for (const action of ["add", "commit", "config", "reset"])
|
|
93
|
+
permissions.deny.push(`command(${bin}git ${action})`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
for (const name of ["allow", "deny", "ask"])
|
|
97
|
+
permissions[name] = [...new Set(permissions[name])];
|
|
98
|
+
return {
|
|
99
|
+
roots,
|
|
100
|
+
settings: { ...settings, agentMode: "", toolPermission: "request-review", permissions },
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
export function antigravitySessionArguments(options) {
|
|
104
|
+
const { roots, settings } = buildAntigravitySession(options);
|
|
105
|
+
const args = [];
|
|
106
|
+
for (let index = 0; index < options.providerArgs.length; index++) {
|
|
107
|
+
const arg = options.providerArgs[index];
|
|
108
|
+
// Go-style flag parsers may also accept a single dash for long options.
|
|
109
|
+
const flag = arg.startsWith("-") && !arg.startsWith("--") && arg.length > 2 ? `-${arg}` : arg;
|
|
110
|
+
if (arg === "--")
|
|
111
|
+
throw new Error("Antigravity provider argument terminator is not supported");
|
|
112
|
+
if ([
|
|
113
|
+
"-p",
|
|
114
|
+
"-i",
|
|
115
|
+
"--print",
|
|
116
|
+
"--prompt",
|
|
117
|
+
"--prompt-interactive",
|
|
118
|
+
"--model",
|
|
119
|
+
"--effort",
|
|
120
|
+
"--input-format",
|
|
121
|
+
"--output-format",
|
|
122
|
+
"--json-schema",
|
|
123
|
+
"--print-timeout",
|
|
124
|
+
"--log-file",
|
|
125
|
+
].includes(flag)) {
|
|
126
|
+
const value = options.providerArgs[++index];
|
|
127
|
+
if (value === undefined)
|
|
128
|
+
throw new Error(`Missing value for ${arg}`);
|
|
129
|
+
args.push(arg, value);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (flag === "--add-dir" || flag.startsWith("--add-dir=")) {
|
|
133
|
+
const dir = flag === "--add-dir" ? options.providerArgs[++index] : flag.slice("--add-dir=".length);
|
|
134
|
+
if (!dir || !roots.includes(canonicalRoot(resolve(options.cwd, dir)))) {
|
|
135
|
+
throw new Error(`Undeclared Antigravity workspace: ${dir ?? "(missing)"}`);
|
|
136
|
+
}
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
if (/^--(?:settings|dangerously-skip-permissions|mode|project|new-project|continue|conversation|agent)(?:=|$)/u.test(flag) ||
|
|
140
|
+
arg === "-c") {
|
|
141
|
+
throw new Error(`Antigravity session permissions cannot be overridden: ${arg}`);
|
|
142
|
+
}
|
|
143
|
+
if (!arg.startsWith("-")) {
|
|
144
|
+
throw new Error(`Use -p or -i for Antigravity prompts; unexpected argument: ${arg}`);
|
|
145
|
+
}
|
|
146
|
+
args.push(arg);
|
|
147
|
+
}
|
|
148
|
+
return [
|
|
149
|
+
...args,
|
|
150
|
+
...roots.flatMap((root) => ["--add-dir", root.replace(/\/$/u, "") || "/"]),
|
|
151
|
+
"--settings",
|
|
152
|
+
JSON.stringify(settings),
|
|
153
|
+
];
|
|
154
|
+
}
|
package/dist/exec/core.js
CHANGED
|
@@ -12,6 +12,7 @@ import { buildPhaseModeIndex, resolveApproach, resolveTaskExecution, resolveTask
|
|
|
12
12
|
export const KNOWN_OWNER_LABELS = ["PO", "PM", "BA", "ARC", "DEV", "QE", "UX", "OPS"];
|
|
13
13
|
export const KNOWN_OWNER_LABELS_TEXT = KNOWN_OWNER_LABELS.join("|");
|
|
14
14
|
const KNOWN_APPROACHES = [
|
|
15
|
+
"draft",
|
|
15
16
|
"fully-guided",
|
|
16
17
|
"recipe-guided",
|
|
17
18
|
"freeform",
|
|
@@ -57,6 +57,20 @@ const PARENT_VALIDATION_REGISTRY = {
|
|
|
57
57
|
displayCommand: "npm run lint:md",
|
|
58
58
|
timeoutMs: 10 * 60 * 1_000,
|
|
59
59
|
},
|
|
60
|
+
"lint-mermaid": {
|
|
61
|
+
id: "lint-mermaid",
|
|
62
|
+
command: process.platform === "win32" ? "npm.cmd" : "npm",
|
|
63
|
+
args: ["run", "lint:mermaid"],
|
|
64
|
+
displayCommand: "npm run lint:mermaid",
|
|
65
|
+
timeoutMs: 10 * 60 * 1_000,
|
|
66
|
+
},
|
|
67
|
+
"lint-d2": {
|
|
68
|
+
id: "lint-d2",
|
|
69
|
+
command: process.platform === "win32" ? "npm.cmd" : "npm",
|
|
70
|
+
args: ["run", "lint:d2"],
|
|
71
|
+
displayCommand: "npm run lint:d2",
|
|
72
|
+
timeoutMs: 10 * 60 * 1_000,
|
|
73
|
+
},
|
|
60
74
|
build: {
|
|
61
75
|
id: "build",
|
|
62
76
|
command: process.platform === "win32" ? "npm.cmd" : "npm",
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { dirname, join, relative } from "node:path";
|
|
4
|
+
import { pathToFileURL } from "node:url";
|
|
5
|
+
import { load } from "../shared/yaml.js";
|
|
6
|
+
import { DEFAULT_MARKDOWNLINT_CONFIG } from "../shared/markdownlint-config.js";
|
|
7
|
+
async function markdownlintApi(repoRoot) {
|
|
8
|
+
// Prefer the consumer's installation, then SpecDojo's development installation.
|
|
9
|
+
// Resolve from markdownlint-cli as well, for package managers without hoisting.
|
|
10
|
+
for (let require of [
|
|
11
|
+
createRequire(join(repoRoot, "package.json")),
|
|
12
|
+
createRequire(import.meta.url),
|
|
13
|
+
]) {
|
|
14
|
+
try {
|
|
15
|
+
try {
|
|
16
|
+
require = createRequire(require.resolve("markdownlint-cli/markdownlint.js"));
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// A direct markdownlint installation is sufficient too.
|
|
20
|
+
}
|
|
21
|
+
const api = (await import(pathToFileURL(require.resolve("markdownlint/sync")).href));
|
|
22
|
+
const parsers = [];
|
|
23
|
+
try {
|
|
24
|
+
const jsonc = require("jsonc-parser");
|
|
25
|
+
parsers.push((text) => {
|
|
26
|
+
const errors = [];
|
|
27
|
+
const value = jsonc.parse(text, errors, { allowTrailingComma: true });
|
|
28
|
+
if (errors.length)
|
|
29
|
+
throw new Error("Invalid JSONC configuration");
|
|
30
|
+
return value;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
// JSON and YAML remain supported without markdownlint-cli's JSONC parser.
|
|
35
|
+
}
|
|
36
|
+
parsers.push((text) => load(text));
|
|
37
|
+
return { ...api, parsers };
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
// Try the next installation without downloading a package.
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
throw new Error("markdownlint not available; install markdownlint-cli in the project to validate plans.");
|
|
44
|
+
}
|
|
45
|
+
function planLintConfig(repoRoot, api) {
|
|
46
|
+
let config;
|
|
47
|
+
// Merge ancestor .markdownlintrc files from outermost to nearest, like the CLI.
|
|
48
|
+
const rcPaths = [];
|
|
49
|
+
for (let dir = repoRoot;; dir = dirname(dir)) {
|
|
50
|
+
const candidate = join(dir, ".markdownlintrc");
|
|
51
|
+
if (existsSync(candidate))
|
|
52
|
+
rcPaths.unshift(candidate);
|
|
53
|
+
if (dirname(dir) === dir)
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
for (const file of rcPaths)
|
|
57
|
+
config = { ...config, ...api.readConfig(file, api.parsers) };
|
|
58
|
+
for (const ext of ["jsonc", "json", "yaml", "yml"]) {
|
|
59
|
+
const file = join(repoRoot, `.markdownlint.${ext}`);
|
|
60
|
+
if (existsSync(file)) {
|
|
61
|
+
config = { ...config, ...api.readConfig(file, api.parsers) };
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return config ?? DEFAULT_MARKDOWNLINT_CONFIG;
|
|
66
|
+
}
|
|
67
|
+
// Lint rendered source before formatting or replacing an existing schedule plan.
|
|
68
|
+
// A string input bypasses ignore globs for generated history directories.
|
|
69
|
+
export async function assertPlanMarkdownlint(repoRoot, taskId, outPath, content) {
|
|
70
|
+
const planPath = relative(repoRoot, outPath);
|
|
71
|
+
const label = `Task ${taskId}, plan ${planPath}`;
|
|
72
|
+
let errors;
|
|
73
|
+
try {
|
|
74
|
+
const api = await markdownlintApi(repoRoot);
|
|
75
|
+
const issues = api.lint({
|
|
76
|
+
strings: { [planPath]: content },
|
|
77
|
+
config: planLintConfig(repoRoot, api),
|
|
78
|
+
configParsers: api.parsers,
|
|
79
|
+
})[planPath] ?? [];
|
|
80
|
+
errors = issues
|
|
81
|
+
.map((issue) => `${planPath}: ${issue.lineNumber} ${issue.ruleNames.join("/")} ${issue.ruleDescription}${issue.errorDetail ? ` [${issue.errorDetail}]` : ""}`)
|
|
82
|
+
.join("\n");
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
throw new Error(`${label}: Failed to run markdownlint before plan generation: ${error instanceof Error ? error.message : String(error)}`);
|
|
86
|
+
}
|
|
87
|
+
if (errors)
|
|
88
|
+
throw new Error(`${label}: Plan Markdown notation violation before generation\n${errors}`);
|
|
89
|
+
}
|
package/dist/exec/plans-core.js
CHANGED
|
@@ -7,7 +7,7 @@ import { specdojoRootDir } from "../shared/specdojo-config.js";
|
|
|
7
7
|
import { kataDirsForKinds, resolveIncludedRulebooks, resolveKataRefs } from "../kata/kata.js";
|
|
8
8
|
import { resolveBasePath, resolveDeliverablePath } from "../catalog/paths.js";
|
|
9
9
|
import { isDctPlanFileName } from "../catalog/plan.js";
|
|
10
|
-
import { buildSpecdojoFrontmatter } from "../docs/frontmatter-namespace.js";
|
|
10
|
+
import { readSpecdojoNamespace, buildSpecdojoFrontmatter } from "../docs/frontmatter-namespace.js";
|
|
11
11
|
import { qualifyPracticeId, SPECDOJO_PRACTICE_AUTHORITY } from "../shared/practice-id.js";
|
|
12
12
|
import { MISSING } from "../shared/plan-templates.js";
|
|
13
13
|
export { MISSING, execTemplatePath, execTemplatesDir, injectCommonConventions, loadPlanTemplate, } from "../shared/plan-templates.js";
|
|
@@ -315,6 +315,33 @@ export function deliverableDependsOn(deliverable, projectId, catalogPath) {
|
|
|
315
315
|
});
|
|
316
316
|
return `\n${lines.join("\n")}`;
|
|
317
317
|
}
|
|
318
|
+
// based_on is declared evidence, not a new dependency edge. Keep the document's IDs verbatim.
|
|
319
|
+
export function deliverableBasedOn(deliverable) {
|
|
320
|
+
if (!deliverable)
|
|
321
|
+
return "なし";
|
|
322
|
+
const path = resolve(specdojoRootDir(), deliverable.resolvedPath);
|
|
323
|
+
if (!/\.(md|mdx|yaml|yml|json)$/.test(path) || !existsSync(path))
|
|
324
|
+
return "なし";
|
|
325
|
+
let metadata;
|
|
326
|
+
try {
|
|
327
|
+
const content = readFileSync(path, "utf8");
|
|
328
|
+
const parsed = /\.mdx?$/.test(path)
|
|
329
|
+
? readSpecdojoNamespace(content)
|
|
330
|
+
: load(content);
|
|
331
|
+
metadata = (parsed?.specdojo ?? parsed);
|
|
332
|
+
}
|
|
333
|
+
catch {
|
|
334
|
+
// Invalid metadata is reported by document validation; it must not prevent plan generation.
|
|
335
|
+
return "なし";
|
|
336
|
+
}
|
|
337
|
+
const refs = metadata?.based_on;
|
|
338
|
+
if (!Array.isArray(refs))
|
|
339
|
+
return "なし";
|
|
340
|
+
const ids = [
|
|
341
|
+
...new Set(refs.filter((ref) => typeof ref === "string" && !!ref.trim())),
|
|
342
|
+
];
|
|
343
|
+
return ids.length ? ids.map((ref) => `[[${ref}]]`).join("、") : "なし";
|
|
344
|
+
}
|
|
318
345
|
const PROJECT_CONTEXT_EXCLUDED_APPROACHES = new Set([
|
|
319
346
|
"cross-deliverable-dedup",
|
|
320
347
|
"rulebook-authoring",
|
|
@@ -357,6 +384,24 @@ export function projectContextSection(refs, deliverable, approach, projectId) {
|
|
|
357
384
|
export function deliverableOverview(deliverable) {
|
|
358
385
|
return deliverable?.deliverable.overview ?? MISSING;
|
|
359
386
|
}
|
|
387
|
+
export function deliverableBrief(deliverable) {
|
|
388
|
+
const brief = deliverable?.deliverable.brief?.trim();
|
|
389
|
+
if (!brief)
|
|
390
|
+
return "";
|
|
391
|
+
if (!brief.includes("\n")) {
|
|
392
|
+
return brief;
|
|
393
|
+
}
|
|
394
|
+
if (brief.startsWith("-")) {
|
|
395
|
+
return `\n ${brief
|
|
396
|
+
.split("\n")
|
|
397
|
+
.map((line) => line.trimEnd())
|
|
398
|
+
.join("\n ")}`;
|
|
399
|
+
}
|
|
400
|
+
return brief
|
|
401
|
+
.split("\n")
|
|
402
|
+
.map((line, idx) => (idx === 0 ? line : ` ${line}`))
|
|
403
|
+
.join("\n");
|
|
404
|
+
}
|
|
360
405
|
export function implementationEvidence(deliverable) {
|
|
361
406
|
const refs = deliverable?.deliverable.evidence_refs ?? [];
|
|
362
407
|
if (refs.length === 0)
|
|
@@ -1,12 +1,14 @@
|
|
|
1
|
+
import { registerInputSection } from "../register/input.js";
|
|
1
2
|
import { mkdirSync, writeFileSync } from "node:fs";
|
|
2
3
|
import { join } from "node:path";
|
|
3
|
-
import { DEFAULT_PROJECT_CONTEXT } from "../shared/specdojo-config.js";
|
|
4
|
+
import { DEFAULT_PROJECT_CONTEXT, specdojoRootDir } from "../shared/specdojo-config.js";
|
|
4
5
|
import { resolveDeliverableSchemaRef, resolveKataRefs } from "../kata/kata.js";
|
|
5
6
|
import { formatMarkdownFile } from "./format.js";
|
|
7
|
+
import { assertPlanMarkdownlint } from "./plan-markdownlint.js";
|
|
6
8
|
import { expandTemplate } from "./shared.js";
|
|
7
9
|
import { isAuthoringApproach } from "../kata/authoring.js";
|
|
8
10
|
import { isPlanningApproach } from "../register/planning.js";
|
|
9
|
-
import { MISSING, applicableReviewCriteria, crossDeliverableTargetDetails, deliverableDependsOn, deliverableName, deliverableOverview, deliverablePath, doneCriteriaChecklist, doneCriteriaGoals, doneCriteriaItems, execDocId, findDeliverableInfo, frontmatter, gradeFindingsText, gradeFindingTargetPath, gradeResultRef, gradeTargetKind, implementationEvidence, injectCommonConventions, kataRefState, loadPlanTemplate, loadRoles, loadViewpoints, ownerRoleFields, phaseDescriptionText, projectContextSection, repoRelativePath, reviewDoneCriteriaRows, reviewGradeSummaryText, rulebookIncludesText, targetDocIds, targetDocIdsForTask, } from "./plans-core.js";
|
|
11
|
+
import { MISSING, applicableReviewCriteria, crossDeliverableTargetDetails, deliverableDependsOn, deliverableBasedOn, deliverableBrief, deliverableName, deliverableOverview, deliverablePath, doneCriteriaChecklist, doneCriteriaGoals, doneCriteriaItems, execDocId, findDeliverableInfo, frontmatter, gradeFindingsText, gradeFindingTargetPath, gradeResultRef, gradeTargetKind, implementationEvidence, injectCommonConventions, kataRefState, loadPlanTemplate, loadRoles, loadViewpoints, ownerRoleFields, phaseDescriptionText, projectContextSection, repoRelativePath, reviewDoneCriteriaRows, reviewGradeSummaryText, rulebookIncludesText, targetDocIds, targetDocIdsForTask, } from "./plans-core.js";
|
|
10
12
|
function buildEditPlanMarkdown(template, task, deliverable, roleMap, vpMap, projectId, catalogPath, projectContext, resultRef, stem, crossDeliverables = new Map(), planOverrides) {
|
|
11
13
|
const cpm = task.cpm;
|
|
12
14
|
const onCriticalPath = cpm !== undefined && cpm.slack === 0;
|
|
@@ -38,6 +40,11 @@ function buildEditPlanMarkdown(template, task, deliverable, roleMap, vpMap, proj
|
|
|
38
40
|
_PHASE_DESCRIPTION_: phaseDescriptionText(task),
|
|
39
41
|
_DELIVERABLE_NAME_: deliverableName(deliverable),
|
|
40
42
|
_DELIVERABLE_DEPENDS_ON_: deliverableDependsOn(deliverable, projectId, catalogPath),
|
|
43
|
+
_DELIVERABLE_BASED_ON_: deliverableBasedOn(deliverable),
|
|
44
|
+
_REGISTER_INPUT_: registerInputSection(planOverrides?.registerInput)
|
|
45
|
+
? "下記「個票の入力(前提)」を参照。"
|
|
46
|
+
: "なし",
|
|
47
|
+
_DELIVERABLE_BRIEF_: deliverableBrief(deliverable),
|
|
41
48
|
_PROJECT_CONTEXT_: projectContextSection(projectContext, deliverable, task.approach, projectId),
|
|
42
49
|
_DELIVERABLE_OVERVIEW_: deliverableOverview(deliverable),
|
|
43
50
|
_IMPLEMENTATION_EVIDENCE_: deliverable?.catalogless
|
|
@@ -79,10 +86,29 @@ function buildEditPlanMarkdown(template, task, deliverable, roleMap, vpMap, proj
|
|
|
79
86
|
.filter((line) => !["recipe", "sample", "template"].some((kind) => refs[kind] === MISSING && line.includes(`_${kind.toUpperCase()}_REF_`)))
|
|
80
87
|
.join("\n")
|
|
81
88
|
: template;
|
|
82
|
-
|
|
89
|
+
const hasBrief = Boolean(deliverable?.deliverable.brief?.trim());
|
|
90
|
+
const templateWithoutBrief = hasBrief
|
|
91
|
+
? effectiveTemplate
|
|
92
|
+
: effectiveTemplate
|
|
93
|
+
.split("\n")
|
|
94
|
+
.filter((line) => !line.includes("_DELIVERABLE_BRIEF_"))
|
|
95
|
+
.join("\n");
|
|
96
|
+
const visibleTemplate = planOverrides?.origin === "register" && !planOverrides.registerInput?.length
|
|
97
|
+
? templateWithoutBrief
|
|
98
|
+
.split("\n")
|
|
99
|
+
.filter((line) => !line.includes("_REGISTER_INPUT_"))
|
|
100
|
+
.join("\n")
|
|
101
|
+
: templateWithoutBrief;
|
|
102
|
+
let body = expandTemplate(visibleTemplate, values);
|
|
83
103
|
if (deliverable?.catalogless && task.approach === "retrofit") {
|
|
84
104
|
body = body.replace("成果物カタログの `evidence_refs` から展開した", "個票に明記する");
|
|
85
105
|
}
|
|
106
|
+
const inputSection = registerInputSection(planOverrides?.registerInput);
|
|
107
|
+
if (inputSection) {
|
|
108
|
+
body = body.includes("_COMMON_CONVENTIONS_")
|
|
109
|
+
? body.replace("_COMMON_CONVENTIONS_", `${inputSection}\n_COMMON_CONVENTIONS_`)
|
|
110
|
+
: `${body.trimEnd()}\n\n${inputSection}`;
|
|
111
|
+
}
|
|
86
112
|
if (!planOverrides?.additionalConditions)
|
|
87
113
|
return body;
|
|
88
114
|
const section = [
|
|
@@ -130,6 +156,9 @@ function buildReviewPlanMarkdown(template, task, deliverable, criteria, vpMap, p
|
|
|
130
156
|
_PHASE_DESCRIPTION_: phaseDescriptionText(task),
|
|
131
157
|
_DELIVERABLE_NAME_: deliverableName(deliverable),
|
|
132
158
|
_DELIVERABLE_DEPENDS_ON_: deliverableDependsOn(deliverable, projectId, catalogPath),
|
|
159
|
+
_DELIVERABLE_BASED_ON_: deliverableBasedOn(deliverable),
|
|
160
|
+
_REGISTER_INPUT_: "なし",
|
|
161
|
+
_DELIVERABLE_BRIEF_: deliverableBrief(deliverable),
|
|
133
162
|
_PROJECT_CONTEXT_: projectContextSection(projectContext, deliverable, task.approach, projectId),
|
|
134
163
|
_DELIVERABLE_OVERVIEW_: deliverableOverview(deliverable),
|
|
135
164
|
_IMPLEMENTATION_EVIDENCE_: implementationEvidence(deliverable),
|
|
@@ -146,7 +175,14 @@ function buildReviewPlanMarkdown(template, task, deliverable, criteria, vpMap, p
|
|
|
146
175
|
_GRADE_SUMMARY_: reviewGradeSummaryText(projectId, gradeSubjectPath, reviewGradeOutcome),
|
|
147
176
|
_DONE_CRITERIA_ROWS_: reviewDoneCriteriaRows(applicableCriteria),
|
|
148
177
|
};
|
|
149
|
-
|
|
178
|
+
const hasBrief = Boolean(deliverable?.deliverable.brief?.trim());
|
|
179
|
+
const visibleTemplate = hasBrief
|
|
180
|
+
? template
|
|
181
|
+
: template
|
|
182
|
+
.split("\n")
|
|
183
|
+
.filter((line) => !line.includes("_DELIVERABLE_BRIEF_"))
|
|
184
|
+
.join("\n");
|
|
185
|
+
return expandTemplate(visibleTemplate, values);
|
|
150
186
|
}
|
|
151
187
|
async function writeTaskPlan(ctx, task, override) {
|
|
152
188
|
const mode = task.mode ?? "edit";
|
|
@@ -187,7 +223,10 @@ async function writeTaskPlan(ctx, task, override) {
|
|
|
187
223
|
? buildReviewPlanMarkdown(template, planTask, deliverable, criteria, ctx.vpMap, ctx.projectId, ctx.catalogPath, ctx.projectContext, resultRef, stem, ctx.reviewGradeOutcome)
|
|
188
224
|
: buildEditPlanMarkdown(template, planTask, deliverable, ctx.roleMap, ctx.vpMap, ctx.projectId, ctx.catalogPath, ctx.projectContext, resultRef, stem, crossDeliverables, override);
|
|
189
225
|
const schemaRef = resolveDeliverableSchemaRef(deliverable?.resolvedPath);
|
|
190
|
-
const content = injectCommonConventions(body, schemaRef, ctx.templateCache, mode)
|
|
226
|
+
const content = `${injectCommonConventions(body, schemaRef, ctx.templateCache, mode).replace(/[\r\n]+$/u, "")}\n`;
|
|
227
|
+
if (task.schedule_file && override?.origin !== "register") {
|
|
228
|
+
await assertPlanMarkdownlint(specdojoRootDir(), task.id, outPath, content);
|
|
229
|
+
}
|
|
191
230
|
writeFileSync(outPath, content, "utf8");
|
|
192
231
|
await formatMarkdownFile(outPath);
|
|
193
232
|
return outPath;
|
|
@@ -254,6 +293,7 @@ export async function generateRegisterApproachPlan(opts) {
|
|
|
254
293
|
targets: opts.targets,
|
|
255
294
|
...(opts.refs ? { refs: opts.refs } : {}),
|
|
256
295
|
...(opts.authoring ? { authoring: opts.authoring } : {}),
|
|
296
|
+
registerInput: opts.registerInput,
|
|
257
297
|
additionalConditions: opts.additionalConditions,
|
|
258
298
|
...(opts.outPath ? { outPath: opts.outPath } : {}),
|
|
259
299
|
stem: opts.stem,
|
|
@@ -37,7 +37,7 @@ export function planningPlanFields(opts) {
|
|
|
37
37
|
}
|
|
38
38
|
else {
|
|
39
39
|
const strategy = join(getProjectSchedulePath(opts.project), `sch-strategy-${unit}.yaml`).replaceAll("\\", "/");
|
|
40
|
-
common.push("### scope・intent の宣言と完了条件", "", `1. \`${join(getProjectTimelinePath(opts.project), "tml-index.yaml").replaceAll("\\", "/")}\` があれば対象 track の domains と依存・着手順を確認する。\`timeline build\` の register 由来の状態と既存カタログも確認する。`, `2. \`${strategy}\` に \`scope.catalogs\`(ID・リポジトリルートからのパス)、\`scope.include_kinds\` と \`approach_rules\` を宣言する。既存 scope の意図を保ち、各成果物の \`local_ids\` と \`intent\`(例: author-deliverable / bootstrap-kata-set / confirm-deliverable)、必要時の \`kata_target\` / \`bootstrap_scope\` を根拠付きで決める。`, "3. 主担当を `owner_rules` または生成時の `--owner` / `--default-owner` で明示する。`done_criteria.roles` を主担当と解釈しない。必要な kata の grade が不足なら先に評価し、不明な判断を推測で補わない。", `4. \`specdojo schedule strategy generate ${projectArg} --track ${unit}\` を実行し、scope・intent・担当・依存関係に関するエラーを解消する。既存 strategy の変更は差分を確認し、必要な場合だけ \`--force\` を指定する。`, `5. \`specdojo schedule build ${projectArg} --track ${unit}\` を通し、\`sch-track-${unit}.yaml\` が生成され、scope の成果物とタスクの対応・依存が一致することを確認する。`, "6. strategy と track の保存、scope 全件の intent と担当の解決、生成・検証の成功を完了基準とし、個票の作業内容・対応結果と実行記録へ判断と検証を記録する。カタログ本体と `tml-index.yaml` は変更しない。");
|
|
40
|
+
common.push("### scope・intent の宣言と完了条件", "", `1. \`${join(getProjectTimelinePath(opts.project), "tml-index.yaml").replaceAll("\\", "/")}\` があれば対象 track の domains と依存・着手順を確認する。\`timeline build\` の register 由来の状態と既存カタログも確認する。`, `2. \`${strategy}\` に \`scope.catalogs\`(ID・リポジトリルートからのパス)、\`scope.include_kinds\` と \`approach_rules\` を宣言する。既存 scope の意図を保ち、各成果物の \`local_ids\` と \`intent\`(例: author-deliverable / bootstrap-kata-set / confirm-deliverable)、必要時の \`kata_target\` / \`bootstrap_scope\` を根拠付きで決める。`, "3. 主担当を `owner_rules` または生成時の `--owner` / `--default-owner` で明示する。`done_criteria.roles` を主担当と解釈しない。必要な kata の grade が不足なら先に評価し、不明な判断を推測で補わない。", " 人の文脈記入から始める場合は `intent: draft-with-context` を選ぶ。必要な kata がすべて利用可能なら `draft` profile(context → draft → refine → review → finalize)になる。context と finalize は human、他は agent とし、refine は `fully-guided` で磨き込む。", ` context の担当者は \`specdojo exec claim ${projectArg} --task <context-task-id> --by <human>\` で着手し、\`specdojo deliverable scaffold ${projectArg} --target <doc-id>\` で雛形を作る。既存成果物は上書きしない。本文の \`_CONTEXT_:\` に固定前提・制約・調査や選定を任せる範囲を書く(例: \`_CONTEXT_: 既存 API を維持し、認証方式の候補を調べて提案してほしい。\`)。result に記入内容を残して \`specdojo exec complete ${projectArg} --task <context-task-id> --by <human>\` で draft へ渡す。human 用の plan は生成しない。`, `4. \`specdojo schedule strategy generate ${projectArg} --track ${unit}\` を実行し、scope・intent・担当・依存関係に関するエラーを解消する。既存 strategy の変更は差分を確認し、必要な場合だけ \`--force\` を指定する。`, `5. \`specdojo schedule build ${projectArg} --track ${unit}\` を通し、\`sch-track-${unit}.yaml\` が生成され、scope の成果物とタスクの対応・依存が一致することを確認する。`, "6. strategy と track の保存、scope 全件の intent と担当の解決、生成・検証の成功を完了基準とし、個票の作業内容・対応結果と実行記録へ判断と検証を記録する。カタログ本体と `tml-index.yaml` は変更しない。");
|
|
41
41
|
}
|
|
42
42
|
return { refs, conditions: common.join("\n") };
|
|
43
43
|
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { existsSync, linkSync, mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync, } from "node:fs";
|
|
3
|
+
import { join, resolve } from "node:path";
|
|
4
|
+
import { isValidBranchName } from "../shared/branch-template.js";
|
|
5
|
+
import { gitOutput, gitResult, worktreeNameFromTaskId } from "./worktree.js";
|
|
6
|
+
function recordDirectory(repoRoot) {
|
|
7
|
+
const common = gitOutput(repoRoot, ["rev-parse", "--git-common-dir"]).trim();
|
|
8
|
+
return resolve(repoRoot, common, "specdojo", "product-branches");
|
|
9
|
+
}
|
|
10
|
+
function recordPath(repoRoot, branch) {
|
|
11
|
+
return join(recordDirectory(repoRoot), `${createHash("sha256").update(branch).digest("hex")}.json`);
|
|
12
|
+
}
|
|
13
|
+
export function productBranchRecords(repoRoot) {
|
|
14
|
+
const directory = recordDirectory(repoRoot);
|
|
15
|
+
if (!existsSync(directory))
|
|
16
|
+
return [];
|
|
17
|
+
return readdirSync(directory)
|
|
18
|
+
.filter((name) => name.endsWith(".json"))
|
|
19
|
+
.map((name) => {
|
|
20
|
+
const record = JSON.parse(readFileSync(join(directory, name), "utf8"));
|
|
21
|
+
if (!record ||
|
|
22
|
+
typeof record !== "object" ||
|
|
23
|
+
!("taskId" in record) ||
|
|
24
|
+
!("branch" in record) ||
|
|
25
|
+
typeof record.taskId !== "string" ||
|
|
26
|
+
typeof record.branch !== "string") {
|
|
27
|
+
throw new Error(`Invalid runner product branch record: ${name}`);
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
taskId: record.taskId,
|
|
31
|
+
branch: record.branch,
|
|
32
|
+
...("startCommit" in record && typeof record.startCommit === "string"
|
|
33
|
+
? { startCommit: record.startCommit }
|
|
34
|
+
: {}),
|
|
35
|
+
};
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export function recordedProductBranch(repoRoot, taskId) {
|
|
39
|
+
const records = productBranchRecords(repoRoot).filter((record) => record.taskId === taskId);
|
|
40
|
+
if (records.length > 1)
|
|
41
|
+
throw new Error(`Multiple runner product branches recorded for ${taskId}`);
|
|
42
|
+
return records[0]?.branch;
|
|
43
|
+
}
|
|
44
|
+
export function productBranchExists(repoRoot, branch) {
|
|
45
|
+
return (gitResult(repoRoot, ["show-ref", "--verify", "--quiet", `refs/heads/${branch}`]).status === 0);
|
|
46
|
+
}
|
|
47
|
+
/** A legacy name is usable only when no other task has explicitly claimed it. */
|
|
48
|
+
export function existingProductTaskBranch(repoRoot, taskId) {
|
|
49
|
+
const recorded = recordedProductBranch(repoRoot, taskId);
|
|
50
|
+
if (recorded)
|
|
51
|
+
return recorded;
|
|
52
|
+
const legacy = `exec/${worktreeNameFromTaskId(taskId)}`;
|
|
53
|
+
if (productBranchRecords(repoRoot).some((record) => record.branch === legacy))
|
|
54
|
+
return undefined;
|
|
55
|
+
return productBranchExists(repoRoot, legacy) ? legacy : undefined;
|
|
56
|
+
}
|
|
57
|
+
/** Legacy runs may be adopted only under their exact conventional branch name. */
|
|
58
|
+
export function assertProductBranchAvailable(repoRoot, taskId, branch) {
|
|
59
|
+
if (!isValidBranchName(repoRoot, branch)) {
|
|
60
|
+
throw new Error(`Invalid product branch name: ${branch}; use --branch <repo>=<name>`);
|
|
61
|
+
}
|
|
62
|
+
const owner = productBranchRecords(repoRoot).find((record) => record.branch === branch)?.taskId;
|
|
63
|
+
const legacy = branch === `exec/${worktreeNameFromTaskId(taskId)}`;
|
|
64
|
+
if ((owner && owner !== taskId) || (!owner && !legacy && productBranchExists(repoRoot, branch))) {
|
|
65
|
+
throw new Error(`Product branch ${branch} already exists or is reserved for ${owner ?? "another item"}; ` +
|
|
66
|
+
`change topic or use exec run --branch <repo>=<name> (no automatic suffix is added)`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/** Exclusive creation also prevents concurrent tasks from reserving the same branch. */
|
|
70
|
+
export function reserveProductBranch(repoRoot, taskId, branch, startPoint = "HEAD") {
|
|
71
|
+
assertProductBranchAvailable(repoRoot, taskId, branch);
|
|
72
|
+
const previous = recordedProductBranch(repoRoot, taskId);
|
|
73
|
+
if (previous && previous !== branch) {
|
|
74
|
+
throw new Error(`Product branch for ${taskId} is already recorded as ${previous}; resume that branch or discard the old lifecycle before choosing ${branch}`);
|
|
75
|
+
}
|
|
76
|
+
mkdirSync(recordDirectory(repoRoot), { recursive: true });
|
|
77
|
+
const path = recordPath(repoRoot, branch);
|
|
78
|
+
if (existsSync(path))
|
|
79
|
+
return;
|
|
80
|
+
const temporary = `${path}.${randomUUID()}.tmp`;
|
|
81
|
+
try {
|
|
82
|
+
const startCommit = gitOutput(repoRoot, [
|
|
83
|
+
"rev-parse",
|
|
84
|
+
"--verify",
|
|
85
|
+
`${startPoint}^{commit}`,
|
|
86
|
+
]).trim();
|
|
87
|
+
// Publish a complete record atomically; readers never observe partial JSON.
|
|
88
|
+
writeFileSync(temporary, JSON.stringify({ taskId, branch, startCommit }), { flag: "wx" });
|
|
89
|
+
linkSync(temporary, path);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code !== "EEXIST")
|
|
93
|
+
throw error;
|
|
94
|
+
assertProductBranchAvailable(repoRoot, taskId, branch);
|
|
95
|
+
}
|
|
96
|
+
finally {
|
|
97
|
+
if (existsSync(temporary))
|
|
98
|
+
unlinkSync(temporary);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
export function forgetProductBranch(repoRoot, branch) {
|
|
102
|
+
const path = recordPath(repoRoot, branch);
|
|
103
|
+
if (existsSync(path))
|
|
104
|
+
unlinkSync(path);
|
|
105
|
+
}
|