@shinnodua/agent-workflows 0.0.0-stage → 0.2.8
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/.agents/agents/backend-developer/agent.md +39 -0
- package/.agents/agents/frontend-developer/agent.md +42 -0
- package/.agents/agents/project-manager/agent.md +37 -0
- package/.agents/agents/tech-lead/agent.md +41 -0
- package/.agents/agents/ui-ux-designer/agent.md +41 -0
- package/.agents/skills/add-project/SKILL.md +90 -0
- package/.agents/skills/add-project/agents/openai.yaml +4 -0
- package/.agents/skills/add-project/references/save-protocol.md +90 -0
- package/.agents/skills/approve-plan/SKILL.md +86 -0
- package/.agents/skills/approve-plan/agents/openai.yaml +4 -0
- package/.agents/skills/approve-prd/SKILL.md +59 -0
- package/.agents/skills/approve-prd/agents/openai.yaml +4 -0
- package/.agents/skills/auto-mode/SKILL.md +103 -0
- package/.agents/skills/auto-mode/agents/openai.yaml +4 -0
- package/.agents/skills/create-design/SKILL.md +197 -0
- package/.agents/skills/create-design/agents/openai.yaml +4 -0
- package/.agents/skills/create-diagram/SKILL.md +83 -0
- package/.agents/skills/create-diagram/agents/openai.yaml +4 -0
- package/.agents/skills/create-plan/SKILL.md +104 -0
- package/.agents/skills/create-plan/agents/openai.yaml +4 -0
- package/.agents/skills/create-prd/SKILL.md +82 -0
- package/.agents/skills/create-prd/agents/openai.yaml +4 -0
- package/.agents/skills/griling-plan/SKILL.md +114 -0
- package/.agents/skills/griling-plan/agents/openai.yaml +4 -0
- package/.agents/skills/griling-prd/SKILL.md +91 -0
- package/.agents/skills/griling-prd/agents/openai.yaml +4 -0
- package/.agents/skills/package-installation/SKILL.md +67 -0
- package/.agents/skills/package-installation/agents/openai.yaml +4 -0
- package/.agents/skills/project-setup/SKILL.md +104 -0
- package/.agents/skills/project-setup/agents/openai.yaml +3 -0
- package/.agents/skills/research/SKILL.md +61 -0
- package/.agents/skills/research/agents/openai.yaml +4 -0
- package/.agents/skills/sprint-meeting/SKILL.md +230 -0
- package/.agents/skills/sprint-meeting/agents/openai.yaml +4 -0
- package/.claude/agents/backend-developer.md +7 -0
- package/.claude/agents/frontend-developer.md +7 -0
- package/.claude/agents/project-manager.md +7 -0
- package/.claude/agents/tech-lead.md +7 -0
- package/.claude/agents/ui-ux-designer.md +7 -0
- package/.claude/skills/add-project/SKILL.md +10 -0
- package/.claude/skills/approve-plan/SKILL.md +8 -0
- package/.claude/skills/approve-prd/SKILL.md +8 -0
- package/.claude/skills/auto-mode/SKILL.md +8 -0
- package/.claude/skills/create-design/SKILL.md +8 -0
- package/.claude/skills/create-diagram/SKILL.md +8 -0
- package/.claude/skills/create-plan/SKILL.md +8 -0
- package/.claude/skills/create-prd/SKILL.md +8 -0
- package/.claude/skills/griling-plan/SKILL.md +8 -0
- package/.claude/skills/griling-prd/SKILL.md +8 -0
- package/.claude/skills/package-installation/SKILL.md +8 -0
- package/.claude/skills/project-setup/SKILL.md +8 -0
- package/.claude/skills/research/SKILL.md +8 -0
- package/.claude/skills/sprint-meeting/SKILL.md +8 -0
- package/.codex/prompts/add-project.md +3 -0
- package/.codex/prompts/approve-plan.md +3 -0
- package/.codex/prompts/approve-prd.md +3 -0
- package/.codex/prompts/auto-mode.md +3 -0
- package/.codex/prompts/create-design.md +3 -0
- package/.codex/prompts/create-diagram.md +3 -0
- package/.codex/prompts/create-plan.md +3 -0
- package/.codex/prompts/create-prd.md +3 -0
- package/.codex/prompts/griling-plan.md +3 -0
- package/.codex/prompts/griling-prd.md +3 -0
- package/.codex/prompts/grilling-plan.md +3 -0
- package/.codex/prompts/project-setup.md +3 -0
- package/.codex/prompts/research.md +3 -0
- package/.codex/prompts/sprint-meeting.md +3 -0
- package/.gitmodules.example +9 -0
- package/AGENTS.md +84 -0
- package/CLAUDE.md +1 -0
- package/INSTALL.md +284 -0
- package/LICENSE +21 -0
- package/README.md +342 -2
- package/bin/postinstall.js +57 -0
- package/bin/workflows.js +1172 -0
- package/bin/workflows.test.mjs +682 -0
- package/commands/add-project.md +20 -0
- package/commands/approve-plan.md +25 -0
- package/commands/approve-prd.md +24 -0
- package/commands/auto-mode.md +15 -0
- package/commands/create-design.md +20 -0
- package/commands/create-diagram.md +16 -0
- package/commands/create-plan.md +22 -0
- package/commands/create-prd.md +16 -0
- package/commands/griling-plan.md +16 -0
- package/commands/griling-prd.md +16 -0
- package/commands/grilling-plan.md +16 -0
- package/commands/project-setup.md +16 -0
- package/commands/research.md +16 -0
- package/commands/sprint-meeting.md +16 -0
- package/dashboard/.agents/skills/coding-conventions/SKILL.md +76 -0
- package/dashboard/.agents/skills/coding-conventions/agents/openai.yaml +4 -0
- package/dashboard/.agents/skills/design-system-guideline/SKILL.md +51 -0
- package/dashboard/.agents/skills/design-system-guideline/agents/openai.yaml +4 -0
- package/dashboard/.agents/skills/lint-and-fix/SKILL.md +55 -0
- package/dashboard/.agents/skills/lint-and-fix/agents/openai.yaml +4 -0
- package/dashboard/.agents/skills/taste-ui/SKILL.md +45 -0
- package/dashboard/.agents/skills/taste-ui/agents/openai.yaml +4 -0
- package/dashboard/AGENTS.md +43 -0
- package/dashboard/bun.lock +352 -0
- package/dashboard/index.html +12 -0
- package/dashboard/package.json +32 -0
- package/dashboard/src/App.tsx +5 -0
- package/dashboard/src/features/task-status/components/ActionRequiredPanel/ActionRequiredPanel.module.css +85 -0
- package/dashboard/src/features/task-status/components/ActionRequiredPanel/ActionRequiredPanel.tsx +80 -0
- package/dashboard/src/features/task-status/components/ArtifactButton/ArtifactButton.module.css +25 -0
- package/dashboard/src/features/task-status/components/ArtifactButton/ArtifactButton.tsx +29 -0
- package/dashboard/src/features/task-status/components/ArtifactSummaryCards/ArtifactSummaryCards.module.css +29 -0
- package/dashboard/src/features/task-status/components/ArtifactSummaryCards/ArtifactSummaryCards.tsx +35 -0
- package/dashboard/src/features/task-status/components/CategoryPanel/CategoryPanel.module.css +85 -0
- package/dashboard/src/features/task-status/components/CategoryPanel/CategoryPanel.tsx +150 -0
- package/dashboard/src/features/task-status/components/DashboardHeader/DashboardHeader.module.css +41 -0
- package/dashboard/src/features/task-status/components/DashboardHeader/DashboardHeader.tsx +41 -0
- package/dashboard/src/features/task-status/components/FilesPanel/FilesPanel.module.css +25 -0
- package/dashboard/src/features/task-status/components/FilesPanel/FilesPanel.tsx +40 -0
- package/dashboard/src/features/task-status/components/HardnessEngineeringPanel/HardnessEngineeringPanel.module.css +330 -0
- package/dashboard/src/features/task-status/components/HardnessEngineeringPanel/HardnessEngineeringPanel.tsx +299 -0
- package/dashboard/src/features/task-status/components/LifecyclePanel/LifecyclePanel.module.css +74 -0
- package/dashboard/src/features/task-status/components/LifecyclePanel/LifecyclePanel.tsx +79 -0
- package/dashboard/src/features/task-status/components/MarkdownDialog/MarkdownDialog.module.css +133 -0
- package/dashboard/src/features/task-status/components/MarkdownDialog/MarkdownDialog.tsx +233 -0
- package/dashboard/src/features/task-status/components/Sidebar/Sidebar.module.css +53 -0
- package/dashboard/src/features/task-status/components/Sidebar/Sidebar.tsx +163 -0
- package/dashboard/src/features/task-status/components/StatusBadge/StatusBadge.module.css +41 -0
- package/dashboard/src/features/task-status/components/StatusBadge/StatusBadge.tsx +48 -0
- package/dashboard/src/features/task-status/components/TaskOverview/TaskOverview.module.css +97 -0
- package/dashboard/src/features/task-status/components/TaskOverview/TaskOverview.tsx +128 -0
- package/dashboard/src/features/task-status/components/TaskStatusDashboard/TaskStatusDashboard.module.css +9 -0
- package/dashboard/src/features/task-status/components/TaskStatusDashboard/TaskStatusDashboard.tsx +318 -0
- package/dashboard/src/features/task-status/components/WorkflowPanel/WorkflowPanel.module.css +221 -0
- package/dashboard/src/features/task-status/components/WorkflowPanel/WorkflowPanel.tsx +344 -0
- package/dashboard/src/features/task-status/taskStatusConfig.ts +100 -0
- package/dashboard/src/features/task-status/utils/actionItems.ts +247 -0
- package/dashboard/src/features/task-status/utils/artifactGrouping.ts +328 -0
- package/dashboard/src/features/task-status/utils/hardnessScanner.ts +406 -0
- package/dashboard/src/features/task-status/utils/lifecycle.ts +73 -0
- package/dashboard/src/features/task-status/utils/markdownInline/markdownInline.module.css +11 -0
- package/dashboard/src/features/task-status/utils/markdownInline/markdownInline.tsx +104 -0
- package/dashboard/src/features/task-status/utils/markdownLinks.ts +83 -0
- package/dashboard/src/features/task-status/utils/markdownRenderer/markdownRenderer.module.css +74 -0
- package/dashboard/src/features/task-status/utils/markdownRenderer/markdownRenderer.tsx +326 -0
- package/dashboard/src/features/task-status/utils/status.ts +7 -0
- package/dashboard/src/features/task-status/utils/test/actionItems.test.ts +134 -0
- package/dashboard/src/features/task-status/utils/test/artifactGrouping.test.ts +294 -0
- package/dashboard/src/features/task-status/utils/test/hardnessScanner.test.ts +138 -0
- package/dashboard/src/features/task-status/utils/test/lifecycle.test.ts +49 -0
- package/dashboard/src/features/task-status/utils/test/markdownInline.test.ts +41 -0
- package/dashboard/src/features/task-status/utils/test/markdownLinks.test.ts +158 -0
- package/dashboard/src/features/task-status/utils/test/workspaceMetadata.test.ts +37 -0
- package/dashboard/src/features/task-status/utils/workspaceMetadata.ts +175 -0
- package/dashboard/src/main.tsx +16 -0
- package/dashboard/src/shared/design-system.css +134 -0
- package/dashboard/src/shared/design-system.tsx +84 -0
- package/dashboard/src/styles.css +41 -0
- package/dashboard/src/types.ts +133 -0
- package/dashboard/src/workspace-artifacts.d.ts +9 -0
- package/dashboard/tsconfig.json +22 -0
- package/dashboard/vite.config.ts +579 -0
- package/designs/.gitkeep +1 -0
- package/docs/add-project-command-completion.md +117 -0
- package/docs/public-npm-registry-completion.md +104 -0
- package/docs/workflows.png +0 -0
- package/docs/workspace-template-setup.md +229 -0
- package/meeting-logs/.gitkeep +1 -0
- package/modules/.gitkeep +1 -0
- package/package.json +96 -5
- package/plans/.gitkeep +1 -0
- package/prds/.gitkeep +1 -0
- package/project/PROJECT.md +26 -0
- package/project/repositories.json +72 -0
- package/project/validation.json +9 -0
- package/project/workflows.json +20 -0
- package/research/.gitkeep +1 -0
- package/roles/backend-developer.md +26 -0
- package/roles/frontend-developer.md +25 -0
- package/roles/project-manager.md +42 -0
- package/roles/tech-lead.md +42 -0
- package/roles/ui-ux-designer.md +43 -0
- package/scripts/add-project.mjs +990 -0
- package/scripts/add-project.test.mjs +804 -0
- package/scripts/check-staged-security.mjs +97 -0
- package/scripts/check-staged-security.test.mjs +68 -0
- package/scripts/workspace-integrity.ts +220 -0
- package/templates/auto-mode-completion-summary-template.md +78 -0
- package/templates/meeting-log-template.md +177 -0
- package/templates/plan-template.md +219 -0
- package/templates/prd-template.md +106 -0
- package/templates/research-template.md +119 -0
- package/workflows.md +590 -0
- package/workspace.config.json +43 -0
|
@@ -0,0 +1,990 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/** Deterministic, explicit-save backend for the conversational add-project skill. */
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
4
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
5
|
+
import fs from "node:fs";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
|
|
10
|
+
const PROFILE = "project/repositories.json";
|
|
11
|
+
const WORKFLOWS = "project/workflows.json";
|
|
12
|
+
const MODULES = ".gitmodules";
|
|
13
|
+
const files = [PROFILE, WORKFLOWS, MODULES];
|
|
14
|
+
const artifacts = ["plans", "designs", "research", "docs"];
|
|
15
|
+
const own = (value, key) => Object.hasOwn(value, key);
|
|
16
|
+
const hasControl = (value) =>
|
|
17
|
+
[...value].some((character) => character.charCodeAt(0) < 32);
|
|
18
|
+
const digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
19
|
+
const json = (value) => `${JSON.stringify(value, null, "\t")}\n`;
|
|
20
|
+
const fail = (message) => {
|
|
21
|
+
throw new Error(message);
|
|
22
|
+
};
|
|
23
|
+
const read = (name) =>
|
|
24
|
+
fs.existsSync(name) ? fs.readFileSync(name, "utf8") : null;
|
|
25
|
+
const run = (root, args, options = {}) => {
|
|
26
|
+
// Hooks export repository-local variables; every operation here selects its
|
|
27
|
+
// repository by cwd, including checkouts whose Git metadata lives elsewhere.
|
|
28
|
+
const environment = { ...process.env, ...options.env };
|
|
29
|
+
for (const key of [
|
|
30
|
+
"GIT_DIR",
|
|
31
|
+
"GIT_WORK_TREE",
|
|
32
|
+
"GIT_INDEX_FILE",
|
|
33
|
+
"GIT_COMMON_DIR",
|
|
34
|
+
"GIT_OBJECT_DIRECTORY",
|
|
35
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
36
|
+
"GIT_PREFIX",
|
|
37
|
+
"GIT_SHALLOW_FILE",
|
|
38
|
+
"GIT_GRAFT_FILE",
|
|
39
|
+
"GIT_IMPLICIT_WORK_TREE",
|
|
40
|
+
])
|
|
41
|
+
delete environment[key];
|
|
42
|
+
const result = spawnSync("git", ["-c", "core.hooksPath=/dev/null", ...args], {
|
|
43
|
+
cwd: root,
|
|
44
|
+
encoding: "utf8",
|
|
45
|
+
env: {
|
|
46
|
+
...environment,
|
|
47
|
+
GIT_TERMINAL_PROMPT: "0",
|
|
48
|
+
GIT_CONFIG_NOSYSTEM: "1",
|
|
49
|
+
},
|
|
50
|
+
input: options.input,
|
|
51
|
+
});
|
|
52
|
+
if (result.status !== 0 && !options.optional)
|
|
53
|
+
fail(
|
|
54
|
+
`Git operation failed (${args[0]}); check repository access and local Git state.`,
|
|
55
|
+
);
|
|
56
|
+
return result.status === 0
|
|
57
|
+
? options.raw
|
|
58
|
+
? result.stdout
|
|
59
|
+
: result.stdout.trimEnd()
|
|
60
|
+
: null;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** Equivalent HTTPS/SSH forms share an identity; paths retain case on unknown hosts. */
|
|
64
|
+
export function normalizeUrl(value, { allowLocal = false } = {}) {
|
|
65
|
+
if (
|
|
66
|
+
typeof value !== "string" ||
|
|
67
|
+
/\s/.test(value) ||
|
|
68
|
+
hasControl(value) ||
|
|
69
|
+
value.startsWith("-")
|
|
70
|
+
)
|
|
71
|
+
fail("Use a clean HTTPS or SSH repository URL without credentials.");
|
|
72
|
+
if (allowLocal && path.isAbsolute(value))
|
|
73
|
+
return `local:${path.resolve(value)}`;
|
|
74
|
+
let host;
|
|
75
|
+
let pathname;
|
|
76
|
+
if (/^https:\/\//.test(value) || /^ssh:\/\//.test(value)) {
|
|
77
|
+
let parsed;
|
|
78
|
+
try {
|
|
79
|
+
parsed = new URL(value);
|
|
80
|
+
} catch {
|
|
81
|
+
fail("Invalid repository URL.");
|
|
82
|
+
}
|
|
83
|
+
if (
|
|
84
|
+
parsed.password ||
|
|
85
|
+
(parsed.protocol === "https:" && parsed.username) ||
|
|
86
|
+
parsed.search ||
|
|
87
|
+
parsed.hash
|
|
88
|
+
)
|
|
89
|
+
fail(
|
|
90
|
+
"Use a clean repository URL without embedded credentials, query, or fragment.",
|
|
91
|
+
);
|
|
92
|
+
host = parsed.host.toLowerCase();
|
|
93
|
+
pathname = parsed.pathname;
|
|
94
|
+
if (parsed.protocol === "ssh:" && parsed.port === "22")
|
|
95
|
+
host = parsed.hostname.toLowerCase();
|
|
96
|
+
} else {
|
|
97
|
+
const scp = value.match(/^(?:[a-zA-Z0-9_.-]+@)?([a-zA-Z0-9.-]+):([^:]+)$/);
|
|
98
|
+
if (!scp)
|
|
99
|
+
fail("Use a clean HTTPS or SSH repository URL without credentials.");
|
|
100
|
+
host = scp[1].toLowerCase();
|
|
101
|
+
pathname = scp[2];
|
|
102
|
+
}
|
|
103
|
+
pathname = pathname.replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
|
|
104
|
+
if (
|
|
105
|
+
!host ||
|
|
106
|
+
host.startsWith("-") ||
|
|
107
|
+
!pathname ||
|
|
108
|
+
pathname
|
|
109
|
+
.split("/")
|
|
110
|
+
.some((part) => !part || part === "." || part === "..") ||
|
|
111
|
+
/[%\\]/.test(pathname)
|
|
112
|
+
)
|
|
113
|
+
fail("Invalid repository identity.");
|
|
114
|
+
if (host === "github.com") pathname = pathname.toLowerCase();
|
|
115
|
+
return `${host}/${pathname}`;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function contained(root, relative, { module = false } = {}) {
|
|
119
|
+
if (
|
|
120
|
+
typeof relative !== "string" ||
|
|
121
|
+
!relative ||
|
|
122
|
+
path.isAbsolute(relative) ||
|
|
123
|
+
relative.includes("\\") ||
|
|
124
|
+
relative
|
|
125
|
+
.split("/")
|
|
126
|
+
.some((part) => !part || part === "." || part === "..") ||
|
|
127
|
+
hasControl(relative)
|
|
128
|
+
)
|
|
129
|
+
fail("Paths must be normalized workspace-relative paths.");
|
|
130
|
+
if (module && (!relative.startsWith("modules/") || relative === "modules/"))
|
|
131
|
+
fail("Repository paths must be below modules/.");
|
|
132
|
+
let cursor = root;
|
|
133
|
+
for (const part of relative.split("/")) {
|
|
134
|
+
cursor = path.join(cursor, part);
|
|
135
|
+
let stat;
|
|
136
|
+
try {
|
|
137
|
+
stat = fs.lstatSync(cursor);
|
|
138
|
+
} catch (error) {
|
|
139
|
+
if (error.code !== "ENOENT") throw error;
|
|
140
|
+
}
|
|
141
|
+
if (stat?.isSymbolicLink())
|
|
142
|
+
fail("Symlink paths require explicit resolution before saving.");
|
|
143
|
+
}
|
|
144
|
+
return path.join(root, relative);
|
|
145
|
+
}
|
|
146
|
+
function validateEntry(root, entry, options) {
|
|
147
|
+
if (!entry || typeof entry !== "object" || Array.isArray(entry))
|
|
148
|
+
fail("Each entry must be a repository profile object.");
|
|
149
|
+
for (const key of ["id", "name", "path", "url", "purpose", "agentGuide"])
|
|
150
|
+
if (typeof entry[key] !== "string" || !entry[key].trim())
|
|
151
|
+
fail(`Entry requires a nonempty ${key}.`);
|
|
152
|
+
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/.test(entry.id))
|
|
153
|
+
fail(
|
|
154
|
+
"Repository IDs must contain only letters, digits, hyphens, or underscores.",
|
|
155
|
+
);
|
|
156
|
+
normalizeUrl(entry.url, options);
|
|
157
|
+
contained(root, entry.path, { module: true });
|
|
158
|
+
for (const key of ["scope", "platforms", "codeScanDirectories", "validation"])
|
|
159
|
+
if (
|
|
160
|
+
!Array.isArray(entry[key]) ||
|
|
161
|
+
entry[key].some((item) => typeof item !== "string" || !item.trim())
|
|
162
|
+
)
|
|
163
|
+
fail(`${key} must be an array of nonempty strings.`);
|
|
164
|
+
if (!entry.scope.length || !entry.platforms.length)
|
|
165
|
+
fail("Accept at least one scope and platform.");
|
|
166
|
+
if (
|
|
167
|
+
!entry.artifactDirectories ||
|
|
168
|
+
typeof entry.artifactDirectories !== "object" ||
|
|
169
|
+
Array.isArray(entry.artifactDirectories)
|
|
170
|
+
)
|
|
171
|
+
fail("artifactDirectories must be an object.");
|
|
172
|
+
for (const relative of [
|
|
173
|
+
entry.agentGuide,
|
|
174
|
+
...artifacts.map((key) => entry.artifactDirectories[key]),
|
|
175
|
+
...Object.values(entry.artifactDirectories),
|
|
176
|
+
...entry.codeScanDirectories,
|
|
177
|
+
]) {
|
|
178
|
+
contained(root, relative);
|
|
179
|
+
if (!relative.startsWith(`${entry.path}/`))
|
|
180
|
+
fail(
|
|
181
|
+
"Repository guidance, artifacts, and scan paths must be inside its checkout.",
|
|
182
|
+
);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Exact shipped records, independent of the consuming workspace's current profile.
|
|
187
|
+
const templateProfiles = JSON.parse(
|
|
188
|
+
fs.readFileSync(
|
|
189
|
+
new URL("../project/repositories.json", import.meta.url),
|
|
190
|
+
"utf8",
|
|
191
|
+
),
|
|
192
|
+
).repositories;
|
|
193
|
+
function isTemplate(entry) {
|
|
194
|
+
const shipped = templateProfiles.find(
|
|
195
|
+
(item) =>
|
|
196
|
+
item.id === entry.id &&
|
|
197
|
+
item.url &&
|
|
198
|
+
normalizeUrl(item.url).startsWith("github.com/example/"),
|
|
199
|
+
);
|
|
200
|
+
return shipped && stable(shipped) === stable(entry);
|
|
201
|
+
}
|
|
202
|
+
function stable(value) {
|
|
203
|
+
if (Array.isArray(value)) return `[${value.map(stable).join(",")}]`;
|
|
204
|
+
if (value && typeof value === "object")
|
|
205
|
+
return `{${Object.keys(value)
|
|
206
|
+
.sort()
|
|
207
|
+
.map((key) => `${JSON.stringify(key)}:${stable(value[key])}`)
|
|
208
|
+
.join(",")}}`;
|
|
209
|
+
return JSON.stringify(value);
|
|
210
|
+
}
|
|
211
|
+
function indexEntry(root, name) {
|
|
212
|
+
return run(root, ["ls-files", "--stage", "--", name]);
|
|
213
|
+
}
|
|
214
|
+
function indexedText(root, name) {
|
|
215
|
+
const entry = indexEntry(root, name);
|
|
216
|
+
if (!entry) return null;
|
|
217
|
+
if (!entry.startsWith("100644 ") && !entry.startsWith("100755 "))
|
|
218
|
+
fail("Resolve nonregular or unmerged configuration index entries first.");
|
|
219
|
+
if (entry.split("\n").length !== 1 || !entry.includes(" 0\t"))
|
|
220
|
+
fail("Resolve unmerged configuration entries first.");
|
|
221
|
+
return run(root, ["show", `:${name}`], { raw: true });
|
|
222
|
+
}
|
|
223
|
+
function configRead(text, key) {
|
|
224
|
+
if (text === null) return null;
|
|
225
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "add-project-config-"));
|
|
226
|
+
try {
|
|
227
|
+
const name = path.join(dir, "config");
|
|
228
|
+
fs.writeFileSync(name, text);
|
|
229
|
+
return run(dir, ["config", "--file", name, "--get", key], {
|
|
230
|
+
optional: true,
|
|
231
|
+
});
|
|
232
|
+
} finally {
|
|
233
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
function moduleRecords(text) {
|
|
237
|
+
if (text === null || !text.trim()) return [];
|
|
238
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "add-project-config-"));
|
|
239
|
+
try {
|
|
240
|
+
const name = path.join(dir, "config");
|
|
241
|
+
fs.writeFileSync(name, text);
|
|
242
|
+
run(dir, ["config", "--file", name, "--list"]);
|
|
243
|
+
const result = run(
|
|
244
|
+
dir,
|
|
245
|
+
["config", "--file", name, "--get-regexp", "^submodule\\..*\\.path$"],
|
|
246
|
+
{ optional: true },
|
|
247
|
+
);
|
|
248
|
+
return result
|
|
249
|
+
? result.split("\n").map((line) => {
|
|
250
|
+
const split = line.indexOf(" ");
|
|
251
|
+
const key = line.slice(0, split);
|
|
252
|
+
const section = key.slice(0, -5);
|
|
253
|
+
return {
|
|
254
|
+
section,
|
|
255
|
+
path: line.slice(split + 1),
|
|
256
|
+
url: configRead(text, `${section}.url`),
|
|
257
|
+
keys: run(dir, [
|
|
258
|
+
"config",
|
|
259
|
+
"--file",
|
|
260
|
+
name,
|
|
261
|
+
"--name-only",
|
|
262
|
+
"--get-regexp",
|
|
263
|
+
`^${section.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\.`,
|
|
264
|
+
]).split("\n"),
|
|
265
|
+
};
|
|
266
|
+
})
|
|
267
|
+
: [];
|
|
268
|
+
} finally {
|
|
269
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
function editModules(text, entries, removals) {
|
|
273
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "add-project-config-"));
|
|
274
|
+
try {
|
|
275
|
+
const name = path.join(dir, "config");
|
|
276
|
+
// git config --remove-section also discards trailing comments. Remove only
|
|
277
|
+
// reviewed template headers/keys, retaining every standalone/inline comment.
|
|
278
|
+
const sections = new Set(
|
|
279
|
+
moduleRecords(text)
|
|
280
|
+
.filter((record) => removals.includes(record.path))
|
|
281
|
+
.map((record) => record.section),
|
|
282
|
+
);
|
|
283
|
+
let removing = false;
|
|
284
|
+
const cleaned = (text ?? "")
|
|
285
|
+
.split("\n")
|
|
286
|
+
.flatMap((line) => {
|
|
287
|
+
if (/^\s*\[/.test(line)) {
|
|
288
|
+
const header = line.match(
|
|
289
|
+
/^\s*\[submodule\s+("(?:[^"\\]|\\.)*")\]([\s\S]*)$/i,
|
|
290
|
+
);
|
|
291
|
+
const legacy = line.match(/^\s*\[submodule\.([^\]]+)\]([\s\S]*)$/i);
|
|
292
|
+
const section = header
|
|
293
|
+
? `submodule.${JSON.parse(header[1])}`
|
|
294
|
+
: legacy
|
|
295
|
+
? `submodule.${legacy[1]}`
|
|
296
|
+
: null;
|
|
297
|
+
removing = sections.has(section);
|
|
298
|
+
if (removing)
|
|
299
|
+
return (header?.[2] ?? legacy?.[2] ?? "").trim()
|
|
300
|
+
? [(header?.[2] ?? legacy?.[2] ?? "").trimStart()]
|
|
301
|
+
: [];
|
|
302
|
+
}
|
|
303
|
+
if (removing && /^\s*(?:path|url)\s*=/i.test(line)) {
|
|
304
|
+
let quoted = false;
|
|
305
|
+
let escaped = false;
|
|
306
|
+
for (let i = 0; i < line.length; i++) {
|
|
307
|
+
const character = line[i];
|
|
308
|
+
if (escaped) {
|
|
309
|
+
escaped = false;
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
if (character === "\\") {
|
|
313
|
+
escaped = true;
|
|
314
|
+
continue;
|
|
315
|
+
}
|
|
316
|
+
if (character === '"') quoted = !quoted;
|
|
317
|
+
if (!quoted && (character === "#" || character === ";"))
|
|
318
|
+
return [line.slice(i)];
|
|
319
|
+
}
|
|
320
|
+
return [];
|
|
321
|
+
}
|
|
322
|
+
return [line];
|
|
323
|
+
})
|
|
324
|
+
.join("\n");
|
|
325
|
+
fs.writeFileSync(name, cleaned);
|
|
326
|
+
for (const entry of entries) {
|
|
327
|
+
const existing = moduleRecords(fs.readFileSync(name, "utf8")).find(
|
|
328
|
+
(record) => record.path === entry.path,
|
|
329
|
+
);
|
|
330
|
+
const section = existing?.section ?? `submodule.${entry.path}`;
|
|
331
|
+
run(dir, ["config", "--file", name, `${section}.path`, entry.path]);
|
|
332
|
+
run(dir, ["config", "--file", name, `${section}.url`, entry.url]);
|
|
333
|
+
}
|
|
334
|
+
return fs.readFileSync(name, "utf8");
|
|
335
|
+
} finally {
|
|
336
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
function checkoutState(root, entry, options) {
|
|
340
|
+
const location = contained(root, entry.path, { module: true });
|
|
341
|
+
const registered = moduleRecords(read(path.join(root, MODULES))).find(
|
|
342
|
+
(record) => record.path === entry.path,
|
|
343
|
+
);
|
|
344
|
+
const indexed = indexEntry(root, entry.path);
|
|
345
|
+
const exists = fs.existsSync(location);
|
|
346
|
+
const revision =
|
|
347
|
+
exists && fs.existsSync(path.join(location, ".git"))
|
|
348
|
+
? run(location, ["rev-parse", "--verify", "HEAD"], { optional: true })
|
|
349
|
+
: null;
|
|
350
|
+
const remote = revision
|
|
351
|
+
? run(location, ["remote", "get-url", "origin"], { optional: true })
|
|
352
|
+
: null;
|
|
353
|
+
const matching =
|
|
354
|
+
remote &&
|
|
355
|
+
normalizeUrl(remote, options) === normalizeUrl(entry.url, options);
|
|
356
|
+
if (
|
|
357
|
+
registered &&
|
|
358
|
+
(!registered.url ||
|
|
359
|
+
normalizeUrl(registered.url, options) !==
|
|
360
|
+
normalizeUrl(entry.url, options))
|
|
361
|
+
)
|
|
362
|
+
fail("Conflicting submodule URL; resolve the existing registration first.");
|
|
363
|
+
if (indexed && !indexed.startsWith("160000 "))
|
|
364
|
+
fail("Repository destination conflicts with tracked files.");
|
|
365
|
+
if (
|
|
366
|
+
indexed &&
|
|
367
|
+
(!registered ||
|
|
368
|
+
!revision ||
|
|
369
|
+
!matching ||
|
|
370
|
+
!indexed.includes(` ${revision} 0\t`))
|
|
371
|
+
)
|
|
372
|
+
fail(
|
|
373
|
+
"Existing gitlink, registration, checkout, or revision conflicts; resolve before saving.",
|
|
374
|
+
);
|
|
375
|
+
if (exists && fs.readdirSync(location).length && !indexed) {
|
|
376
|
+
const marker = ownedMarker(root, entry);
|
|
377
|
+
if (
|
|
378
|
+
!revision ||
|
|
379
|
+
!matching ||
|
|
380
|
+
read(marker) !== normalizeUrl(entry.url, options)
|
|
381
|
+
)
|
|
382
|
+
fail("Nonempty unregistered destination will not be adopted.");
|
|
383
|
+
}
|
|
384
|
+
const localUrl = run(
|
|
385
|
+
root,
|
|
386
|
+
[
|
|
387
|
+
"config",
|
|
388
|
+
"--get",
|
|
389
|
+
`${registered?.section ?? `submodule.${entry.path}`}.url`,
|
|
390
|
+
],
|
|
391
|
+
{ optional: true },
|
|
392
|
+
);
|
|
393
|
+
if (
|
|
394
|
+
localUrl &&
|
|
395
|
+
normalizeUrl(localUrl, options) !== normalizeUrl(entry.url, options)
|
|
396
|
+
)
|
|
397
|
+
fail("Local submodule configuration conflicts with the accepted URL.");
|
|
398
|
+
return {
|
|
399
|
+
id: entry.id,
|
|
400
|
+
path: entry.path,
|
|
401
|
+
revision,
|
|
402
|
+
state:
|
|
403
|
+
indexed && localUrl
|
|
404
|
+
? "registered"
|
|
405
|
+
: revision
|
|
406
|
+
? "checkout-ready"
|
|
407
|
+
: "pending",
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
function ownedMarker(root, entry) {
|
|
411
|
+
const gitDir = run(root, ["rev-parse", "--absolute-git-dir"]);
|
|
412
|
+
return contained(gitDir, `add-project/${digest(entry.path)}`);
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
function prepare(rootInput, request, options = {}) {
|
|
416
|
+
const root = fs.realpathSync(rootInput);
|
|
417
|
+
if (!request || !Array.isArray(request.entries))
|
|
418
|
+
fail("Request must contain entries[].");
|
|
419
|
+
if (run(root, ["rev-parse", "--show-toplevel"]) !== root)
|
|
420
|
+
fail("Target must be the parent Git workspace root.");
|
|
421
|
+
for (const file of files) contained(root, file);
|
|
422
|
+
const original = Object.fromEntries(
|
|
423
|
+
files.map((file) => [file, read(path.join(root, file))]),
|
|
424
|
+
);
|
|
425
|
+
const profile = JSON.parse(
|
|
426
|
+
original[PROFILE] ?? fail("Repository profile is missing."),
|
|
427
|
+
);
|
|
428
|
+
if (!Array.isArray(profile.repositories))
|
|
429
|
+
fail("Profile requires repositories[].");
|
|
430
|
+
const entries = request.entries;
|
|
431
|
+
for (const [i, entry] of entries.entries()) {
|
|
432
|
+
validateEntry(root, entry, options);
|
|
433
|
+
if (
|
|
434
|
+
entries
|
|
435
|
+
.slice(0, i)
|
|
436
|
+
.some(
|
|
437
|
+
(pending) =>
|
|
438
|
+
pending.id === entry.id ||
|
|
439
|
+
normalizeUrl(pending.url, options) ===
|
|
440
|
+
normalizeUrl(entry.url, options) ||
|
|
441
|
+
pending.path === entry.path ||
|
|
442
|
+
pending.path.startsWith(`${entry.path}/`) ||
|
|
443
|
+
entry.path.startsWith(`${pending.path}/`),
|
|
444
|
+
)
|
|
445
|
+
)
|
|
446
|
+
fail("Duplicate pending repository identity, URL, or path.");
|
|
447
|
+
}
|
|
448
|
+
const explicit = request.removeExamples ?? [];
|
|
449
|
+
if (!Array.isArray(explicit) || explicit.some((id) => typeof id !== "string"))
|
|
450
|
+
fail("removeExamples must be an array of reviewed IDs.");
|
|
451
|
+
const remove = entries.length
|
|
452
|
+
? profile.repositories.filter(
|
|
453
|
+
(entry) => isTemplate(entry) || explicit.includes(entry.id),
|
|
454
|
+
)
|
|
455
|
+
: [];
|
|
456
|
+
if (
|
|
457
|
+
explicit.some(
|
|
458
|
+
(id) =>
|
|
459
|
+
!profile.repositories.some(
|
|
460
|
+
(entry) =>
|
|
461
|
+
entry.id === id &&
|
|
462
|
+
(templateProfiles.some((shipped) => shipped.id === entry.id) ||
|
|
463
|
+
templateProfiles.some(
|
|
464
|
+
(shipped) =>
|
|
465
|
+
normalizeUrl(shipped.url, options) ===
|
|
466
|
+
normalizeUrl(entry.url, options),
|
|
467
|
+
)),
|
|
468
|
+
),
|
|
469
|
+
)
|
|
470
|
+
)
|
|
471
|
+
fail("Cleanup selections must name existing template-like entries.");
|
|
472
|
+
const retained = profile.repositories.filter(
|
|
473
|
+
(entry) => !remove.includes(entry),
|
|
474
|
+
);
|
|
475
|
+
const all = [...retained];
|
|
476
|
+
for (const entry of entries) {
|
|
477
|
+
const match = all.find(
|
|
478
|
+
(saved) => saved.id === entry.id && stable(saved) === stable(entry),
|
|
479
|
+
);
|
|
480
|
+
if (match && retained.includes(match)) continue;
|
|
481
|
+
for (const saved of all) {
|
|
482
|
+
if (
|
|
483
|
+
saved.id === entry.id ||
|
|
484
|
+
normalizeUrl(saved.url, options) === normalizeUrl(entry.url, options) ||
|
|
485
|
+
saved.path === entry.path ||
|
|
486
|
+
saved.path.startsWith(`${entry.path}/`) ||
|
|
487
|
+
entry.path.startsWith(`${saved.path}/`)
|
|
488
|
+
)
|
|
489
|
+
fail(
|
|
490
|
+
"Duplicate or overlapping repository identity, URL, or path; resolve before saving.",
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
all.push(entry);
|
|
494
|
+
}
|
|
495
|
+
const records = moduleRecords(original[MODULES]);
|
|
496
|
+
if (new Set(records.map((record) => record.path)).size !== records.length)
|
|
497
|
+
fail("Duplicate .gitmodules paths require resolution before saving.");
|
|
498
|
+
const indexText = indexedText(root, MODULES);
|
|
499
|
+
for (const removed of remove) {
|
|
500
|
+
if (indexEntry(root, removed.path))
|
|
501
|
+
fail(
|
|
502
|
+
"Template cleanup would remove a registered checkout; resolve it explicitly first.",
|
|
503
|
+
);
|
|
504
|
+
for (const record of [...records, ...moduleRecords(indexText)].filter(
|
|
505
|
+
(item) => item.path === removed.path,
|
|
506
|
+
))
|
|
507
|
+
if (
|
|
508
|
+
record.url !== removed.url ||
|
|
509
|
+
record.section !== `submodule.${removed.path}` ||
|
|
510
|
+
record.keys.length !== 2
|
|
511
|
+
)
|
|
512
|
+
fail(
|
|
513
|
+
"Template .gitmodules reference was modified; resolve it explicitly first.",
|
|
514
|
+
);
|
|
515
|
+
}
|
|
516
|
+
for (const entry of entries) {
|
|
517
|
+
for (const record of [...records, ...moduleRecords(indexText)]) {
|
|
518
|
+
if (
|
|
519
|
+
record.path !== entry.path &&
|
|
520
|
+
(record.path.startsWith(`${entry.path}/`) ||
|
|
521
|
+
entry.path.startsWith(`${record.path}/`) ||
|
|
522
|
+
(record.url &&
|
|
523
|
+
normalizeUrl(record.url, options) ===
|
|
524
|
+
normalizeUrl(entry.url, options)))
|
|
525
|
+
)
|
|
526
|
+
fail("Submodule registration conflicts with the reviewed repository.");
|
|
527
|
+
if (
|
|
528
|
+
record.path === entry.path &&
|
|
529
|
+
normalizeUrl(record.url, options) !== normalizeUrl(entry.url, options)
|
|
530
|
+
)
|
|
531
|
+
fail("Submodule URL conflicts with the reviewed repository.");
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
const states = entries.map((entry) => checkoutState(root, entry, options));
|
|
535
|
+
const removedIds = remove.map((entry) => entry.id);
|
|
536
|
+
let workflows =
|
|
537
|
+
original[WORKFLOWS] === null ? null : JSON.parse(original[WORKFLOWS]);
|
|
538
|
+
if (workflows && removedIds.length) {
|
|
539
|
+
if (!Array.isArray(workflows.implementationStages))
|
|
540
|
+
fail("Workflow implementationStages must be an array.");
|
|
541
|
+
workflows = {
|
|
542
|
+
...workflows,
|
|
543
|
+
implementationStages: workflows.implementationStages.flatMap((stage) => {
|
|
544
|
+
const affected =
|
|
545
|
+
stage.repositoryIds?.filter((id) => removedIds.includes(id)) ?? [];
|
|
546
|
+
if (!affected.length) return [stage];
|
|
547
|
+
const templateId = {
|
|
548
|
+
shared: "example-core",
|
|
549
|
+
backend: "example-service",
|
|
550
|
+
frontend: "example-web",
|
|
551
|
+
}[stage.id];
|
|
552
|
+
const exact =
|
|
553
|
+
stable(stage) ===
|
|
554
|
+
stable({
|
|
555
|
+
id: stage.id,
|
|
556
|
+
repositoryIds: [templateId],
|
|
557
|
+
parallel: stage.id === "frontend",
|
|
558
|
+
...(stage.id === "frontend"
|
|
559
|
+
? {
|
|
560
|
+
condition:
|
|
561
|
+
"Run after required shared contracts and APIs are available locally.",
|
|
562
|
+
}
|
|
563
|
+
: {}),
|
|
564
|
+
});
|
|
565
|
+
if (
|
|
566
|
+
exact &&
|
|
567
|
+
affected.every((id) => !own(request.workflowReplacements ?? {}, id))
|
|
568
|
+
)
|
|
569
|
+
return [];
|
|
570
|
+
const repositoryIds = stage.repositoryIds.flatMap((id) => {
|
|
571
|
+
if (!removedIds.includes(id)) return [id];
|
|
572
|
+
const replacements = request.workflowReplacements?.[id];
|
|
573
|
+
if (
|
|
574
|
+
!Array.isArray(replacements) ||
|
|
575
|
+
replacements.some(
|
|
576
|
+
(replacement) => !all.some((entry) => entry.id === replacement),
|
|
577
|
+
)
|
|
578
|
+
)
|
|
579
|
+
fail(
|
|
580
|
+
"Custom workflow references require reviewed workflowReplacements arrays.",
|
|
581
|
+
);
|
|
582
|
+
return replacements;
|
|
583
|
+
});
|
|
584
|
+
return [{ ...stage, repositoryIds: [...new Set(repositoryIds)] }];
|
|
585
|
+
}),
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
const removals = remove.map((entry) => entry.path);
|
|
589
|
+
const next = entries.length
|
|
590
|
+
? {
|
|
591
|
+
[PROFILE]: json({ ...profile, repositories: all }),
|
|
592
|
+
[WORKFLOWS]: workflows === null ? null : json(workflows),
|
|
593
|
+
[MODULES]: editModules(original[MODULES], entries, removals),
|
|
594
|
+
}
|
|
595
|
+
: { ...original };
|
|
596
|
+
const effects = {
|
|
597
|
+
repositories: entries.map((entry) => ({
|
|
598
|
+
id: entry.id,
|
|
599
|
+
url: entry.url,
|
|
600
|
+
path: entry.path,
|
|
601
|
+
})),
|
|
602
|
+
removeExamples: removedIds,
|
|
603
|
+
files: files.filter((file) => next[file] !== original[file]),
|
|
604
|
+
index: entries.length
|
|
605
|
+
? [MODULES, ...entries.map((entry) => entry.path)]
|
|
606
|
+
: [],
|
|
607
|
+
workflowReplacements: request.workflowReplacements ?? {},
|
|
608
|
+
};
|
|
609
|
+
const token = digest(
|
|
610
|
+
stable({
|
|
611
|
+
root,
|
|
612
|
+
entries,
|
|
613
|
+
effects,
|
|
614
|
+
removedRecords: remove,
|
|
615
|
+
workflowTouched:
|
|
616
|
+
original[WORKFLOWS] === null
|
|
617
|
+
? []
|
|
618
|
+
: JSON.parse(original[WORKFLOWS]).implementationStages?.filter(
|
|
619
|
+
(stage) =>
|
|
620
|
+
stage.repositoryIds?.some((id) => removedIds.includes(id)),
|
|
621
|
+
),
|
|
622
|
+
index: indexEntry(root, MODULES),
|
|
623
|
+
states,
|
|
624
|
+
}),
|
|
625
|
+
);
|
|
626
|
+
return {
|
|
627
|
+
root,
|
|
628
|
+
entries,
|
|
629
|
+
original,
|
|
630
|
+
next,
|
|
631
|
+
indexText,
|
|
632
|
+
removals,
|
|
633
|
+
effects,
|
|
634
|
+
token,
|
|
635
|
+
states,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
export function preview(root, request, options = {}) {
|
|
639
|
+
try {
|
|
640
|
+
const prepared = prepare(root, request, options);
|
|
641
|
+
return {
|
|
642
|
+
status: "preview",
|
|
643
|
+
token: prepared.token,
|
|
644
|
+
effects: prepared.effects,
|
|
645
|
+
repositories: prepared.states,
|
|
646
|
+
note: "Ready to save — not saved yet. Save clones and registers submodules; it creates no commits.",
|
|
647
|
+
};
|
|
648
|
+
} catch (error) {
|
|
649
|
+
return {
|
|
650
|
+
status: "conflict",
|
|
651
|
+
error:
|
|
652
|
+
error instanceof SyntaxError
|
|
653
|
+
? "Invalid configuration JSON."
|
|
654
|
+
: error.message,
|
|
655
|
+
};
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
function replace(root, file, value, expected) {
|
|
660
|
+
const target = contained(root, file);
|
|
661
|
+
if (read(target) !== expected)
|
|
662
|
+
fail(`Concurrent change to ${file}; review a fresh preview.`);
|
|
663
|
+
if (value === null) {
|
|
664
|
+
if (expected !== null) fs.unlinkSync(target);
|
|
665
|
+
return;
|
|
666
|
+
}
|
|
667
|
+
const temporary = `${target}.add-project-${randomUUID()}`;
|
|
668
|
+
try {
|
|
669
|
+
fs.writeFileSync(temporary, value, {
|
|
670
|
+
flag: "wx",
|
|
671
|
+
mode: fs.existsSync(target) ? fs.statSync(target).mode : 0o644,
|
|
672
|
+
});
|
|
673
|
+
fs.renameSync(temporary, target);
|
|
674
|
+
} finally {
|
|
675
|
+
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
function stageModules(root, text, expectedIndex) {
|
|
679
|
+
if (indexEntry(root, MODULES) !== expectedIndex)
|
|
680
|
+
fail(
|
|
681
|
+
"Concurrent .gitmodules index change; review recovery before retrying.",
|
|
682
|
+
);
|
|
683
|
+
const object = run(root, ["hash-object", "-w", "--stdin"], { input: text });
|
|
684
|
+
run(root, [
|
|
685
|
+
"update-index",
|
|
686
|
+
"--add",
|
|
687
|
+
"--cacheinfo",
|
|
688
|
+
`${expectedIndex?.split(" ")[0] || "100644"},${object},${MODULES}`,
|
|
689
|
+
]);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
/** Save only the exact preview the user reviewed. Partial Git work is retained for retry. */
|
|
693
|
+
export function save(rootInput, request, options = {}) {
|
|
694
|
+
let prepared;
|
|
695
|
+
try {
|
|
696
|
+
prepared = prepare(rootInput, request, options);
|
|
697
|
+
} catch (error) {
|
|
698
|
+
return {
|
|
699
|
+
status: "conflict",
|
|
700
|
+
error:
|
|
701
|
+
error instanceof SyntaxError
|
|
702
|
+
? "Invalid configuration JSON."
|
|
703
|
+
: error.message,
|
|
704
|
+
changedFiles: [],
|
|
705
|
+
restoredFiles: [],
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
if (!prepared.entries.length)
|
|
709
|
+
return {
|
|
710
|
+
status: "empty",
|
|
711
|
+
repositories: [],
|
|
712
|
+
changedFiles: [],
|
|
713
|
+
restoredFiles: [],
|
|
714
|
+
};
|
|
715
|
+
if (!request.token || request.token !== prepared.token)
|
|
716
|
+
return {
|
|
717
|
+
status: "conflict",
|
|
718
|
+
error:
|
|
719
|
+
"A current reviewed preview token is required; review this preview before choosing Save again.",
|
|
720
|
+
preview: preview(rootInput, request, options),
|
|
721
|
+
changedFiles: [],
|
|
722
|
+
restoredFiles: [],
|
|
723
|
+
};
|
|
724
|
+
const { root, entries, original, next, indexText, removals } = prepared;
|
|
725
|
+
const states = prepared.states.map((state) => ({ ...state }));
|
|
726
|
+
const changedFiles = [];
|
|
727
|
+
const restoredFiles = [];
|
|
728
|
+
const createdPaths = [];
|
|
729
|
+
const configWritten = [];
|
|
730
|
+
const initialIndexEntries = Object.fromEntries(
|
|
731
|
+
[MODULES, ...entries.map((entry) => entry.path)].map((file) => [
|
|
732
|
+
file,
|
|
733
|
+
indexEntry(root, file),
|
|
734
|
+
]),
|
|
735
|
+
);
|
|
736
|
+
const initialPaths = new Set(
|
|
737
|
+
entries
|
|
738
|
+
.filter((entry) => fs.existsSync(path.join(root, entry.path)))
|
|
739
|
+
.map((entry) => entry.path),
|
|
740
|
+
);
|
|
741
|
+
const actualIndexEffects = () =>
|
|
742
|
+
Object.keys(initialIndexEntries).filter(
|
|
743
|
+
(file) => indexEntry(root, file) !== initialIndexEntries[file],
|
|
744
|
+
);
|
|
745
|
+
let currentModules = original[MODULES];
|
|
746
|
+
let currentIndex = indexEntry(root, MODULES);
|
|
747
|
+
let currentIndexText = indexText;
|
|
748
|
+
let active = -1;
|
|
749
|
+
let cleanupSnapshot = null;
|
|
750
|
+
try {
|
|
751
|
+
for (let i = 0; i < entries.length; i++) {
|
|
752
|
+
active = i;
|
|
753
|
+
const entry = entries[i];
|
|
754
|
+
const state = states[i];
|
|
755
|
+
if (state.state === "registered") continue;
|
|
756
|
+
for (const file of [PROFILE, WORKFLOWS])
|
|
757
|
+
if (read(path.join(root, file)) !== original[file])
|
|
758
|
+
fail(`Concurrent change to ${file}; review a fresh preview.`);
|
|
759
|
+
if (
|
|
760
|
+
read(path.join(root, MODULES)) !== currentModules ||
|
|
761
|
+
indexEntry(root, MODULES) !== currentIndex
|
|
762
|
+
)
|
|
763
|
+
fail("Concurrent .gitmodules change; stop and review before retrying.");
|
|
764
|
+
if (state.state !== "checkout-ready") {
|
|
765
|
+
const gitDir = run(root, ["rev-parse", "--absolute-git-dir"]);
|
|
766
|
+
const metadata = contained(gitDir, `modules/${entry.path}`);
|
|
767
|
+
if (fs.existsSync(metadata))
|
|
768
|
+
fail(
|
|
769
|
+
"Existing submodule Git metadata conflicts; inspect recovery before retrying.",
|
|
770
|
+
);
|
|
771
|
+
fs.mkdirSync(path.dirname(metadata), { recursive: true });
|
|
772
|
+
const marker = ownedMarker(root, entry);
|
|
773
|
+
fs.mkdirSync(path.dirname(marker), { recursive: true });
|
|
774
|
+
fs.writeFileSync(marker, normalizeUrl(entry.url, options));
|
|
775
|
+
const destination = contained(root, entry.path, { module: true });
|
|
776
|
+
fs.mkdirSync(path.dirname(destination), { recursive: true });
|
|
777
|
+
state.state = "cloning";
|
|
778
|
+
options.onProgress?.({ ...state });
|
|
779
|
+
run(root, [
|
|
780
|
+
...(options.allowLocal ? ["-c", "protocol.file.allow=always"] : []),
|
|
781
|
+
"clone",
|
|
782
|
+
"--no-recurse-submodules",
|
|
783
|
+
"--separate-git-dir",
|
|
784
|
+
metadata,
|
|
785
|
+
"--",
|
|
786
|
+
entry.url,
|
|
787
|
+
destination,
|
|
788
|
+
]);
|
|
789
|
+
createdPaths.push(entry.path);
|
|
790
|
+
state.revision = run(destination, ["rev-parse", "--verify", "HEAD"]);
|
|
791
|
+
state.state = "checkout-ready";
|
|
792
|
+
}
|
|
793
|
+
options.beforeRegister?.(entry);
|
|
794
|
+
if (
|
|
795
|
+
read(path.join(root, MODULES)) !== currentModules ||
|
|
796
|
+
indexEntry(root, MODULES) !== currentIndex
|
|
797
|
+
)
|
|
798
|
+
fail(
|
|
799
|
+
"Concurrent .gitmodules change during clone; checkout retained for retry.",
|
|
800
|
+
);
|
|
801
|
+
if (indexEntry(root, entry.path) !== initialIndexEntries[entry.path])
|
|
802
|
+
fail(
|
|
803
|
+
"Concurrent destination index change; preserve staged work and resolve before retrying.",
|
|
804
|
+
);
|
|
805
|
+
checkoutState(root, entry, options);
|
|
806
|
+
const modules = editModules(currentModules, [entry], []);
|
|
807
|
+
replace(root, MODULES, modules, currentModules);
|
|
808
|
+
currentModules = modules;
|
|
809
|
+
if (!changedFiles.includes(MODULES)) changedFiles.push(MODULES);
|
|
810
|
+
currentIndexText = editModules(currentIndexText, [entry], []);
|
|
811
|
+
stageModules(root, currentIndexText, currentIndex);
|
|
812
|
+
currentIndex = indexEntry(root, MODULES);
|
|
813
|
+
run(root, [
|
|
814
|
+
"update-index",
|
|
815
|
+
"--add",
|
|
816
|
+
"--cacheinfo",
|
|
817
|
+
`160000,${state.revision},${entry.path}`,
|
|
818
|
+
]);
|
|
819
|
+
const section =
|
|
820
|
+
moduleRecords(currentModules).find(
|
|
821
|
+
(record) => record.path === entry.path,
|
|
822
|
+
)?.section ?? `submodule.${entry.path}`;
|
|
823
|
+
run(root, ["config", `${section}.url`, entry.url]);
|
|
824
|
+
run(root, ["config", `${section}.active`, "true"]);
|
|
825
|
+
state.state = "registered";
|
|
826
|
+
options.onProgress?.({ ...state });
|
|
827
|
+
}
|
|
828
|
+
active = -1;
|
|
829
|
+
// Configuration is published only after every checkout and registration succeeded.
|
|
830
|
+
for (const entry of entries) checkoutState(root, entry, options);
|
|
831
|
+
for (const file of [PROFILE, WORKFLOWS])
|
|
832
|
+
if (read(path.join(root, file)) !== original[file])
|
|
833
|
+
fail(
|
|
834
|
+
`Concurrent change to ${file}; registered repositories retained for retry.`,
|
|
835
|
+
);
|
|
836
|
+
if (
|
|
837
|
+
read(path.join(root, MODULES)) !== currentModules ||
|
|
838
|
+
indexEntry(root, MODULES) !== currentIndex
|
|
839
|
+
)
|
|
840
|
+
fail("Concurrent .gitmodules change before cleanup.");
|
|
841
|
+
for (const file of [WORKFLOWS, PROFILE]) {
|
|
842
|
+
if (next[file] === original[file]) continue;
|
|
843
|
+
options.beforeWrite?.(file);
|
|
844
|
+
replace(root, file, next[file], original[file]);
|
|
845
|
+
configWritten.push(file);
|
|
846
|
+
changedFiles.push(file);
|
|
847
|
+
}
|
|
848
|
+
const finalModules = editModules(currentModules, [], removals);
|
|
849
|
+
cleanupSnapshot = {
|
|
850
|
+
working: currentModules,
|
|
851
|
+
index: currentIndex,
|
|
852
|
+
indexText: currentIndexText,
|
|
853
|
+
next: finalModules,
|
|
854
|
+
stagedNext: editModules(currentIndexText, [], removals),
|
|
855
|
+
};
|
|
856
|
+
options.beforeWrite?.(MODULES);
|
|
857
|
+
replace(root, MODULES, finalModules, currentModules);
|
|
858
|
+
currentModules = finalModules;
|
|
859
|
+
stageModules(root, cleanupSnapshot.stagedNext, currentIndex);
|
|
860
|
+
cleanupSnapshot.writtenIndex = indexEntry(root, MODULES);
|
|
861
|
+
for (const entry of entries) checkoutState(root, entry, options);
|
|
862
|
+
return {
|
|
863
|
+
status: "saved",
|
|
864
|
+
repositories: states,
|
|
865
|
+
changedFiles,
|
|
866
|
+
restoredFiles,
|
|
867
|
+
createdPaths,
|
|
868
|
+
indexEffects: actualIndexEffects(),
|
|
869
|
+
setupActions: entries.flatMap((entry) =>
|
|
870
|
+
[entry.agentGuide, ...Object.values(entry.artifactDirectories)]
|
|
871
|
+
.filter((relative) => !fs.existsSync(path.join(root, relative)))
|
|
872
|
+
.map((relative) => `Unverified or missing: ${relative}`),
|
|
873
|
+
),
|
|
874
|
+
recovery: [],
|
|
875
|
+
};
|
|
876
|
+
} catch (error) {
|
|
877
|
+
// Undo only the final cleanup, retaining successful new registrations.
|
|
878
|
+
const recoveryErrors = [];
|
|
879
|
+
try {
|
|
880
|
+
if (cleanupSnapshot) {
|
|
881
|
+
if (read(path.join(root, MODULES)) === cleanupSnapshot.next) {
|
|
882
|
+
replace(root, MODULES, cleanupSnapshot.working, cleanupSnapshot.next);
|
|
883
|
+
restoredFiles.push(MODULES);
|
|
884
|
+
}
|
|
885
|
+
if (
|
|
886
|
+
cleanupSnapshot.writtenIndex &&
|
|
887
|
+
indexEntry(root, MODULES) === cleanupSnapshot.writtenIndex
|
|
888
|
+
)
|
|
889
|
+
stageModules(
|
|
890
|
+
root,
|
|
891
|
+
cleanupSnapshot.indexText,
|
|
892
|
+
cleanupSnapshot.writtenIndex,
|
|
893
|
+
);
|
|
894
|
+
}
|
|
895
|
+
} catch {
|
|
896
|
+
recoveryErrors.push(
|
|
897
|
+
"Could not restore final .gitmodules cleanup; inspect working-tree and index references before retrying.",
|
|
898
|
+
);
|
|
899
|
+
}
|
|
900
|
+
for (const file of configWritten.reverse()) {
|
|
901
|
+
try {
|
|
902
|
+
if (read(path.join(root, file)) === next[file]) {
|
|
903
|
+
replace(root, file, original[file], next[file]);
|
|
904
|
+
restoredFiles.push(file);
|
|
905
|
+
}
|
|
906
|
+
} catch {
|
|
907
|
+
recoveryErrors.push(
|
|
908
|
+
`Could not restore ${file}; inspect the actual configuration before retrying.`,
|
|
909
|
+
);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
for (let i = 0; i < entries.length; i++) {
|
|
913
|
+
try {
|
|
914
|
+
states[i] = checkoutState(root, entries[i], options);
|
|
915
|
+
} catch {
|
|
916
|
+
states[i] = { ...states[i], state: "needs-recovery" };
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
if (active >= 0 && states[active].state === "pending")
|
|
920
|
+
states[active].state = "failed";
|
|
921
|
+
return {
|
|
922
|
+
status: "incomplete",
|
|
923
|
+
error:
|
|
924
|
+
error instanceof SyntaxError
|
|
925
|
+
? "Invalid configuration JSON."
|
|
926
|
+
: error.message,
|
|
927
|
+
repositories: states,
|
|
928
|
+
changedFiles: [...new Set(changedFiles)].filter((file) => {
|
|
929
|
+
try {
|
|
930
|
+
return read(path.join(root, file)) !== original[file];
|
|
931
|
+
} catch {
|
|
932
|
+
return true;
|
|
933
|
+
}
|
|
934
|
+
}),
|
|
935
|
+
restoredFiles,
|
|
936
|
+
createdPaths: entries
|
|
937
|
+
.filter(
|
|
938
|
+
(entry) =>
|
|
939
|
+
!initialPaths.has(entry.path) &&
|
|
940
|
+
fs.existsSync(path.join(root, entry.path)),
|
|
941
|
+
)
|
|
942
|
+
.map((entry) => entry.path),
|
|
943
|
+
indexEffects: (() => {
|
|
944
|
+
try {
|
|
945
|
+
return actualIndexEffects();
|
|
946
|
+
} catch {
|
|
947
|
+
return ["Unknown — inspect Git index"];
|
|
948
|
+
}
|
|
949
|
+
})(),
|
|
950
|
+
recovery: [
|
|
951
|
+
...recoveryErrors,
|
|
952
|
+
"Keep accepted entries. Inspect the reported checkouts, .gitmodules, and Git index; request a new preview and Save to resume. No existing checkout or unrelated index entry was reset.",
|
|
953
|
+
],
|
|
954
|
+
};
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
if (
|
|
959
|
+
process.argv[1] &&
|
|
960
|
+
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
|
961
|
+
) {
|
|
962
|
+
try {
|
|
963
|
+
const [operation, ...args] = process.argv.slice(2);
|
|
964
|
+
if (
|
|
965
|
+
!["preview", "save"].includes(operation) ||
|
|
966
|
+
args.length !== 4 ||
|
|
967
|
+
args[0] !== "--root" ||
|
|
968
|
+
args[2] !== "--request"
|
|
969
|
+
)
|
|
970
|
+
fail(
|
|
971
|
+
"Usage: node add-project.mjs preview|save --root <workspace> --request <json-file>",
|
|
972
|
+
);
|
|
973
|
+
const request = JSON.parse(fs.readFileSync(args[3], "utf8"));
|
|
974
|
+
const result =
|
|
975
|
+
operation === "preview"
|
|
976
|
+
? preview(args[1], request)
|
|
977
|
+
: save(args[1], request, {
|
|
978
|
+
onProgress: (state) =>
|
|
979
|
+
process.stderr.write(`${JSON.stringify(state)}\n`),
|
|
980
|
+
});
|
|
981
|
+
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
|
|
982
|
+
if (!["preview", "saved", "empty"].includes(result.status))
|
|
983
|
+
process.exitCode = 1;
|
|
984
|
+
} catch (error) {
|
|
985
|
+
process.stdout.write(
|
|
986
|
+
`${JSON.stringify({ status: "conflict", error: error instanceof SyntaxError ? "Invalid request JSON." : error.message })}\n`,
|
|
987
|
+
);
|
|
988
|
+
process.exitCode = 1;
|
|
989
|
+
}
|
|
990
|
+
}
|