@kyuki3rain/cupola 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +26 -0
- package/LICENSE +202 -0
- package/README.md +40 -2
- package/dist/adr.js +106 -0
- package/dist/catalog.js +137 -0
- package/dist/check.js +192 -0
- package/dist/cli.js +8 -0
- package/dist/code.js +216 -0
- package/dist/commands/change.js +522 -0
- package/dist/commands/epic.js +311 -0
- package/dist/commands/install.js +109 -0
- package/dist/commands/locks.js +175 -0
- package/dist/commands/procedure.js +92 -0
- package/dist/commands/revision.js +139 -0
- package/dist/commands/run.js +1015 -0
- package/dist/commands/setup.js +382 -0
- package/dist/commands/spec.js +80 -0
- package/dist/commands/status.js +1158 -0
- package/dist/commands/trace.js +397 -0
- package/dist/commands/wait.js +102 -0
- package/dist/commands/work.js +121 -0
- package/dist/commands/workspace.js +126 -0
- package/dist/commands/worktree.js +422 -0
- package/dist/config.js +289 -0
- package/dist/day.js +29 -0
- package/dist/e2e-project.js +62 -0
- package/dist/e2e.js +207 -0
- package/dist/engine/cc-sdd.js +164 -0
- package/dist/epic.js +360 -0
- package/dist/feedback.js +34 -0
- package/dist/frontmatter.js +20 -0
- package/dist/git.js +365 -0
- package/dist/host/github.js +290 -0
- package/dist/host/host.js +1 -0
- package/dist/install.js +182 -0
- package/dist/io.js +46 -0
- package/dist/main.js +771 -0
- package/dist/method/v1.js +56 -0
- package/dist/procedure.js +60 -0
- package/dist/record.js +473 -0
- package/dist/release.js +84 -0
- package/dist/repo.js +13 -0
- package/dist/runbook.js +111 -0
- package/dist/safe-write.js +80 -0
- package/dist/spec.js +171 -0
- package/dist/status.js +190 -0
- package/dist/templates.js +49 -0
- package/dist/trace.js +275 -0
- package/dist/tracker/files.js +156 -0
- package/dist/tracker/github-issues.js +217 -0
- package/dist/tracker/index.js +27 -0
- package/dist/tracker/tracker.js +69 -0
- package/dist/tree.js +42 -0
- package/dist/trust.js +13 -0
- package/dist/version.js +5 -0
- package/dist/work.js +149 -0
- package/dist/workspace.js +299 -0
- package/npm-shrinkwrap.json +2014 -0
- package/package.json +41 -4
- package/skills/cupola-abort/SKILL.md +45 -0
- package/skills/cupola-adr/SKILL.md +41 -0
- package/skills/cupola-ask/SKILL.md +42 -0
- package/skills/cupola-catalog/SKILL.md +41 -0
- package/skills/cupola-catalog-draft/SKILL.md +114 -0
- package/skills/cupola-complete/SKILL.md +87 -0
- package/skills/cupola-decide/SKILL.md +60 -0
- package/skills/cupola-doc/SKILL.md +52 -0
- package/skills/cupola-e2e-setup/SKILL.md +78 -0
- package/skills/cupola-e2e-test/SKILL.md +115 -0
- package/skills/cupola-epic-accept/SKILL.md +162 -0
- package/skills/cupola-epic-create/SKILL.md +120 -0
- package/skills/cupola-epic-revise/SKILL.md +71 -0
- package/skills/cupola-epic-run/SKILL.md +127 -0
- package/skills/cupola-fix/SKILL.md +115 -0
- package/skills/cupola-init/SKILL.md +88 -0
- package/skills/cupola-intake/SKILL.md +78 -0
- package/skills/cupola-operate/SKILL.md +64 -0
- package/skills/cupola-resolve/SKILL.md +86 -0
- package/skills/cupola-review/SKILL.md +132 -0
- package/skills/cupola-spec-design/SKILL.md +164 -0
- package/skills/cupola-spec-impl/SKILL.md +135 -0
- package/skills/cupola-spec-run/SKILL.md +125 -0
- package/skills/cupola-steering/SKILL.md +46 -0
- package/templates/install/.kiro/steering/e2e.md +48 -0
- package/templates/install/.kiro/steering/operations.md +109 -0
- package/templates/install/.kiro/steering/principles.md +25 -0
- package/templates/install/CLAUDE.md +19 -0
- package/templates/install/adr/TEMPLATE.md +38 -0
- package/templates/install/cc-sdd/patches.json +31 -0
- package/templates/method-1/behavior-area.md +43 -0
- package/templates/method-1/behavior-index.md +16 -0
- package/templates/method-1/card.md +41 -0
- package/templates/method-1/case-draft.md +25 -0
- package/templates/method-1/case.md +38 -0
- package/templates/method-1/catalog-spec.md +33 -0
- package/templates/method-1/changes/adr.md +4 -0
- package/templates/method-1/changes/catalog.md +29 -0
- package/templates/method-1/changes/doc.md +5 -0
- package/templates/method-1/changes/e2e.md +7 -0
- package/templates/method-1/changes/epic.md +29 -0
- package/templates/method-1/changes/fix.md +21 -0
- package/templates/method-1/changes/release.md +23 -0
- package/templates/method-1/changes/spec.md +55 -0
- package/templates/method-1/changes/system.md +13 -0
- package/templates/method-1/cupola-issue-draft.md +17 -0
- package/templates/method-1/epic.md +136 -0
- package/templates/method-1/fix-spec.md +34 -0
- package/templates/method-1/fix.md +39 -0
- package/templates/method-1/lock.json +13 -0
- package/templates/method-1/phase-outcome.json +29 -0
- package/templates/method-1/record.json +63 -0
- package/templates/method-1/report.md +27 -0
- package/templates/method-1/runbook.md +39 -0
- package/templates/method-1/runner-result.json +6 -0
- package/templates/method-1/send-back.md +23 -0
- package/templates/methods.json +13 -0
package/dist/trace.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { glob, readFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { XMLParser } from "fast-xml-parser";
|
|
5
|
+
import { git, gitRaw } from "./git.js";
|
|
6
|
+
const REF = /@req\s+([a-z0-9-]+\.[a-z0-9-]+|[a-z0-9-]+#[A-Z]+[0-9]+(?:\.[ag][0-9]+)?)/g;
|
|
7
|
+
const TEST_NAME = [
|
|
8
|
+
/\b(?:it|test|specify|scenario|t\.Run)\s*(?:\.\w+\s*)?\(\s*(["'`])(.+?)\1/, // JS/TS, Go subtests
|
|
9
|
+
/\bdef\s+(test_\w+)/, // Python
|
|
10
|
+
/\bfunc\s+(Test\w+)/, // Go
|
|
11
|
+
/\bfn\s+(\w+)\s*\(/, // Rust (after #[test])
|
|
12
|
+
/\bfun\s+`?([^`(]+?)`?\s*\(/, // Kotlin
|
|
13
|
+
/\bvoid\s+(\w+)\s*\(/, // JVM
|
|
14
|
+
];
|
|
15
|
+
function testName(line) {
|
|
16
|
+
for (const re of TEST_NAME) {
|
|
17
|
+
const m = re.exec(line);
|
|
18
|
+
if (m)
|
|
19
|
+
return m[2] ?? m[1];
|
|
20
|
+
}
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Finds `@req` markers in tracked text files with `git grep`, so a large
|
|
25
|
+
* repository is not read file by file. A marker scopes to the test on its own
|
|
26
|
+
* line, or to the next test declared within a few lines below it.
|
|
27
|
+
*/
|
|
28
|
+
export async function findMarkers(root, exclude = [],
|
|
29
|
+
/** A commit to read instead of the working tree. */
|
|
30
|
+
at) {
|
|
31
|
+
let out;
|
|
32
|
+
try {
|
|
33
|
+
out = await git(root, [
|
|
34
|
+
"grep",
|
|
35
|
+
"-n",
|
|
36
|
+
"-o",
|
|
37
|
+
"-I",
|
|
38
|
+
"-z",
|
|
39
|
+
"-E",
|
|
40
|
+
"@req[[:space:]]",
|
|
41
|
+
...(at ? [at] : []),
|
|
42
|
+
"--",
|
|
43
|
+
":!*.md",
|
|
44
|
+
// Cupola's own records; the acceptance checks under `.cupola/` carry markers too.
|
|
45
|
+
":!.cupola/runs/",
|
|
46
|
+
":!.cupola/work/",
|
|
47
|
+
":!.cupola/*.json",
|
|
48
|
+
...exclude.map((d) => `:!${d}/`),
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
51
|
+
catch (error) {
|
|
52
|
+
if (error.code === 1)
|
|
53
|
+
return []; // no matches
|
|
54
|
+
throw error;
|
|
55
|
+
}
|
|
56
|
+
const byFile = new Map(); // -o prints a line once per match
|
|
57
|
+
for (const line of out.split("\n")) {
|
|
58
|
+
const [named, lineNo] = line.split("\0");
|
|
59
|
+
// At a commit, git grep names each file `<commit>:<path>`.
|
|
60
|
+
const file = at && named?.startsWith(`${at}:`) ? named.slice(at.length + 1) : named;
|
|
61
|
+
if (!file || !lineNo)
|
|
62
|
+
continue;
|
|
63
|
+
byFile.set(file, (byFile.get(file) ?? new Set()).add(Number(lineNo)));
|
|
64
|
+
}
|
|
65
|
+
const markers = [];
|
|
66
|
+
for (const [file, numbers] of byFile) {
|
|
67
|
+
const text = at
|
|
68
|
+
? await gitRaw(root, ["show", `${at}:${file}`])
|
|
69
|
+
: await readFile(join(root, file), "utf8");
|
|
70
|
+
const lines = text.split(/\r?\n/);
|
|
71
|
+
for (const n of numbers) {
|
|
72
|
+
const line = lines[n - 1] ?? "";
|
|
73
|
+
for (const m of line.matchAll(REF)) {
|
|
74
|
+
let test = testName(line);
|
|
75
|
+
for (let j = n; !test && j < Math.min(lines.length, n + 5); j++)
|
|
76
|
+
test = testName(lines[j] ?? "");
|
|
77
|
+
markers.push({ ref: m[1] ?? "", file, line: n, test });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return markers;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The markers of a checkout and of the code mounted in it (`documents: "hub"`): each mounted
|
|
85
|
+
* repository is grepped on its own, its
|
|
86
|
+
* files named from the hub's root (`<clone>/<path>`). With `at`, the hub is
|
|
87
|
+
* read at that commit and each mounted repository at the commit `codeAt`
|
|
88
|
+
* gives it; a repository it gives none is skipped.
|
|
89
|
+
*/
|
|
90
|
+
export async function findAllMarkers(root, mounts, exclude = [], at) {
|
|
91
|
+
const out = await findMarkers(root, exclude, at?.hub);
|
|
92
|
+
for (const mount of mounts) {
|
|
93
|
+
const source = typeof mount === "string" ? { dir: mount, path: join(root, mount) } : mount;
|
|
94
|
+
const { dir, path } = source;
|
|
95
|
+
if (!existsSync(join(path, ".git")))
|
|
96
|
+
continue;
|
|
97
|
+
const commit = at ? await at.codeAt(dir) : source.ref;
|
|
98
|
+
if (at && !commit)
|
|
99
|
+
continue;
|
|
100
|
+
for (const m of await findMarkers(path, [], commit))
|
|
101
|
+
out.push({ ...m, file: `${dir}/${m.file}` });
|
|
102
|
+
}
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
/** Test results from JUnit XML reports matching the configured globs. Unreadable reports are skipped. */
|
|
106
|
+
export async function readReports(root, patterns,
|
|
107
|
+
/** Top-level directories not to look in: the other repositories cloned under the hub. */
|
|
108
|
+
skip = []) {
|
|
109
|
+
const parser = new XMLParser({
|
|
110
|
+
ignoreAttributes: false,
|
|
111
|
+
attributeNamePrefix: "",
|
|
112
|
+
isArray: (n) => n === "testcase" || n === "testsuite",
|
|
113
|
+
});
|
|
114
|
+
const results = [];
|
|
115
|
+
const warnings = [];
|
|
116
|
+
for (const pattern of patterns) {
|
|
117
|
+
const exclude = (f) => skip.some((d) => f === d || f.startsWith(`${d}/`));
|
|
118
|
+
for await (const file of glob(pattern, { cwd: root, exclude })) {
|
|
119
|
+
if (exclude(file))
|
|
120
|
+
continue;
|
|
121
|
+
let xml;
|
|
122
|
+
try {
|
|
123
|
+
xml = parser.parse(await readFile(join(root, file), "utf8"), true);
|
|
124
|
+
}
|
|
125
|
+
catch (error) {
|
|
126
|
+
warnings.push(`${file}: not readable as JUnit XML (${error.message.split("\n")[0]})`);
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
const walk = (node, suiteFile) => {
|
|
130
|
+
if (!node || typeof node !== "object")
|
|
131
|
+
return;
|
|
132
|
+
const n = node;
|
|
133
|
+
const here = typeof n.file === "string" ? n.file : suiteFile;
|
|
134
|
+
if (Array.isArray(n.testcase)) {
|
|
135
|
+
for (const c of n.testcase) {
|
|
136
|
+
const result = "failure" in c || "error" in c ? "failed" : "skipped" in c ? "skipped" : "passed";
|
|
137
|
+
results.push({
|
|
138
|
+
name: String(c.name ?? ""),
|
|
139
|
+
file: typeof c.file === "string" ? c.file : here,
|
|
140
|
+
classname: typeof c.classname === "string" ? c.classname : undefined,
|
|
141
|
+
result,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
for (const key of ["testsuites", "testsuite"]) {
|
|
146
|
+
const child = n[key];
|
|
147
|
+
if (Array.isArray(child))
|
|
148
|
+
for (const c of child)
|
|
149
|
+
walk(c, here);
|
|
150
|
+
else
|
|
151
|
+
walk(child, here);
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
walk(xml, undefined);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
return { results, warnings };
|
|
158
|
+
}
|
|
159
|
+
function sameTest(name, test) {
|
|
160
|
+
return (name === test ||
|
|
161
|
+
name.endsWith(` > ${test}`) || // vitest; jest-junit with ancestorSeparator " > "
|
|
162
|
+
name.endsWith(` › ${test}`) ||
|
|
163
|
+
name.startsWith(`${test}[`) || // pytest parameters
|
|
164
|
+
name.startsWith(`${test}/`) || // a Go test with subtests
|
|
165
|
+
name.endsWith(`/${test.replaceAll(" ", "_")}`) // a Go subtest, from t.Run
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
const slashes = (path) => path.replaceAll("\\", "/");
|
|
169
|
+
/** Whether two repository paths name the same file, one possibly relative to a subdirectory. */
|
|
170
|
+
function samePath(a, b) {
|
|
171
|
+
return a === b || a.endsWith(`/${b}`) || b.endsWith(`/${a}`);
|
|
172
|
+
}
|
|
173
|
+
/** Whether a result comes from the marker's file, judged by whatever the report gives. */
|
|
174
|
+
function sameFile(marker, r) {
|
|
175
|
+
if (r.file)
|
|
176
|
+
return samePath(slashes(r.file), marker.file);
|
|
177
|
+
const cls = r.classname ? slashes(r.classname).replace(/\$.*$/, "") : undefined;
|
|
178
|
+
if (!cls)
|
|
179
|
+
return undefined;
|
|
180
|
+
const ext = /\.[A-Za-z0-9]+$/.exec(marker.file)?.[0];
|
|
181
|
+
if (ext && cls.endsWith(ext))
|
|
182
|
+
return samePath(cls, marker.file); // a file path: vitest, jest
|
|
183
|
+
if (cls.includes("/")) {
|
|
184
|
+
// a package path: go-junit-report
|
|
185
|
+
const dir = marker.file.split("/").slice(0, -1).join("/");
|
|
186
|
+
if (dir === "")
|
|
187
|
+
return undefined; // the module's root package: nothing to compare
|
|
188
|
+
return samePath(cls, dir) || dir.split("/").at(-1) === cls.split("/").at(-1);
|
|
189
|
+
}
|
|
190
|
+
if (cls.includes(".")) {
|
|
191
|
+
// a dotted module, possibly followed by classes: pytest, surefire
|
|
192
|
+
const dotted = marker.file.replace(/\.[^./]+$/, "").replaceAll("/", ".");
|
|
193
|
+
const parts = cls.split(".");
|
|
194
|
+
for (let k = 0; k < Math.min(3, parts.length - 1) + 1; k++) {
|
|
195
|
+
const c = parts.slice(0, parts.length - k).join(".");
|
|
196
|
+
if (c === dotted || dotted.endsWith(`.${c}`))
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
return false;
|
|
200
|
+
}
|
|
201
|
+
// A bare name, such as pytest's module at the root: it can only be the file's own name.
|
|
202
|
+
const stem = marker.file
|
|
203
|
+
.split("/")
|
|
204
|
+
.at(-1)
|
|
205
|
+
?.replace(/\.[^.]+$/, "");
|
|
206
|
+
return cls === stem ? true : undefined;
|
|
207
|
+
}
|
|
208
|
+
function matches(marker, r, results) {
|
|
209
|
+
if (!marker.test || !sameTest(r.name, marker.test))
|
|
210
|
+
return false;
|
|
211
|
+
const file = sameFile(marker, r);
|
|
212
|
+
if (file !== undefined)
|
|
213
|
+
return file;
|
|
214
|
+
// No file to go by: accept the name only when no other test result shares it.
|
|
215
|
+
return results.filter((x) => sameTest(x.name, marker.test)).length === 1;
|
|
216
|
+
}
|
|
217
|
+
/** The epic references a catalog entry answers to, through its `origin: epic <id> <ref>`. */
|
|
218
|
+
function epicRefsOf(origin, epics) {
|
|
219
|
+
const m = /^epic\s+(\S+)\s+(\S+)$/.exec(origin?.trim() ?? "");
|
|
220
|
+
if (!m)
|
|
221
|
+
return [];
|
|
222
|
+
const [, epic = "", ref = ""] = m;
|
|
223
|
+
return [ref, ...(epics.get(epic)?.get(ref) ?? [])].map((r) => `${epic}#${r}`);
|
|
224
|
+
}
|
|
225
|
+
export function buildTrace(areas, markers, results, warnings = [], epics = new Map()) {
|
|
226
|
+
const ids = new Set(areas.flatMap((a) => a.entries.map((e) => e.id)));
|
|
227
|
+
const entries = areas.flatMap((a) => a.entries.map((e) => {
|
|
228
|
+
const refs = new Set([e.id, ...epicRefsOf(e.origin, epics)]);
|
|
229
|
+
const tests = markers
|
|
230
|
+
.filter((m) => refs.has(m.ref))
|
|
231
|
+
.map((m) => {
|
|
232
|
+
const found = results.filter((r) => matches(m, r, results));
|
|
233
|
+
const result = found.some((r) => r.result === "failed")
|
|
234
|
+
? "failed"
|
|
235
|
+
: found.some((r) => r.result === "passed")
|
|
236
|
+
? "passed"
|
|
237
|
+
: found.length > 0
|
|
238
|
+
? "skipped"
|
|
239
|
+
: null;
|
|
240
|
+
return { file: m.file, line: m.line, test: m.test, result };
|
|
241
|
+
});
|
|
242
|
+
let status;
|
|
243
|
+
if (tests.length === 0) {
|
|
244
|
+
status = e.verified?.startsWith("manual")
|
|
245
|
+
? "manual"
|
|
246
|
+
: e.verified?.startsWith("untestable")
|
|
247
|
+
? "untestable"
|
|
248
|
+
: "unverified";
|
|
249
|
+
}
|
|
250
|
+
else if (tests.some((t) => t.result === "failed"))
|
|
251
|
+
status = "failing";
|
|
252
|
+
else if (tests.some((t) => t.result === "passed"))
|
|
253
|
+
status = "passing";
|
|
254
|
+
else
|
|
255
|
+
status = "no-result";
|
|
256
|
+
return {
|
|
257
|
+
id: e.id,
|
|
258
|
+
area: a.area,
|
|
259
|
+
component: a.component,
|
|
260
|
+
path: a.path,
|
|
261
|
+
line: e.line,
|
|
262
|
+
origin: e.origin,
|
|
263
|
+
verified: e.verified,
|
|
264
|
+
mark: e.mark,
|
|
265
|
+
tests,
|
|
266
|
+
status,
|
|
267
|
+
};
|
|
268
|
+
}));
|
|
269
|
+
return {
|
|
270
|
+
entries,
|
|
271
|
+
warnings,
|
|
272
|
+
orphans: markers.filter((m) => !m.ref.includes("#") && !ids.has(m.ref)),
|
|
273
|
+
epicRefs: markers.filter((m) => m.ref.includes("#")),
|
|
274
|
+
};
|
|
275
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
import { mkdtemp, rm } from "node:fs/promises";
|
|
2
|
+
import { tmpdir } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { parseFrontMatter } from "../frontmatter.js";
|
|
5
|
+
import { git, gitWith } from "../git.js";
|
|
6
|
+
import { appendLog, CaseError, closeCase, parseCase, } from "./tracker.js";
|
|
7
|
+
/** The hub's branch that holds cases, committed and pushed to directly. */
|
|
8
|
+
export const WORK_BRANCH = "cupola/work";
|
|
9
|
+
const DIR = ".cupola/work";
|
|
10
|
+
const TIP = "refs/cupola/work-tip";
|
|
11
|
+
/**
|
|
12
|
+
* The `files` tracker: cases as Markdown under `.cupola/work/` on the hub's
|
|
13
|
+
* `cupola/work` branch. Writes go through a temporary index straight to a
|
|
14
|
+
* commit, so no checkout is touched, and are pushed at once so that a filed
|
|
15
|
+
* case is visible to everyone.
|
|
16
|
+
*/
|
|
17
|
+
export function filesTracker(root) {
|
|
18
|
+
/** origin's tip of the branch, fetched; undefined while no case was ever filed. */
|
|
19
|
+
async function tip() {
|
|
20
|
+
try {
|
|
21
|
+
await git(root, [
|
|
22
|
+
"ls-remote",
|
|
23
|
+
"--exit-code",
|
|
24
|
+
"--heads",
|
|
25
|
+
"origin",
|
|
26
|
+
`refs/heads/${WORK_BRANCH}`,
|
|
27
|
+
]);
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
if (error.code === 2)
|
|
31
|
+
return undefined;
|
|
32
|
+
throw new Error(`cannot reach origin to read ${WORK_BRANCH}; try again when it is reachable`);
|
|
33
|
+
}
|
|
34
|
+
await git(root, ["fetch", "--quiet", "origin", `+refs/heads/${WORK_BRANCH}:${TIP}`]);
|
|
35
|
+
return git(root, ["rev-parse", TIP]);
|
|
36
|
+
}
|
|
37
|
+
async function read(commit, id) {
|
|
38
|
+
try {
|
|
39
|
+
return await git(root, ["show", `${commit}:${DIR}/${id}.md`]);
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
const summary = (id, text) => {
|
|
46
|
+
const { data } = parseFrontMatter(text);
|
|
47
|
+
return {
|
|
48
|
+
id,
|
|
49
|
+
title: typeof data.title === "string" ? data.title : "",
|
|
50
|
+
url: `${WORK_BRANCH}:${DIR}/${id}.md`,
|
|
51
|
+
open: !data.closed,
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* Commits the case `id` on top of the tip and pushes it, retried when
|
|
56
|
+
* someone pushed first. `change` gives the new text, or undefined when it is
|
|
57
|
+
* already there — after a retry, a push that failed to report may have landed.
|
|
58
|
+
*/
|
|
59
|
+
async function write(id, change, message) {
|
|
60
|
+
for (let attempt = 0;; attempt++) {
|
|
61
|
+
const parent = await tip();
|
|
62
|
+
const text = change(parent ? await read(parent, id) : undefined, attempt > 0);
|
|
63
|
+
if (text === undefined)
|
|
64
|
+
return;
|
|
65
|
+
const dir = await mkdtemp(join(tmpdir(), "cupola-work-"));
|
|
66
|
+
try {
|
|
67
|
+
const env = { GIT_INDEX_FILE: join(dir, "index") };
|
|
68
|
+
await gitWith(root, parent ? ["read-tree", parent] : ["read-tree", "--empty"], { env });
|
|
69
|
+
const blob = await gitWith(root, ["hash-object", "-w", "--stdin"], { input: text });
|
|
70
|
+
await gitWith(root, ["update-index", "--add", "--cacheinfo", `100644,${blob},${DIR}/${id}.md`], { env });
|
|
71
|
+
const tree = await gitWith(root, ["write-tree"], { env });
|
|
72
|
+
const commit = await gitWith(root, ["commit-tree", tree, ...(parent ? ["-p", parent] : []), "-m", message], { env });
|
|
73
|
+
try {
|
|
74
|
+
await git(root, ["push", "--quiet", "origin", `${commit}:refs/heads/${WORK_BRANCH}`]);
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
const stderr = error.stderr ?? "";
|
|
79
|
+
// Only a race is retried: someone else's case landed first. Anything else is reported.
|
|
80
|
+
const raced = /non-fast-forward|fetch first|\(stale info\)/.test(stderr);
|
|
81
|
+
if (!raced || attempt >= 2) {
|
|
82
|
+
const detail = stderr
|
|
83
|
+
.split("\n")
|
|
84
|
+
.map((l) => l.trim())
|
|
85
|
+
.filter((l) => /^(!|error:|fatal:|remote:)/.test(l) && !/^remote:\s*$/.test(l))
|
|
86
|
+
.join("; ") || "unknown reason";
|
|
87
|
+
throw new Error(`could not push ${WORK_BRANCH} to origin (${detail})`);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
finally {
|
|
92
|
+
await rm(dir, { recursive: true, force: true });
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
async list() {
|
|
98
|
+
const at = await tip();
|
|
99
|
+
if (!at)
|
|
100
|
+
return [];
|
|
101
|
+
const names = (await git(root, ["ls-tree", "--name-only", at, `${DIR}/`]))
|
|
102
|
+
.split("\n")
|
|
103
|
+
.filter((p) => p.endsWith(".md"));
|
|
104
|
+
const cases = [];
|
|
105
|
+
for (const path of names) {
|
|
106
|
+
const id = path.slice(DIR.length + 1, -".md".length);
|
|
107
|
+
const text = await read(at, id);
|
|
108
|
+
if (text !== undefined)
|
|
109
|
+
cases.push(summary(id, text));
|
|
110
|
+
}
|
|
111
|
+
return cases;
|
|
112
|
+
},
|
|
113
|
+
async show(id) {
|
|
114
|
+
const at = await tip();
|
|
115
|
+
const text = at ? await read(at, id) : undefined;
|
|
116
|
+
if (text === undefined)
|
|
117
|
+
return undefined;
|
|
118
|
+
return { ...summary(id, text), text: `${text}\n` };
|
|
119
|
+
},
|
|
120
|
+
async file(text) {
|
|
121
|
+
const { id, title } = parseCase(text);
|
|
122
|
+
await write(id, (old, retried) => {
|
|
123
|
+
if (old === undefined)
|
|
124
|
+
return text;
|
|
125
|
+
if (retried && old.trim() === text.trim())
|
|
126
|
+
return undefined;
|
|
127
|
+
throw new CaseError(`case ${id} is already filed`);
|
|
128
|
+
}, `case: file ${id}`);
|
|
129
|
+
return { id, title, url: `${WORK_BRANCH}:${DIR}/${id}.md`, open: true };
|
|
130
|
+
},
|
|
131
|
+
async close(id, line, day) {
|
|
132
|
+
let closed = false;
|
|
133
|
+
await write(id, (old) => {
|
|
134
|
+
if (old === undefined)
|
|
135
|
+
throw new CaseError(`no case ${id}`);
|
|
136
|
+
// Closed already: by an earlier run, or by someone else while this one raced.
|
|
137
|
+
if (parseFrontMatter(old).data.closed) {
|
|
138
|
+
closed = false;
|
|
139
|
+
return undefined;
|
|
140
|
+
}
|
|
141
|
+
closed = true;
|
|
142
|
+
return appendLog(closeCase(old, day), line);
|
|
143
|
+
}, `case: close ${id}`);
|
|
144
|
+
return closed;
|
|
145
|
+
},
|
|
146
|
+
async log(id, line) {
|
|
147
|
+
await write(id, (old, retried) => {
|
|
148
|
+
if (old === undefined)
|
|
149
|
+
throw new CaseError(`no case ${id}`);
|
|
150
|
+
if (retried && old.trimEnd().endsWith(`- ${line}`))
|
|
151
|
+
return undefined;
|
|
152
|
+
return appendLog(old, line);
|
|
153
|
+
}, `case: log ${id}`);
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
}
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { stringify } from "yaml";
|
|
2
|
+
import { gh, withBody } from "../host/github.js";
|
|
3
|
+
import { DEFAULT_TRUST, trustedBy } from "../trust.js";
|
|
4
|
+
import { CaseError, parseCase } from "./tracker.js";
|
|
5
|
+
export const CASE_LABEL = "type:case";
|
|
6
|
+
const BLOCKS = /<!-- cupola:case (\{[^\n]*?\}) -->/g;
|
|
7
|
+
/**
|
|
8
|
+
* The case's hidden block: the last one that holds valid JSON. Text a person
|
|
9
|
+
* adds after it on the host does not lose it, and a mention of the block in
|
|
10
|
+
* prose (which holds no valid JSON) is not taken for it.
|
|
11
|
+
*/
|
|
12
|
+
function metaOf(body) {
|
|
13
|
+
let meta;
|
|
14
|
+
for (const m of body.matchAll(BLOCKS)) {
|
|
15
|
+
try {
|
|
16
|
+
const value = JSON.parse(m[1] ?? "");
|
|
17
|
+
if (value && typeof value === "object" && !Array.isArray(value))
|
|
18
|
+
meta = value;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// not the block
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return meta;
|
|
25
|
+
}
|
|
26
|
+
/** Text whose Cupola markers record nothing: they no longer read as markers. */
|
|
27
|
+
export function inert(text) {
|
|
28
|
+
return text.replace(/<!--(\s*)cupola:/g, "<!--$1cupola-inert:");
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* A comment as a Log line. What someone who cannot write to the repository
|
|
32
|
+
* wrote stays, named, on one line (it adds nothing to the case's structure),
|
|
33
|
+
* and records nothing.
|
|
34
|
+
*/
|
|
35
|
+
export function logLine(c, trust = DEFAULT_TRUST) {
|
|
36
|
+
return trustedBy(trust, who(c))
|
|
37
|
+
? `- ${c.body.trim()}`
|
|
38
|
+
: `- (from ${c.author?.login ?? "someone"}, not trusted by the configuration) ${inert(c.body.trim()).replace(/\s*\n\s*/g, " ")}`;
|
|
39
|
+
}
|
|
40
|
+
function who(w) {
|
|
41
|
+
return { author: w.author?.login ?? "", association: w.authorAssociation ?? "NONE" };
|
|
42
|
+
}
|
|
43
|
+
const ISSUE_QUERY = `query($owner: String!, $name: String!, $number: Int!, $endCursor: String) {
|
|
44
|
+
repository(owner: $owner, name: $name) {
|
|
45
|
+
issue(number: $number) {
|
|
46
|
+
body closedAt authorAssociation author { login }
|
|
47
|
+
comments(first: 100, after: $endCursor) {
|
|
48
|
+
nodes { body authorAssociation author { login } }
|
|
49
|
+
pageInfo { hasNextPage endCursor }
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}`;
|
|
54
|
+
/** An issue's body and every comment, with their authors: one request for up to 100 comments. */
|
|
55
|
+
async function issueView(root, hub, number) {
|
|
56
|
+
const [owner, name] = hub.split("/");
|
|
57
|
+
const pages = JSON.parse(await gh(root, [
|
|
58
|
+
"api",
|
|
59
|
+
"graphql",
|
|
60
|
+
"--paginate",
|
|
61
|
+
"--slurp",
|
|
62
|
+
"-f",
|
|
63
|
+
`query=${ISSUE_QUERY}`,
|
|
64
|
+
"-F",
|
|
65
|
+
`owner=${owner}`,
|
|
66
|
+
"-F",
|
|
67
|
+
`name=${name}`,
|
|
68
|
+
"-F",
|
|
69
|
+
`number=${number}`,
|
|
70
|
+
]));
|
|
71
|
+
const first = pages[0]?.data.repository.issue;
|
|
72
|
+
if (!first)
|
|
73
|
+
throw new Error(`${hub}#${number}: no such issue`);
|
|
74
|
+
return { ...first, comments: pages.flatMap((p) => p.data.repository.issue.comments.nodes) };
|
|
75
|
+
}
|
|
76
|
+
/** The body without its hidden blocks or the template's guidance comments, which are not for the issue's readers. */
|
|
77
|
+
function visible(body) {
|
|
78
|
+
return body
|
|
79
|
+
.replace(/<!--[\s\S]*?-->\n?/g, "")
|
|
80
|
+
.replace(/\n{3,}/g, "\n\n")
|
|
81
|
+
.trim();
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* The case's front matter other than `title` (and `kind`, `closed`, which the
|
|
85
|
+
* issue itself carries), as the trailing hidden block of the issue.
|
|
86
|
+
*/
|
|
87
|
+
export function issueBody(body, data) {
|
|
88
|
+
const { kind: _k, title: _t, closed: _c, ...meta } = data;
|
|
89
|
+
return `${visible(body)}\n\n<!-- cupola:case ${JSON.stringify(meta)} -->\n`;
|
|
90
|
+
}
|
|
91
|
+
/** The case id an issue carries in its hidden block; an issue filed by hand has only its number. */
|
|
92
|
+
export function caseIdOf(issue) {
|
|
93
|
+
const id = metaOf(issue.body)?.id;
|
|
94
|
+
return typeof id === "string" && id !== "" ? id : String(issue.number);
|
|
95
|
+
}
|
|
96
|
+
/** The `github-issues` tracker: cases are issues labeled `type:case`. */
|
|
97
|
+
export function githubIssues(root, hub, trust = DEFAULT_TRUST) {
|
|
98
|
+
const LIMIT = 5000;
|
|
99
|
+
async function issues() {
|
|
100
|
+
const out = await gh(root, [
|
|
101
|
+
"issue",
|
|
102
|
+
"list",
|
|
103
|
+
"--repo",
|
|
104
|
+
hub,
|
|
105
|
+
"--label",
|
|
106
|
+
CASE_LABEL,
|
|
107
|
+
"--state",
|
|
108
|
+
"all",
|
|
109
|
+
"--limit",
|
|
110
|
+
String(LIMIT),
|
|
111
|
+
"--json",
|
|
112
|
+
"number,title,url,state,body",
|
|
113
|
+
]);
|
|
114
|
+
const all = JSON.parse(out);
|
|
115
|
+
if (all.length >= LIMIT) {
|
|
116
|
+
throw new Error(`${hub} has ${LIMIT} or more cases; Cupola cannot read them all yet`);
|
|
117
|
+
}
|
|
118
|
+
return all;
|
|
119
|
+
}
|
|
120
|
+
const summary = (i) => ({
|
|
121
|
+
id: caseIdOf(i),
|
|
122
|
+
title: i.title,
|
|
123
|
+
url: i.url,
|
|
124
|
+
open: i.state === "OPEN",
|
|
125
|
+
});
|
|
126
|
+
async function find(id) {
|
|
127
|
+
const all = await issues();
|
|
128
|
+
const n = /^#?(\d+)$/.exec(id)?.[1];
|
|
129
|
+
return all.find((i) => caseIdOf(i) === id || (n !== undefined && i.number === Number(n)));
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
async list() {
|
|
133
|
+
return (await issues()).map(summary);
|
|
134
|
+
},
|
|
135
|
+
async show(id) {
|
|
136
|
+
const issue = await find(id);
|
|
137
|
+
if (!issue)
|
|
138
|
+
return undefined;
|
|
139
|
+
const view = await issueView(root, hub, issue.number);
|
|
140
|
+
// The body is the case: one written by someone not trusted could be rewritten under it.
|
|
141
|
+
if (!trustedBy(trust, who(view))) {
|
|
142
|
+
throw new CaseError(`${caseIdOf(issue)} was opened by ${view.author?.login ?? "someone"}, whom the configuration does not trust: file it as a case of your own with cupola-intake, linking ${issue.url}`);
|
|
143
|
+
}
|
|
144
|
+
const meta = metaOf(view.body) ?? {};
|
|
145
|
+
const front = {
|
|
146
|
+
kind: "case",
|
|
147
|
+
...meta,
|
|
148
|
+
id: caseIdOf(issue),
|
|
149
|
+
title: issue.title,
|
|
150
|
+
};
|
|
151
|
+
// The issue's state is the case's `closed`.
|
|
152
|
+
if (issue.state === "CLOSED")
|
|
153
|
+
front.closed = view.closedAt?.slice(0, 10) ?? true;
|
|
154
|
+
const body = visible(view.body);
|
|
155
|
+
// Each comment is one Log line, dated when it was written (`cupola work log`).
|
|
156
|
+
const log = view.comments.map((c) => logLine(c, trust));
|
|
157
|
+
const text = `---\n${stringify(front).trimEnd()}\n---\n\n${body}\n${log.length > 0 && !/^## Log\s*$/m.test(body) ? "\n## Log\n" : ""}${log.length > 0 ? `\n${log.join("\n")}\n` : ""}`;
|
|
158
|
+
return { ...summary(issue), text };
|
|
159
|
+
},
|
|
160
|
+
async file(text) {
|
|
161
|
+
const { id, title, data, body } = parseCase(text);
|
|
162
|
+
if ((await issues()).some((i) => caseIdOf(i) === id))
|
|
163
|
+
throw new CaseError(`case ${id} is already filed`);
|
|
164
|
+
// Creates the label if it is missing; an existing one is left as it is.
|
|
165
|
+
await gh(root, [
|
|
166
|
+
"label",
|
|
167
|
+
"create",
|
|
168
|
+
CASE_LABEL,
|
|
169
|
+
"--repo",
|
|
170
|
+
hub,
|
|
171
|
+
"--description",
|
|
172
|
+
"A problem, filed by Cupola or by hand",
|
|
173
|
+
], (_code, stderr) => /already exists/i.test(stderr));
|
|
174
|
+
const url = await withBody(issueBody(body, data), (file) => gh(root, [
|
|
175
|
+
"issue",
|
|
176
|
+
"create",
|
|
177
|
+
"--repo",
|
|
178
|
+
hub,
|
|
179
|
+
"--title",
|
|
180
|
+
title,
|
|
181
|
+
"--body-file",
|
|
182
|
+
file,
|
|
183
|
+
"--label",
|
|
184
|
+
CASE_LABEL,
|
|
185
|
+
]));
|
|
186
|
+
return { id, title, url: url.split("\n").at(-1) ?? url, open: true };
|
|
187
|
+
},
|
|
188
|
+
async close(id, line) {
|
|
189
|
+
const issue = await find(id);
|
|
190
|
+
if (!issue)
|
|
191
|
+
throw new CaseError(`no case ${id}`);
|
|
192
|
+
if (issue.state === "CLOSED")
|
|
193
|
+
return false;
|
|
194
|
+
// The comment first, unless an earlier run that failed to close already wrote it.
|
|
195
|
+
const view = JSON.parse(await gh(root, [
|
|
196
|
+
"issue",
|
|
197
|
+
"view",
|
|
198
|
+
String(issue.number),
|
|
199
|
+
"--repo",
|
|
200
|
+
hub,
|
|
201
|
+
"--json",
|
|
202
|
+
"comments",
|
|
203
|
+
]));
|
|
204
|
+
if (view.comments.at(-1)?.body.trim() !== line.trim()) {
|
|
205
|
+
await withBody(line, (file) => gh(root, ["issue", "comment", String(issue.number), "--repo", hub, "--body-file", file]));
|
|
206
|
+
}
|
|
207
|
+
await gh(root, ["issue", "close", String(issue.number), "--repo", hub]);
|
|
208
|
+
return true;
|
|
209
|
+
},
|
|
210
|
+
async log(id, line) {
|
|
211
|
+
const issue = await find(id);
|
|
212
|
+
if (!issue)
|
|
213
|
+
throw new CaseError(`no case ${id}`);
|
|
214
|
+
await withBody(line, (file) => gh(root, ["issue", "comment", String(issue.number), "--repo", hub, "--body-file", file]));
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { git } from "../git.js";
|
|
2
|
+
import { repoOf } from "../host/github.js";
|
|
3
|
+
import { filesTracker } from "./files.js";
|
|
4
|
+
import { githubIssues } from "./github-issues.js";
|
|
5
|
+
/**
|
|
6
|
+
* The tracker the configuration names. Cases live in the hub: the
|
|
7
|
+
* github-issues tracker names it on every call; the files tracker writes to
|
|
8
|
+
* origin's `cupola/work`, so it runs only in the hub's own checkout.
|
|
9
|
+
*/
|
|
10
|
+
export async function trackerFor(root, config) {
|
|
11
|
+
if (config.tracker.kind === "github-issues")
|
|
12
|
+
return githubIssues(root, config.hub, config.trust);
|
|
13
|
+
let url = "";
|
|
14
|
+
try {
|
|
15
|
+
url = await git(root, ["remote", "get-url", "origin"]);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
url = "";
|
|
19
|
+
}
|
|
20
|
+
// A local path names no hosted repository to compare with the hub: taken as the hub.
|
|
21
|
+
const local = /^(\/|file:|[A-Za-z]:[\\/]|\.)/.test(url);
|
|
22
|
+
const origin = repoOf(url);
|
|
23
|
+
if (!local && origin !== config.hub.toLowerCase()) {
|
|
24
|
+
throw new Error(`the files tracker keeps cases in the hub ${config.hub}, but origin here is ${origin ?? "missing"}; run from the hub's checkout`);
|
|
25
|
+
}
|
|
26
|
+
return filesTracker(root);
|
|
27
|
+
}
|