@elvis1513/auto-coding-skill 4.3.7 → 5.0.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.
Files changed (33) hide show
  1. package/README.md +26 -761
  2. package/cli/assets/managed-install.json +38 -1
  3. package/cli/assets/skill/SKILL.md +15 -100
  4. package/cli/assets/skill/data/templates/ENVIRONMENT.md +30 -0
  5. package/cli/assets/skill/data/templates/architecture/.gitkeep +1 -0
  6. package/cli/assets/skill/data/templates/bridges/AGENTS.md +39 -145
  7. package/cli/assets/skill/data/templates/deployment/.gitkeep +1 -0
  8. package/cli/assets/skill/data/templates/design/.gitkeep +1 -0
  9. package/cli/assets/skill/data/templates/interfaces/.gitkeep +1 -0
  10. package/cli/assets/skill/data/templates/product/.gitkeep +1 -0
  11. package/cli/src/index.js +127 -2589
  12. package/cli/src/sync-assets.js +38 -95
  13. package/package.json +9 -17
  14. package/cli/assets/agents/browser-debugger.toml +0 -27
  15. package/cli/assets/agents/docs-researcher.toml +0 -18
  16. package/cli/assets/agents/explorer.toml +0 -26
  17. package/cli/assets/agents/fixer.toml +0 -29
  18. package/cli/assets/agents/reviewer.toml +0 -50
  19. package/cli/assets/skill/data/contracts/orchestration-v1.schema.json +0 -567
  20. package/cli/assets/skill/data/policies/feedback-resolutions-v1.json +0 -68
  21. package/cli/assets/skill/data/policies/workflow-migrations-v1.json +0 -657
  22. package/cli/assets/skill/data/templates/ENGINEERING.md +0 -115
  23. package/cli/assets/skill/data/templates/tools/ap.py +0 -16
  24. package/cli/assets/skill/requirements.txt +0 -1
  25. package/cli/assets/skill/scripts/ap.py +0 -17791
  26. package/cli/assets/skill/scripts/core.py +0 -510
  27. package/cli/assets/skill/scripts/http_checks.py +0 -92
  28. package/cli/assets/skill/scripts/install_integrity.py +0 -427
  29. package/cli/assets/skill/scripts/scaffold_templates.py +0 -325
  30. package/cli/tests/ap_concurrency_test.py +0 -3602
  31. package/cli/tests/ap_profiles_test.py +0 -3272
  32. package/cli/tests/core_shell_test.py +0 -345
  33. package/cli/tests/index.test.js +0 -2967
@@ -1,2967 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import crypto from "node:crypto";
5
- import zlib from "node:zlib";
6
- import { spawn, spawnSync } from "node:child_process";
7
- import { fileURLToPath } from "node:url";
8
-
9
- const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
10
- const cli = path.join(repoRoot, "cli", "src", "index.js");
11
- const assetAp = path.join(repoRoot, "cli", "assets", "skill", "scripts", "ap.py");
12
- const projectConfigRelativePath = path.join("docs", "project", "auto-coding-skill.yaml");
13
- const projectConfigSchema = "auto-coding-skill/project-config/v1";
14
- // Frozen gzip/base64 fixture of the official v2.2.0 ENGINEERING body (frontmatter excluded).
15
- const officialV220EngineeringBody = zlib.gunzipSync(Buffer.from(
16
- "H4sIAAAAAAAAE51YwY7bOBK98ysKk8PuApaMnezuoTMYwNPuzfZObyboJDPHFk2WJMYUqWGR7mjQH78oUpLdQA6ZviRtWSSrXr33qmjxCm5cZxxiMK6D33w4ttY/CvGxNwStsQiGIPYIZFxnEQbpkrR2gkEaF6VxqOFxXgXKu9Z0KchovKvhZ8QRTATjxFsTa9hpDX7k76QFQsV/EXhnJ3js0eVjxuA/o4qATh4slqMDWhlRA6XQSoW1EK9ewc0XVIl34CUcKAnRLJHU87MrkCn6BggtqshnIfgWYh8QAduWYzjhusOVEE/wvnyAJ/g4jUZJm/ODJ3grIz+9tp5SQBi8RngST1BVFXzlX/EEzWBU8A08gfaKthEpUsX5buCEYQIapLVgyJf85nNUL12HmlfhqexDUTotg+atfNDGyTBBizJyINJp0Mi5LDssr19u0Zuur4KhI++x/2krU+y3o5wGdHGrcbR+2h6SsXquIvgAGpWVATXwYuDF8ARtshaeOAHTTvAkRFMwNnMp5Yy2DzV87L8CM78p7aOcaAFoc5HhRvhwGW0NO1g/AZmOyaOkcz7CAUH7R9cFqRk+E3uQcH13C62VOQEpFj6FZLGGnQP8MlqjTATnXcWRr2EFHK1USJkzfyGw/nHrfBikhYMktMZhfUExrv/VDEMD0pKHgL8nE2bWZpw6GZmv7+comvyZY6EGBjktCEMzytgTA6H8MEin89+k/IjNJldYulU7oplDbmq4niWH55U1H/LAxzfwVx/AYifVdPE9f/XALzV/g9YHcYaXk3sDEqzp+sgArkyaF4P2SMDYK59cBEkgn2X66hX8zzjDoD1zAyHuCziaj4QZV40ntH5kDl4JUcFzdJsraDSeGg6kmYF+9tICwxUUDm6+Sih4TijeYWZF7eSA/EBGsCgpZoNIxNaTE1rSfrMmg8CSLQZy+QatFiZgNTElmW8YlCFcZL1ZMS11zeDlQhNHltM0qjholKHD+IDu9DBTSzd50fPXPqM7Gkfnd4S4KzVfqnbEiYCS6rlgZyLkMhcmbKD5PRl1fGCT4k/z/9Jp0WRfaCAgmz5QGkcfIuoa7pODRnsWe5Pril+kijAY4nZRtQatBm1k5zxFo6gW4rcMU04MLrNgVyimz8BoDc05+7pHaWP/wDJ8SME2Jaz5KUunKd2lDd5FdHp7kOqITsOn+7vZljg6BgiJrRadHr1xEVSP6kglT+s747aEKmCEgC0GdOwH5w51kGQU+0PP4a7b1ZCz+m+pAxgSzzOZC9QUizKRsqFsP/tDDnADhyCd6jcgQzStVIshw4BRahnlRkQzoE9xA59ut7v3t5AIQwkbRkn06IOGk7SJww2A7mSCd6yri0Rq+OQSoRZr76XeJ6uXwsoD5QUy9hgg9tLxBGAXa83u2HurMVBR+h5bmWxcBwAh9s8E/fca7lFqiOswwfGyOcrSEaKkI6CLYarF94VOuUySPGsp+NT10CgribjZVFUWSmnqtXjN2yvOPA8o3EyRIkPTJvYWbhbsVfgGVEAW636/3e3vLwpqnGb+oa7FP2q4HUaLGTTe0KFCIu60RbqQmNSAXwxF/mNROcWQ1NqJAyZCyOSiWvyzJFWmGPL2hHrtN8Ux/7Um0exvfq2u7375cLNvNlm6Js4VTtTXQvxn9emstLmPXYpoxnw9UdpLc/6e2wXverHp6xp+LZ18pixc324XIudqZRVWl4ya5zDKmC3Bv999+MC+8e/d7d3sue939x9vd3cNy3LgkidpAU9GMxtrnjFzKXsfTJSZDz5oDDMdCW7evb19d3Nzf/vu7SZT5eD9cSuD6s0JabNUmKVrXMQcFIQcD20gYBeQyHi3PaTu/FzN89sSCO/DYpvFUt4SMbNj4cM80O59bn2DDEdIDvMEinr2ELZWBqFI48NKitFboyYh3qLDYNQFXZZ1zBx9MuTDBAeeCbKq8vQ05SkhIBtuURCZP3Aj2uSyhMvHIpoOv1TsK5rj9iFWB5+40Uzz1MQ+kzK1JzhYr45nHYhmjapG1/qgctpX5T3jujzeLZSz07kdchPA0ZOJPkyVy2UUuUQRz6JQfhiNxZBH4BV5iPLIUyEqLJ/9CQN0M05ODsZ1oscUTGkecJ+1tQqwRztiKDSVJ280uy1/kdxyZQhIo3dkDsaaaJBE9CBtQKknsMzsDCq9AV1KS6M1PNtohAED2gmiB5LRUDvluchhmXxqIT4RQrNMhmCciVBVj8FEhKpKo5YRq4JTM3efFadHo3ElwnzDqMVOKRxjHrcp+pDvHhoPPOda7zoCU3SdEcrpLafnfmd9V7h37WfY18uW9ipxQamIbmYYkJJt68vIH7PkMiNWuz6rrvjQIh0+Ca6zpQoaURlpzR+oz8ec73PZ4R2izkPxcCVE0zBovRin2Hv3er4aeW+J7yR+NGNJSY71OJ1DlKNZ4P2zS2efeOHqZ2R+4R4BTwYfX7qaRcO0fnH6q729cIdD6ujF8Fm7Lm2aRojnkpnn2Q5dRWkYZJiald/MGBPApzimSKBNQBXtVK6VZYIQZ4JekLOwNfqxsjyPwH5fZJ6tNrvifNtmVC3qDgO94blB8DBLVXlUzZ0Gqmq00jVwwDYrKz/mpXzkKtdpEd8weLdeC/4s38sw/Y0vf3Uw+sa1efav8hXmcjVUFdu8NO5bC700jiq3s5eEUkadigcS+OHj7sPPD7f7H6GqBurgu/XBFfwwM+TH774dzLWYObpvXMeoVPOYVkjLjLMyOcWTMfMn5HvP1/ZoQCNfuSP/DuAvfzsLyfEYz7+HNbXs2Ci3dDR23qBSnrtXlR9tSQUzRmrW1qQTd98iCxmXzWrxf3x8K0DDEwAA",
17
- "base64",
18
- )).toString("utf8");
19
- const managedAgentEfforts = {
20
- "browser-debugger.toml": "xhigh",
21
- "docs-researcher.toml": "medium",
22
- "explorer.toml": "medium",
23
- "fixer.toml": "medium",
24
- "reviewer.toml": "xhigh",
25
- };
26
- const exactDocs = [
27
- "docs/ENGINEERING.md",
28
- "docs/architecture/adr/_TEMPLATE-ADR.md",
29
- "docs/architecture/structure-standard.md",
30
- "docs/bugs/bug-list.md",
31
- "docs/deployment/deploy-records/_TEMPLATE-DEPLOY-RECORD.md",
32
- "docs/deployment/deploy-runbook.md",
33
- "docs/design/_TEMPLATE-DD.md",
34
- "docs/interfaces/api-change-log.md",
35
- "docs/interfaces/api.md",
36
- "docs/project/overview.md",
37
- "docs/project/repository-map.md",
38
- "docs/project/runtime.md",
39
- "docs/reviews/_TEMPLATE-REVIEW.md",
40
- "docs/skill-feedback/README.md",
41
- "docs/skill-feedback/_TEMPLATE-SKILL-FEEDBACK.md",
42
- "docs/testing/regression-matrix.md",
43
- "docs/tools/autopipeline/ap.py",
44
- ];
45
-
46
- function assert(condition, message) {
47
- if (!condition) throw new Error(message);
48
- }
49
-
50
- function exists(p) {
51
- return fs.existsSync(p);
52
- }
53
-
54
- function tmpdir(name) {
55
- return fs.mkdtempSync(path.join(os.tmpdir(), `autocoding-${name}.`));
56
- }
57
-
58
- function run(command, args, options = {}) {
59
- const result = spawnSync(command, args, {
60
- cwd: options.cwd ?? repoRoot,
61
- env: options.env ? { ...process.env, ...options.env } : process.env,
62
- encoding: "utf8",
63
- stdio: "pipe",
64
- });
65
- if (options.check !== false && result.status !== 0) {
66
- throw new Error([
67
- `command failed: ${command} ${args.join(" ")}`,
68
- `cwd=${options.cwd ?? repoRoot}`,
69
- `status=${result.status}`,
70
- result.stdout,
71
- result.stderr,
72
- ].join("\n"));
73
- }
74
- return result;
75
- }
76
-
77
- function pythonEnvWithHome(home) {
78
- const yamlSite = run(
79
- "python3",
80
- ["-c", "import pathlib, yaml; print(pathlib.Path(yaml.__file__).resolve().parent.parent)"],
81
- ).stdout.trim();
82
- return {
83
- HOME: home,
84
- PYTHONPATH: [yamlSite, process.env.PYTHONPATH].filter(Boolean).join(path.delimiter),
85
- };
86
- }
87
-
88
- function writeFile(file, text) {
89
- fs.mkdirSync(path.dirname(file), { recursive: true });
90
- fs.writeFileSync(file, text);
91
- }
92
-
93
- function installTrustedEngineeringDefault(repo, content, version) {
94
- const installedRelative = path.join(
95
- ".agents",
96
- "skills",
97
- "auto-coding-skill",
98
- "data",
99
- "templates",
100
- "ENGINEERING.md",
101
- );
102
- writeFile(path.join(repo, installedRelative), content);
103
- const manifestPath = path.join(repo, ".agents", "managed-install.json");
104
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
105
- manifest.skill_version = version;
106
- const entry = manifest.entries.find(item => item.path === installedRelative);
107
- assert(entry, "installed manifest must contain the managed ENGINEERING source template");
108
- Object.assign(entry, {
109
- source: "skill/data/templates/ENGINEERING.md",
110
- ownership: "exact",
111
- sha256: crypto.createHash("sha256").update(content).digest("hex"),
112
- version,
113
- });
114
- writeFile(manifestPath, `${JSON.stringify(manifest)}\n`);
115
- }
116
-
117
- function readEngineeringConfig(file) {
118
- const script = [
119
- "import json, pathlib, sys, yaml",
120
- "text = pathlib.Path(sys.argv[1]).read_text(encoding='utf-8')",
121
- "parts = text.split('---', 2)",
122
- "assert len(parts) == 3 and not parts[0].strip(), 'missing YAML frontmatter'",
123
- "print(json.dumps(yaml.safe_load(parts[1]) or {}, sort_keys=True))",
124
- ].join("; ");
125
- return JSON.parse(run("python3", ["-c", script, file]).stdout);
126
- }
127
-
128
- function readYamlConfig(file) {
129
- const script = [
130
- "import json, pathlib, sys, yaml",
131
- "value = yaml.safe_load(pathlib.Path(sys.argv[1]).read_text(encoding='utf-8'))",
132
- "print(json.dumps(value, sort_keys=True))",
133
- ].join("; ");
134
- return JSON.parse(run("python3", ["-c", script, file]).stdout);
135
- }
136
-
137
- function projectConfigPath(repo) {
138
- return path.join(repo, projectConfigRelativePath);
139
- }
140
-
141
- function writeProjectConfig(repo, overrides) {
142
- writeFile(projectConfigPath(repo), `${JSON.stringify({ schema: projectConfigSchema, overrides }, null, 2)}\n`);
143
- }
144
-
145
- function renderYaml(value) {
146
- const script = [
147
- "import json, sys, yaml",
148
- "print(yaml.safe_dump(json.loads(sys.argv[1]), allow_unicode=True, sort_keys=False), end='')",
149
- ].join("; ");
150
- return run("python3", ["-c", script, JSON.stringify(value)]).stdout;
151
- }
152
-
153
- function readEffectiveConfig(repo) {
154
- const script = [
155
- "import json, pathlib, sys",
156
- "repo = pathlib.Path(sys.argv[1]).resolve()",
157
- "sys.path.insert(0, str(repo / '.agents' / 'skills' / 'auto-coding-skill' / 'scripts'))",
158
- "import core",
159
- "print(json.dumps(core.load_effective_config(repo), sort_keys=True))",
160
- ].join("; ");
161
- return JSON.parse(run("python3", ["-c", script, repo]).stdout);
162
- }
163
-
164
- function canonicalJson(value) {
165
- if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
166
- if (value && typeof value === "object") {
167
- return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonicalJson(value[key])}`).join(",")}}`;
168
- }
169
- return JSON.stringify(value);
170
- }
171
-
172
- function readTomlString(text, key, file) {
173
- const match = text.match(new RegExp(`^${key}\\s*=\\s*"([^"]+)"\\s*$`, "m"));
174
- assert(match, `${file}: missing ${key}`);
175
- return match[1];
176
- }
177
-
178
- function managedAgentHeader(text) {
179
- return text.split(/^developer_instructions\s*=\s*(?:"""|''')/m, 1)[0];
180
- }
181
-
182
- function assertManagedAgents(agentsDir, expectedModel = null) {
183
- for (const [filename, effort] of Object.entries(managedAgentEfforts)) {
184
- const file = path.join(agentsDir, filename);
185
- assert(exists(file), `missing managed agent: ${filename}`);
186
- const text = fs.readFileSync(file, "utf8");
187
- assert(readTomlString(text, "model_reasoning_effort", file) === effort, `${filename}: unexpected effort`);
188
- const model = managedAgentHeader(text).match(/^model\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? null;
189
- assert(model === expectedModel, `${filename}: expected model ${expectedModel ?? "inherit"}, got ${model}`);
190
- }
191
- }
192
-
193
- function listProjectFiles(root) {
194
- const out = [];
195
- function walk(current) {
196
- for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
197
- if (entry.name === ".git" || entry.name === "__pycache__" || entry.name.endsWith(".pyc")) continue;
198
- const file = path.join(current, entry.name);
199
- if (entry.isDirectory()) walk(file);
200
- else out.push(file);
201
- }
202
- }
203
- walk(root);
204
- return out;
205
- }
206
-
207
- function fillLegacyEngineeringAccess(repo, password = "local-dev-password") {
208
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
209
- const text = fs.readFileSync(engineering, "utf8");
210
- const block = [
211
- "access:",
212
- " project:",
213
- " frontend:",
214
- ' url: "http://project-frontend.local"',
215
- ' username: "project-frontend-user"',
216
- ` password: ${JSON.stringify(password)}`,
217
- " backend:",
218
- ' url: "http://project-backend.local"',
219
- ' username: "project-backend-user"',
220
- ` password: ${JSON.stringify(password)}`,
221
- " jenkins:",
222
- " frontend:",
223
- ' url: "http://jenkins-frontend.local"',
224
- ' username: "jenkins-frontend-user"',
225
- ` password: ${JSON.stringify(password)}`,
226
- " backend:",
227
- ' url: "http://jenkins-backend.local"',
228
- ' username: "jenkins-backend-user"',
229
- ` password: ${JSON.stringify(password)}`,
230
- " gitlab:",
231
- ' url: "http://gitlab.local"',
232
- ' username: "gitlab-user"',
233
- ` password: ${JSON.stringify(password)}`,
234
- " nexus:",
235
- " frontend:",
236
- ' url: "http://nexus-frontend.local"',
237
- ' username: "nexus-frontend-user"',
238
- ` password: ${JSON.stringify(password)}`,
239
- ].join("\n");
240
- const withAccess = text.replace(/^access:\r?\n[\s\S]*?(?=^concurrency:)/m, `${block}\n\n`);
241
- const updated = withAccess
242
- .replace(/ project_fast: (?:""|'')/, ' project_fast: "true"')
243
- .replace(
244
- " routes: []",
245
- [
246
- " routes:",
247
- ' - name: "project-code"',
248
- ' paths: ["**"]',
249
- ' exclude: ["*.md", "docs/**"]',
250
- ' commands: ["project_fast"]',
251
- ].join("\n"),
252
- );
253
- assert(updated !== text || text.includes(password), "required project values should be replaceable");
254
- fs.writeFileSync(engineering, updated);
255
- }
256
-
257
- function fillRequiredAccess(repo, password = "local-dev-password") {
258
- const overlay = projectConfigPath(repo);
259
- const existing = exists(overlay) ? (readYamlConfig(overlay).overrides ?? {}) : {};
260
- const required = requiredProjectOverrides(existing.project?.name ?? path.basename(repo), password);
261
- writeProjectConfig(repo, {
262
- ...existing,
263
- project: { ...required.project, ...(existing.project ?? {}) },
264
- access: required.access,
265
- commands: { ...(existing.commands ?? {}), ...required.commands },
266
- validation: { ...(existing.validation ?? {}), ...required.validation },
267
- });
268
- }
269
-
270
- function requiredProjectOverrides(projectName, password = "overlay-local-dev-password") {
271
- return {
272
- project: {
273
- name: projectName,
274
- },
275
- access: {
276
- project: {
277
- frontend: { url: "http://project-frontend.local", username: "project-frontend-user", password },
278
- backend: { url: "http://project-backend.local", username: "project-backend-user", password },
279
- },
280
- jenkins: {
281
- frontend: { url: "http://jenkins-frontend.local", username: "jenkins-frontend-user", password },
282
- backend: { url: "http://jenkins-backend.local", username: "jenkins-backend-user", password },
283
- },
284
- gitlab: { url: "http://gitlab.local", username: "gitlab-user", password },
285
- nexus: {
286
- frontend: { url: "http://nexus-frontend.local", username: "nexus-frontend-user", password },
287
- },
288
- },
289
- commands: {
290
- project_fast: "true",
291
- },
292
- validation: {
293
- routes: [
294
- {
295
- name: "project-code",
296
- paths: ["**"],
297
- exclude: ["*.md", "docs/**"],
298
- commands: ["project_fast"],
299
- },
300
- ],
301
- },
302
- };
303
- }
304
-
305
- function assertStatusOk(repo) {
306
- fillRequiredAccess(repo);
307
- const result = run("node", [cli, "status", "--projects", repo, "--json"]);
308
- const parsed = JSON.parse(result.stdout);
309
- assert(parsed.results[0].ok === true, `status should be ok: ${result.stdout}`);
310
- }
311
-
312
- function testInitFullyConvergesExistingProject() {
313
- const repo = tmpdir("full-init");
314
- run("node", [cli, "init"], { cwd: repo });
315
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
316
- const structureStandard = path.join(repo, "docs", "architecture", "structure-standard.md");
317
- assert(
318
- fs.readFileSync(structureStandard, "utf8").startsWith("# Project Structure Standard"),
319
- "first init must scaffold the project structure standard",
320
- );
321
- const customStructureStandard = "# XJMate Structure Standard\n\nProject-owned architecture policy.\n";
322
- const expectedRiskRules = [
323
- {
324
- name: "frontend-manifest-and-extension-policy",
325
- paths: ["package.json", "frontend/package.json", "frontend/extensions/**"],
326
- profile: "high-risk",
327
- review: "required",
328
- design: "required",
329
- },
330
- ];
331
- const expectedStructure = {
332
- enabled: false,
333
- enforcement: "blocking",
334
- architecture_standard: "xjmate-clean-architecture",
335
- exclude: ["docs/**"],
336
- allow_large_files: ["generated/**"],
337
- reusable_tool_dirs: ["tools/**"],
338
- max_file_lines_warn: 701,
339
- max_file_lines_block: 1401,
340
- max_function_lines_warn: 101,
341
- max_added_lines_to_large_file: 41,
342
- require_reuse_search: false,
343
- block_new_responsibility_in_large_file: false,
344
- accepted_debt_paths: ["legacy/accepted/**"],
345
- layer_rules: {
346
- enabled: false,
347
- block: true,
348
- rules: [
349
- {
350
- name: "project-domain",
351
- paths: ["src/domain/**"],
352
- forbidden_imports: ["src/infrastructure/**"],
353
- },
354
- ],
355
- },
356
- };
357
- writeProjectConfig(repo, {
358
- ...requiredProjectOverrides(path.basename(repo), "preserved-project-secret"),
359
- risk: { rules: expectedRiskRules },
360
- structure: expectedStructure,
361
- });
362
- const overlayBefore = fs.readFileSync(projectConfigPath(repo));
363
- writeFile(engineering, fs.readFileSync(engineering, "utf8")
364
- .replace("# Project Facts", "# Obsolete workflow rules\n\nRun a full build every time.\n\n# Project Facts"));
365
- writeFile(path.join(repo, "docs", "legacy", "old-taskbook.md"), "historical\n");
366
- writeFile(path.join(repo, "docs", "architecture", "system-context.md"), "# System context\n\nKeep me.\n");
367
- writeFile(path.join(repo, "docs", "architecture", "adr", "0042-project-choice.md"), "# ADR-0042\n\nKeep me.\n");
368
- writeFile(path.join(repo, "docs", "interfaces", "event-contracts.md"), "# Events\n\nKeep me.\n");
369
- writeFile(path.join(repo, "docs", "project", "operations.md"), "# Project operations\n\nKeep me.\n");
370
- const projectAssets = new Map([
371
- ["docs/architecture/diagrams/system.svg", Buffer.from("<svg>architecture</svg>\n")],
372
- ["docs/bugs/attachments/trace.bin", Buffer.from([0, 1, 2, 255])],
373
- ["docs/deployment/assets/values.yaml", Buffer.from("replicas: 2\n")],
374
- ["docs/design/T0055-login-comparison.png", Buffer.from([137, 80, 78, 71, 0, 255])],
375
- ["docs/interfaces/schemas/event.json", Buffer.from('{"type":"object"}\n')],
376
- ["docs/project/assets/logo.bin", Buffer.from([10, 20, 30, 40])],
377
- ["docs/reviews/evidence/chart.svg", Buffer.from("<svg>review</svg>\n")],
378
- ["docs/testing/fixtures/sample.dat", Buffer.from("fixture\u0000bytes")],
379
- ]);
380
- for (const [relative, bytes] of projectAssets) writeFile(path.join(repo, relative), bytes);
381
- writeFile(path.join(repo, "docs", "legacy", "orphan.bin"), Buffer.from([7, 8, 9]));
382
- const skillFeedback = path.join(repo, "docs", "skill-feedback", "reports", "2026-07-18-review-timeout-a13f82c1.md");
383
- const skillFeedbackContent = "project-owned feedback bytes\n";
384
- writeFile(skillFeedback, skillFeedbackContent);
385
- writeFile(structureStandard, customStructureStandard);
386
- writeFile(path.join(repo, ".agents", "agents", "custom.toml"), 'name = "custom"\n');
387
- writeFile(path.join(repo, ".agents", "skills", "auto-coding-skill", "obsolete.txt"), "obsolete\n");
388
-
389
- const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
390
- const dryActions = JSON.parse(dryRun.stdout).results[0].actions;
391
- for (const [relative, bytes] of projectAssets) {
392
- assert(!dryActions.some(item => item.path === relative && item.action === "would-delete"), `${relative}: dry-run must preserve project-owned assets`);
393
- assert(fs.readFileSync(path.join(repo, relative)).equals(bytes), `${relative}: dry-run must preserve bytes`);
394
- }
395
-
396
- run("node", [cli, "init"], { cwd: repo });
397
- const installedDocs = listProjectFiles(path.join(repo, "docs"))
398
- .map(file => path.relative(repo, file).split(path.sep).join("/"))
399
- .sort();
400
- const expectedInstalledDocs = [
401
- ...exactDocs,
402
- "docs/architecture/adr/0042-project-choice.md",
403
- "docs/architecture/system-context.md",
404
- "docs/interfaces/event-contracts.md",
405
- "docs/project/auto-coding-skill.yaml",
406
- "docs/project/operations.md",
407
- "docs/skill-feedback/reports/2026-07-18-review-timeout-a13f82c1.md",
408
- ...projectAssets.keys(),
409
- ].sort();
410
- assert(JSON.stringify(installedDocs) === JSON.stringify(expectedInstalledDocs), `docs framework must converge while preserving valid artifacts: ${installedDocs.join(", ")}`);
411
- const converged = fs.readFileSync(engineering, "utf8");
412
- const convergedConfig = readEffectiveConfig(repo);
413
- assert(convergedConfig.access?.project?.frontend?.password === "preserved-project-secret", "project access values must survive init in the overlay");
414
- assert(!converged.includes("preserved-project-secret"), "managed ENGINEERING must not retain project access values");
415
- assert(!converged.includes("Run a full build every time"), "legacy workflow text must be removed");
416
- assert(canonicalJson(convergedConfig.risk?.rules) === canonicalJson(expectedRiskRules), "project risk.rules must survive init path-for-path");
417
- for (const [key, expected] of Object.entries(expectedStructure)) {
418
- assert(
419
- canonicalJson(convergedConfig.structure?.[key]) === canonicalJson(expected),
420
- `supported structure.${key} must survive init`,
421
- );
422
- }
423
- assert(exists(path.join(repo, ".agents", "agents", "custom.toml")), "project-owned custom agents must survive init");
424
- assert(!exists(path.join(repo, ".agents", "skills", "auto-coding-skill", "obsolete.txt")), "extra Skill files must be removed");
425
- assert(exists(path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "legacy", "old-taskbook.md")), "removed docs must be archived outside active docs");
426
- assert(exists(path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "legacy", "orphan.bin")), "unowned legacy binary assets must still be archived");
427
- assert(fs.readFileSync(structureStandard, "utf8") === customStructureStandard, "init must preserve a project-owned structure standard");
428
- assert(fs.readFileSync(path.join(repo, "docs", "architecture", "adr", "0042-project-choice.md"), "utf8").includes("Keep me"), "numbered ADR artifacts must survive init");
429
- assert(fs.readFileSync(path.join(repo, "docs", "architecture", "system-context.md"), "utf8").includes("Keep me"), "architecture artifacts must survive init");
430
- assert(fs.readFileSync(path.join(repo, "docs", "interfaces", "event-contracts.md"), "utf8").includes("Keep me"), "interface artifacts must survive init");
431
- assert(fs.readFileSync(path.join(repo, "docs", "project", "operations.md"), "utf8").includes("Keep me"), "project fact documents promised by the manifest must survive init");
432
- assert(fs.readFileSync(skillFeedback, "utf8") === skillFeedbackContent, "project Skill feedback must survive init byte-for-byte");
433
- assert(fs.readFileSync(projectConfigPath(repo)).equals(overlayBefore), "init must preserve the project configuration overlay byte-for-byte");
434
- for (const [relative, bytes] of projectAssets) {
435
- assert(fs.readFileSync(path.join(repo, relative)).equals(bytes), `${relative}: init must preserve project-owned bytes`);
436
- }
437
-
438
- run("node", [cli, "init"], { cwd: repo });
439
- assert(fs.readFileSync(engineering, "utf8") === converged, "repeated init must be byte-idempotent for ENGINEERING.md");
440
- assert(fs.readFileSync(projectConfigPath(repo)).equals(overlayBefore), "repeated init must preserve the project configuration overlay byte-for-byte");
441
- assert(fs.readFileSync(structureStandard, "utf8") === customStructureStandard, "repeated init must preserve the project structure standard byte-for-byte");
442
- assert(fs.readFileSync(skillFeedback, "utf8") === skillFeedbackContent, "repeated init must preserve project Skill feedback byte-for-byte");
443
- for (const [relative, bytes] of projectAssets) {
444
- assert(fs.readFileSync(path.join(repo, relative)).equals(bytes), `${relative}: repeated init must preserve project-owned bytes`);
445
- }
446
- const secondDocs = listProjectFiles(path.join(repo, "docs"))
447
- .map(file => path.relative(repo, file).split(path.sep).join("/"))
448
- .sort();
449
- assert(JSON.stringify(secondDocs) === JSON.stringify(expectedInstalledDocs), "repeated init must stay idempotent");
450
- }
451
-
452
- function testStructureBlockWarningsDefaultsPreserveAndConverge() {
453
- const repo = tmpdir("structure-block-warnings");
454
- run("node", [cli, "init"], { cwd: repo });
455
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
456
- const initialized = fs.readFileSync(engineering, "utf8");
457
- const initializedConfig = readEngineeringConfig(engineering);
458
- assert(
459
- initializedConfig.structure?.block_warnings === false,
460
- "new projects must default structure.block_warnings to false",
461
- );
462
-
463
- const initialOverrides = readYamlConfig(projectConfigPath(repo)).overrides;
464
- writeProjectConfig(repo, {
465
- ...initialOverrides,
466
- structure: { ...(initialOverrides.structure ?? {}), block_warnings: true },
467
- });
468
- const customized = fs.readFileSync(projectConfigPath(repo));
469
-
470
- run("node", [cli, "init"], { cwd: repo });
471
- const converged = fs.readFileSync(engineering, "utf8");
472
- assert(
473
- readEffectiveConfig(repo).structure?.block_warnings === true,
474
- "init must apply an explicit true project structure.block_warnings override",
475
- );
476
- assert(fs.readFileSync(projectConfigPath(repo)).equals(customized), "init must preserve the block_warnings overlay byte-for-byte");
477
- run("node", [cli, "init"], { cwd: repo });
478
- assert(
479
- fs.readFileSync(engineering, "utf8") === converged,
480
- "repeated init must be byte-idempotent for managed defaults",
481
- );
482
-
483
- run("node", [cli, "sync", "--projects", repo]);
484
- const synced = fs.readFileSync(engineering, "utf8");
485
- assert(
486
- readEffectiveConfig(repo).structure?.block_warnings === true,
487
- "sync must preserve an explicit true project structure.block_warnings override",
488
- );
489
- assert(synced === converged, "sync must not rewrite a converged block_warnings=true config");
490
- assert(fs.readFileSync(projectConfigPath(repo)).equals(customized), "sync must preserve the block_warnings overlay byte-for-byte");
491
- run("node", [cli, "sync", "--projects", repo]);
492
- assert(
493
- fs.readFileSync(engineering, "utf8") === synced,
494
- "repeated sync must be byte-idempotent with block_warnings=true",
495
- );
496
- }
497
-
498
- function testProjectDocumentationSpecialFilesFailBeforeWrites() {
499
- if (process.platform === "win32") return;
500
- const repo = tmpdir("docs-special-files");
501
- run("node", [cli, "init"], { cwd: repo });
502
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
503
- const sentinel = "stale-skill-must-survive-rejected-docs-preflight\n";
504
- writeFile(skill, sentinel);
505
-
506
- const externalFile = path.join(tmpdir("docs-special-target"), "external.png");
507
- writeFile(externalFile, "external-target\n");
508
- const linkedFile = path.join(repo, "docs", "design", "linked.png");
509
- fs.symlinkSync(externalFile, linkedFile);
510
- let rejected = run("node", [cli, "sync", "--projects", repo], { check: false });
511
- assert(rejected.status !== 0 && rejected.stderr.includes("regular non-symlink files"), "project document file symlinks must fail before writes");
512
- assert(fs.readFileSync(skill, "utf8") === sentinel && fs.readFileSync(externalFile, "utf8") === "external-target\n", "rejected file symlink must not mutate managed or external files");
513
- fs.unlinkSync(linkedFile);
514
-
515
- const externalDir = tmpdir("docs-special-directory-target");
516
- const linkedDir = path.join(repo, "docs", "reviews", "linked-assets");
517
- fs.symlinkSync(externalDir, linkedDir);
518
- rejected = run("node", [cli, "sync", "--projects", repo], { check: false });
519
- assert(rejected.status !== 0 && rejected.stderr.includes("regular non-symlink files"), "project document directory symlinks must fail before writes");
520
- assert(fs.readFileSync(skill, "utf8") === sentinel && fs.readdirSync(externalDir).length === 0, "rejected directory symlink must preserve both roots");
521
- fs.unlinkSync(linkedDir);
522
-
523
- const fifo = path.join(repo, "docs", "testing", "fixture.pipe");
524
- run("mkfifo", [fifo]);
525
- rejected = run("node", [cli, "sync", "--projects", repo], { check: false });
526
- assert(rejected.status !== 0 && rejected.stderr.includes("regular non-symlink files"), "project document FIFOs must fail before writes");
527
- assert(fs.readFileSync(skill, "utf8") === sentinel, "rejected special files must preserve managed bytes");
528
- fs.unlinkSync(fifo);
529
- }
530
-
531
- function testManagedPolicySummaryPreservesProjectConfiguration() {
532
- const repo = tmpdir("managed-policy-summary");
533
- run("node", [cli, "init"], { cwd: repo });
534
- fs.unlinkSync(projectConfigPath(repo));
535
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
536
- const current = fs.readFileSync(engineering, "utf8");
537
- const neutralSummary = "- `structure` and `optimization`: managed defaults that the project overlay may\n replace explicitly.";
538
- const legacySummary = "- `structure` and `optimization`: advisory architecture and no-new-debt policy.";
539
- const installedOldDefault = current
540
- .replace(/^ skill_version:.*$/m, " skill_version: 4.2.5")
541
- .replace("managed-workflow:start version=4.3.7", "managed-workflow:start version=4.2.5")
542
- .replace(neutralSummary, legacySummary);
543
- installTrustedEngineeringDefault(repo, installedOldDefault, "4.2.5");
544
- const customized = current
545
- .replace(/^ skill_version:.*$/m, " skill_version: 4.2.5")
546
- .replace("managed-workflow:start version=4.3.7", "managed-workflow:start version=4.2.5")
547
- .replace(neutralSummary, legacySummary)
548
- .replace(/^ enforcement:.*$/m, " enforcement: blocking")
549
- .replace(" block_warnings: false", " block_warnings: true")
550
- .replace(" block: false", " block: true")
551
- .replace(/^ completion_policy:.*$/m, " completion_policy: baseline-aware")
552
- .replace(" require_baseline_for_global_review: false", " require_baseline_for_global_review: true")
553
- .replace(" report_accepted_debt_as_findings: false", " report_accepted_debt_as_findings: true");
554
- assert(customized !== current && customized.includes(legacySummary), "fixture must represent the 4.2.5 managed summary");
555
- writeFile(engineering, customized);
556
- const beforeUpgrade = readEngineeringConfig(engineering);
557
- assert(beforeUpgrade.workflow?.skill_version === "4.2.5", "fixture must identify the previous workflow version");
558
- assert(beforeUpgrade.structure?.enforcement === "blocking", "fixture must enable blocking structure enforcement");
559
- assert(beforeUpgrade.optimization?.completion_policy === "baseline-aware", "fixture must enable baseline-aware completion");
560
-
561
- run("node", [cli, "init"], { cwd: repo });
562
- const upgraded = fs.readFileSync(engineering, "utf8");
563
- const managedAfterUpgrade = readEngineeringConfig(engineering);
564
- const afterUpgrade = readEffectiveConfig(repo);
565
- assert(managedAfterUpgrade.workflow?.skill_version === "4.3.7", "init must upgrade the managed workflow version");
566
- assert(canonicalJson(afterUpgrade.structure) === canonicalJson(beforeUpgrade.structure), "init must preserve the complete project structure policy");
567
- assert(canonicalJson(afterUpgrade.optimization) === canonicalJson(beforeUpgrade.optimization), "init must preserve the complete project optimization policy");
568
- assert(upgraded.includes(neutralSummary), "upgraded managed text must defer to frontmatter policy");
569
- assert(!upgraded.includes(legacySummary), "upgraded managed text must remove the hard-coded default policy description");
570
-
571
- const migratedOverlay = fs.readFileSync(projectConfigPath(repo));
572
- run("node", [cli, "init"], { cwd: repo });
573
- assert(fs.readFileSync(engineering, "utf8") === upgraded, "repeated init must be byte-idempotent after the policy-summary upgrade");
574
- assert(fs.readFileSync(projectConfigPath(repo)).equals(migratedOverlay), "repeated init must preserve the migrated project policy overlay byte-for-byte");
575
- }
576
-
577
- function testInitRejectsMissingPythonRuntimeBeforeWrites() {
578
- if (process.platform === "win32") return;
579
- const repo = tmpdir("missing-python-runtime");
580
- const fakePython = path.join(repo, "python-without-yaml");
581
- writeFile(fakePython, "#!/bin/sh\necho 'No module named yaml' >&2\nexit 1\n");
582
- fs.chmodSync(fakePython, 0o755);
583
- const result = run("node", [cli, "init"], {
584
- cwd: repo,
585
- check: false,
586
- env: { AUTOCODING_PYTHON: fakePython },
587
- });
588
- assert(result.status !== 0, "init should fail when its Python runtime cannot import PyYAML");
589
- assert(result.stderr.includes("Python runtime dependency check failed"), "init should identify the runtime dependency failure");
590
- assert(result.stderr.includes("requirements.txt") && result.stderr.includes("Then rerun autocoding init"), "init should print one deterministic recovery command");
591
- assert(!exists(path.join(repo, ".agents")), "runtime preflight must fail before writing .agents");
592
- }
593
-
594
- function testDestVariants() {
595
- const variants = [
596
- { name: "repo-root", dest(root) { return root; } },
597
- { name: "agents-root", dest(root) { return path.join(root, ".agents"); } },
598
- { name: "skills-dir", dest(root) { return path.join(root, ".agents", "skills"); } },
599
- { name: "agents-dir", dest(root) { return path.join(root, ".agents", "agents"); } },
600
- { name: "direct-skill", dest(root) { return path.join(root, ".agents", "skills", "auto-coding-skill"); } },
601
- ];
602
-
603
- for (const variant of variants) {
604
- const root = tmpdir(`dest-${variant.name}`);
605
- const dest = variant.dest(root);
606
- fs.mkdirSync(dest, { recursive: true });
607
- run("node", [cli, "init", "--dest", dest, "--force"]);
608
- assert(exists(path.join(root, ".agents", "skills", "auto-coding-skill", "SKILL.md")), `${variant.name}: missing skill`);
609
- assert(exists(path.join(root, ".agents", "agents", "explorer.toml")), `${variant.name}: missing agent`);
610
- assert(!exists(path.join(root, ".agents", ".agents")), `${variant.name}: nested .agents should not be created`);
611
- }
612
- }
613
-
614
- function testLauncherFallsBackToGlobalRuntime() {
615
- const fakeHome = tmpdir("global-runtime-home");
616
- const project = tmpdir("global-runtime-project");
617
- const env = pythonEnvWithHome(fakeHome);
618
- run("node", [cli, "init", "--mode", "global", "--dest", fakeHome, "--force"]);
619
- const globalAp = path.join(fakeHome, ".agents", "skills", "auto-coding-skill", "scripts", "ap.py");
620
- run("python3", [globalAp, "--repo", project, "install"], { env });
621
- assert(!exists(path.join(project, ".agents", "skills", "auto-coding-skill")), "fixture should rely on the global runtime only");
622
- const launcher = path.join(project, "docs", "tools", "autopipeline", "ap.py");
623
- const help = run("python3", [launcher, "--help"], { env });
624
- assert(help.stdout.includes("autopipeline"), "project launcher should execute the global runtime when no project copy exists");
625
- }
626
-
627
- function testMinimalInitConvergesWithinBudget() {
628
- const repo = tmpdir("minimal-sync");
629
- run("node", [cli, "init"], { cwd: repo });
630
-
631
- for (const rel of exactDocs) {
632
- assert(exists(path.join(repo, rel)), `missing core scaffold file: ${rel}`);
633
- }
634
- for (const rel of ["docs/tasks/taskbook.md", "docs/tasks/closure-log.md", "docs/tools/autopipeline/core.py", "docs/tools/autopipeline/http_checks.py"]) {
635
- assert(!exists(path.join(repo, rel)), `optional/duplicate file should not be installed: ${rel}`);
636
- }
637
-
638
- const files = listProjectFiles(repo);
639
- const lines = files.reduce((total, file) => total + fs.readFileSync(file, "utf8").split(/\r?\n/).length, 0);
640
- assert(files.length <= 40, `minimal scaffold file budget exceeded: ${files.length}`);
641
- // Integrity, staging, fail-closed classification, immutable Reviewer snapshots,
642
- // bounded runtime supervision, failure-evidence binding, immutable one-shot
643
- // Reviewer migration audits, contract helpers,
644
- // effective-config overlay parsing/migration, release-aware metadata-only
645
- // feedback lifecycle collection, and the language-aware structure scanner are executable
646
- // support code, not prompt context. Keep a measured ceiling while leaving
647
- // safety checks readable.
648
- assert(lines <= 21250, `minimal scaffold line budget exceeded: ${lines}`);
649
- const engineering = fs.readFileSync(path.join(repo, "docs", "ENGINEERING.md"), "utf8");
650
- const managedConfig = readEngineeringConfig(path.join(repo, "docs", "ENGINEERING.md"));
651
- assert(managedConfig.workflow?.profile === "auto", "engineering should enable adaptive profiles");
652
- assert(managedConfig.concurrency?.isolation === "adaptive", "engineering should default to adaptive clean-branch/worktree isolation");
653
- assert(managedConfig.workflow?.completion === "push", "engineering should complete normal development at push");
654
- assert(managedConfig.commands?.project_fast === "", "generic projects should expose an optional project-fast command");
655
- assert(managedConfig.validation?.max_command_seconds === 120, "engineering should bound each final route command");
656
- assert(managedConfig.validation?.max_total_seconds === 180, "engineering should bound the complete final gate");
657
- assert(readYamlConfig(projectConfigPath(repo)).overrides?.project?.name === path.basename(repo), "project name should be initialized in the project-owned overlay");
658
- assert(managedConfig.project?.name === "", "managed ENGINEERING must keep the neutral project-name default");
659
- assert(!engineering.includes("## Design, review, and subagents"), "engineering must not duplicate the behavioral protocol");
660
- const agentsProtocol = fs.readFileSync(path.join(repo, "AGENTS.md"), "utf8");
661
- assert(agentsProtocol.includes("## Minimum mechanism budget"), "AGENTS should own the shared behavioral protocol");
662
- assert(agentsProtocol.includes("One writer in a clean checkout works directly"), "AGENTS should enforce direct clean serial work");
663
- const fixer = fs.readFileSync(path.join(repo, ".agents", "agents", "fixer.toml"), "utf8");
664
- const reviewer = fs.readFileSync(path.join(repo, ".agents", "agents", "reviewer.toml"), "utf8");
665
- const browserDebugger = fs.readFileSync(path.join(repo, ".agents", "agents", "browser-debugger.toml"), "utf8");
666
- assert(fixer.includes("owned_paths"), "fixer should receive explicit path ownership");
667
- assert(fixer.includes("不提交、不推送、不集成"), "fixer should leave Git lifecycle to the main agent");
668
- assert(reviewer.includes("diff_fingerprint"), "reviewer verdict should bind to a stable diff");
669
- assert(reviewer.includes("agent-result-template"), "reviewer should use the complete result skeleton");
670
- assert(reviewer.includes("AUTOCODING_REVIEW_ASSIGNMENT"), "reviewer should receive the supervised assignment path");
671
- assert(reviewer.includes("150 秒"), "reviewer should enforce the focused review budget");
672
- assert(agentsProtocol.includes("ap.py review-run"), "AGENTS should use the supervised Reviewer runtime");
673
- assert(agentsProtocol.includes("review-runtime-override"), "AGENTS should document the audited runtime bypass");
674
- assert(agentsProtocol.includes("cannot stop an in-app subagent"), "AGENTS should state the supervision boundary honestly");
675
- assert(browserDebugger.includes('sandbox_mode = "read-only"'), "browser discovery should be read-only");
676
-
677
- const incomplete = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
678
- assert(incomplete.status !== 0, "status should require access values after scaffold creation");
679
- const missing = JSON.parse(incomplete.stdout).results[0].missingConfigTokens;
680
- for (const field of [
681
- "access.project.frontend.password",
682
- "access.project.backend.password",
683
- "access.jenkins.frontend.password",
684
- "access.jenkins.backend.password",
685
- "access.gitlab.password",
686
- "access.nexus.frontend.password",
687
- ]) {
688
- assert(missing.includes(field), `status should report missing direct credential: ${field}`);
689
- }
690
- assert(!JSON.parse(incomplete.stdout).results[0].next.includes("upgrade"), "fresh projects with present blank fields should be told to fill them directly");
691
-
692
- assertStatusOk(repo);
693
-
694
- const doctor = run("python3", [path.join(repo, "docs", "tools", "autopipeline", "ap.py"), "--repo", repo, "doctor"], { check: false });
695
- const doctorOutput = `${doctor.stdout}\n${doctor.stderr}`;
696
- assert(doctor.status === 0, `filled generic project should pass the local doctor: ${doctorOutput}`);
697
- for (const unexpected of ["target_env.name", "backend_root", "jenkins.base_url", "docs.api_doc", "gate_full"]) {
698
- assert(!doctorOutput.includes(unexpected), `default doctor should not require optional field: ${unexpected}`);
699
- }
700
- }
701
-
702
- function testSkillFeedbackTemplatesAndReportsSurviveSync() {
703
- const repo = tmpdir("skill-feedback-sync");
704
- run("node", [cli, "init"], { cwd: repo });
705
- fillRequiredAccess(repo);
706
- const feedbackReadme = path.join(repo, "docs", "skill-feedback", "README.md");
707
- const feedbackTemplate = path.join(repo, "docs", "skill-feedback", "_TEMPLATE-SKILL-FEEDBACK.md");
708
- const report = path.join(repo, "docs", "skill-feedback", "reports", "2026-07-18-installer-gap-a13f82c1.md");
709
- const reportBytes = Buffer.from("project-owned\u0000feedback\n", "utf8");
710
- fs.mkdirSync(path.dirname(report), { recursive: true });
711
- fs.writeFileSync(report, reportBytes);
712
- assert(exists(feedbackReadme) && exists(feedbackTemplate), "init must install managed Skill feedback guidance and template");
713
-
714
- writeFile(feedbackReadme, "managed template drift\n");
715
- const dry = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
716
- const dryResult = JSON.parse(dry.stdout).results[0];
717
- assert(
718
- dryResult.actions.some(item => item.path === "docs/skill-feedback/README.md" && item.action === "would-replace"),
719
- "sync dry-run must report managed feedback template drift",
720
- );
721
- assert(fs.readFileSync(feedbackReadme, "utf8") === "managed template drift\n", "sync dry-run must not write feedback templates");
722
- assert(fs.readFileSync(report).equals(reportBytes), "sync dry-run must not touch project feedback reports");
723
-
724
- run("node", [cli, "sync", "--projects", repo, "--json"]);
725
- assert(fs.readFileSync(feedbackReadme, "utf8").includes("Auto Coding Skill Feedback"), "sync must restore the managed feedback README");
726
- assert(fs.readFileSync(report).equals(reportBytes), "sync must preserve project feedback reports byte-for-byte");
727
- assertStatusOk(repo);
728
-
729
- if (process.platform !== "win32") {
730
- const external = path.join(tmpdir("feedback-managed-symlink"), "external.md");
731
- const installedSkill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
732
- const skillBefore = fs.readFileSync(installedSkill);
733
- writeFile(external, "external must not change\n");
734
- fs.unlinkSync(feedbackReadme);
735
- fs.symlinkSync(external, feedbackReadme);
736
- const unsafeInit = run("node", [cli, "init"], { cwd: repo, check: false });
737
- assert(unsafeInit.status !== 0 && unsafeInit.stderr.includes("non-symlink"), "init must reject a managed feedback template symlink before writes");
738
- assert(fs.readFileSync(external, "utf8") === "external must not change\n", "init must never follow a managed feedback template symlink");
739
- assert(fs.readFileSync(installedSkill).equals(skillBefore), "managed feedback symlink preflight must happen before install writes");
740
- fs.unlinkSync(feedbackReadme);
741
- run("node", [cli, "init"], { cwd: repo });
742
- assert(fs.readFileSync(report).equals(reportBytes), "feedback report must survive repair of a managed template symlink");
743
-
744
- const parentLinkRepo = tmpdir("feedback-managed-parent-symlink");
745
- const externalDir = tmpdir("feedback-managed-parent-external");
746
- run("node", [cli, "init"], { cwd: parentLinkRepo });
747
- const parentInstalledSkill = path.join(parentLinkRepo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
748
- const parentSkillBefore = fs.readFileSync(parentInstalledSkill);
749
- fs.rmSync(path.join(parentLinkRepo, "docs", "skill-feedback"), { recursive: true, force: true });
750
- fs.symlinkSync(externalDir, path.join(parentLinkRepo, "docs", "skill-feedback"));
751
- const unsafeParentInit = run("node", [cli, "init"], { cwd: parentLinkRepo, check: false });
752
- assert(unsafeParentInit.status !== 0 && unsafeParentInit.stderr.includes("real directory"), "init must reject a symlink in the managed feedback parent chain");
753
- assert(fs.readdirSync(externalDir).length === 0, "init must not write through a managed feedback parent symlink");
754
- assert(fs.readFileSync(parentInstalledSkill).equals(parentSkillBefore), "parent symlink preflight must happen before install writes");
755
- }
756
- }
757
-
758
- function testStatusRejectsLegacyIsolation() {
759
- const repo = tmpdir("legacy-isolation-status");
760
- run("node", [cli, "init"], { cwd: repo });
761
- run("node", [cli, "sync", "--projects", repo]);
762
- fillRequiredAccess(repo);
763
- const overrides = readYamlConfig(projectConfigPath(repo)).overrides;
764
- writeProjectConfig(repo, {
765
- ...overrides,
766
- concurrency: { ...(overrides.concurrency ?? {}), isolation: "legacy" },
767
- });
768
-
769
- const result = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
770
- assert(result.status !== 0, "status must reject legacy isolation");
771
- const parsed = JSON.parse(result.stdout).results[0];
772
- assert(
773
- parsed.invalidConfigTokens.includes("concurrency.isolation (must be adaptive or worktree)"),
774
- `status should identify the invalid isolation value: ${result.stdout}`,
775
- );
776
- assert(parsed.next.includes("autocoding init"), "status should direct legacy projects through authoritative init");
777
- }
778
-
779
- function testStatusRejectsLegacyGateEscalation() {
780
- const repo = tmpdir("legacy-gate-status");
781
- run("node", [cli, "init"], { cwd: repo });
782
- run("node", [cli, "sync", "--projects", repo]);
783
- const overrides = readYamlConfig(projectConfigPath(repo)).overrides;
784
- writeProjectConfig(repo, {
785
- ...overrides,
786
- gate: {
787
- full_on_unknown: "true",
788
- full_on: ["prod_config"],
789
- rules: [{ match: ["Jenkinsfile"], scope: "full", commands: ["gate_full"] }],
790
- },
791
- });
792
- const status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
793
- assert(status.status === 2, "legacy automatic gate escalation must make status non-zero");
794
- const invalid = JSON.parse(status.stdout).results[0].invalidConfigTokens;
795
- for (const expected of ["gate.full_on", "gate.full_on_unknown", "gate.rules[0].scope", "gate.rules[0].commands"]) {
796
- assert(invalid.some(item => item.includes(expected)), `status should report ${expected}: ${status.stdout}`);
797
- }
798
- }
799
-
800
- function testStatusAcceptsValidIndentlessYamlRoutes() {
801
- const repo = tmpdir("indentless-routes");
802
- run("node", [cli, "init"], { cwd: repo });
803
- fillRequiredAccess(repo);
804
- const overlay = projectConfigPath(repo);
805
- const parsed = readYamlConfig(overlay);
806
- const text = renderYaml(parsed);
807
- assert(/^ routes:\r?\n - /m.test(text), "fixture must use a valid indentless YAML route sequence");
808
- writeFile(overlay, text);
809
- const status = run("node", [cli, "status", "--projects", repo, "--json"]);
810
- assert(JSON.parse(status.stdout).results[0].ok === true, "valid indentless YAML routes must not be reported as empty");
811
- }
812
-
813
- function testOrdinaryNodeTestIsNotPromotedToAutomaticGate() {
814
- const repo = tmpdir("node-gate-inference");
815
- writeFile(path.join(repo, "package.json"), JSON.stringify({ scripts: { test: "node --test" } }, null, 2) + "\n");
816
- run("node", [cli, "init"], { cwd: repo });
817
- run("node", [cli, "sync", "--projects", repo]);
818
- const effective = readEffectiveConfig(repo);
819
- assert(effective.commands?.project_fast === "", "ordinary test must not be promoted to the project-fast command");
820
- assert(effective.commands?.gate_standard === undefined, "ordinary test must not seed an automatic standard gate");
821
- assert(effective.commands?.gate_full === undefined, "ordinary test must not seed an automatic full gate");
822
-
823
- fillRequiredAccess(repo);
824
- run("git", ["init", "-q"], { cwd: repo });
825
- run("git", ["config", "user.email", "test@example.com"], { cwd: repo });
826
- run("git", ["config", "user.name", "Auto Coding Test"], { cwd: repo });
827
- run("git", ["add", "-A"], { cwd: repo });
828
- run("git", ["commit", "-qm", "baseline"], { cwd: repo });
829
- writeFile(path.join(repo, "migrations", "001.sql"), "-- migration\n");
830
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
831
- const doctor = run("python3", [launcher, "--repo", repo, "doctor"], { check: false });
832
- assert(doctor.status === 0, `high-risk paths must not expand the local gate: ${doctor.stdout}\n${doctor.stderr}`);
833
- const gate = run("python3", [launcher, "--repo", repo, "light-gate", "--scope", "changed"]);
834
- assert(gate.stdout.includes("[run] project_fast"), "the configured project-fast route should run");
835
- assert((gate.stdout.match(/\[diff-check\] OK/g) || []).length === 1, "the built-in fast diff gate should run exactly once");
836
- const expanded = run("python3", [launcher, "--repo", repo, "light-gate", "--scope", "full"], { check: false });
837
- assert(expanded.status !== 0 && expanded.stderr.includes("invalid choice"), "light-gate must reject standard/full scopes instead of silently downgrading them");
838
- }
839
-
840
- function testAccessPasswordsAreRequiredButNeverPrintedByStatus() {
841
- const repo = tmpdir("required-access");
842
- const secret = "unique-local-secret-7f91";
843
- run("node", [cli, "init"], { cwd: repo });
844
- run("node", [cli, "sync", "--projects", repo]);
845
- fillRequiredAccess(repo, secret);
846
-
847
- const healthy = run("node", [cli, "status", "--projects", repo, "--json"]);
848
- assert(!healthy.stdout.includes(secret), "status JSON must not echo configured passwords");
849
-
850
- const overlay = projectConfigPath(repo);
851
- const missingPassword = readYamlConfig(overlay).overrides;
852
- missingPassword.access.project.frontend.password = "";
853
- missingPassword.access.project.frontend.password_env = "PROJECT_FRONTEND_PASSWORD";
854
- writeProjectConfig(repo, missingPassword);
855
- const missing = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
856
- assert(missing.status !== 0, "an environment reference must not replace the required direct password");
857
- assert(JSON.parse(missing.stdout).results[0].missingConfigTokens.includes("access.project.frontend.password"), "status should name the missing direct password field");
858
- assert(!missing.stdout.includes(secret), "failed status JSON must not echo other configured passwords");
859
- assert(!JSON.parse(missing.stdout).results[0].next.includes("upgrade"), "present but blank fields should not trigger a no-op upgrade recommendation");
860
-
861
- fillRequiredAccess(repo);
862
- const validOverlaySource = fs.readFileSync(overlay, "utf8");
863
- for (const yamlValue of ["false", "[]", "{}", "2026-07-13", "0x10", "|"]) {
864
- const invalid = validOverlaySource.replace('"password": "local-dev-password"', `"password": ${yamlValue}`);
865
- assert(invalid !== validOverlaySource, `${yamlValue}: fixture must replace one overlay password`);
866
- writeFile(overlay, invalid);
867
- const nonString = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
868
- assert(JSON.parse(nonString.stdout).results[0].missingConfigTokens.includes("access.project.frontend.password"), `YAML non-string ${yamlValue} must not count as a credential string: ${nonString.stdout}`);
869
- }
870
- writeFile(overlay, validOverlaySource.replace('"password": "local-dev-password"', '"password": "TO\\u0044O"'));
871
- const escapedPlaceholder = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
872
- assert(JSON.parse(escapedPlaceholder.stdout).results[0].missingConfigTokens.includes("access.project.frontend.password"), "escaped YAML placeholders must be decoded before validation");
873
-
874
- const absentOverrides = readYamlConfig(overlay).overrides;
875
- delete absentOverrides.access;
876
- writeProjectConfig(repo, absentOverrides);
877
- const absent = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
878
- const absentStatus = JSON.parse(absent.stdout).results[0];
879
- assert(absentStatus.unfilledConfigTokens.includes("access.project.frontend.password"), `status must retain its redacted required-field summary: ${absent.stdout}`);
880
- assert(absentStatus.invalidConfigTokens.some(item => item.includes("access.project.frontend.password") && item.includes("explicitly filled string")), `status must consume the complete doctor contract: ${absent.stdout}`);
881
- assert(absentStatus.next.includes("doctor"), `invalid effective configuration must direct the user through doctor: ${absent.stdout}`);
882
- }
883
-
884
- function testProjectConfigOverlayMigratesLegacyEngineeringAndStaysByteStable() {
885
- const repo = tmpdir("project-config-migration");
886
- const secret = "legacy-overlay-secret-6e2f";
887
- run("git", ["init", "-q"], { cwd: repo });
888
- run("node", [cli, "init"], { cwd: repo });
889
- const overlay = projectConfigPath(repo);
890
- assert(exists(overlay), "new project init must create the project-owned config overlay");
891
- const initializedOverlay = readYamlConfig(overlay);
892
- assert(initializedOverlay.schema === projectConfigSchema, "new project overlay must use the versioned schema");
893
- assert(initializedOverlay.overrides?.project?.name === path.basename(repo), "new project overlay must own the inferred project name");
894
-
895
- // Simulate the last pre-overlay release: project values lived directly in the
896
- // otherwise managed ENGINEERING frontmatter and no overlay existed yet.
897
- fs.unlinkSync(overlay);
898
- fillLegacyEngineeringAccess(repo, secret);
899
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
900
- const current = fs.readFileSync(engineering, "utf8");
901
- const legacy = current
902
- .replace(/^ name:.*$/m, ' name: "legacy-specialized-project"')
903
- .replace(/^ stack:.*$/m, ' stack: "node-go-specialized"')
904
- .replace(/^ target_branch:.*$/m, ' target_branch: "dev"')
905
- .replace(/^ cleanup_merged: true$/m, " cleanup_merged: 1")
906
- .replace(/^ max_command_seconds: 120$/m, " max_command_seconds: 120.0")
907
- .replace(/^risk:\r?\n rules: \[\]$/m, [
908
- "risk:",
909
- " rules:",
910
- " - name: project-device-credentials",
911
- " paths: [src/device-credentials/**]",
912
- " profile: high-risk",
913
- " review: required",
914
- ].join("\n"))
915
- .replace(/^structure:\r?\n enabled: true$/m, "structure:\n enabled: false")
916
- .replace(/^ block_warnings: false$/m, " block_warnings: true")
917
- .replace(/^ block: false$/m, " block: 0")
918
- .replace(/^ api_docs_required: false$/m, " api_docs_required: true");
919
- assert(legacy !== current, "legacy migration fixture must contain project-specific frontmatter changes");
920
- writeFile(engineering, legacy);
921
-
922
- run("node", [cli, "init"], { cwd: repo });
923
- const migrated = readYamlConfig(overlay);
924
- assert(migrated.schema === projectConfigSchema, "migration must create the current project overlay schema");
925
- assert(migrated.overrides?.project?.name === "legacy-specialized-project", "migration must extract project.name from legacy ENGINEERING");
926
- assert(migrated.overrides?.project?.stack === "node-go-specialized", "migration must extract the project stack");
927
- assert(migrated.overrides?.concurrency?.target_branch === "dev", "migration must extract the target branch");
928
- assert(migrated.overrides?.concurrency?.cleanup_merged === 1, "migration must distinguish integer 1 from boolean true");
929
- assert(migrated.overrides?.validation?.max_command_seconds === 120, "migration must retain the numeric timeout value");
930
- assert(migrated.overrides?.access?.project?.frontend?.password === secret, "migration must extract project access without printing it");
931
- assert(migrated.overrides?.risk?.rules?.[0]?.name === "project-device-credentials", "migration must extract project risk rules");
932
- assert(migrated.overrides?.structure?.enabled === false && migrated.overrides?.structure?.block_warnings === true, "migration must extract explicit project structure policy");
933
- assert(migrated.overrides?.structure?.layer_rules?.block === 0, "migration must distinguish integer 0 from boolean false");
934
- assert(migrated.overrides?.docs?.api_docs_required === true, "migration must extract project documentation policy");
935
- assert(migrated.overrides?.workflow?.skill_version === undefined, "migration must never copy the managed Skill version into project overrides");
936
- const migratedOverlaySource = fs.readFileSync(overlay, "utf8");
937
- assert(migratedOverlaySource.includes("max_command_seconds: 120.0"), "migration must distinguish float 120.0 from integer 120");
938
-
939
- const managed = readEngineeringConfig(engineering);
940
- assert(managed.project?.name === "" && managed.project?.stack === "generic", "ENGINEERING must converge to managed defaults after migration");
941
- assert(managed.access?.project?.frontend?.password === "", "ENGINEERING must no longer retain project access after migration");
942
- assert(managed.risk?.rules?.length === 0 && managed.structure?.enabled === true, "ENGINEERING policy defaults must remain release-owned");
943
- const effective = readEffectiveConfig(repo);
944
- assert(effective.project?.name === "legacy-specialized-project", "effective config must retain the migrated project identity");
945
- assert(effective.concurrency?.cleanup_merged === 1, "effective config must preserve integer 1 instead of restoring boolean true");
946
- assert(effective.structure?.layer_rules?.block === 0, "effective config must preserve integer 0 instead of restoring boolean false");
947
- assert(effective.access?.project?.frontend?.password === secret, "effective config must retain migrated access values");
948
- assert(effective.docs?.api_docs_required === true, "effective config must apply migrated project overrides");
949
- assert(effective.docs?.api_change_log === "docs/interfaces/api-change-log.md", "fields absent from the legacy project config must inherit the new managed default");
950
-
951
- const stableOverlay = fs.readFileSync(overlay);
952
- const stableEngineering = fs.readFileSync(engineering);
953
- run("node", [cli, "init"], { cwd: repo });
954
- assert(fs.readFileSync(overlay).equals(stableOverlay), "repeated init must preserve the project overlay byte-for-byte");
955
- assert(fs.readFileSync(engineering).equals(stableEngineering), "repeated init must keep the managed default document stable");
956
- run("node", [cli, "sync", "--projects", repo]);
957
- assert(fs.readFileSync(overlay).equals(stableOverlay), "sync must preserve the project overlay byte-for-byte");
958
- run("node", [cli, "sync", "--projects", repo]);
959
- assert(fs.readFileSync(overlay).equals(stableOverlay), "repeated sync must preserve the project overlay byte-for-byte");
960
- run("node", [cli, "sync", "--projects", repo]);
961
- assert(fs.readFileSync(overlay).equals(stableOverlay), "transactional sync must preserve an existing project overlay byte-for-byte");
962
- }
963
-
964
- function testProjectConfigOverlayMergeKeepsExplicitFalseZeroEmptyAndList() {
965
- const repo = tmpdir("project-config-merge");
966
- run("node", [cli, "init"], { cwd: repo });
967
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
968
- const managedDefault = fs.readFileSync(engineering, "utf8");
969
- const base = managedDefault
970
- .replace(/^ target_branch: (?:(?:""|'')|null)$/m, ' target_branch: "release-default"')
971
- .replace(/^risk:\r?\n rules: \[\]$/m, [
972
- "risk:",
973
- " rules:",
974
- " - name: new-managed-default",
975
- " paths: [managed-default/**]",
976
- " profile: high-risk",
977
- " review: required",
978
- ].join("\n"))
979
- .replace(/^structure:\r?\n enabled: true$/m, "structure:\n enabled: true\n max_file_lines_warn: 777")
980
- .replace(/^ api_docs_required: false$/m, " api_docs_required: true");
981
- writeFile(engineering, base);
982
- writeProjectConfig(repo, {
983
- project: { name: "explicit-overlay-values" },
984
- concurrency: { target_branch: "" },
985
- risk: { rules: [] },
986
- structure: { enabled: false, max_file_lines_warn: 0 },
987
- });
988
-
989
- const effective = readEffectiveConfig(repo);
990
- assert(effective.project?.name === "explicit-overlay-values", "project scalar must override the managed default");
991
- assert(effective.structure?.enabled === false, "explicit false must override a true managed default");
992
- assert(effective.structure?.max_file_lines_warn === 0, "explicit zero must not fall back to a non-zero managed default");
993
- assert(effective.concurrency?.target_branch === "", "explicit empty string must override a non-empty managed default");
994
- assert(Array.isArray(effective.risk?.rules) && effective.risk.rules.length === 0, "explicit empty list must replace the managed list instead of merging it");
995
- assert(effective.docs?.api_docs_required === true, "an unoverridden field must inherit a new managed default");
996
-
997
- const overlay = projectConfigPath(repo);
998
- const stableOverlay = fs.readFileSync(overlay);
999
- writeFile(engineering, managedDefault);
1000
- run("node", [cli, "init"], { cwd: repo });
1001
- run("node", [cli, "sync", "--projects", repo]);
1002
- assert(fs.readFileSync(overlay).equals(stableOverlay), "managed convergence must never normalize or rewrite an existing valid overlay");
1003
- const convergedEffective = readEffectiveConfig(repo);
1004
- assert(convergedEffective.structure?.enabled === false && convergedEffective.structure?.max_file_lines_warn === 0, "project scalar overrides must survive managed convergence");
1005
- assert(convergedEffective.concurrency?.target_branch === "" && convergedEffective.risk?.rules?.length === 0, "project empty values must survive managed convergence");
1006
- }
1007
-
1008
- function testOversizedLegacyMigrationFailsBeforeCreatingAnInvalidOverlay() {
1009
- const repo = tmpdir("project-config-oversized-migration");
1010
- run("git", ["init", "-q"], { cwd: repo });
1011
- run("node", [cli, "init"], { cwd: repo });
1012
- const overlay = projectConfigPath(repo);
1013
- fs.unlinkSync(overlay);
1014
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1015
- const current = fs.readFileSync(engineering, "utf8");
1016
- const oversized = current.replace(
1017
- /^project:\r?\n/m,
1018
- `project:\n oversized_legacy_value: ${JSON.stringify("x".repeat(140 * 1024))}\n`,
1019
- );
1020
- assert(oversized !== current, "oversized legacy migration fixture must modify managed frontmatter");
1021
- writeFile(engineering, oversized);
1022
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1023
- const manifest = path.join(repo, ".agents", "managed-install.json");
1024
- const before = {
1025
- engineering: fs.readFileSync(engineering),
1026
- skill: fs.readFileSync(skill),
1027
- manifest: fs.readFileSync(manifest),
1028
- };
1029
-
1030
- const failed = run("node", [cli, "init"], { cwd: repo, check: false });
1031
- const output = `${failed.stdout}\n${failed.stderr}`;
1032
- assert(failed.status !== 0 && output.includes("exceeds its size limit"), `oversized migrated overlay must fail before writes: ${output}`);
1033
- assert(!exists(overlay), "installer must not create an overlay that violates its own size contract");
1034
- assert(fs.readFileSync(engineering).equals(before.engineering), "oversized migration failure must preserve legacy ENGINEERING bytes");
1035
- assert(fs.readFileSync(skill).equals(before.skill), "oversized migration failure must not switch the installed Skill");
1036
- assert(fs.readFileSync(manifest).equals(before.manifest), "oversized migration failure must not replace the install manifest");
1037
- }
1038
-
1039
- function testInvalidProjectConfigOverlayFailsBeforeAnyWrites() {
1040
- const invalidCases = [
1041
- {
1042
- name: "null",
1043
- content: `${JSON.stringify({ schema: projectConfigSchema, overrides: { structure: { enabled: null } } }, null, 2)}\n`,
1044
- hints: ["null"],
1045
- },
1046
- {
1047
- name: "duplicate",
1048
- content: [
1049
- `schema: ${projectConfigSchema}`,
1050
- "overrides:",
1051
- " project:",
1052
- " name: duplicate-one",
1053
- " name: duplicate-two",
1054
- "",
1055
- ].join("\n"),
1056
- hints: ["duplicate"],
1057
- },
1058
- {
1059
- name: "alias",
1060
- content: [
1061
- `schema: ${projectConfigSchema}`,
1062
- "overrides:",
1063
- " project: &shared_project",
1064
- " name: alias-project",
1065
- " docs: *shared_project",
1066
- "",
1067
- ].join("\n"),
1068
- hints: ["alias", "anchor"],
1069
- },
1070
- ];
1071
- for (const invalid of invalidCases) {
1072
- const repo = tmpdir(`project-config-invalid-${invalid.name}`);
1073
- run("node", [cli, "init"], { cwd: repo });
1074
- const overlay = projectConfigPath(repo);
1075
- writeFile(overlay, invalid.content);
1076
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1077
- writeFile(skill, `must-stay-${invalid.name}\n`);
1078
- const engineeringBefore = fs.readFileSync(path.join(repo, "docs", "ENGINEERING.md"));
1079
- const result = run("node", [cli, "init"], { cwd: repo, check: false });
1080
- const output = `${result.stdout}\n${result.stderr}`.toLowerCase();
1081
- assert(result.status !== 0, `${invalid.name}: invalid project overlay must reject init`);
1082
- assert(invalid.hints.some(hint => output.includes(hint)), `${invalid.name}: failure must identify the unsafe YAML construct: ${output}`);
1083
- assert(fs.readFileSync(skill, "utf8") === `must-stay-${invalid.name}\n`, `${invalid.name}: overlay validation must happen before managed Skill writes`);
1084
- assert(fs.readFileSync(path.join(repo, "docs", "ENGINEERING.md")).equals(engineeringBefore), `${invalid.name}: overlay validation must happen before managed document writes`);
1085
- assert(fs.readFileSync(overlay, "utf8") === invalid.content, `${invalid.name}: rejected init must not rewrite the project overlay`);
1086
- }
1087
-
1088
- const batchFirst = tmpdir("project-config-invalid-batch-first");
1089
- const batchSecond = tmpdir("project-config-invalid-batch-second");
1090
- run("node", [cli, "init"], { cwd: batchFirst });
1091
- run("node", [cli, "init"], { cwd: batchSecond });
1092
- const firstSkill = path.join(batchFirst, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1093
- writeFile(firstSkill, "batch-must-stay\n");
1094
- writeFile(projectConfigPath(batchSecond), invalidCases[0].content);
1095
- const batch = run("node", [cli, "sync", "--projects", `${batchFirst},${batchSecond}`], { check: false });
1096
- assert(batch.status !== 0, "one invalid overlay must reject the complete multi-project sync batch");
1097
- assert(fs.readFileSync(firstSkill, "utf8") === "batch-must-stay\n", "multi-project overlay preflight must run before writing an earlier valid project");
1098
- assert(fs.readFileSync(projectConfigPath(batchSecond), "utf8") === invalidCases[0].content, "multi-project rejection must not rewrite the invalid overlay");
1099
-
1100
- if (process.platform !== "win32") {
1101
- const repo = tmpdir("project-config-invalid-symlink");
1102
- run("node", [cli, "init"], { cwd: repo });
1103
- const overlay = projectConfigPath(repo);
1104
- const external = path.join(tmpdir("project-config-external"), "outside.yaml");
1105
- const externalBytes = `${JSON.stringify({ schema: projectConfigSchema, overrides: { project: { name: "outside" } } }, null, 2)}\n`;
1106
- writeFile(external, externalBytes);
1107
- fs.unlinkSync(overlay);
1108
- fs.symlinkSync(external, overlay);
1109
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1110
- writeFile(skill, "must-stay-symlink\n");
1111
- const result = run("node", [cli, "sync", "--projects", repo], { check: false });
1112
- const output = `${result.stdout}\n${result.stderr}`.toLowerCase();
1113
- assert(result.status !== 0 && (output.includes("symlink") || output.includes("non-symlink")), "overlay symlink must reject sync before writes");
1114
- assert(fs.readFileSync(skill, "utf8") === "must-stay-symlink\n", "overlay symlink preflight must happen before managed Skill writes");
1115
- assert(fs.readFileSync(external, "utf8") === externalBytes, "overlay validation must never follow or rewrite a symlink target");
1116
- assert(fs.lstatSync(overlay).isSymbolicLink(), "rejected sync must leave the project-owned symlink untouched");
1117
- }
1118
- }
1119
-
1120
- function testStatusRejectsManagedAgentSymlinksWithoutLeakingExternalContent() {
1121
- if (process.platform === "win32") return;
1122
- for (const target of ["agents-directory", "agents-parent"]) {
1123
- const repo = tmpdir(`status-agent-symlink-${target}`);
1124
- const secret = `UNIQUE_STATUS_AGENT_SYMLINK_SECRET_${target}_7f42`;
1125
- run("node", [cli, "init"], { cwd: repo });
1126
- fillRequiredAccess(repo);
1127
- const agentsRoot = path.join(repo, ".agents");
1128
- const agentsDir = path.join(agentsRoot, "agents");
1129
-
1130
- if (target === "agents-directory") {
1131
- const external = path.join(tmpdir("status-external-agents-directory"), "agents");
1132
- fs.mkdirSync(external);
1133
- writeFile(path.join(external, "explorer.toml"), `description = ${JSON.stringify(secret)}\n`);
1134
- fs.rmSync(agentsDir, { recursive: true });
1135
- fs.symlinkSync(external, agentsDir);
1136
- } else {
1137
- const external = path.join(tmpdir("status-external-agents-parent"), "agents-root");
1138
- fs.renameSync(agentsRoot, external);
1139
- fs.appendFileSync(path.join(external, "agents", "explorer.toml"), `\n# ${secret}\n`);
1140
- fs.symlinkSync(external, agentsRoot);
1141
- }
1142
-
1143
- const status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
1144
- const output = `${status.stdout}\n${status.stderr}`;
1145
- assert(status.status !== 0, `${target}: status must reject a managed-agent path that escapes through a symlink`);
1146
- assert(!output.includes(secret), `${target}: status must never echo content read from the external symlink target: ${output}`);
1147
- assert(/symlink|junction|real directory|non-directory/i.test(output), `${target}: status must explain the unsafe managed target shape: ${output}`);
1148
- }
1149
- }
1150
-
1151
- function testMultiProjectSyncRejectsManagedTargetSymlinksBeforeAnyProjectWrite() {
1152
- if (process.platform === "win32") return;
1153
- for (const target of ["parent", "leaf"]) {
1154
- const first = tmpdir(`managed-target-batch-first-${target}`);
1155
- const second = tmpdir(`managed-target-batch-second-${target}`);
1156
- run("node", [cli, "init"], { cwd: first });
1157
- run("node", [cli, "init"], { cwd: second });
1158
-
1159
- const firstProtected = [
1160
- path.join(first, ".agents", "skills", "auto-coding-skill", "SKILL.md"),
1161
- path.join(first, ".agents", "managed-install.json"),
1162
- path.join(first, ".agents", "agents", "explorer.toml"),
1163
- path.join(first, "docs", "ENGINEERING.md"),
1164
- ];
1165
- writeFile(firstProtected[0], `first-project-zero-write-sentinel-${target}\n`);
1166
- const before = new Map(firstProtected.map(file => [file, fs.readFileSync(file)]));
1167
- const secret = `UNIQUE_BATCH_MANAGED_TARGET_SECRET_${target}_98d1`;
1168
- const external = path.join(tmpdir(`managed-target-external-${target}`), "target");
1169
- let linked;
1170
- let externalFile;
1171
- if (target === "parent") {
1172
- fs.mkdirSync(external);
1173
- externalFile = path.join(external, "explorer.toml");
1174
- writeFile(externalFile, `description = ${JSON.stringify(secret)}\n`);
1175
- linked = path.join(second, ".agents", "agents");
1176
- fs.rmSync(linked, { recursive: true });
1177
- fs.symlinkSync(external, linked);
1178
- } else {
1179
- externalFile = external;
1180
- writeFile(external, `description = ${JSON.stringify(secret)}\n`);
1181
- linked = path.join(second, ".agents", "agents", "explorer.toml");
1182
- fs.unlinkSync(linked);
1183
- fs.symlinkSync(external, linked);
1184
- }
1185
-
1186
- const sync = run("node", [cli, "sync", "--projects", `${first},${second}`], { check: false });
1187
- const output = `${sync.stdout}\n${sync.stderr}`;
1188
- assert(sync.status !== 0, `${target}: one unsafe managed target must reject multi-project sync`);
1189
- assert(/symlink|junction|non-directory/i.test(output), `${target}: batch rejection must identify the unsafe target shape: ${output}`);
1190
- assert(!output.includes(secret), `${target}: batch rejection must not echo the external managed-target content: ${output}`);
1191
- for (const file of firstProtected) {
1192
- assert(fs.readFileSync(file).equals(before.get(file)), `${target}: second-project preflight failure must leave first project untouched: ${path.relative(first, file)}`);
1193
- }
1194
- assert(fs.lstatSync(linked).isSymbolicLink(), `${target}: rejected batch must leave the unsafe second-project link untouched`);
1195
- assert(fs.readFileSync(externalFile, "utf8").includes(secret), `${target}: rejected batch must leave the external target untouched`);
1196
- }
1197
- }
1198
-
1199
- function testTamperedInstalledDefaultRejectsInitAndSyncWithoutWrites() {
1200
- const repo = tmpdir("project-config-tampered-old-default");
1201
- run("node", [cli, "init"], { cwd: repo });
1202
- const overlay = projectConfigPath(repo);
1203
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1204
- const installedTemplate = path.join(
1205
- repo,
1206
- ".agents",
1207
- "skills",
1208
- "auto-coding-skill",
1209
- "data",
1210
- "templates",
1211
- "ENGINEERING.md",
1212
- );
1213
- const manifest = path.join(repo, ".agents", "managed-install.json");
1214
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1215
- const oldDefault = fs.readFileSync(engineering, "utf8")
1216
- .replace(/^ skill_version:.*$/m, ' skill_version: "4.2.7"')
1217
- .replace("managed-workflow:start version=4.3.7", "managed-workflow:start version=4.2.7");
1218
- installTrustedEngineeringDefault(repo, oldDefault, "4.2.7");
1219
- writeFile(engineering, oldDefault);
1220
- fs.unlinkSync(overlay);
1221
- fillLegacyEngineeringAccess(repo, "tampered-old-default-secret");
1222
- fs.appendFileSync(installedTemplate, "\n# untrusted template mutation\n");
1223
- writeFile(skill, "tampered-template-zero-write-sentinel\n");
1224
-
1225
- const protectedPaths = [engineering, installedTemplate, manifest, skill];
1226
- for (const args of [["init"], ["sync", "--projects", repo]]) {
1227
- const before = new Map(protectedPaths.map(file => [file, fs.readFileSync(file)]));
1228
- const result = run("node", [cli, ...args], { cwd: repo, check: false });
1229
- const output = `${result.stdout}\n${result.stderr}`;
1230
- assert(result.status !== 0, `${args[0]} must reject a tampered installed old default`);
1231
- assert(output.includes("managed manifest identity check"), `${args[0]} must identify the untrusted installed template: ${output}`);
1232
- for (const file of protectedPaths) {
1233
- assert(fs.readFileSync(file).equals(before.get(file)), `${args[0]} must perform zero writes before rejecting ${path.relative(repo, file)}`);
1234
- }
1235
- assert(!exists(overlay), `${args[0]} must not create an overlay from an untrusted installed default`);
1236
- }
1237
- }
1238
-
1239
- function testExistingOverlayConflictRejectsInitAndSyncWithoutWrites() {
1240
- const repo = tmpdir("project-config-existing-conflict");
1241
- run("node", [cli, "init"], { cwd: repo });
1242
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1243
- const overlay = projectConfigPath(repo);
1244
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1245
- const conflicting = fs.readFileSync(engineering, "utf8")
1246
- .replace(/^ name:.*$/m, ' name: "legacy-conflicting-name"');
1247
- writeFile(engineering, conflicting);
1248
- writeFile(skill, "overlay-conflict-zero-write-sentinel\n");
1249
-
1250
- const protectedPaths = [engineering, overlay, skill, path.join(repo, ".agents", "managed-install.json")];
1251
- for (const args of [["init"], ["sync", "--projects", repo]]) {
1252
- const before = new Map(protectedPaths.map(file => [file, fs.readFileSync(file)]));
1253
- const result = run("node", [cli, ...args], { cwd: repo, check: false });
1254
- const output = `${result.stdout}\n${result.stderr}`;
1255
- assert(result.status !== 0, `${args[0]} must reject legacy values that conflict with an existing overlay`);
1256
- assert(output.includes("overlay conflicts with legacy project configuration"), `${args[0]} must explain the conflicting ownership boundary: ${output}`);
1257
- for (const file of protectedPaths) {
1258
- assert(fs.readFileSync(file).equals(before.get(file)), `${args[0]} must perform zero writes before rejecting ${path.relative(repo, file)}`);
1259
- }
1260
- }
1261
- }
1262
-
1263
- function testExistingOverlayLegacyDeletionRejectsInitAndSyncWithoutWrites() {
1264
- const repo = tmpdir("project-config-existing-deletion");
1265
- run("node", [cli, "init"], { cwd: repo });
1266
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1267
- const overlay = projectConfigPath(repo);
1268
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
1269
- const current = fs.readFileSync(engineering, "utf8");
1270
- const deletedDefault = current.replace(/^ api_change_log: "docs\/interfaces\/api-change-log\.md"\r?\n/m, "");
1271
- assert(deletedDefault !== current, "legacy deletion fixture must remove one managed default key");
1272
- writeFile(engineering, deletedDefault);
1273
- writeFile(skill, "legacy-deletion-zero-write-sentinel\n");
1274
-
1275
- const protectedPaths = [engineering, overlay, skill, path.join(repo, ".agents", "managed-install.json")];
1276
- for (const args of [["init"], ["sync", "--projects", repo]]) {
1277
- const before = new Map(protectedPaths.map(file => [file, fs.readFileSync(file)]));
1278
- const result = run("node", [cli, ...args], { cwd: repo, check: false });
1279
- const output = `${result.stdout}\n${result.stderr}`;
1280
- assert(result.status !== 0, `${args[0]} must reject a legacy deletion that additive overrides cannot represent`);
1281
- assert(output.includes("cannot be represented as additive overrides"), `${args[0]} must explain the deleted-default ambiguity: ${output}`);
1282
- for (const file of protectedPaths) {
1283
- assert(fs.readFileSync(file).equals(before.get(file)), `${args[0]} must perform zero writes before rejecting ${path.relative(repo, file)}`);
1284
- }
1285
- }
1286
- }
1287
-
1288
- function testLiveInstallTransactionRejectsSecondInstallerWithoutWrites() {
1289
- const repo = tmpdir("live-install-owner");
1290
- run("node", [cli, "init"], { cwd: repo });
1291
- const installedAp = path.join(repo, ".agents", "skills", "auto-coding-skill", "scripts", "ap.py");
1292
- writeFile(installedAp, "live-owner-sentinel\n");
1293
-
1294
- const first = spawn(
1295
- process.execPath,
1296
- [cli, "sync", "--projects", repo],
1297
- {
1298
- cwd: repo,
1299
- env: {
1300
- ...process.env,
1301
- AUTOCODING_TEST_HOLD_PHASE: "after-stage-copy",
1302
- AUTOCODING_TEST_HOLD_MILLISECONDS: "5000",
1303
- },
1304
- stdio: "ignore",
1305
- },
1306
- );
1307
- const transaction = path.join(repo, ".agents", ".auto-coding-skill-install-transaction");
1308
- const statePath = path.join(transaction, "state.json");
1309
- const sleep = new Int32Array(new SharedArrayBuffer(4));
1310
- const stagedDeadline = Date.now() + 10000;
1311
- while (!exists(statePath) && Date.now() < stagedDeadline) Atomics.wait(sleep, 0, 0, 5);
1312
- assert(exists(statePath), "first installer must publish a durable state before the concurrency check");
1313
- const owner = JSON.parse(fs.readFileSync(path.join(transaction, "owner.json"), "utf8"));
1314
- assert(owner.pid === first.pid, "transaction owner lease must bind the live installer pid");
1315
-
1316
- const protectedPaths = [
1317
- installedAp,
1318
- path.join(repo, ".agents", "managed-install.json"),
1319
- path.join(repo, "docs", "ENGINEERING.md"),
1320
- projectConfigPath(repo),
1321
- ];
1322
- const beforeSecond = new Map(protectedPaths.map(file => [file, fs.readFileSync(file)]));
1323
- const second = run("node", [cli, "sync", "--projects", repo], { cwd: repo, check: false });
1324
- const secondOutput = `${second.stdout}\n${second.stderr}`;
1325
- assert(second.status !== 0, "a second installer must reject a live install transaction");
1326
- assert(secondOutput.includes("install transaction is active under owner pid"), `live-owner rejection must be explicit: ${secondOutput}`);
1327
- assert(exists(transaction), "second installer must not remove the live transaction");
1328
- for (const file of protectedPaths) {
1329
- assert(fs.readFileSync(file).equals(beforeSecond.get(file)), `second installer must perform zero canonical writes: ${path.relative(repo, file)}`);
1330
- }
1331
-
1332
- const waitForCompletion = [
1333
- "const fs = require('node:fs');",
1334
- "const target = process.argv[1];",
1335
- "const sleep = new Int32Array(new SharedArrayBuffer(4));",
1336
- "const deadline = Date.now() + 15000;",
1337
- "while (fs.existsSync(target) && Date.now() < deadline) Atomics.wait(sleep, 0, 0, 10);",
1338
- "process.exit(fs.existsSync(target) ? 2 : 0);",
1339
- ].join("\n");
1340
- const completed = run(process.execPath, ["-e", waitForCompletion, transaction], { check: false });
1341
- first.kill();
1342
- assert(completed.status === 0, "live owner must finish normally after the rejected second installer");
1343
- assert(!fs.readFileSync(installedAp, "utf8").includes("live-owner-sentinel"), "the live owner must retain control and finish its own upgrade");
1344
- }
1345
-
1346
- function testStagedRuntimeTamperingIsRejectedBeforeExecution() {
1347
- const repo = tmpdir("staged-runtime-tamper");
1348
- run("node", [cli, "init"], { cwd: repo });
1349
-
1350
- // Keep beginInstallTransaction busy after it has hashed new-skill. The
1351
- // watcher uses old-skill creation as the deterministic signal that this
1352
- // binding has already happened, then changes the staged runtime.
1353
- const installedSkill = path.join(repo, ".agents", "skills", "auto-coding-skill");
1354
- fs.writeFileSync(path.join(installedSkill, "zzzz-staging-delay.bin"), Buffer.alloc(32 * 1024 * 1024, 0x61));
1355
- const installedAp = path.join(installedSkill, "scripts", "ap.py");
1356
- const installedBefore = fs.readFileSync(installedAp);
1357
- const transaction = path.join(repo, ".agents", ".auto-coding-skill-install-transaction");
1358
- const oldSkill = path.join(transaction, "old-skill");
1359
- const stagedAp = path.join(transaction, "new-skill", "scripts", "ap.py");
1360
- const ready = path.join(repo, "attacker-ready");
1361
- const tampered = path.join(repo, "staged-runtime-tampered");
1362
- const executed = path.join(repo, "tampered-runtime-executed");
1363
- const malicious = [
1364
- "from pathlib import Path",
1365
- `Path(${JSON.stringify(executed)}).write_text('executed', encoding='utf-8')`,
1366
- "print('{}')",
1367
- "",
1368
- ].join("\n");
1369
- const watcher = [
1370
- "const fs = require('node:fs');",
1371
- "const [oldSkill, stagedAp, ready, tampered, malicious] = process.argv.slice(1);",
1372
- "fs.writeFileSync(ready, 'ready');",
1373
- "const deadline = Date.now() + 15000;",
1374
- "const sleep = new Int32Array(new SharedArrayBuffer(4));",
1375
- "while (Date.now() < deadline) {",
1376
- " if (fs.existsSync(oldSkill) && fs.existsSync(stagedAp)) {",
1377
- " fs.writeFileSync(stagedAp, Buffer.from(malicious, 'base64'));",
1378
- " fs.writeFileSync(tampered, 'tampered');",
1379
- " process.exit(0);",
1380
- " }",
1381
- " Atomics.wait(sleep, 0, 0, 1);",
1382
- "}",
1383
- "process.exit(3);",
1384
- ].join("\n");
1385
- const attacker = spawn(
1386
- process.execPath,
1387
- ["-e", watcher, oldSkill, stagedAp, ready, tampered, Buffer.from(malicious).toString("base64")],
1388
- { stdio: "ignore" },
1389
- );
1390
- const sleep = new Int32Array(new SharedArrayBuffer(4));
1391
- const readyDeadline = Date.now() + 5000;
1392
- while (!exists(ready) && Date.now() < readyDeadline) Atomics.wait(sleep, 0, 0, 5);
1393
- assert(exists(ready), "staged-runtime tamper watcher must start before sync");
1394
-
1395
- const result = run("node", [cli, "sync", "--projects", repo], { cwd: repo, check: false });
1396
- attacker.kill();
1397
- const output = `${result.stdout}\n${result.stderr}`;
1398
- assert(exists(tampered), `test watcher must alter the staged runtime: ${output}`);
1399
- assert(result.status !== 0, "transaction must reject a staged runtime changed after its binding hash");
1400
- assert(output.includes("staged Skill failed its transaction identity check"), `tamper failure must identify the staged Skill binding: ${output}`);
1401
- assert(!exists(executed), "tampered staged ap.py must never execute");
1402
- assert(fs.readFileSync(installedAp).equals(installedBefore), "pre-switch tamper rejection must leave the installed runtime unchanged");
1403
- assert(exists(path.join(transaction, "state.json")), "tamper rejection must retain the verified rollback transaction");
1404
- }
1405
-
1406
- function testInterruptedStagedInstallRecoversForInitAndSync() {
1407
- const cases = [
1408
- {
1409
- name: "init-after-config-finalize",
1410
- phase: "after-config-finalize",
1411
- args() { return ["init"]; },
1412
- },
1413
- {
1414
- name: "sync-after-runtime-switch",
1415
- phase: "after-runtime-switch",
1416
- args(repo) { return ["sync", "--projects", repo]; },
1417
- },
1418
- ];
1419
-
1420
- for (const interrupted of cases) {
1421
- const repo = tmpdir(`staged-recovery-${interrupted.name}`);
1422
- const projectName = `specialized-${interrupted.name}`;
1423
- const projectStack = `stack-${interrupted.name}`;
1424
- const secret = `secret-${interrupted.name}`;
1425
- run("node", [cli, "init"], { cwd: repo });
1426
-
1427
- // Exercise the migration/finalize boundary: prepare must first extract
1428
- // these project-owned values from a legacy managed document into a new
1429
- // overlay, and recovery must never normalize or lose that overlay.
1430
- fs.unlinkSync(projectConfigPath(repo));
1431
- fillLegacyEngineeringAccess(repo, secret);
1432
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1433
- const specialized = fs.readFileSync(engineering, "utf8")
1434
- .replace(/^ name:.*$/m, ` name: ${JSON.stringify(projectName)}`)
1435
- .replace(/^ stack:.*$/m, ` stack: ${JSON.stringify(projectStack)}`)
1436
- .replace(/^ target_branch:.*$/m, ' target_branch: "dev"')
1437
- .replace(/^ api_docs_required: false$/m, " api_docs_required: true");
1438
- writeFile(engineering, specialized);
1439
-
1440
- const args = interrupted.args(repo);
1441
- const failed = run("node", [cli, ...args], {
1442
- cwd: repo,
1443
- check: false,
1444
- env: { AUTOCODING_TEST_FAIL_PHASE: interrupted.phase },
1445
- });
1446
- const failedOutput = `${failed.stdout}\n${failed.stderr}`;
1447
- assert(failed.status !== 0, `${interrupted.name}: injected staged install must fail`);
1448
- assert(failedOutput.includes(`injected auto-coding-skill install fault: ${interrupted.phase}`), `${interrupted.name}: failure must identify the injected phase: ${failedOutput}`);
1449
-
1450
- const transaction = path.join(repo, ".agents", ".auto-coding-skill-install-transaction");
1451
- assert(exists(transaction), `${interrupted.name}: interrupted install must retain its recovery transaction`);
1452
- const overlay = projectConfigPath(repo);
1453
- assert(exists(overlay), `${interrupted.name}: prepare must durably create the project overlay before runtime switching`);
1454
- const overlayAfterFailure = fs.readFileSync(overlay);
1455
- const migrated = readYamlConfig(overlay).overrides;
1456
- assert(migrated.project?.name === projectName && migrated.project?.stack === projectStack, `${interrupted.name}: interrupted prepare must preserve specialized project values`);
1457
- assert(migrated.access?.project?.frontend?.password === secret, `${interrupted.name}: interrupted prepare must preserve specialized access values`);
1458
-
1459
- run("node", [cli, ...args], { cwd: repo });
1460
- assert(fs.readFileSync(overlay).equals(overlayAfterFailure), `${interrupted.name}: retry recovery must preserve overlay bytes exactly`);
1461
- const effective = readEffectiveConfig(repo);
1462
- assert(effective.project?.name === projectName && effective.project?.stack === projectStack, `${interrupted.name}: recovered effective config must retain specialized project identity`);
1463
- assert(effective.concurrency?.target_branch === "dev", `${interrupted.name}: recovered effective config must retain the specialized target branch`);
1464
- assert(effective.access?.project?.frontend?.password === secret, `${interrupted.name}: recovered effective config must retain specialized access values`);
1465
- assert(effective.docs?.api_docs_required === true, `${interrupted.name}: recovered effective config must retain specialized documentation policy`);
1466
- assert(!exists(transaction), `${interrupted.name}: successful retry must remove the active install transaction`);
1467
- const transactionArtifacts = fs.readdirSync(path.join(repo, ".agents"))
1468
- .filter(name => name.startsWith(".auto-coding-skill-install-"));
1469
- assert(transactionArtifacts.length === 0, `${interrupted.name}: successful retry must clean every install transaction artifact: ${transactionArtifacts.join(", ")}`);
1470
-
1471
- const status = run("node", [cli, "status", "--projects", repo, "--json"]);
1472
- assert(JSON.parse(status.stdout).results[0].ok === true, `${interrupted.name}: recovered installation must be complete and healthy: ${status.stdout}`);
1473
- assert(fs.readFileSync(overlay).equals(overlayAfterFailure), `${interrupted.name}: read-only status must leave overlay bytes stable`);
1474
- }
1475
- }
1476
-
1477
- function testArchiveFallbackCollisionsNeverLosePreviousContent() {
1478
- const digest12 = payload => crypto.createHash("sha256").update(payload).digest("hex").slice(0, 12);
1479
- const assertUnchanged = (file, expected, label) => {
1480
- assert(fs.readFileSync(file).equals(expected), `${label}: occupied archive bytes must not be overwritten`);
1481
- };
1482
- const assertPreservedAnywhere = (repo, expected, label) => {
1483
- assert(
1484
- listProjectFiles(repo).some(file => fs.readFileSync(file).equals(expected)),
1485
- `${label}: occupied archive bytes must remain available somewhere in project history`,
1486
- );
1487
- };
1488
- const assertArchived = (directory, expected, label, suffix = false) => {
1489
- const archived = listProjectFiles(directory).some(file => {
1490
- const payload = fs.readFileSync(file);
1491
- if (!suffix) return payload.equals(expected);
1492
- return payload.length >= expected.length
1493
- && payload.subarray(payload.length - expected.length).equals(expected);
1494
- });
1495
- assert(archived, `${label}: previous content must survive default and digest archive collisions`);
1496
- };
1497
-
1498
- {
1499
- const repo = tmpdir("archive-collision-engineering");
1500
- run("node", [cli, "init"], { cwd: repo });
1501
- fs.unlinkSync(projectConfigPath(repo));
1502
- fillLegacyEngineeringAccess(repo, "archive-collision-secret");
1503
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
1504
- fs.appendFileSync(engineering, "\n## Archive collision sentinel\n\nPreserve these ENGINEERING bytes.\n");
1505
- const previous = fs.readFileSync(engineering);
1506
- const archiveDir = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs");
1507
- const preferred = path.join(archiveDir, "ENGINEERING.md");
1508
- const legacyDigest = path.join(archiveDir, `ENGINEERING-${digest12(previous)}.md`);
1509
- const occupiedPreferred = Buffer.from("occupied-engineering-default\n");
1510
- const occupiedDigest = Buffer.from("occupied-engineering-digest\n");
1511
- writeFile(preferred, occupiedPreferred);
1512
- writeFile(legacyDigest, occupiedDigest);
1513
-
1514
- run("node", [cli, "init"], { cwd: repo });
1515
-
1516
- assertUnchanged(preferred, occupiedPreferred, "ENGINEERING default collision");
1517
- assertUnchanged(legacyDigest, occupiedDigest, "ENGINEERING digest collision");
1518
- assertArchived(archiveDir, previous, "ENGINEERING migration", true);
1519
- assert(
1520
- readEffectiveConfig(repo).access?.project?.frontend?.password === "archive-collision-secret",
1521
- "ENGINEERING archive fallback must not disrupt project configuration migration",
1522
- );
1523
- }
1524
-
1525
- {
1526
- const repo = tmpdir("archive-collision-managed-template");
1527
- run("node", [cli, "init"], { cwd: repo });
1528
- const managed = path.join(repo, "docs", "design", "_TEMPLATE-DD.md");
1529
- const previous = Buffer.from("# Project-specific design template\n\nPreserve these exact bytes.\n");
1530
- fs.writeFileSync(managed, previous);
1531
- const archiveDir = path.join(
1532
- repo,
1533
- ".agents",
1534
- "archive",
1535
- "auto-coding-skill",
1536
- "4.3.7",
1537
- "docs",
1538
- "design",
1539
- );
1540
- const preferred = path.join(archiveDir, "_TEMPLATE-DD.md");
1541
- const legacyDigest = path.join(archiveDir, `_TEMPLATE-DD-${digest12(previous)}.md`);
1542
- const occupiedPreferred = Buffer.from("occupied-template-default\n");
1543
- const occupiedDigest = Buffer.from("occupied-template-digest\n");
1544
- writeFile(preferred, occupiedPreferred);
1545
- writeFile(legacyDigest, occupiedDigest);
1546
-
1547
- run("node", [cli, "init"], { cwd: repo });
1548
-
1549
- assertUnchanged(preferred, occupiedPreferred, "managed template default collision");
1550
- assertUnchanged(legacyDigest, occupiedDigest, "managed template digest collision");
1551
- assertArchived(archiveDir, previous, "managed template migration");
1552
- assert(!fs.readFileSync(managed).equals(previous), "managed template must still converge after safe archival");
1553
- }
1554
-
1555
- {
1556
- const repo = tmpdir("archive-collision-agents-sync");
1557
- run("node", [cli, "init"], { cwd: repo });
1558
- const agents = path.join(repo, "AGENTS.md");
1559
- const previous = Buffer.from("# Project AGENTS before sync\n\nPreserve this sync history.\n");
1560
- fs.writeFileSync(agents, previous);
1561
- const archiveDir = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7");
1562
- const preferred = path.join(archiveDir, "AGENTS.md");
1563
- const legacyDigest = path.join(archiveDir, `AGENTS-${digest12(previous)}.md`);
1564
- const occupiedPreferred = Buffer.from("occupied-sync-default\n");
1565
- const occupiedDigest = Buffer.from("occupied-sync-digest\n");
1566
- writeFile(preferred, occupiedPreferred);
1567
- writeFile(legacyDigest, occupiedDigest);
1568
-
1569
- run("node", [cli, "sync", "--projects", repo]);
1570
-
1571
- assertPreservedAnywhere(repo, occupiedPreferred, "sync AGENTS default collision");
1572
- assertPreservedAnywhere(repo, occupiedDigest, "sync AGENTS digest collision");
1573
- assertArchived(archiveDir, previous, "sync AGENTS migration", true);
1574
- assert(!fs.readFileSync(agents).equals(previous), "sync AGENTS must still converge after safe archival");
1575
- }
1576
-
1577
- {
1578
- const repo = tmpdir("archive-collision-agents-init");
1579
- run("node", [cli, "init"], { cwd: repo });
1580
- const agents = path.join(repo, "AGENTS.md");
1581
- const previous = Buffer.from("# Project AGENTS before init\n\nPreserve this init history.\n");
1582
- fs.writeFileSync(agents, previous);
1583
- const archiveDir = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7");
1584
- const preferred = path.join(archiveDir, "AGENTS.md");
1585
- const legacyDigest = path.join(archiveDir, `AGENTS-${digest12(previous)}.md`);
1586
- const occupiedPreferred = Buffer.from("occupied-init-default\n");
1587
- const occupiedDigest = Buffer.from("occupied-init-digest\n");
1588
- writeFile(preferred, occupiedPreferred);
1589
- writeFile(legacyDigest, occupiedDigest);
1590
-
1591
- run("node", [cli, "init"], { cwd: repo });
1592
-
1593
- assertUnchanged(preferred, occupiedPreferred, "init AGENTS default collision");
1594
- assertUnchanged(legacyDigest, occupiedDigest, "init AGENTS digest collision");
1595
- assertArchived(archiveDir, previous, "init AGENTS migration");
1596
- assert(!fs.readFileSync(agents).equals(previous), "init AGENTS must still converge after safe archival");
1597
- }
1598
- }
1599
-
1600
- function testProjectMutationAndInstallSwitchRejectParentSwap() {
1601
- if (process.platform === "win32") return;
1602
-
1603
- const assertExternalUntouched = (external, sentinel, label) => {
1604
- const files = listProjectFiles(external);
1605
- assert(files.length === 1 && files[0] === sentinel, `${label}: project mutation must not create external files`);
1606
- assert(fs.readFileSync(sentinel, "utf8") === "external-sentinel\n", `${label}: external sentinel must remain unchanged`);
1607
- };
1608
- const restoreParent = (target, backup) => {
1609
- assert(fs.lstatSync(target).isSymbolicLink(), `swap fixture must leave a symlink at ${target}`);
1610
- fs.unlinkSync(target);
1611
- fs.renameSync(backup, target);
1612
- };
1613
-
1614
- {
1615
- const repo = tmpdir("project-file-parent-swap");
1616
- run("node", [cli, "init"], { cwd: repo });
1617
- const external = tmpdir("project-file-parent-swap-external");
1618
- const sentinel = path.join(external, "sentinel.txt");
1619
- writeFile(sentinel, "external-sentinel\n");
1620
- const parent = path.join(repo, ".agents", "agents");
1621
- const backup = path.join(repo, ".agents", "agents.autocoding-test-backup");
1622
- const failed = run("node", [cli, "init"], {
1623
- cwd: repo,
1624
- check: false,
1625
- env: {
1626
- AUTOCODING_TEST_MODE: "1",
1627
- AUTOCODING_TEST_PROJECT_FILE_SWAP_PATH: ".agents/agents/browser-debugger.toml",
1628
- AUTOCODING_TEST_PROJECT_FILE_SWAP_EXTERNAL: external,
1629
- AUTOCODING_TEST_PROJECT_FILE_SWAP_BACKUP: backup,
1630
- },
1631
- });
1632
- const output = `${failed.stdout}\n${failed.stderr}`;
1633
- assert(failed.status !== 0 && output.includes("Project path parent changed"), `project file parent swap must fail closed: ${output}`);
1634
- assertExternalUntouched(external, sentinel, "project file parent swap");
1635
- restoreParent(parent, backup);
1636
- run("node", [cli, "init"], { cwd: repo });
1637
- assertExternalUntouched(external, sentinel, "project file parent swap recovery");
1638
- }
1639
-
1640
- {
1641
- const repo = tmpdir("install-switch-parent-swap");
1642
- run("node", [cli, "init"], { cwd: repo });
1643
- const external = tmpdir("install-switch-parent-swap-external");
1644
- const sentinel = path.join(external, "sentinel.txt");
1645
- writeFile(sentinel, "external-sentinel\n");
1646
- const parent = path.join(repo, ".agents", "skills");
1647
- const backup = path.join(repo, ".agents", "skills.autocoding-test-backup");
1648
- const failed = run("node", [cli, "init"], {
1649
- cwd: repo,
1650
- check: false,
1651
- env: {
1652
- AUTOCODING_TEST_MODE: "1",
1653
- AUTOCODING_TEST_INSTALL_IO_SWAP_PHASE: "switch",
1654
- AUTOCODING_TEST_INSTALL_IO_SWAP_PARENT: ".agents/skills",
1655
- AUTOCODING_TEST_INSTALL_IO_SWAP_EXTERNAL: external,
1656
- AUTOCODING_TEST_INSTALL_IO_SWAP_BACKUP: backup,
1657
- },
1658
- });
1659
- const output = `${failed.stdout}\n${failed.stderr}`;
1660
- assert(failed.status !== 0 && output.includes("Install I/O project parent changed"), `install switch parent swap must fail closed: ${output}`);
1661
- assertExternalUntouched(external, sentinel, "install switch parent swap");
1662
- restoreParent(parent, backup);
1663
- run("node", [cli, "init"], { cwd: repo });
1664
- assertExternalUntouched(external, sentinel, "install switch parent swap recovery");
1665
- }
1666
- }
1667
-
1668
- function testNoChangeLightGateRejectsInvalidEffectiveContracts() {
1669
- const cases = [
1670
- {
1671
- name: "risk-rules",
1672
- mutate(overrides) {
1673
- overrides.risk = { rules: { invalid: true } };
1674
- },
1675
- hints: ["risk.rules", "must be a list"],
1676
- },
1677
- {
1678
- name: "validation-route",
1679
- mutate(overrides) {
1680
- overrides.validation = {
1681
- ...(overrides.validation ?? {}),
1682
- routes: [{ name: "invalid-empty-command-route", paths: ["**"], commands: [] }],
1683
- };
1684
- },
1685
- hints: ["validation.routes[0].commands", "must not be empty"],
1686
- },
1687
- {
1688
- name: "validation-budget",
1689
- mutate(overrides) {
1690
- overrides.validation = {
1691
- ...(overrides.validation ?? {}),
1692
- max_command_seconds: 181,
1693
- max_total_seconds: 180,
1694
- };
1695
- },
1696
- hints: ["max_command_seconds", "max_total_seconds"],
1697
- },
1698
- ];
1699
-
1700
- for (const invalid of cases) {
1701
- const repo = tmpdir(`no-change-light-gate-${invalid.name}`);
1702
- run("node", [cli, "init"], { cwd: repo });
1703
- fillRequiredAccess(repo);
1704
- const overrides = readYamlConfig(projectConfigPath(repo)).overrides;
1705
- invalid.mutate(overrides);
1706
- writeProjectConfig(repo, overrides);
1707
- run("git", ["init", "-q"], { cwd: repo });
1708
- run("git", ["config", "user.email", "test@example.com"], { cwd: repo });
1709
- run("git", ["config", "user.name", "Auto Coding Test"], { cwd: repo });
1710
- run("git", ["add", "-A"], { cwd: repo });
1711
- run("git", ["commit", "-qm", "invalid contract baseline"], { cwd: repo });
1712
- assert(run("git", ["status", "--porcelain"], { cwd: repo }).stdout === "", `${invalid.name}: fixture must have no changed files`);
1713
-
1714
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
1715
- if (invalid.name === "risk-rules") {
1716
- const classify = run("python3", [
1717
- launcher,
1718
- "--repo", repo,
1719
- "classify",
1720
- "--planned-path", "sensitive/example.txt",
1721
- "--json",
1722
- ], { cwd: repo, check: false });
1723
- const classifyOutput = `${classify.stdout}\n${classify.stderr}`;
1724
- assert(classify.status !== 0, "malformed risk.rules must fail classify instead of downgrading a sensitive path");
1725
- assert(classifyOutput.includes("risk.rules must be a list"), `classify must identify malformed risk.rules: ${classifyOutput}`);
1726
-
1727
- const taskStart = run("python3", [
1728
- launcher,
1729
- "--repo", repo,
1730
- "task-start", "INVALID-RISK-CONTRACT",
1731
- "--owned-path", "sensitive/example.txt",
1732
- "--force-lifecycle",
1733
- ], { cwd: repo, check: false });
1734
- const taskOutput = `${taskStart.stdout}\n${taskStart.stderr}`;
1735
- assert(taskStart.status !== 0, "malformed risk.rules must fail task-start before isolation/review decisions");
1736
- assert(taskOutput.includes("risk.rules must be a list"), `task-start must identify malformed risk.rules: ${taskOutput}`);
1737
- }
1738
- const gate = run("python3", [launcher, "--repo", repo, "light-gate", "--scope", "changed"], { cwd: repo, check: false });
1739
- const output = `${gate.stdout}\n${gate.stderr}`;
1740
- assert(gate.status !== 0, `${invalid.name}: an invalid effective contract must fail light-gate even with no changed files`);
1741
- for (const hint of invalid.hints) {
1742
- assert(output.includes(hint), `${invalid.name}: light-gate must report ${hint}: ${output}`);
1743
- }
1744
- }
1745
- }
1746
-
1747
- function testStatusRejectsInvalidStructureEnforcementFromDoctorContract() {
1748
- const repo = tmpdir("invalid-structure-enforcement-status");
1749
- run("node", [cli, "init"], { cwd: repo });
1750
- fillRequiredAccess(repo);
1751
- const overrides = readYamlConfig(projectConfigPath(repo)).overrides;
1752
- writeProjectConfig(repo, {
1753
- ...overrides,
1754
- structure: { ...(overrides.structure ?? {}), enforcement: "strict-but-unknown" },
1755
- });
1756
-
1757
- const status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
1758
- assert(status.status !== 0, "status must reject an invalid structure enforcement value");
1759
- const parsed = JSON.parse(status.stdout).results[0];
1760
- assert(
1761
- parsed.invalidConfigTokens.includes("structure.enforcement must be advisory or blocking"),
1762
- `status must expose the structure issue from the complete doctor contract: ${status.stdout}`,
1763
- );
1764
- }
1765
-
1766
- function testProjectConfigOverlayIsHighRiskAndReviewRequired() {
1767
- const repo = tmpdir("project-config-classification");
1768
- run("git", ["init", "-q"], { cwd: repo });
1769
- run("node", [cli, "init"], { cwd: repo });
1770
- run("git", ["config", "user.email", "test@example.com"], { cwd: repo });
1771
- run("git", ["config", "user.name", "Auto Coding Test"], { cwd: repo });
1772
- run("git", ["add", "-A"], { cwd: repo });
1773
- run("git", ["commit", "-qm", "baseline"], { cwd: repo });
1774
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
1775
- for (const plannedPath of ["docs/ENGINEERING.md", "docs/project/auto-coding-skill.yaml"]) {
1776
- const result = run("python3", [
1777
- launcher,
1778
- "--repo", repo,
1779
- "classify",
1780
- "--planned-path", plannedPath,
1781
- "--intent", `change Skill configuration at ${plannedPath}`,
1782
- "--json",
1783
- ]);
1784
- const parsed = JSON.parse(result.stdout);
1785
- assert(parsed.profile === "high-risk", `${plannedPath} changes must be high-risk: ${result.stdout}`);
1786
- assert(parsed.review_required === true, `${plannedPath} changes must require independent review: ${result.stdout}`);
1787
- }
1788
- }
1789
-
1790
- function testStatusAndFeedbackUseEffectiveProjectConfigWithoutLeakingAccess() {
1791
- const repo = tmpdir("project-config-consumers");
1792
- const projectName = "effective-overlay-project";
1793
- const secret = "overlay-access-must-not-leak-c819";
1794
- run("node", [cli, "init"], { cwd: repo });
1795
- writeProjectConfig(repo, requiredProjectOverrides(projectName, secret));
1796
- const engineering = readEngineeringConfig(path.join(repo, "docs", "ENGINEERING.md"));
1797
- assert(engineering.project?.name === "", "managed ENGINEERING must not provide the effective project identity");
1798
- assert(engineering.access?.project?.frontend?.password === "", "managed ENGINEERING must not provide effective access values");
1799
-
1800
- const status = run("node", [cli, "status", "--projects", repo, "--json"]);
1801
- assert(JSON.parse(status.stdout).results[0].ok === true, `status must validate the effective overlay configuration: ${status.stdout}`);
1802
- assert(!status.stdout.includes(secret), "status must never print access values loaded from the project overlay");
1803
-
1804
- const signature = `sha256:${"c".repeat(64)}`;
1805
- const report = path.join(repo, "docs", "skill-feedback", "reports", "2026-07-18-effective-config-c819a2e4.md");
1806
- writeFile(report, [
1807
- "---",
1808
- "schema: auto-coding-skill-feedback/v1",
1809
- "report_id: ACSF-effective-20260718-c819a2e4",
1810
- "status: open",
1811
- 'created_at: "2026-07-18T10:00:00+08:00"',
1812
- `project: ${projectName}`,
1813
- `observed_skill_version: ${engineering.workflow.skill_version}`,
1814
- "component: config-overlay",
1815
- "kind: defect",
1816
- "impact: minor",
1817
- "origin_surface: managed-script",
1818
- "suspected_scope: shared",
1819
- `signature: ${signature}`,
1820
- "export: metadata-only",
1821
- "---",
1822
- "# Effective config consumer",
1823
- "",
1824
- "## Symptom",
1825
- "A consumer ignored the project overlay.",
1826
- "",
1827
- "## Expected",
1828
- "Every consumer uses the effective project configuration.",
1829
- "",
1830
- "## Minimal reproduction",
1831
- "Read this report using the configured project identity.",
1832
- "",
1833
- "## Evidence",
1834
- "The metadata is intentionally non-sensitive.",
1835
- "",
1836
- "## Workaround",
1837
- "None.",
1838
- "",
1839
- "## Why shared",
1840
- "The project-independent consumer is managed by the Skill.",
1841
- "",
1842
- ].join("\n"));
1843
- const feedback = run("node", [cli, "feedback", "--projects", repo, "--json"]);
1844
- const collected = JSON.parse(feedback.stdout);
1845
- assert(collected.projects[0]?.project === projectName, `feedback collection must use effective project.name: ${feedback.stdout}`);
1846
- assert(collected.report_count === 1 && collected.metadata[0]?.project === projectName, "feedback metadata must retain the effective project identity");
1847
- assert(!feedback.stdout.includes(secret), "feedback collection must never print access values loaded from the project overlay");
1848
- }
1849
-
1850
- function testManagedAgentModelsInheritAndOverridesSurvive() {
1851
- const repo = tmpdir("agent-models");
1852
- run("node", [cli, "init"], { cwd: repo });
1853
- const agentsDir = path.join(repo, ".agents", "agents");
1854
- assertManagedAgents(agentsDir);
1855
-
1856
- const custom = path.join(agentsDir, "custom-local.toml");
1857
- const customText = 'name = "custom-local"\ndescription = "custom"\nmodel = "vendor/custom"\n';
1858
- writeFile(custom, customText);
1859
- for (const filename of Object.keys(managedAgentEfforts)) {
1860
- const file = path.join(agentsDir, filename);
1861
- const stale = fs.readFileSync(file, "utf8")
1862
- .replace(/^description\s*=.*$/m, '$&\nmodel = "vendor/project-model"')
1863
- .replace(/^model_reasoning_effort\s*=.*$/m, 'model_reasoning_effort = "low"');
1864
- writeFile(file, stale);
1865
- }
1866
-
1867
- run("node", [cli, "sync", "--projects", repo]);
1868
- assertManagedAgents(agentsDir, "vendor/project-model");
1869
- assert(fs.readFileSync(custom, "utf8") === customText, "sync should preserve custom agent contents");
1870
- assertStatusOk(repo);
1871
-
1872
- run("node", [cli, "sync", "--projects", repo, "--reset-agent-models"]);
1873
- assertManagedAgents(agentsDir);
1874
- assert(fs.readFileSync(custom, "utf8") === customText, "model reset must not touch custom agents");
1875
- }
1876
-
1877
- function testForcePreservesCustomAgentsAndModelOverrides() {
1878
- const repo = tmpdir("force-agent");
1879
- run("node", [cli, "init", "--force"], { cwd: repo });
1880
- const agentsDir = path.join(repo, ".agents", "agents");
1881
- const custom = path.join(agentsDir, "custom-local.toml");
1882
- const customText = 'name = "custom-local"\ndescription = "custom"\n';
1883
- writeFile(custom, customText);
1884
- const explorer = path.join(agentsDir, "explorer.toml");
1885
- writeFile(explorer, fs.readFileSync(explorer, "utf8").replace(/^description\s*=.*$/m, '$&\nmodel = "vendor/override"'));
1886
- run("node", [cli, "init", "--force"], { cwd: repo });
1887
- assert(fs.readFileSync(custom, "utf8") === customText, "init must preserve agents outside the managed set");
1888
- assert(fs.readFileSync(explorer, "utf8").includes('model = "vendor/override"'), "init --force should preserve explicit managed-agent model overrides");
1889
- }
1890
-
1891
- function testInvalidManagedAgentModelsFailStatusAndAreDroppedOnSync() {
1892
- const repo = tmpdir("invalid-agent-model");
1893
- run("node", [cli, "init"], { cwd: repo });
1894
- run("node", [cli, "sync", "--projects", repo]);
1895
- const explorer = path.join(repo, ".agents", "agents", "explorer.toml");
1896
-
1897
- for (const invalidLine of ["model = [", 'model = ""']) {
1898
- const canonical = fs.readFileSync(explorer, "utf8").replace(/^model\s*=.*(?:\r?\n|$)/m, "");
1899
- writeFile(explorer, canonical.replace(/^description\s*=.*$/m, `$&\n${invalidLine}`));
1900
-
1901
- const status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
1902
- assert(status.status !== 0, `status should fail for invalid managed model: ${invalidLine}`);
1903
- const parsed = JSON.parse(status.stdout).results[0];
1904
- const finding = parsed.agentDiffs.find(item => item.path === "explorer.toml");
1905
- assert(finding?.status === "invalid-model", `status should report invalid-model: ${status.stdout}`);
1906
- assert(finding.detail?.includes("model"), `invalid model should include a useful detail: ${status.stdout}`);
1907
- assert(parsed.agentBindings.find(item => item.agent === "explorer.toml")?.model === "invalid", "invalid binding should be explicit in status JSON");
1908
-
1909
- run("node", [cli, "sync", "--projects", repo]);
1910
- assert(!/^model\s*=/m.test(managedAgentHeader(fs.readFileSync(explorer, "utf8"))), "sync must not preserve an invalid model override");
1911
- assertStatusOk(repo);
1912
- }
1913
- }
1914
-
1915
- function testModelTextInsideInstructionsIsNotPromotedToOverride() {
1916
- const repo = tmpdir("model-in-instructions");
1917
- run("node", [cli, "init"], { cwd: repo });
1918
- run("node", [cli, "sync", "--projects", repo]);
1919
- const explorer = path.join(repo, ".agents", "agents", "explorer.toml");
1920
- const withExample = fs.readFileSync(explorer, "utf8").replace(
1921
- 'developer_instructions = """',
1922
- 'developer_instructions = """\nmodel = "example/in-docs"',
1923
- );
1924
- writeFile(explorer, withExample);
1925
-
1926
- run("node", [cli, "sync", "--projects", repo]);
1927
- const synced = fs.readFileSync(explorer, "utf8");
1928
- assert(!/^model\s*=/m.test(managedAgentHeader(synced)), "instruction text must not become a top-level model override");
1929
- assert(!synced.includes('model = "example/in-docs"'), "sync should refresh stale managed instructions without promoting their example model");
1930
- assertStatusOk(repo);
1931
- }
1932
-
1933
- function testCommandSpecificArgumentsAreRejectedBeforeWrites() {
1934
- const dryRunDest = tmpdir("invalid-init-dry-run");
1935
- const invalidInit = run("node", [cli, "init", "--dest", dryRunDest, "--dry-run"], { check: false });
1936
- assert(invalidInit.status !== 0 && invalidInit.stderr.includes("not valid for 'init'"), "init should reject --dry-run");
1937
- assert(!exists(path.join(dryRunDest, ".agents")), "invalid init arguments must not write files");
1938
-
1939
- const positionalDest = tmpdir("invalid-init-positional");
1940
- const invalidPositional = run("node", [cli, "init", "unexpected-project"], { cwd: positionalDest, check: false });
1941
- assert(invalidPositional.status !== 0 && invalidPositional.stderr.includes("not valid for 'init'"), "init should reject positional project arguments");
1942
- assert(!exists(path.join(positionalDest, ".agents")), "invalid positional init must not write files");
1943
-
1944
- const repo = tmpdir("invalid-command-options");
1945
- run("node", [cli, "init"], { cwd: repo });
1946
- run("node", [cli, "sync", "--projects", repo]);
1947
- const explorer = path.join(repo, ".agents", "agents", "explorer.toml");
1948
- writeFile(explorer, fs.readFileSync(explorer, "utf8").replace(/^description\s*=.*$/m, '$&\nmodel = "vendor/keep"'));
1949
-
1950
- const invalidStatus = run("node", [cli, "status", "--projects", repo, "--reset-agent-models"], { check: false });
1951
- assert(invalidStatus.status !== 0 && invalidStatus.stderr.includes("not valid for 'status'"), "status should reject --reset-agent-models");
1952
- assert(managedAgentHeader(fs.readFileSync(explorer, "utf8")).includes('model = "vendor/keep"'), "rejected status command must not reset models");
1953
-
1954
- const invalidSync = run("node", [cli, "sync", "--projects", repo, "--force"], { check: false });
1955
- assert(invalidSync.status !== 0 && invalidSync.stderr.includes("not valid for 'sync'"), "sync should reject --force");
1956
- const validDryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--reset-agent-models"]);
1957
- assert(validDryRun.status === 0, "sync should accept its documented dry-run/reset options together");
1958
- assert(managedAgentHeader(fs.readFileSync(explorer, "utf8")).includes('model = "vendor/keep"'), "dry-run must not reset models on disk");
1959
- }
1960
-
1961
- function testBridgeIsGeneric() {
1962
- const repo = tmpdir("bridge");
1963
- run("node", [cli, "init", "--force"], { cwd: repo });
1964
- assert(exists(path.join(repo, "AGENTS.md")), "generic bridge should be created");
1965
- const bridge = fs.readFileSync(path.join(repo, "AGENTS.md"), "utf8");
1966
- assert(bridge.includes("Every delegated fixer or parallel writer owns a task ID/worktree"), "bridge should expose delegated-writer isolation");
1967
- assert(bridge.includes("integrates in dependency order"), "bridge should expose dependency ordering");
1968
- for (const filename of [`CO${"DEX.md"}`, `CLA${"UDE.md"}`]) {
1969
- assert(!exists(path.join(repo, filename)), "client-named bridge should not be created");
1970
- }
1971
- }
1972
-
1973
- function testSyncCleansAllManagedSkillExtras() {
1974
- const repo = tmpdir("sync-extra");
1975
- run("git", ["init", "-q"], { cwd: repo });
1976
- run("node", [cli, "init", "--force"], { cwd: repo });
1977
- run("node", [cli, "sync", "--projects", repo]);
1978
- writeFile(path.join(repo, ".agents", "skills", "auto-coding-skill", "data", "templates", "bridges", "OLD.md"), "old\n");
1979
- writeFile(path.join(repo, ".agents", "skills", "auto-coding-skill", "custom.txt"), "custom\n");
1980
- run("node", [cli, "sync", "--projects", repo]);
1981
- assert(!exists(path.join(repo, ".agents", "skills", "auto-coding-skill", "data", "templates", "bridges", "OLD.md")), "managed bridge extra should be removed");
1982
- assert(!exists(path.join(repo, ".agents", "skills", "auto-coding-skill", "custom.txt")), "fully managed Skill extras should be removed");
1983
- }
1984
-
1985
- function testOptionalDocsAndLegacyToolsDoNotCauseDrift() {
1986
- const repo = tmpdir("legacy-extras");
1987
- run("node", [cli, "init"], { cwd: repo });
1988
- run("node", [cli, "sync", "--projects", repo]);
1989
- writeFile(path.join(repo, "docs", "interfaces", "api.md"), "# Existing API\n");
1990
- writeFile(path.join(repo, "docs", "tools", "autopipeline", "core.py"), "# legacy copy\n");
1991
- writeFile(path.join(repo, "docs", "tools", "autopipeline", "http_checks.py"), "# legacy copy\n");
1992
- fillRequiredAccess(repo);
1993
- const drift = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
1994
- assert(drift.status !== 0, "extra runtime copies must be reported as drift");
1995
- run("node", [cli, "init"], { cwd: repo });
1996
- assert(!exists(path.join(repo, "docs", "tools", "autopipeline", "core.py")), "legacy runtime copy must be removed");
1997
- assert(!exists(path.join(repo, "docs", "tools", "autopipeline", "http_checks.py")), "legacy HTTP copy must be removed");
1998
- assert(fs.readFileSync(path.join(repo, "docs", "interfaces", "api.md"), "utf8") === "# Existing API\n", "mutable project docs must survive init");
1999
- assertStatusOk(repo);
2000
- }
2001
-
2002
- function testOptionalScaffoldIsOnDemandAndIdempotent() {
2003
- const repo = tmpdir("optional-scaffold");
2004
- run("node", [cli, "init"], { cwd: repo });
2005
- run("node", [cli, "sync", "--projects", repo]);
2006
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2007
- run("python3", [launcher, "--repo", repo, "scaffold", "api", "--write"]);
2008
- const api = path.join(repo, "docs", "interfaces", "api.md");
2009
- assert(exists(api), "api scaffold should be created on demand");
2010
- writeFile(api, "# User API\n");
2011
- run("python3", [launcher, "--repo", repo, "scaffold", "api", "--write"]);
2012
- assert(fs.readFileSync(api, "utf8") === "# User API\n", "scaffold should not overwrite existing docs without --force");
2013
- }
2014
-
2015
- function testTestingScaffoldMatchesCheckMatrixSchema() {
2016
- const repo = tmpdir("testing-scaffold");
2017
- run("node", [cli, "init"], { cwd: repo });
2018
- run("node", [cli, "sync", "--projects", repo]);
2019
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2020
- run("python3", [launcher, "--repo", repo, "scaffold", "testing", "--write"]);
2021
-
2022
- const matrix = path.join(repo, "docs", "testing", "regression-matrix.md");
2023
- const initial = fs.readFileSync(matrix, "utf8");
2024
- const row = initial.split(/\r?\n/).find(line => line.startsWith("| R-001 |"));
2025
- assert(row, "testing scaffold should include R-001");
2026
- const columns = row.split("|").slice(1, -1).map(value => value.trim());
2027
- assert(columns.length === 8, `regression row should have 8 columns, got ${columns.length}`);
2028
-
2029
- const pending = run("python3", [launcher, "--repo", repo, "check-matrix"], { check: false });
2030
- const pendingOutput = `${pending.stdout}\n${pending.stderr}`;
2031
- assert(pending.status !== 0 && pendingOutput.includes("R-001: TODO"), `generated matrix should be parsed as pending: ${pendingOutput}`);
2032
- assert(!pendingOutput.includes("No regression rows found"), "generated matrix must not be rejected as malformed");
2033
-
2034
- writeFile(matrix, initial.replace("| TODO | <evidence> |", "| PASS | logs/regression.txt |"));
2035
- run("python3", [launcher, "--repo", repo, "check-matrix"]);
2036
- }
2037
-
2038
- function testReviewScaffoldLeavesBaselineGenerationToBaselineCommand() {
2039
- const repo = tmpdir("review-scaffold");
2040
- run("node", [cli, "init"], { cwd: repo });
2041
- run("node", [cli, "sync", "--projects", repo]);
2042
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2043
-
2044
- run("python3", [launcher, "--repo", repo, "scaffold", "review", "--write"]);
2045
- assert(exists(path.join(repo, "docs", "reviews", "_TEMPLATE-REVIEW.md")), "review scaffold should create its review template");
2046
- for (const rel of ["docs/reviews/project-health-baseline.md", "docs/reviews/optimization-backlog.md"]) {
2047
- assert(!exists(path.join(repo, rel)), `review scaffold must leave generated baseline output absent: ${rel}`);
2048
- }
2049
-
2050
- run("git", ["init", "-q"], { cwd: repo });
2051
- run("git", ["config", "user.email", "test@example.com"], { cwd: repo });
2052
- run("git", ["config", "user.name", "Auto Coding Test"], { cwd: repo });
2053
- run("git", ["add", "-A"], { cwd: repo });
2054
- run("git", ["commit", "-qm", "baseline"], { cwd: repo });
2055
- run("python3", [launcher, "--repo", repo, "baseline", "init", "--write"]);
2056
- assert(fs.readFileSync(path.join(repo, "docs", "reviews", "project-health-baseline.md"), "utf8").includes("Generated by `ap.py baseline init`"), "baseline command should generate the health baseline");
2057
- assert(fs.readFileSync(path.join(repo, "docs", "reviews", "optimization-backlog.md"), "utf8").includes("Generated by `ap.py baseline init`"), "baseline command should generate the optimization backlog");
2058
- }
2059
-
2060
- function testBaselineUpdateConfigWritesOnlyProjectOverlay() {
2061
- const repo = tmpdir("baseline-project-overlay-only");
2062
- run("git", ["init", "-q"], { cwd: repo });
2063
- run("node", [cli, "init"], { cwd: repo });
2064
- run("git", ["config", "user.email", "test@example.com"], { cwd: repo });
2065
- run("git", ["config", "user.name", "Auto Coding Test"], { cwd: repo });
2066
- writeFile(path.join(repo, "src", "large-module.js"), "export const line = 1;\n".repeat(801));
2067
- run("git", ["add", "-A"], { cwd: repo });
2068
- run("git", ["commit", "-qm", "baseline source"], { cwd: repo });
2069
-
2070
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2071
- const overlay = projectConfigPath(repo);
2072
- const engineeringBefore = fs.readFileSync(engineering);
2073
- const overlayBefore = fs.readFileSync(overlay);
2074
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2075
- const baseline = run("python3", [
2076
- launcher,
2077
- "--repo", repo,
2078
- "baseline", "init",
2079
- "--write",
2080
- "--update-config",
2081
- "--json",
2082
- ]);
2083
- const parsed = JSON.parse(baseline.stdout);
2084
-
2085
- assert(parsed.updated_accepted_debt_paths.includes("src/large-module.js"), `baseline must discover the tracked large file: ${baseline.stdout}`);
2086
- assert(fs.readFileSync(engineering).equals(engineeringBefore), "baseline --update-config must never modify managed ENGINEERING defaults");
2087
- assert(!fs.readFileSync(overlay).equals(overlayBefore), "baseline --update-config must persist accepted debt in the project overlay");
2088
- assert(readEffectiveConfig(repo).structure?.accepted_debt_paths?.includes("src/large-module.js"), "the overlay update must affect effective accepted_debt_paths");
2089
- const changed = run("git", ["status", "--porcelain"], { cwd: repo }).stdout;
2090
- assert(changed.includes("docs/project/auto-coding-skill.yaml"), `baseline must report the overlay as the changed configuration file: ${changed}`);
2091
- assert(!changed.includes("docs/ENGINEERING.md"), `baseline must not report managed ENGINEERING as changed: ${changed}`);
2092
- }
2093
-
2094
- function testSyncUsesPackagedAssetsAndIgnoresRetiredTemplates() {
2095
- const repo = tmpdir("sync-packaged-source");
2096
- const fakeHome = tmpdir("sync-stale-home");
2097
- run("git", ["init", "-q"], { cwd: repo });
2098
- run("node", [cli, "init"], { cwd: repo });
2099
- run("node", [cli, "sync", "--projects", repo]);
2100
-
2101
- const projectSkill = path.join(repo, ".agents", "skills", "auto-coding-skill");
2102
- writeFile(path.join(projectSkill, "data", "templates", "docs", "interfaces", "api.md"), "# Retired project template\n");
2103
-
2104
- const staleGlobal = path.join(fakeHome, ".agents", "skills", "auto-coding-skill");
2105
- writeFile(path.join(staleGlobal, "scripts", "ap.py"), "# legacy runtime\n");
2106
- writeFile(path.join(staleGlobal, "data", "templates", "ENGINEERING.md"), "---\n---\n");
2107
- writeFile(path.join(staleGlobal, "data", "templates", "docs", "interfaces", "api.md"), "# Retired global template\n");
2108
-
2109
- run("node", [cli, "sync", "--projects", repo], { env: pythonEnvWithHome(fakeHome) });
2110
- assert(!exists(path.join(projectSkill, "data", "templates", "docs", "interfaces", "api.md")), "transactional sync must replace retired files in the managed Skill namespace");
2111
- assert(fs.readFileSync(path.join(repo, "docs", "interfaces", "api.md"), "utf8").startsWith("# API Contract"), "transactional sync must not replace the canonical API doc with a retired physical template");
2112
- }
2113
-
2114
- function testInitInitializesNewEngineeringDefaults() {
2115
- const repo = tmpdir("init-engineering-defaults");
2116
- run("git", ["init", "-q"], { cwd: repo });
2117
- writeFile(path.join(repo, "package.json"), JSON.stringify({ scripts: { test: "node --test", "test:changed": "node --test" } }, null, 2) + "\n");
2118
- run("node", [cli, "init"], { cwd: repo });
2119
-
2120
- const effective = readEffectiveConfig(repo);
2121
- assert(effective.project?.name === path.basename(repo), "init should initialize a newly created project name in the overlay");
2122
- assert(effective.commands?.project_fast === "npm run test:changed", "init should infer only a dedicated changed-scope test in the overlay");
2123
- assert(effective.commands?.gate_standard === undefined, "init must not infer an automatic standard gate");
2124
- assert(effective.commands?.gate_full === undefined, "init must not infer an automatic full gate");
2125
- }
2126
-
2127
- function testInitMigratesLegacyAutomaticGateToFastDefault() {
2128
- const repo = tmpdir("init-legacy-fast-gate");
2129
- run("git", ["init", "-q"], { cwd: repo });
2130
- writeFile(path.join(repo, "package.json"), JSON.stringify({ scripts: { test: "node --test" } }, null, 2) + "\n");
2131
- run("node", [cli, "init"], { cwd: repo });
2132
- fs.unlinkSync(projectConfigPath(repo));
2133
- const legacyEngineering = [
2134
- "---",
2135
- "workflow:",
2136
- ' skill_version: "4.2.8"',
2137
- " mode: dev",
2138
- " profile: auto",
2139
- " completion: push",
2140
- "project:",
2141
- ' name: "legacy"',
2142
- "concurrency:",
2143
- " isolation: legacy",
2144
- " base_ref: origin/dev",
2145
- " target_branch: dev",
2146
- "commands:",
2147
- ' gate_changed: "npm test"',
2148
- ' gate_standard: "npm test"',
2149
- ' gate_full: "npm run test:full"',
2150
- "gate:",
2151
- " default_scope: auto",
2152
- " fallback_scope: standard",
2153
- " full_on_unknown: true",
2154
- " no_change_scope: standard",
2155
- " rules: []",
2156
- "---",
2157
- "# Legacy engineering",
2158
- "",
2159
- ].join("\n");
2160
- writeFile(path.join(repo, "docs", "ENGINEERING.md"), legacyEngineering);
2161
- const legacyInstalledDefault = legacyEngineering
2162
- .replace(' name: "legacy"', ' name: ""')
2163
- .replace(" base_ref: origin/dev", ' base_ref: ""')
2164
- .replace(" target_branch: dev", ' target_branch: ""');
2165
- installTrustedEngineeringDefault(repo, legacyInstalledDefault, "4.2.8");
2166
-
2167
- run("node", [cli, "init"], { cwd: repo });
2168
- const managed = readEngineeringConfig(path.join(repo, "docs", "ENGINEERING.md"));
2169
- const effective = readEffectiveConfig(repo);
2170
- assert(effective.commands?.project_fast === "", "init should not promote an ordinary npm test to the project-fast gate");
2171
- assert(managed.workflow?.mode === "dev", "init should retain the managed fast development mode");
2172
- assert(managed.workflow?.completion === "push", "init should retain managed push completion");
2173
- assert(managed.concurrency?.isolation === "adaptive", "init should retain managed adaptive isolation");
2174
- assert(managed.validation?.on_unmapped === "error", "init should retain the fail-closed unmapped default");
2175
- assert(managed.risk?.rules?.length === 0, "init should retain empty managed project-risk defaults");
2176
- assert(effective.project?.name === "legacy" && effective.concurrency?.target_branch === "dev", "init must migrate supported legacy project values into the overlay");
2177
- assert(effective.gate === undefined && effective.commands?.gate_full === undefined, "init must drop removed automatic gate escalation fields");
2178
- }
2179
-
2180
- function testRemovedVerificationFlagsFailFast() {
2181
- const repo = tmpdir("removed-verification-flags");
2182
- const result = run("python3", [assetAp, "--repo", repo, "commit-push", "T1", "--msg", "T1: test", "--require-jenkins"], { check: false });
2183
- assert(result.status !== 0 && result.stderr.includes("unrecognized arguments"), "removed post-push verification flags must fail instead of being ignored");
2184
- }
2185
-
2186
- function testInstallBootstrapsRuntimeRequiredByLauncher() {
2187
- const repo = tmpdir("install-missing-runtime");
2188
- const fakeHome = tmpdir("install-global-runtime-home");
2189
- const env = pythonEnvWithHome(fakeHome);
2190
- run("git", ["init", "-q"], { cwd: repo });
2191
- run("node", [cli, "init", "--mode", "global", "--dest", fakeHome, "--force"]);
2192
- const globalAp = path.join(fakeHome, ".agents", "skills", "auto-coding-skill", "scripts", "ap.py");
2193
- run("python3", [globalAp, "--repo", repo, "install"], { env });
2194
- const projectRuntime = path.join(repo, ".agents", "skills", "auto-coding-skill", "scripts", "ap.py");
2195
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2196
- assert(!exists(projectRuntime), "runtime bootstrap install must continue to rely on the invoking global Skill copy");
2197
- assert(readYamlConfig(projectConfigPath(repo)).overrides?.project?.name === path.basename(repo), "bootstrap install must initialize the project overlay");
2198
- const help = run("python3", [launcher, "--help"], { env });
2199
- assert(help.stdout.includes("autopipeline"), "bootstrapped launcher should remain executable through the invoking runtime");
2200
- }
2201
-
2202
- function testCliInstallArchivesFeedbackTemplatesAndPreservesReports() {
2203
- const repo = tmpdir("cli-feedback-ownership");
2204
- run("git", ["init", "-q"], { cwd: repo });
2205
- const feedbackReadme = path.join(repo, "docs", "skill-feedback", "README.md");
2206
- const report = path.join(repo, "docs", "skill-feedback", "reports", "2026-07-18-upgrade-gap-a13f82c1.md");
2207
- const previousReadme = "project content that occupied the future managed feedback README\n";
2208
- const reportContent = "project-owned feedback report bytes\n";
2209
- writeFile(feedbackReadme, previousReadme);
2210
- writeFile(report, reportContent);
2211
-
2212
- run("node", [cli, "init"], { cwd: repo });
2213
- const archive = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "skill-feedback", "README.md");
2214
- assert(fs.readFileSync(feedbackReadme, "utf8").includes("Auto Coding Skill Feedback"), "transactional init must install the managed feedback README");
2215
- assert(fs.readFileSync(archive, "utf8") === previousReadme, "transactional init must archive a pre-existing feedback README before replacement");
2216
- assert(fs.readFileSync(report, "utf8") === reportContent, "transactional init must preserve project feedback reports byte-for-byte");
2217
-
2218
- const archiveBefore = fs.readFileSync(archive);
2219
- run("node", [cli, "sync", "--projects", repo]);
2220
- assert(fs.readFileSync(archive).equals(archiveBefore), "repeated transactional sync must keep the original feedback archive stable");
2221
- assert(fs.readFileSync(report, "utf8") === reportContent, "repeated transactional sync must keep project feedback reports stable");
2222
- }
2223
-
2224
- function testLegacyUpgradeWriteFailsWithoutAnyWrites() {
2225
- const repo = tmpdir("legacy-upgrade-write-rejected");
2226
- run("git", ["init", "-q"], { cwd: repo });
2227
- run("node", [cli, "init"], { cwd: repo });
2228
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2229
- writeFile(skill, "legacy-upgrade-zero-write-sentinel\n");
2230
- const beforeFiles = listProjectFiles(repo)
2231
- .map(file => [path.relative(repo, file), fs.readFileSync(file)])
2232
- .sort(([left], [right]) => left.localeCompare(right));
2233
- const projectAp = path.join(repo, ".agents", "skills", "auto-coding-skill", "scripts", "ap.py");
2234
-
2235
- const rejected = run("python3", [projectAp, "--repo", repo, "upgrade", "--write"], { check: false });
2236
- const output = `${rejected.stdout}\n${rejected.stderr}`;
2237
- assert(rejected.status !== 0, "legacy ap.py upgrade --write must be rejected");
2238
- assert(output.includes("retired") && output.includes("autocoding init") && output.includes("autocoding sync"), `legacy write rejection must direct callers to the transactional CLI: ${output}`);
2239
- const afterFiles = listProjectFiles(repo)
2240
- .map(file => [path.relative(repo, file), fs.readFileSync(file)])
2241
- .sort(([left], [right]) => left.localeCompare(right));
2242
- assert(afterFiles.length === beforeFiles.length, "rejected legacy write must not create or delete project files");
2243
- for (let index = 0; index < beforeFiles.length; index += 1) {
2244
- assert(afterFiles[index][0] === beforeFiles[index][0], `rejected legacy write must preserve the file set: ${beforeFiles[index][0]}`);
2245
- assert(afterFiles[index][1].equals(beforeFiles[index][1]), `rejected legacy write must preserve bytes: ${beforeFiles[index][0]}`);
2246
- }
2247
- }
2248
-
2249
- function testLedgerArchiveRecognizesSettledStatuses() {
2250
- const repo = tmpdir("ledger-status");
2251
- run("git", ["init", "-q"], { cwd: repo });
2252
- run("node", [cli, "init", "--force"], { cwd: repo });
2253
- run("node", [cli, "sync", "--projects", repo]);
2254
- writeFile(path.join(repo, "docs", "tasks", "taskbook.md"), [
2255
- "# Taskbook", "", "## Task T001 - superseded work", "- Status: Superseded by T002", "",
2256
- "## Task T002 - external dependency", "- Status: External Dependency", "",
2257
- "## Task T003 - deployed work", "- Status: Deployed / Jenkins #123 SUCCESS", "",
2258
- "## Task T004 - local pass", "- Status: Local PASS,待生产迁移窗口", "",
2259
- "## Task T005 - markdown done", "- Status: `Done / PASS`", "",
2260
- "## Task T006 - localized done", "- 状态:Done(PASS)", "",
2261
- ].join("\n"));
2262
- writeFile(path.join(repo, "docs", "tasks", "closure-log.md"), [
2263
- "# Closure Log", "", "## T001 - superseded work", "- Result: DEV-CLOSED", "",
2264
- "## T002 - external dependency", "- Result: PARTIAL", "",
2265
- "## T003 - deployed work", "- Result: PASS", "",
2266
- "## T004 - local pass", "- Result: DEV-CLOSED", "",
2267
- "## T005 - markdown done", "- Result: PASS", "",
2268
- "## T006 - localized done", "- Result: PASS", "",
2269
- ].join("\n"));
2270
- const result = run("python3", [assetAp, "--repo", repo, "docs-ledger-archive", "--plan", "--period", "2026-06", "--json"]);
2271
- const parsed = JSON.parse(result.stdout);
2272
- assert(parsed.counts.taskbook_sections === 6, `settled task sections should archive: ${result.stdout}`);
2273
- assert(parsed.active_task_conflicts.length === 0, `settled statuses should not conflict: ${result.stdout}`);
2274
- }
2275
-
2276
- function testLedgerArchiveUpdatesExistingPeriodIndex() {
2277
- const repo = tmpdir("ledger-index-update");
2278
- run("git", ["init", "-q"], { cwd: repo });
2279
- run("node", [cli, "init", "--force"], { cwd: repo });
2280
- run("node", [cli, "sync", "--projects", repo]);
2281
-
2282
- const taskbook = path.join(repo, "docs", "tasks", "taskbook.md");
2283
- const closure = path.join(repo, "docs", "tasks", "closure-log.md");
2284
- const designDir = path.join(repo, "docs", "design");
2285
- writeFile(taskbook, "# Taskbook\n\n## Task T001 - first\n- Status: Done\n");
2286
- writeFile(closure, "# Closure Log\n\n## T001 - first\n- Result: PASS\n");
2287
- writeFile(path.join(designDir, "T001-first.md"), "# T001\n");
2288
- run("python3", [assetAp, "--repo", repo, "docs-ledger-archive", "--write", "--period", "2026-06", "--json"]);
2289
-
2290
- fs.appendFileSync(taskbook, "\n## Task T002 - second\n- Status: `Done / PASS`\n");
2291
- fs.appendFileSync(closure, "\n## T002 - second\n- Result: PASS\n");
2292
- writeFile(path.join(designDir, "T002-second.md"), "# T002\n");
2293
- run("python3", [assetAp, "--repo", repo, "docs-ledger-archive", "--write", "--period", "2026-06", "--json"]);
2294
-
2295
- const index = fs.readFileSync(path.join(repo, "docs", "tasks", "archive-index.md"), "utf8");
2296
- assert((index.match(/^## 2026-06$/gm) || []).length === 1, `archive period should be unique: ${index}`);
2297
- assert(index.includes("(2 sections)"), `archive index should report cumulative task/closure counts: ${index}`);
2298
- assert(index.includes("(2 files)"), `archive index should report cumulative design count: ${index}`);
2299
- }
2300
-
2301
- function testManagedEngineeringInitIsAuthoritativeAndIdempotent() {
2302
- const repo = tmpdir("managed-engineering");
2303
- run("node", [cli, "init"], { cwd: repo });
2304
- run("node", [cli, "sync", "--projects", repo]);
2305
-
2306
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2307
- const initial = fs.readFileSync(engineering, "utf8");
2308
- const startPattern = /<!-- auto-coding-skill:managed-workflow:start version=4\.3\.3 -->/;
2309
- const endMarker = "<!-- auto-coding-skill:managed-workflow:end -->";
2310
- assert(startPattern.test(initial), "new projects should include a versioned managed workflow marker");
2311
- assert(initial.includes(endMarker), "new projects should include the managed workflow end marker");
2312
-
2313
- const customized = initial
2314
- .replace("workflow:\n", "# project-frontmatter-comment\nworkflow:\n")
2315
- .replace(startPattern, "project note before managed workflow\n<!-- auto-coding-skill:managed-workflow:start version=3.0.0 -->")
2316
- .replace(endMarker, `${endMarker}\nproject note after managed workflow`)
2317
- .replace("The frontmatter contract is:", "Stale managed workflow contract:");
2318
- writeFile(engineering, customized);
2319
- const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
2320
- const dryResult = JSON.parse(dryRun.stdout).results[0];
2321
- assert(dryResult.managedWorkflow.state === "stale", `dry-run should expose stale workflow state: ${dryRun.stdout}`);
2322
- assert(dryResult.managedWorkflow.version === "4.3.7", "dry-run should expose the target workflow version");
2323
- assert(dryResult.actions.some(item => item.action === "would-replace" && item.path === "docs/ENGINEERING.md"), "dry-run should plan exact replacement of the managed default document");
2324
- assert(fs.readFileSync(engineering, "utf8") === customized, "dry-run must not write ENGINEERING.md");
2325
-
2326
- run("node", [cli, "init"], { cwd: repo });
2327
- const updated = fs.readFileSync(engineering, "utf8");
2328
- assert(!updated.includes("project note before") && !updated.includes("project note after"), "init must remove text outside the canonical ENGINEERING body");
2329
- assert(updated.includes("version=4.3.7"), "init should install the current managed workflow version");
2330
- assert(updated.includes("The frontmatter contract is:"), "init should refresh stale managed workflow content");
2331
-
2332
- fillRequiredAccess(repo);
2333
- const status = run("node", [cli, "status", "--projects", repo, "--json"]);
2334
- const statusResult = JSON.parse(status.stdout).results[0];
2335
- assert(statusResult.managedWorkflow.state === "current", `status should expose current managed workflow state: ${status.stdout}`);
2336
- assert(statusResult.managedWorkflow.version === "4.3.7", "status should expose the installed managed workflow version");
2337
-
2338
- const beforeSecondInit = fs.readFileSync(engineering, "utf8");
2339
- run("node", [cli, "init"], { cwd: repo });
2340
- assert(fs.readFileSync(engineering, "utf8") === beforeSecondInit, "idempotent init must not rewrite ENGINEERING.md");
2341
- }
2342
-
2343
- function testLegacyEngineeringMigrationPreservesExistingBody() {
2344
- const repo = tmpdir("legacy-managed-engineering");
2345
- run("node", [cli, "init"], { cwd: repo });
2346
- run("node", [cli, "sync", "--projects", repo]);
2347
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2348
- const current = fs.readFileSync(engineering, "utf8");
2349
- const start = current.indexOf("<!-- auto-coding-skill:managed-workflow:start");
2350
- const endMarker = "<!-- auto-coding-skill:managed-workflow:end -->";
2351
- const end = current.indexOf(endMarker) + endMarker.length;
2352
- const legacyNote = "\n## Legacy project facts\n\nKeep this project note exactly.\n";
2353
- const legacy = `${current.slice(0, start)}${legacyNote}${current.slice(end)}`;
2354
- writeFile(engineering, legacy);
2355
-
2356
- const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
2357
- const dryResult = JSON.parse(dryRun.stdout).results[0];
2358
- assert(dryResult.managedWorkflow.state === "legacy-custom", "unknown unmarked documents should be reported as a custom legacy migration");
2359
- assert(dryResult.managedWorkflow.preservedCustom === true, "custom legacy migration should expose its preservation policy");
2360
- assert(dryResult.actions.some(item => item.action === "would-replace" && item.path === "docs/ENGINEERING.md"), "custom legacy migration must plan exact managed replacement");
2361
- assert(dryResult.actions.some(item => item.action === "would-archive" && item.path.endsWith("/docs/ENGINEERING.md")), "custom legacy migration must plan archival before replacement");
2362
- run("node", [cli, "sync", "--projects", repo]);
2363
- const migrated = fs.readFileSync(engineering, "utf8");
2364
- assert(migrated.includes("version=4.3.7"), "legacy migration should insert the current managed workflow");
2365
- assert(!migrated.includes(legacyNote), "legacy project text must not remain in the exact managed default document");
2366
- const archive = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "ENGINEERING.md");
2367
- assert(fs.readFileSync(archive, "utf8").includes(legacyNote), "legacy migration must preserve the complete previous body in history");
2368
- const stable = fs.readFileSync(engineering, "utf8");
2369
- run("node", [cli, "sync", "--projects", repo]);
2370
- assert(fs.readFileSync(engineering, "utf8") === stable, "legacy migration should converge after one sync");
2371
- }
2372
-
2373
- function testOfficialLegacyEngineeringBodyIsReplacedWithoutDuplication() {
2374
- const repo = tmpdir("official-legacy-engineering");
2375
- run("node", [cli, "init"], { cwd: repo });
2376
- run("node", [cli, "sync", "--projects", repo]);
2377
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2378
- const current = fs.readFileSync(engineering, "utf8");
2379
- const frontmatter = current.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)?.[0];
2380
- assert(frontmatter, "official legacy fixture requires frontmatter");
2381
- const customizedFrontmatter = frontmatter.replace("workflow:\n", "# keep-official-migration-config\nworkflow:\n");
2382
- writeFile(engineering, `${customizedFrontmatter}${officialV220EngineeringBody}`);
2383
-
2384
- const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
2385
- const dryResult = JSON.parse(dryRun.stdout).results[0];
2386
- assert(dryResult.managedWorkflow.state === "legacy-official", `official body hash should select replacement migration: ${dryRun.stdout}`);
2387
- assert(dryResult.actions.some(item => item.action === "would-replace" && item.path === "docs/ENGINEERING.md"), "official legacy migration must plan exact managed replacement");
2388
- run("node", [cli, "sync", "--projects", repo]);
2389
- const migrated = fs.readFileSync(engineering, "utf8");
2390
- const canonicalEngineering = fs.readFileSync(path.join(repoRoot, "cli", "assets", "skill", "data", "templates", "ENGINEERING.md"), "utf8");
2391
- assert(migrated === canonicalEngineering, "official legacy migration must install the exact managed default document");
2392
- assert((migrated.match(/auto-coding-skill:managed-workflow:start/g) || []).length === 1, "official legacy migration should install exactly one managed workflow");
2393
- assert((migrated.match(/^## Execution profiles$/gm) || []).length === 0, "official legacy migration must remove the old duplicated workflow body");
2394
- const archive = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "ENGINEERING.md");
2395
- assert(fs.readFileSync(archive, "utf8").includes("## Execution profiles"), "official legacy body must remain available in the historical archive");
2396
-
2397
- const stable = fs.readFileSync(engineering, "utf8");
2398
- run("node", [cli, "sync", "--projects", repo]);
2399
- assert(fs.readFileSync(engineering, "utf8") === stable, "official legacy migration should be idempotent");
2400
- }
2401
-
2402
- function testMalformedManagedMarkersFailClosed() {
2403
- const cases = {
2404
- "single-start": "<!-- auto-coding-skill:managed-workflow:start version=3.0.0 -->\nold\n",
2405
- "single-end": "old\n<!-- auto-coding-skill:managed-workflow:end -->\n",
2406
- duplicate: "<!-- auto-coding-skill:managed-workflow:start version=3.0.0 -->\n<!-- auto-coding-skill:managed-workflow:start version=3.0.0 -->\n<!-- auto-coding-skill:managed-workflow:end -->\n",
2407
- nested: "<!-- auto-coding-skill:managed-workflow:start version=3.0.0 -->\n<!-- auto-coding-skill:managed-workflow:end -->\n<!-- auto-coding-skill:managed-workflow:end -->\n",
2408
- };
2409
- for (const [name, malformed] of Object.entries(cases)) {
2410
- const repo = tmpdir(`managed-marker-${name}`);
2411
- run("node", [cli, "init"], { cwd: repo });
2412
- run("node", [cli, "sync", "--projects", repo]);
2413
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2414
- const text = fs.readFileSync(engineering, "utf8");
2415
- const start = text.indexOf("<!-- auto-coding-skill:managed-workflow:start");
2416
- const endMarker = "<!-- auto-coding-skill:managed-workflow:end -->";
2417
- const end = text.indexOf(endMarker) + endMarker.length;
2418
- writeFile(engineering, `${text.slice(0, start)}${malformed}${text.slice(end)}`);
2419
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2420
- writeFile(skill, `user-sentinel-${name}\n`);
2421
- const before = fs.readFileSync(engineering, "utf8");
2422
-
2423
- const result = run("node", [cli, "sync", "--projects", repo], { check: false });
2424
- assert(result.status !== 0 && result.stderr.includes("refusing"), `${name}: malformed markers should reject sync`);
2425
- assert(fs.readFileSync(engineering, "utf8") === before, `${name}: rejected sync must not touch ENGINEERING.md`);
2426
- assert(fs.readFileSync(skill, "utf8") === `user-sentinel-${name}\n`, `${name}: preflight must reject before writing the skill`);
2427
- }
2428
- }
2429
-
2430
- function testPartialSkillSyncIsRejectedWithoutWrites() {
2431
- const repo = tmpdir("partial-skill-sync");
2432
- run("git", ["init", "-q"], { cwd: repo });
2433
- run("node", [cli, "init"], { cwd: repo });
2434
- run("node", [cli, "sync", "--projects", repo]);
2435
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2436
- writeFile(skill, "stale skill\n");
2437
- const rejected = run("node", [cli, "sync", "--projects", repo, "--components", "skill"], { check: false });
2438
- assert(rejected.status !== 0 && rejected.stderr.includes("removed in 4.1"), "partial sync must explain whole-install convergence");
2439
- assert(fs.readFileSync(skill, "utf8") === "stale skill\n", "rejected partial sync must not write the skill");
2440
- }
2441
-
2442
- function testLegacyTaskPreflightRejectsWholeBatchAtomically() {
2443
- const first = tmpdir("legacy-batch-first");
2444
- const second = tmpdir("legacy-batch-second");
2445
- for (const repo of [first, second]) {
2446
- run("git", ["init", "-q"], { cwd: repo });
2447
- run("node", [cli, "init"], { cwd: repo });
2448
- run("node", [cli, "sync", "--projects", repo]);
2449
- }
2450
- const firstSkill = path.join(first, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2451
- const secondAgent = path.join(second, ".agents", "agents", "explorer.toml");
2452
- writeFile(firstSkill, "first-project-sentinel\n");
2453
- writeFile(secondAgent, `${fs.readFileSync(secondAgent, "utf8")}\n# second-project-sentinel\n`);
2454
- const secondAgentBefore = fs.readFileSync(secondAgent);
2455
- writeFile(path.join(second, ".git", "auto-coding-skill", "tasks", "T-V3.json"), JSON.stringify({ schema: 3, task_id: "T-V3", state: "active" }));
2456
-
2457
- const result = run("node", [cli, "sync", "--projects", `${first},${second}`], { check: false });
2458
- assert(result.status !== 0 && result.stderr.includes("entire sync batch"), "one legacy task should reject the complete multi-project batch");
2459
- assert(fs.readFileSync(firstSkill, "utf8") === "first-project-sentinel\n", "batch preflight must reject before writing an earlier clean project");
2460
- assert(fs.readFileSync(secondAgent).equals(secondAgentBefore), "batch preflight must not write the project containing the legacy task");
2461
- }
2462
-
2463
- function testManagedAgentsMigrationReplacesWholeFileAndArchivesPreviousRules() {
2464
- const repo = tmpdir("managed-agents-document");
2465
- run("node", [cli, "init"], { cwd: repo });
2466
- run("node", [cli, "sync", "--projects", repo]);
2467
- const agents = path.join(repo, "AGENTS.md");
2468
- const initial = fs.readFileSync(agents, "utf8");
2469
- assert(initial.includes("managed-agents:start version=4.3.7"), "new projects should receive the versioned root AGENTS block");
2470
-
2471
- const custom = [
2472
- "# Project rules",
2473
- "",
2474
- "- Preserve this repository-specific rule exactly.",
2475
- "- `high-risk` cannot be downgraded and must execute `commands.gate_full`; changed or standard fallbacks do not count. Use `PASS / FAIL / PARTIAL` only from the required executed evidence.",
2476
- "",
2477
- ].join("\n");
2478
- writeFile(agents, custom);
2479
- const legacyActiveArchive = path.join(repo, "docs", "archive", "workflow", "AGENTS.pre-4.3.1.md");
2480
- const legacyActiveArchiveBytes = Buffer.from("# Historical 4.3.1 AGENTS archive\n");
2481
- writeFile(legacyActiveArchive, legacyActiveArchiveBytes);
2482
- const dryRun = run("node", [cli, "sync", "--projects", repo, "--dry-run", "--json"]);
2483
- const plan = JSON.parse(dryRun.stdout).results[0].managedAgentsDocument;
2484
- assert(plan.state === "legacy-custom", `unmarked custom AGENTS should be migrated: ${dryRun.stdout}`);
2485
- assert(plan.migrations.includes("agents-whole-file-replacement"), "AGENTS should use the whole-file convergence migration");
2486
- const dryActions = JSON.parse(dryRun.stdout).results[0].actions;
2487
- assert(dryActions.some(item => item.action === "would-archive"), "dry-run should expose the historical AGENTS archive");
2488
-
2489
- run("node", [cli, "sync", "--projects", repo]);
2490
- const migrated = fs.readFileSync(agents, "utf8");
2491
- assert(migrated.includes("managed-agents:start version=4.3.7"), "AGENTS migration should install the current managed block");
2492
- assert(!migrated.includes("Preserve this repository-specific rule exactly."), "root AGENTS must contain no project-specific tail");
2493
- assert(!migrated.includes("must execute `commands.gate_full`"), "known official conflicting rule should be removed");
2494
- const canonical = fs.readFileSync(path.join(repoRoot, "cli", "assets", "skill", "data", "templates", "bridges", "AGENTS.md"), "utf8");
2495
- assert(migrated === canonical, "root AGENTS must be byte-identical to the packaged canonical file");
2496
- const archive = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "AGENTS.md");
2497
- assert(fs.readFileSync(archive, "utf8").includes("Preserve this repository-specific rule exactly."), "previous AGENTS content must be archived once");
2498
- assert(!exists(legacyActiveArchive), "legacy active-doc AGENTS archives must leave docs/archive during upgrade");
2499
- const migratedLegacyArchiveDir = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "archive", "workflow");
2500
- assert(
2501
- listProjectFiles(migratedLegacyArchiveDir).some(file => fs.readFileSync(file).equals(legacyActiveArchiveBytes)),
2502
- "legacy active-doc AGENTS archive bytes must survive under the managed archive root",
2503
- );
2504
- const stable = fs.readFileSync(agents);
2505
- run("node", [cli, "sync", "--projects", repo]);
2506
- assert(fs.readFileSync(agents).equals(stable), "managed AGENTS sync should be idempotent");
2507
- fillRequiredAccess(repo);
2508
- const postUpgradeStatus = JSON.parse(run("node", [cli, "status", "--projects", repo, "--json"]).stdout).results[0];
2509
- assert(postUpgradeStatus.ok === true && postUpgradeStatus.docsDiffs.length === 0, "status must be current immediately after AGENTS archive migration");
2510
- }
2511
-
2512
- function testUnknownWorkflowConflictFailsWholeBatchBeforeWrites() {
2513
- const first = tmpdir("workflow-conflict-first");
2514
- const second = tmpdir("workflow-conflict-second");
2515
- for (const repo of [first, second]) {
2516
- run("git", ["init", "-q"], { cwd: repo });
2517
- run("node", [cli, "init"], { cwd: repo });
2518
- run("node", [cli, "sync", "--projects", repo]);
2519
- }
2520
- const firstSkill = path.join(first, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2521
- writeFile(firstSkill, "batch-sentinel\n");
2522
- const secondEngineering = path.join(second, "docs", "ENGINEERING.md");
2523
- const secret = "UNIQUE_POLICY_BEARER_SECRET_4d920f7a";
2524
- fs.appendFileSync(secondEngineering, `\nHigh-risk changes must run the real full gate before push. Authorization: Bearer ${secret}\n`);
2525
-
2526
- const status = run("node", [cli, "status", "--projects", second, "--json"], { check: false });
2527
- assert(status.status !== 0, "status must be non-ok for an unknown conflicting workflow rule");
2528
- assert(!`${status.stdout}\n${status.stderr}`.includes(secret), `status must redact Bearer values from policy-conflict excerpts: ${status.stdout}\n${status.stderr}`);
2529
- const statusPlan = JSON.parse(status.stdout).results[0].managedWorkflow;
2530
- assert(statusPlan.state === "conflict", `status should expose the document conflict: ${status.stdout}`);
2531
- assert(statusPlan.conflicts[0].file === "docs/ENGINEERING.md" && statusPlan.conflicts[0].line > 0, "status conflict should include file and line");
2532
-
2533
- const launcher = path.join(second, "docs", "tools", "autopipeline", "ap.py");
2534
- const effective = run("python3", [launcher, "--repo", second, "config-effective", "--json"]);
2535
- assert(!`${effective.stdout}\n${effective.stderr}`.includes(secret), `config-effective must redact Bearer values from policy conflicts: ${effective.stdout}\n${effective.stderr}`);
2536
- const effectiveStatus = JSON.parse(effective.stdout);
2537
- assert(effectiveStatus.contract_valid === false && effectiveStatus.policy_issues.length > 0, `config-effective must retain redacted conflict diagnostics: ${effective.stdout}`);
2538
-
2539
- const sync = run("node", [cli, "sync", "--projects", `${first},${second}`], { check: false });
2540
- assert(sync.status !== 0 && sync.stderr.includes("entire sync batch before writes"), "one unknown conflict must reject the complete batch");
2541
- assert(!`${sync.stdout}\n${sync.stderr}`.includes(secret), `sync preflight must redact Bearer values from conflict diagnostics: ${sync.stdout}\n${sync.stderr}`);
2542
- assert(fs.readFileSync(firstSkill, "utf8") === "batch-sentinel\n", "batch conflict preflight must run before an earlier project's skill write");
2543
- }
2544
-
2545
- function testEngineeringMarkerBoundaryIsNormalized() {
2546
- const repo = tmpdir("engineering-marker-boundary");
2547
- run("node", [cli, "init"], { cwd: repo });
2548
- run("node", [cli, "sync", "--projects", repo]);
2549
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2550
- const marker = "<!-- auto-coding-skill:managed-workflow:end -->";
2551
- const current = fs.readFileSync(engineering, "utf8");
2552
- writeFile(engineering, current.replace(`${marker}\n`, `${marker}# Project-specific workflow\n`));
2553
- run("node", [cli, "sync", "--projects", repo]);
2554
- const normalized = fs.readFileSync(engineering, "utf8");
2555
- assert(normalized === current, "sync should restore the exact managed document when text is glued to its end marker");
2556
- assert(!normalized.includes("# Project-specific workflow"), "project workflow text must not remain in the managed default document");
2557
- const archive = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "ENGINEERING.md");
2558
- assert(fs.readFileSync(archive, "utf8").includes(`${marker}# Project-specific workflow`), "the malformed previous document must remain available in history");
2559
- }
2560
-
2561
- function testEngineeringFrameworkRejectsAnyNonCanonicalWorkflowText() {
2562
- const repo = tmpdir("engineering-framework");
2563
- run("node", [cli, "init"], { cwd: repo });
2564
- run("node", [cli, "sync", "--projects", repo]);
2565
- fillRequiredAccess(repo);
2566
- const engineering = path.join(repo, "docs", "ENGINEERING.md");
2567
- fs.appendFileSync(engineering, "\n# Project Facts\n\n## Repository boundaries\n\n- backend owns APIs.\n");
2568
- const status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
2569
- assert(status.status !== 0, "text outside the canonical ENGINEERING body must be drift");
2570
- assert(JSON.parse(status.stdout).results[0].docsDiffs.some(item => item.path === "docs/ENGINEERING.md"), "status should identify ENGINEERING convergence");
2571
-
2572
- run("node", [cli, "init"], { cwd: repo });
2573
- assert(!fs.readFileSync(engineering, "utf8").includes("backend owns APIs"), "init must restore the canonical ENGINEERING body");
2574
- const archived = path.join(repo, ".agents", "archive", "auto-coding-skill", "4.3.7", "docs", "ENGINEERING.md");
2575
- assert(fs.readFileSync(archived, "utf8").includes("backend owns APIs"), "removed project text should remain in non-authoritative history");
2576
- }
2577
-
2578
- function testManagedInstallIntegrityIsBoundedAndRepairable() {
2579
- const repo = tmpdir("managed-integrity");
2580
- const initialized = run("node", [cli, "init"], { cwd: repo });
2581
- assert(initialized.stdout.includes("verify: .agents/managed-install.json"), "init must verify managed files before reporting success");
2582
- fillRequiredAccess(repo);
2583
-
2584
- const manifestPath = path.join(repo, ".agents", "managed-install.json");
2585
- const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
2586
- assert(manifest.schema_version === 1 && manifest.skill_version === "4.3.7", "installed manifest must identify the release");
2587
- assert(manifest.entries.length > 0, "installed manifest must list managed files");
2588
- for (const entry of manifest.entries) {
2589
- assert(typeof entry.path === "string" && !path.isAbsolute(entry.path) && !entry.path.includes(".."), "manifest paths must be safe relative paths");
2590
- assert(/^[0-9a-f]{64}$/.test(entry.sha256), `${entry.path}: manifest hash must be sha256`);
2591
- assert(entry.version === "4.3.7" && typeof entry.executable === "boolean", `${entry.path}: version/executable metadata missing`);
2592
- }
2593
- assert(!manifest.managed_namespaces.some(item => item.path === ".agents" || item.path === "docs"), "manifest must not mirror entire project-owned trees");
2594
-
2595
- const customAgent = path.join(repo, ".agents", "agents", "project-specialist.toml");
2596
- const archiveNote = path.join(repo, ".agents", "archive", "owner-note.md");
2597
- const adr = path.join(repo, "docs", "architecture", "adr", "0042-project-choice.md");
2598
- writeFile(customAgent, 'name = "project-specialist"\ndescription = "project owned"\n');
2599
- writeFile(archiveNote, "historical\n");
2600
- writeFile(adr, "# ADR-0042\n\nProject owned.\n");
2601
- assertStatusOk(repo);
2602
- const launcher = path.join(repo, "docs", "tools", "autopipeline", "ap.py");
2603
- run("python3", [launcher, "--repo", repo, "doctor"]);
2604
-
2605
- const skill = path.join(repo, ".agents", "skills", "auto-coding-skill", "SKILL.md");
2606
- fs.appendFileSync(skill, "\nmanaged drift\n");
2607
- let doctor = run("python3", [launcher, "--repo", repo, "doctor"], { check: false });
2608
- assert(doctor.status !== 0 && `${doctor.stdout}\n${doctor.stderr}`.includes("SKILL.md: managed content drift"), "doctor must identify managed Skill drift");
2609
- run("node", [cli, "init"], { cwd: repo });
2610
-
2611
- const extraSkill = path.join(repo, ".agents", "skills", "auto-coding-skill", "obsolete.txt");
2612
- writeFile(extraSkill, "obsolete\n");
2613
- let status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
2614
- let parsed = JSON.parse(status.stdout).results[0];
2615
- assert(status.status !== 0 && parsed.installIntegrity.errors.some(item => item.includes("unexpected file in managed namespace")), "status must reject extras in the exact Skill namespace");
2616
- run("node", [cli, "init"], { cwd: repo });
2617
-
2618
- const oldRuntime = path.join(repo, "docs", "tools", "autopipeline", "core.py");
2619
- writeFile(oldRuntime, "# obsolete project runtime copy\n");
2620
- status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
2621
- parsed = JSON.parse(status.stdout).results[0];
2622
- assert(status.status !== 0 && parsed.installIntegrity.errors.some(item => item.includes("docs/tools/autopipeline/core.py")), "launcher namespace extras must be drift");
2623
- run("node", [cli, "init"], { cwd: repo });
2624
- assert(!exists(oldRuntime), "init must clean obsolete files from the exact launcher namespace");
2625
-
2626
- if (process.platform !== "win32") {
2627
- const core = path.join(repo, ".agents", "skills", "auto-coding-skill", "scripts", "core.py");
2628
- fs.chmodSync(core, fs.statSync(core).mode & ~0o111);
2629
- status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
2630
- parsed = JSON.parse(status.stdout).results[0];
2631
- assert(status.status !== 0 && parsed.installIntegrity.errors.some(item => item.includes("core.py: executable bit drift")), "status must detect executable-bit drift");
2632
- run("node", [cli, "init"], { cwd: repo });
2633
- assert((fs.statSync(core).mode & 0o111) !== 0, "init must restore the declared executable bit");
2634
- }
2635
-
2636
- const explorer = path.join(repo, ".agents", "agents", "explorer.toml");
2637
- writeFile(explorer, fs.readFileSync(explorer, "utf8").replace(/^description\s*=.*$/m, '$&\nmodel = "vendor/project-model"'));
2638
- assertStatusOk(repo);
2639
- writeFile(explorer, fs.readFileSync(explorer, "utf8").replace('model = "vendor/project-model"', "model = []"));
2640
- doctor = run("python3", [launcher, "--repo", repo, "doctor"], { check: false });
2641
- assert(doctor.status !== 0 && `${doctor.stdout}\n${doctor.stderr}`.includes("model must be a non-empty TOML string"), "doctor must reject invalid normalized-agent overrides");
2642
- run("node", [cli, "init"], { cwd: repo });
2643
-
2644
- const staleManifest = JSON.parse(fs.readFileSync(manifestPath, "utf8"));
2645
- staleManifest.skill_version = "0.0.0";
2646
- writeFile(manifestPath, `${JSON.stringify(staleManifest)}\n`);
2647
- status = run("node", [cli, "status", "--projects", repo, "--json"], { check: false });
2648
- parsed = JSON.parse(status.stdout).results[0];
2649
- assert(status.status !== 0 && parsed.installManifestDiffs.some(item => item.status === "stale"), "status must compare the local manifest with the release manifest");
2650
- doctor = run("python3", [launcher, "--repo", repo, "doctor"], { check: false });
2651
- assert(doctor.status !== 0 && `${doctor.stdout}\n${doctor.stderr}`.includes("manifest version"), "doctor must reject a mismatched local manifest");
2652
- run("node", [cli, "init"], { cwd: repo });
2653
-
2654
- assert(fs.readFileSync(customAgent, "utf8").includes("project owned"), "init must preserve project-owned custom agents");
2655
- assert(fs.readFileSync(archiveNote, "utf8") === "historical\n", "init must preserve archives untouched");
2656
- assert(fs.readFileSync(adr, "utf8").includes("Project owned"), "init must preserve project-owned documents");
2657
- assertStatusOk(repo);
2658
- }
2659
-
2660
- function testSkillFeedbackCollectionIsBoundedReadOnlyAndMetadataOnly() {
2661
- const first = tmpdir("feedback-collect-first");
2662
- const second = tmpdir("feedback-collect-second");
2663
- const third = tmpdir("feedback-collect-empty");
2664
- run("node", [cli, "init"], { cwd: first });
2665
- run("node", [cli, "init"], { cwd: second });
2666
- run("node", [cli, "init"], { cwd: third });
2667
- const emptyStatus = JSON.parse(
2668
- run("node", [cli, "status", "--projects", third, "--json"], { check: false }).stdout,
2669
- ).results[0];
2670
- assert(emptyStatus.feedback.available === true, "status must expose feedback before the first report");
2671
- assert(emptyStatus.feedback.skillVersion === "4.3.7", "empty feedback status must expose the installed Skill version");
2672
- const signature = `sha256:${"a".repeat(64)}`;
2673
- const marker = path.join(os.tmpdir(), `autocoding-feedback-must-not-execute-${crypto.randomUUID()}`);
2674
- const render = (project, reportId, privateMarker) => [
2675
- "---",
2676
- "schema: auto-coding-skill-feedback/v1",
2677
- `report_id: ${reportId}`,
2678
- "status: open",
2679
- 'created_at: "2026-07-18T10:00:00+08:00"',
2680
- `project: ${project}`,
2681
- "observed_skill_version: 4.3.7",
2682
- "component: reviewer-runtime",
2683
- "kind: defect",
2684
- "impact: blocking",
2685
- "origin_surface: managed-script",
2686
- "suspected_scope: shared",
2687
- `signature: ${signature}`,
2688
- "export: metadata-only",
2689
- "---",
2690
- "# Reviewer runtime stalls",
2691
- "",
2692
- "## Symptom",
2693
- `${privateMarker}; $(touch ${marker})`,
2694
- "",
2695
- "## Expected",
2696
- "The managed runtime must return before its deadline.",
2697
- "",
2698
- "## Minimal reproduction",
2699
- "Use a synthetic read-only assignment.",
2700
- "",
2701
- "## Evidence",
2702
- "The bounded local fixture reproduced the timeout.",
2703
- "",
2704
- "## Workaround",
2705
- "Use the explicit runtime override only with user authorization.",
2706
- "",
2707
- "## Why shared",
2708
- "Managed runtime behavior reproduces outside project configuration.",
2709
- "",
2710
- ].join("\n");
2711
- const renderV2 = (project, reportId, privateMarker, options) => render(project, reportId, privateMarker)
2712
- .replace("schema: auto-coding-skill-feedback/v1", "schema: auto-coding-skill-feedback/v2")
2713
- .replace("status: open", `status: ${options.status ?? "open"}`)
2714
- .replace('created_at: "2026-07-18T10:00:00+08:00"', 'created_at: "2026-07-18T10:00:00+08:00"\nupdated_at: "2026-07-19T10:00:00+08:00"')
2715
- .replace("observed_skill_version: 4.3.7", `observed_skill_version: ${options.observed ?? "4.3.7"}\nlast_verified_skill_version: ${options.lastVerified ?? options.observed ?? "4.3.7"}`)
2716
- .replace(signature, options.signature)
2717
- .replace("export: metadata-only", `resolution: ${options.resolution ?? "pending"}\nexport: metadata-only`);
2718
- const firstReport = path.join(first, "docs", "skill-feedback", "reports", "2026-07-18-review-timeout-a13f82c1.md");
2719
- const firstOtherReport = path.join(first, "docs", "skill-feedback", "reports", "2026-07-18-installer-gap-c35fa4e3.md");
2720
- const secondReport = path.join(second, "docs", "skill-feedback", "reports", "2026-07-18-review-timeout-b24f93d2.md");
2721
- const closedReport = path.join(third, "docs", "skill-feedback", "reports", "2026-07-18-resolved-gap-d45fa4e3.md");
2722
- const fixedReport = path.join(first, "docs", "skill-feedback", "reports", "2026-07-18-project-assets-fd5748e4.md");
2723
- const rerouteReport = path.join(third, "docs", "skill-feedback", "reports", "2026-07-18-project-policy-a5eeb5eb.md");
2724
- const firstContent = render(path.basename(first), "ACSF-geesight-20260718-a13f82c1", "PRIVATE-BODY-FIRST");
2725
- const firstOtherContent = render(path.basename(first), "ACSF-geesight-20260718-c35fa4e3", "PRIVATE-BODY-OTHER")
2726
- .replaceAll(signature, `sha256:${"b".repeat(64)}`);
2727
- const secondContent = render(path.basename(second), "ACSF-xjmate-20260718-b24f93d2", "PRIVATE-BODY-SECOND");
2728
- const closedContent = render(path.basename(third), "ACSF-closed-20260718-d45fa4e3", "PRIVATE-BODY-CLOSED")
2729
- .replace("status: open", "status: resolved")
2730
- .replaceAll(signature, `sha256:${"d".repeat(64)}`);
2731
- const fixedContent = renderV2(path.basename(first), "ACSF-assets-20260718-fd5748e4", "PRIVATE-BODY-FIXED", {
2732
- signature: "sha256:fd5748e4ae40e9f86762c4f62b3302bbbb2b8ae9661adf9e0e07a2327ccf7a36",
2733
- observed: "4.3.0",
2734
- lastVerified: "4.3.0",
2735
- });
2736
- const rerouteContent = renderV2(path.basename(third), "ACSF-policy-20260718-a5eeb5eb", "PRIVATE-BODY-REROUTE", {
2737
- signature: "sha256:a5eeb5eb0ef5073dbeec726fa6c2016593b43eb1230171e3028f364c5b07bd86",
2738
- });
2739
- writeFile(firstReport, firstContent);
2740
- writeFile(firstOtherReport, firstOtherContent);
2741
- writeFile(secondReport, secondContent);
2742
- writeFile(closedReport, closedContent);
2743
- writeFile(fixedReport, fixedContent);
2744
- writeFile(rerouteReport, rerouteContent);
2745
-
2746
- const collected = run("node", [cli, "feedback", "--projects", `${first},${second},${third}`, "--json"]);
2747
- const result = JSON.parse(collected.stdout);
2748
- assert(result.schema === "auto-coding-skill-feedback-collection/v2", "feedback collection must identify its active-only grouping schema");
2749
- assert(result.report_count === 6 && result.active_report_count === 3 && result.groups.length === 2, "feedback collection must group only current active reports");
2750
- assert(result.closed_report_count === 1 && result.lifecycle_counts.closed === 1, "closed v1 feedback must remain readable but leave active grouping");
2751
- assert(result.action_required_count === 2, `catalog resolutions must produce bounded project actions: ${collected.stdout}`);
2752
- const fixedAction = result.action_required.find(item => item.report_id === "ACSF-assets-20260718-fd5748e4");
2753
- assert(fixedAction?.lifecycle === "verification-due" && fixedAction.recommended_action.includes("verify-fix"), "a project at the fixed release must verify and close its old report");
2754
- const rerouteAction = result.action_required.find(item => item.report_id === "ACSF-policy-20260718-a5eeb5eb");
2755
- assert(rerouteAction?.lifecycle === "reroute-due" && rerouteAction.recommended_action.includes("docs/project/auto-coding-skill.yaml"), "project preferences must route to the project overlay");
2756
- const statusWithFeedback = run("node", [cli, "status", "--projects", first, "--json"], { check: false });
2757
- const statusFeedback = JSON.parse(statusWithFeedback.stdout).results[0].feedback;
2758
- assert(statusFeedback.available === true && statusFeedback.actionRequiredCount >= 1, "status must surface feedback maintenance without making it installation drift");
2759
- assert(result.projects.length === 3 && result.projects.every(item => item.source_project && item.project), "feedback collection must retain every explicit initialized project, including one with no reports");
2760
- const sharedGroup = result.groups.find(item => item.signature === signature);
2761
- assert(sharedGroup?.cross_project === true && sharedGroup.project_count === 2, "same signature from two explicit roots must be cross-project");
2762
- const localGroup = result.groups.find(item => item.signature === `sha256:${"b".repeat(64)}`);
2763
- assert(localGroup?.cross_project === false && localGroup.project_count === 1, "a separate one-project signature must remain a local candidate group");
2764
- const rawReportDigests = [firstContent, firstOtherContent, secondContent, closedContent, fixedContent, rerouteContent]
2765
- .map(content => crypto.createHash("sha256").update(content).digest("hex"));
2766
- assert(result.metadata.every(item => !("content_sha256" in item) && item.size_bytes > 0), "feedback metadata must not export a hash oracle over private report bodies");
2767
- assert(rawReportDigests.every(digest => !collected.stdout.includes(digest)), "collector output must not expose raw report body digests");
2768
- assert(!collected.stdout.includes("PRIVATE-BODY") && !collected.stdout.includes("touch"), "collector output must never include report bodies");
2769
- assert(!collected.stdout.includes(first) && !collected.stdout.includes(second) && !collected.stdout.includes(third), "collector output must not expose absolute project roots");
2770
- assert(!exists(marker), "collector must never execute report content");
2771
- assert(fs.readFileSync(firstReport, "utf8") === firstContent && fs.readFileSync(firstOtherReport, "utf8") === firstOtherContent && fs.readFileSync(secondReport, "utf8") === secondContent, "collection must not modify reports");
2772
- assert(fs.readFileSync(closedReport, "utf8") === closedContent && fs.readFileSync(fixedReport, "utf8") === fixedContent && fs.readFileSync(rerouteReport, "utf8") === rerouteContent, "lifecycle collection must preserve every project-owned report byte-for-byte");
2773
-
2774
- writeFile(fixedReport, fixedContent.replace("last_verified_skill_version: 4.3.0", "last_verified_skill_version: 4.3.3"));
2775
- let lifecycleCheck = JSON.parse(run("node", [cli, "feedback", "--projects", first, "--json"]).stdout);
2776
- assert(lifecycleCheck.metadata.find(item => item.report_id === "ACSF-assets-20260718-fd5748e4")?.lifecycle === "regression-current", "a fixed signature reproduced on the fixed release must re-enter active triage as a regression");
2777
- writeFile(fixedReport, fixedContent);
2778
-
2779
- writeFile(firstOtherReport, firstOtherContent.replace("observed_skill_version: 4.3.7", "observed_skill_version: 4.2.8"));
2780
- lifecycleCheck = JSON.parse(run("node", [cli, "feedback", "--projects", first, "--json"]).stdout);
2781
- assert(lifecycleCheck.metadata.find(item => item.report_id === "ACSF-geesight-20260718-c35fa4e3")?.lifecycle === "recheck-due", "an unresolved v1 report from an older Skill version must require recheck");
2782
- writeFile(firstOtherReport, firstOtherContent);
2783
-
2784
- writeFile(secondReport, render("spoofed-project", "ACSF-xjmate-20260718-b24f93d2", "PRIVATE-BODY-SECOND"));
2785
- const spoofed = run("node", [cli, "feedback", "--projects", second, "--json"], { check: false });
2786
- assert(spoofed.status !== 0 && spoofed.stderr.includes("project must equal") && spoofed.stderr.includes("project.name"), "collector must bind report project identity to effective project configuration");
2787
- writeFile(secondReport, secondContent);
2788
-
2789
- const secondOverlay = projectConfigPath(second);
2790
- const secondOverlayContent = fs.readFileSync(secondOverlay);
2791
- const secondOverrides = readYamlConfig(secondOverlay).overrides;
2792
- writeProjectConfig(second, {
2793
- ...secondOverrides,
2794
- project: { ...(secondOverrides.project ?? {}), name: path.basename(first) },
2795
- });
2796
- writeFile(secondReport, render(path.basename(first), "ACSF-xjmate-20260718-b24f93d2", "PRIVATE-BODY-SECOND"));
2797
- const duplicateIdentity = run("node", [cli, "feedback", "--projects", `${first},${second}`, "--json"], { check: false });
2798
- assert(duplicateIdentity.status !== 0 && duplicateIdentity.stderr.includes("distinct") && duplicateIdentity.stderr.includes("project.name"), "collector must not count two roots declaring one effective project identity as cross-project evidence");
2799
- fs.writeFileSync(secondOverlay, secondOverlayContent);
2800
- writeFile(secondReport, secondContent);
2801
-
2802
- const firstOverlay = projectConfigPath(first);
2803
- const firstOverlayContent = fs.readFileSync(firstOverlay);
2804
- fs.writeFileSync(firstOverlay, Buffer.alloc(128 * 1024 + 1, "a"));
2805
- const oversizedConfig = run("node", [cli, "feedback", "--projects", first, "--json"], { check: false });
2806
- assert(oversizedConfig.status !== 0 && oversizedConfig.stderr.includes("size limit"), "collector must bound project overlay reads");
2807
- fs.writeFileSync(firstOverlay, firstOverlayContent);
2808
-
2809
- const implicit = run("node", [cli, "feedback", first, "--json"], { check: false });
2810
- assert(implicit.status !== 0 && implicit.stderr.includes("requires explicit --projects"), "feedback collection must reject implicit or positional project scope");
2811
-
2812
- if (process.platform !== "win32") {
2813
- const linked = path.join(first, "docs", "skill-feedback", "reports", "2026-07-18-linked-report-deadbeef.md");
2814
- fs.symlinkSync(secondReport, linked);
2815
- const unsafe = run("node", [cli, "feedback", "--projects", first, "--json"], { check: false });
2816
- assert(unsafe.status !== 0 && unsafe.stderr.includes("regular non-symlink file"), "collector must reject feedback symlinks without following them");
2817
-
2818
- fs.rmSync(path.join(first, "docs", "skill-feedback"), { recursive: true, force: true });
2819
- const externalFeedback = tmpdir("feedback-collector-parent-external");
2820
- fs.mkdirSync(path.join(externalFeedback, "reports"), { recursive: true });
2821
- writeFile(path.join(externalFeedback, "reports", path.basename(firstReport)), firstContent);
2822
- fs.symlinkSync(externalFeedback, path.join(first, "docs", "skill-feedback"));
2823
- const unsafeParent = run("node", [cli, "feedback", "--projects", first, "--json"], { check: false });
2824
- assert(unsafeParent.status !== 0 && unsafeParent.stderr.includes("real directory"), "collector must reject a symlink in the feedback parent chain");
2825
- }
2826
- }
2827
-
2828
- function testReleaseVersionMarkersStayInSync() {
2829
- const expected = "4.3.7";
2830
- const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
2831
- const lock = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8"));
2832
- const policy = JSON.parse(fs.readFileSync(
2833
- path.join(repoRoot, "src", "auto-coding-skill", "data", "policies", "workflow-migrations-v1.json"),
2834
- "utf8",
2835
- ));
2836
- assert(pkg.version === expected, "package version must match the 4.3.7 release");
2837
- assert(lock.version === expected && lock.packages[""].version === expected, "package-lock versions must match");
2838
- assert(policy.managed_versions.engineering === expected && policy.managed_versions.agents === expected, "managed workflow versions must match");
2839
- const manifest = JSON.parse(fs.readFileSync(path.join(repoRoot, "cli", "assets", "managed-install.json"), "utf8"));
2840
- assert(manifest.skill_version === expected && manifest.schema_version === 1, "managed install manifest version/schema must match");
2841
- assert(manifest.entries.every(entry => entry.version === expected && /^[0-9a-f]{64}$/.test(entry.sha256)), "managed install entries must carry release hashes and versions");
2842
- assert(manifest.entries.find(entry => entry.path === "docs/ENGINEERING.md")?.ownership === "exact", "managed ENGINEERING must be installed as an exact default layer");
2843
- assert(!manifest.entries.some(entry => entry.path === "docs/architecture/structure-standard.md"), "project structure standard must not be exact-managed");
2844
- assert(manifest.preserved.includes("docs/architecture/structure-standard.md"), "manifest must declare the project structure standard preserved");
2845
- assert(manifest.entries.some(entry => entry.path === "docs/skill-feedback/README.md"), "feedback README must be exact-managed");
2846
- assert(manifest.entries.some(entry => entry.path === "docs/skill-feedback/_TEMPLATE-SKILL-FEEDBACK.md"), "feedback template must be exact-managed");
2847
- assert(manifest.entries.some(entry => entry.path === ".agents/skills/auto-coding-skill/data/policies/feedback-resolutions-v1.json"), "feedback resolution catalog must be exact-managed");
2848
- assert(manifest.preserved.includes("docs/skill-feedback/reports/*.md"), "manifest must declare project feedback reports preserved");
2849
- assert(!manifest.managed_namespaces.some(item => item.path === "docs/skill-feedback"), "project feedback reports must stay outside managed namespaces");
2850
- assert(manifest.preserved.includes("docs/project/auto-coding-skill.yaml"), "manifest must declare the project configuration overlay preserved");
2851
- assert(!manifest.entries.some(entry => entry.path === "docs/project/auto-coding-skill.yaml"), "project configuration overlay must never be exact-managed");
2852
- assert(!manifest.managed_namespaces.some(item => item.path === "docs/project"), "project configuration overlay must stay outside managed namespaces");
2853
- for (const root of ["architecture", "bugs", "deployment", "design", "interfaces", "project", "reviews", "testing"]) {
2854
- assert(manifest.preserved.includes(`docs/${root}/** (except exact-managed entries)`), `manifest must preserve recursive project-owned ${root} assets`);
2855
- }
2856
- const resolutionCatalog = JSON.parse(fs.readFileSync(
2857
- path.join(repoRoot, "src", "auto-coding-skill", "data", "policies", "feedback-resolutions-v1.json"),
2858
- "utf8",
2859
- ));
2860
- assert(resolutionCatalog.schema === "auto-coding-skill-feedback-resolutions/v1", "feedback resolution catalog schema must be stable");
2861
- const resolutionSignatures = resolutionCatalog.entries.map(item => item.signature);
2862
- assert(JSON.stringify(resolutionSignatures) === JSON.stringify([...new Set(resolutionSignatures)].sort()), "feedback resolution signatures must be unique and sorted");
2863
- assert(resolutionCatalog.entries.every(item => /^\d+\.\d+\.\d+$/.test(item.effective_skill_version)), "feedback resolution releases must be stable SemVer");
2864
- const publishWorkflow = fs.readFileSync(path.join(repoRoot, ".github", "workflows", "npm-publish.yml"), "utf8");
2865
- const runtimeRequirements = fs.readFileSync(path.join(repoRoot, "src", "auto-coding-skill", "requirements.txt"), "utf8");
2866
- assert(publishWorkflow.includes("tags:\n - \"v*\""), "npm publish must run from version tag pushes");
2867
- assert(publishWorkflow.includes("actions/setup-python@v6") && publishWorkflow.includes("src/auto-coding-skill/requirements.txt"), "npm publish must install the pinned Python runtime before verification");
2868
- assert(publishWorkflow.includes("NPM_TOKEN_AVAILABLE") && publishWorkflow.includes("Require external publication"), "npm publish must support local-token publication when no GitHub secret exists");
2869
- assert(runtimeRequirements.trim() === "PyYAML==6.0.3", "the runtime must have one pinned third-party dependency");
2870
- assert(!runtimeRequirements.toLowerCase().includes("requests"), "HTTP checks must stay on the Python standard library");
2871
- assert(publishWorkflow.includes("Verify release identity"), "npm publish must bind the tag to package version");
2872
- assert(publishWorkflow.includes("Check npm registry") && publishWorkflow.includes("Verify npm publication"), "npm publish must be idempotent and registry-verified");
2873
- for (const rel of [
2874
- "src/auto-coding-skill/data/templates/ENGINEERING.md",
2875
- "src/auto-coding-skill/data/templates/bridges/AGENTS.md",
2876
- "cli/assets/skill/data/templates/ENGINEERING.md",
2877
- "cli/assets/skill/data/templates/bridges/AGENTS.md",
2878
- ]) {
2879
- assert(fs.readFileSync(path.join(repoRoot, rel), "utf8").includes(`version=${expected}`), `${rel}: missing ${expected} marker`);
2880
- }
2881
- }
2882
-
2883
- function testProtocolResponsibilitiesStaySeparated() {
2884
- const skill = fs.readFileSync(path.join(repoRoot, "src", "auto-coding-skill", "SKILL.md"), "utf8");
2885
- const agents = fs.readFileSync(path.join(repoRoot, "src", "auto-coding-skill", "data", "templates", "bridges", "AGENTS.md"), "utf8");
2886
- const engineering = fs.readFileSync(path.join(repoRoot, "src", "auto-coding-skill", "data", "templates", "ENGINEERING.md"), "utf8");
2887
- const totalLines = [skill, agents, engineering].reduce((sum, text) => sum + text.split(/\r?\n/).length, 0);
2888
- // The project-overlay ownership boundary adds a small, measured protocol
2889
- // contract without adding another workflow document.
2890
- assert(totalLines <= 370, `shared protocol context budget exceeded: ${totalLines} lines`);
2891
- assert(agents.includes("## Minimum mechanism budget") && agents.includes("## Bounded real validation"), "AGENTS must remain the behavioral protocol");
2892
- assert(skill.includes("## Select the minimum mechanism set") && !skill.includes("## Authority"), "SKILL must remain invocation guidance");
2893
- assert(engineering.includes("The frontmatter contract is:") && !engineering.includes("## Git and parallel work"), "ENGINEERING must remain project configuration/facts");
2894
- assert(engineering.includes("docs/project/auto-coding-skill.yaml") && engineering.includes("project overlay"), "ENGINEERING must direct project specialization to the preserved overlay");
2895
- assert(engineering.includes("owns this document byte-for-byte"), "ENGINEERING must identify itself as the managed default layer");
2896
- assert(!engineering.includes("advisory architecture and no-new-debt policy"), "ENGINEERING policy summary must not hard-code template defaults");
2897
- }
2898
-
2899
- testInitFullyConvergesExistingProject();
2900
- testStructureBlockWarningsDefaultsPreserveAndConverge();
2901
- testProjectDocumentationSpecialFilesFailBeforeWrites();
2902
- testManagedPolicySummaryPreservesProjectConfiguration();
2903
- testInitRejectsMissingPythonRuntimeBeforeWrites();
2904
- testDestVariants();
2905
- testLauncherFallsBackToGlobalRuntime();
2906
- testMinimalInitConvergesWithinBudget();
2907
- testSkillFeedbackTemplatesAndReportsSurviveSync();
2908
- testStatusRejectsLegacyIsolation();
2909
- testStatusRejectsLegacyGateEscalation();
2910
- testStatusAcceptsValidIndentlessYamlRoutes();
2911
- testOrdinaryNodeTestIsNotPromotedToAutomaticGate();
2912
- testAccessPasswordsAreRequiredButNeverPrintedByStatus();
2913
- testProjectConfigOverlayMigratesLegacyEngineeringAndStaysByteStable();
2914
- testProjectConfigOverlayMergeKeepsExplicitFalseZeroEmptyAndList();
2915
- testOversizedLegacyMigrationFailsBeforeCreatingAnInvalidOverlay();
2916
- testInvalidProjectConfigOverlayFailsBeforeAnyWrites();
2917
- testStatusRejectsManagedAgentSymlinksWithoutLeakingExternalContent();
2918
- testMultiProjectSyncRejectsManagedTargetSymlinksBeforeAnyProjectWrite();
2919
- testTamperedInstalledDefaultRejectsInitAndSyncWithoutWrites();
2920
- testExistingOverlayConflictRejectsInitAndSyncWithoutWrites();
2921
- testExistingOverlayLegacyDeletionRejectsInitAndSyncWithoutWrites();
2922
- testLiveInstallTransactionRejectsSecondInstallerWithoutWrites();
2923
- testStagedRuntimeTamperingIsRejectedBeforeExecution();
2924
- testInterruptedStagedInstallRecoversForInitAndSync();
2925
- testArchiveFallbackCollisionsNeverLosePreviousContent();
2926
- testProjectMutationAndInstallSwitchRejectParentSwap();
2927
- testNoChangeLightGateRejectsInvalidEffectiveContracts();
2928
- testStatusRejectsInvalidStructureEnforcementFromDoctorContract();
2929
- testProjectConfigOverlayIsHighRiskAndReviewRequired();
2930
- testStatusAndFeedbackUseEffectiveProjectConfigWithoutLeakingAccess();
2931
- testManagedAgentModelsInheritAndOverridesSurvive();
2932
- testForcePreservesCustomAgentsAndModelOverrides();
2933
- testInvalidManagedAgentModelsFailStatusAndAreDroppedOnSync();
2934
- testModelTextInsideInstructionsIsNotPromotedToOverride();
2935
- testCommandSpecificArgumentsAreRejectedBeforeWrites();
2936
- testBridgeIsGeneric();
2937
- testSyncCleansAllManagedSkillExtras();
2938
- testOptionalDocsAndLegacyToolsDoNotCauseDrift();
2939
- testOptionalScaffoldIsOnDemandAndIdempotent();
2940
- testTestingScaffoldMatchesCheckMatrixSchema();
2941
- testReviewScaffoldLeavesBaselineGenerationToBaselineCommand();
2942
- testBaselineUpdateConfigWritesOnlyProjectOverlay();
2943
- testSyncUsesPackagedAssetsAndIgnoresRetiredTemplates();
2944
- testInitInitializesNewEngineeringDefaults();
2945
- testInitMigratesLegacyAutomaticGateToFastDefault();
2946
- testRemovedVerificationFlagsFailFast();
2947
- testInstallBootstrapsRuntimeRequiredByLauncher();
2948
- testCliInstallArchivesFeedbackTemplatesAndPreservesReports();
2949
- testLegacyUpgradeWriteFailsWithoutAnyWrites();
2950
- testLedgerArchiveRecognizesSettledStatuses();
2951
- testLedgerArchiveUpdatesExistingPeriodIndex();
2952
- testManagedEngineeringInitIsAuthoritativeAndIdempotent();
2953
- testLegacyEngineeringMigrationPreservesExistingBody();
2954
- testOfficialLegacyEngineeringBodyIsReplacedWithoutDuplication();
2955
- testMalformedManagedMarkersFailClosed();
2956
- testPartialSkillSyncIsRejectedWithoutWrites();
2957
- testLegacyTaskPreflightRejectsWholeBatchAtomically();
2958
- testManagedAgentsMigrationReplacesWholeFileAndArchivesPreviousRules();
2959
- testUnknownWorkflowConflictFailsWholeBatchBeforeWrites();
2960
- testEngineeringMarkerBoundaryIsNormalized();
2961
- testEngineeringFrameworkRejectsAnyNonCanonicalWorkflowText();
2962
- testManagedInstallIntegrityIsBoundedAndRepairable();
2963
- testSkillFeedbackCollectionIsBoundedReadOnlyAndMetadataOnly();
2964
- testReleaseVersionMarkersStayInSync();
2965
- testProtocolResponsibilitiesStaySeparated();
2966
-
2967
- console.log("cli-installer-regression-ok");