-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsdlc.ts
More file actions
357 lines (325 loc) · 12.5 KB
/
Copy pathsdlc.ts
File metadata and controls
357 lines (325 loc) · 12.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
#!/usr/bin/env bun
import { spawnSync } from "node:child_process";
import { existsSync, readdirSync, statSync } from "node:fs";
import { basename, dirname, join, relative, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
import {
hasBlocker,
hasLinkTo,
isConcrete,
labelValue,
linkTargets,
parseArtifact,
type Artifact,
} from "./artifact-parse";
import {
bundleIsImplementationReady,
discoverStageBundles,
isCanonicalStagePath,
planCoversPath,
validateLocalLinks,
validateCleanup,
validateStageBundle,
type StageBundle,
} from "./stage-bundle";
export const REQUIRED_FILES = [
".agents/skills/codetwo-develop/SKILL.md",
".agents/skills/codetwo-develop/references/workflow.md",
".agents/skills/codetwo-develop/templates/intent.md",
".agents/skills/codetwo-develop/templates/spec.md",
".agents/skills/codetwo-develop/templates/plan.md",
".agents/skills/codetwo-develop/templates/verification.md",
".agents/skills/codetwo-develop/templates/eval.md",
".agents/skills/codetwo-release/SKILL.md",
".agents/skills/codetwo-operations/SKILL.md",
".agents/skills/codetwo-operations/templates/incident.md",
] as const;
const LEGACY_PATHS = [
"docs/superpowers",
"docs/sdlc/specs",
"docs/sdlc/plans",
"docs/sdlc/changes/2026-08-29-sdlc-bootstrap.md",
"docs/sdlc/evals/legacy-workflow-single-source.md",
] as const;
const ALLOWED_EVAL_STATUSES = new Set(["draft", "active", "blocked", "failed", "retired"]);
const ALLOWED_INCIDENT_STATUSES = new Set([
"draft",
"investigating",
"mitigated",
"blocked",
"resolved",
"closed",
"superseded",
]);
function repoPath(root: string, path: string): string {
return relative(root, path).split(sep).join("/");
}
function markdownFiles(root: string): string[] {
if (!existsSync(root)) return [];
const files: string[] = [];
for (const entry of readdirSync(root)) {
const path = join(root, entry);
if (statSync(path).isDirectory()) files.push(...markdownFiles(path));
else if (entry.endsWith(".md")) files.push(path);
}
return files.sort();
}
function validateEval(artifact: Artifact, path: string): string[] {
const errors: string[] = [];
const status = artifact.metadata.status ?? "";
if (!ALLOWED_EVAL_STATUSES.has(status)) {
errors.push(`${path}: invalid eval status ${JSON.stringify(status)}`);
}
if (new Set(["active", "failed", "retired"]).has(status)) {
if (linkTargets(artifact.sections.provenance ?? "").length === 0) {
errors.push(`${path}: status ${status} requires linked provenance`);
}
const result = (labelValue(artifact.sections["last result"] ?? "", "Result") ?? "")
.toLowerCase()
.replace(/\.$/, "");
if (!new Set(["pass", "fail", "blocked"]).has(result)) {
errors.push(`${path}: status ${status} requires Result pass, fail, or blocked`);
}
if (!isConcrete(labelValue(artifact.sections["last result"] ?? "", "Revision"))) {
errors.push(`${path}: status ${status} requires Revision`);
}
}
return errors;
}
function validateIncident(artifact: Artifact, path: string): string[] {
const errors: string[] = [];
const status = artifact.metadata.status ?? "";
if (!ALLOWED_INCIDENT_STATUSES.has(status)) {
errors.push(`${path}: invalid incident status ${JSON.stringify(status)}`);
}
if (status !== "resolved" && status !== "closed") return errors;
const recovery = artifact.sections["mitigation and recovery"] ?? "";
if ((labelValue(recovery, "Recovery verdict") ?? "").toLowerCase().replace(/\.$/, "") !== "recovered") {
errors.push(`${path}: status ${status} requires Recovery verdict: recovered`);
}
const followUps = artifact.sections["follow-ups"] ?? "";
if (!hasLinkTo(followUps, "/changes/") && !hasBlocker(followUps)) {
errors.push(`${path}: status ${status} requires linked follow-up change or Blocked reason`);
}
const regression = artifact.sections["regression eval"] ?? "";
if (!hasLinkTo(regression, "/evals/") && !hasBlocker(regression)) {
errors.push(`${path}: status ${status} requires linked regression Eval or Blocked reason`);
}
return errors;
}
interface ChangedPath {
status: string;
paths: string[];
}
function parseChangedPaths(output: string): ChangedPath[] {
return output
.split(/\r?\n/)
.filter(Boolean)
.map((line) => {
const [status, ...paths] = line.split("\t");
return { status, paths };
})
.filter((change) => change.paths.length > 0);
}
function gateChangedPaths(changes: ChangedPath[]): string[] {
// Deletions and both sides of renames require approval just like additions.
return changes.flatMap((change) => change.paths);
}
function changedPaths(
root: string,
base: string | undefined,
worktree: boolean,
): { changes: ChangedPath[]; errors: string[] } {
const comparison = worktree ? "HEAD" : `${base}...HEAD`;
const result = spawnSync("git", ["diff", "--name-status", "--find-renames", comparison], {
cwd: root,
encoding: "utf8",
});
if (result.status !== 0) {
const detail = result.stderr.trim() || result.stdout.trim() || "git diff failed";
return { changes: [], errors: [`cannot compare changes: ${detail}`] };
}
const changes = parseChangedPaths(result.stdout);
if (worktree) {
const untracked = spawnSync("git", ["ls-files", "--others", "--exclude-standard"], {
cwd: root,
encoding: "utf8",
});
if (untracked.status !== 0) {
return { changes: [], errors: ["cannot list untracked worktree files"] };
}
for (const path of untracked.stdout.split(/\r?\n/).filter(Boolean)) {
changes.push({ status: "A", paths: [path] });
}
}
return { changes, errors: [] };
}
function validateChangedArtifactGate(
root: string,
base: string | undefined,
worktree: boolean,
bundles: Map<string, StageBundle>,
ready = false,
): string[] {
const { changes, errors } = changedPaths(root, base, worktree);
if (errors.length > 0 || changes.length === 0) return errors;
const changed = new Set(gateChangedPaths(changes));
const changedBundleIds = new Set(
Array.from(changed)
.filter(isCanonicalStagePath)
.map((path) => path.match(/^docs\/sdlc\/changes\/([^/]+)\//)?.[1])
.filter(Boolean) as string[],
);
for (const id of changedBundleIds) {
const bundle = bundles.get(id);
if (bundle?.intent.metadata.schema === "5" && bundle.verification && bundle.verification.metadata.cleanup_status === undefined) {
errors.push(...validateCleanup(bundle.verification, true));
}
}
if (errors.length > 0) return errors;
if (ready) {
for (const id of changedBundleIds) {
const bundle = bundles.get(id);
if (bundle && (!bundleIsImplementationReady(bundle) || bundle.verification?.metadata.status !== "passed")) {
return [`${id}: Ready PR requires accepted intent/design and verification passed`];
}
}
}
const readyBundles = Array.from(bundles.values()).filter(
(bundle) => changedBundleIds.has(bundle.id) && bundleIsImplementationReady(bundle),
);
const nonStageChanges = Array.from(changed).filter(
(path) => !isCanonicalStagePath(path) && !path.match(/docs\/sdlc\/changes\/[^/]+\/evidence\//),
);
if (nonStageChanges.length > 0 && readyBundles.length === 0) {
return [
"repository implementation changes require accepted authorization and plan in a changed bundle",
];
}
for (const path of nonStageChanges) {
if (readyBundles.some((bundle) => planCoversPath(bundle, path))) continue;
return [`${path}: changed path is not covered by an accepted plan scope`];
}
return [];
}
function validateReleaseGate(bundles: Map<string, StageBundle>, changeId: string): string[] {
const normalized = changeId.startsWith("change-") ? changeId.slice("change-".length) : changeId;
const bundle = bundles.get(normalized);
if (!bundle) return [`release change bundle not found: ${changeId}`];
const verification = bundle.verification;
if (verification?.metadata.status !== "passed") {
return [`release change ${changeId} requires verification passed`];
}
if (bundle.intent.metadata.schema === "5") {
const errors = validateCleanup(verification, true);
if (errors.length) return errors;
}
const target = verification.metadata.release_target ?? "";
if (!isConcrete(target) || target.toLowerCase().replace(/\.$/, "") === "none") {
return [`release change ${changeId} requires a concrete release_target`];
}
const review = verification.sections["review and release"] ?? "";
if (!isConcrete(labelValue(review, "Approval"))) {
return [`release change ${changeId} requires release Approval`];
}
if (!isConcrete(labelValue(review, "Rollback"))) {
return [`release change ${changeId} requires Rollback`];
}
return [];
}
export function validateRepository(
repositoryRoot: string,
base?: string,
releaseChange?: string,
worktree = false,
ready = false,
): string[] {
const root = resolve(repositoryRoot);
const errors: string[] = [];
for (const path of REQUIRED_FILES) {
if (!existsSync(join(root, path))) errors.push(`missing required SDLC file: ${path}`);
}
for (const path of LEGACY_PATHS) {
if (existsSync(join(root, path))) errors.push(`legacy or superseded lifecycle path is forbidden: ${path}`);
}
const bundles = new Map<string, StageBundle>();
for (const bundleDir of discoverStageBundles(root)) {
const { bundle, errors: bundleErrors } = validateStageBundle(root, bundleDir);
errors.push(...bundleErrors);
if (bundle) bundles.set(bundle.id, bundle);
}
if (bundles.size === 0) errors.push("at least one canonical change record is required");
for (const path of markdownFiles(join(root, "docs", "sdlc", "incidents"))) {
const parsed = parseArtifact(path);
errors.push(...parsed.errors);
if (!parsed.artifact) continue;
const rel = repoPath(root, path);
errors.push(...validateIncident(parsed.artifact, rel));
errors.push(...validateLocalLinks(root, path));
}
for (const path of markdownFiles(join(root, "docs", "sdlc", "evals"))) {
const parsed = parseArtifact(path);
errors.push(...parsed.errors);
if (!parsed.artifact) continue;
const rel = repoPath(root, path);
if (parsed.artifact.metadata.id !== `eval-${basename(path, ".md")}`) {
errors.push(`${rel}: eval id must match eval-<slug>`);
}
errors.push(...validateEval(parsed.artifact, rel));
errors.push(...validateLocalLinks(root, path));
}
const workflow = join(root, ".agents/skills/codetwo-develop/references/workflow.md");
if (existsSync(workflow)) errors.push(...validateLocalLinks(root, workflow));
if (ready && !base && !worktree) errors.push("--ready requires --base or --worktree");
if (base && worktree) errors.push("--base and --worktree are mutually exclusive");
else if (base || worktree) errors.push(...validateChangedArtifactGate(root, base, worktree, bundles, ready));
if (releaseChange) errors.push(...validateReleaseGate(bundles, releaseChange));
return errors;
}
function parseArguments(argv: string[]): {
root: string;
base?: string;
releaseChange?: string;
worktree: boolean;
ready: boolean;
} {
let root = resolve(dirname(fileURLToPath(import.meta.url)), "../..");
let base: string | undefined;
let releaseChange: string | undefined;
let worktree = false;
let ready = false;
for (let index = 0; index < argv.length; index += 1) {
const argument = argv[index];
if (argument === "--ready") { ready = true; continue; }
if (argument === "--worktree") {
worktree = true;
continue;
}
const value = argv[index + 1];
if (!["--root", "--base", "--release-change"].includes(argument) || !value) {
throw new Error(
"usage: bun script/verify/sdlc.ts [--root PATH] [--base SHA | --worktree] [--release-change ID] [--ready]",
);
}
if (argument === "--root") root = value;
if (argument === "--base") base = value;
if (argument === "--release-change") releaseChange = value;
index += 1;
}
return { root, base, releaseChange, worktree, ready };
}
if (import.meta.main) {
try {
const args = parseArguments(process.argv.slice(2));
const errors = validateRepository(args.root, args.base, args.releaseChange, args.worktree, args.ready);
if (errors.length > 0) {
for (const error of errors) console.error(`[sdlc] error: ${error}`);
console.error(`[sdlc] failed with ${errors.length} error(s)`);
process.exit(1);
}
console.log("[sdlc] contract valid");
} catch (error) {
console.error(`[sdlc] error: ${error instanceof Error ? error.message : String(error)}`);
process.exit(2);
}
}