@krysoworks/kryso 0.0.2 → 2.0.0-rc.1
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/LICENSE +21 -0
- package/README.md +146 -6
- package/bin/kryso +31 -0
- package/bin/ship-it-status +14 -0
- package/bin/ship-ledger +14 -0
- package/bin/ship-loop +14 -0
- package/bin/ship-pass +14 -0
- package/bin/warden +14 -0
- package/dist/answer.d.ts +38 -0
- package/dist/answer.js +48 -0
- package/dist/bytes.d.ts +5 -0
- package/dist/bytes.js +35 -0
- package/dist/cleanup.d.ts +1 -0
- package/dist/cleanup.js +629 -0
- package/dist/commands.d.ts +48 -0
- package/dist/commands.js +293 -0
- package/dist/completions.d.ts +24 -0
- package/dist/completions.js +239 -0
- package/dist/daemon.d.ts +15 -0
- package/dist/daemon.js +23 -0
- package/dist/diagnose.d.ts +47 -0
- package/dist/diagnose.js +314 -0
- package/dist/doctor.d.ts +1 -0
- package/dist/doctor.js +241 -0
- package/dist/env.d.ts +9 -0
- package/dist/env.js +17 -0
- package/dist/evidence.d.ts +39 -0
- package/dist/evidence.js +327 -0
- package/dist/home.d.ts +3 -0
- package/dist/home.js +27 -0
- package/dist/install.d.ts +59 -0
- package/dist/install.js +137 -0
- package/dist/isolate.d.ts +28 -0
- package/dist/isolate.js +402 -0
- package/dist/leftovers.d.ts +5 -0
- package/dist/leftovers.js +156 -0
- package/dist/machine.d.ts +6 -0
- package/dist/machine.js +185 -0
- package/dist/palette.d.ts +147 -0
- package/dist/palette.js +167 -0
- package/dist/plan.d.ts +1 -0
- package/dist/plan.js +133 -0
- package/dist/proc.d.ts +23 -0
- package/dist/proc.js +23 -0
- package/dist/read.d.ts +1 -0
- package/dist/read.js +297 -0
- package/dist/readiness.d.ts +5 -0
- package/dist/readiness.js +64 -0
- package/dist/remote.d.ts +6 -0
- package/dist/remote.js +85 -0
- package/dist/self-update.d.ts +1 -0
- package/dist/self-update.js +224 -0
- package/dist/semver.d.ts +7 -0
- package/dist/semver.js +42 -0
- package/dist/style.d.ts +71 -0
- package/dist/style.js +187 -0
- package/dist/update.d.ts +47 -0
- package/dist/update.js +190 -0
- package/dist/work.d.ts +25 -0
- package/dist/work.js +449 -0
- package/dist/workflows.d.ts +4 -0
- package/dist/workflows.js +73 -0
- package/docker/entrypoint.sh +44 -0
- package/docker/runner.Dockerfile +39 -0
- package/package.json +55 -22
- package/scripts/install-skills.sh +607 -0
- package/skills/code-review/SKILL.md +231 -0
- package/skills/kryso/SKILL.md +107 -0
- package/skills/kryso/golden/help.rounded.ansi +23 -0
- package/skills/kryso/golden/help.square.ansi +23 -0
- package/skills/kryso/golden/help.txt +23 -0
- package/skills/kryso/golden/table-narrow.json +11 -0
- package/skills/kryso/golden/table-narrow.rounded.ansi +4 -0
- package/skills/kryso/golden/table-narrow.square.ansi +4 -0
- package/skills/kryso/golden/table.ansi +5 -0
- package/skills/kryso/golden/table.json +11 -0
- package/skills/kryso/ledger.sh +2146 -0
- package/skills/kryso/palette.json +57 -0
- package/skills/kryso/reference/resuming.md +30 -0
- package/skills/kryso/reference/routing.md +23 -0
- package/skills/kryso/reference/stage-1-claim.md +79 -0
- package/skills/kryso/reference/stage-2-build.md +133 -0
- package/skills/kryso/reference/stage-3-prove.md +51 -0
- package/skills/kryso/reference/stage-4-pr.md +76 -0
- package/skills/kryso/reference/stage-5-reconcile.md +81 -0
- package/skills/kryso/reference/stage-6-merge-or-park.md +73 -0
- package/skills/kryso/reference/stage-7-close-out.md +62 -0
- package/skills/kryso/reference/terminal.md +7 -0
- package/skills/kryso/ship-it-status.sh +1503 -0
- package/skills/kryso/ui.py +274 -0
- package/skills/kryso/ui.sh +609 -0
- package/skills/kryso-build/SKILL.md +168 -0
- package/skills/kryso-shift/SKILL.md +167 -0
- package/skills/kryso-shift/archive.py +2784 -0
- package/skills/kryso-shift/archive_checker.py +462 -0
- package/skills/kryso-shift/archive_checker_lambda.py +155 -0
- package/skills/kryso-shift/archive_health.py +364 -0
- package/skills/kryso-shift/archive_launchd.py +140 -0
- package/skills/kryso-shift/archive_remote.py +990 -0
- package/skills/kryso-shift/archiving-checker.md +140 -0
- package/skills/kryso-shift/archiving-keep.md +115 -0
- package/skills/kryso-shift/archiving-recovery.md +112 -0
- package/skills/kryso-shift/archiving-remote.md +166 -0
- package/skills/kryso-shift/archiving.md +146 -0
- package/skills/kryso-shift/coverage.schema.json +225 -0
- package/skills/kryso-shift/deadline.sh +254 -0
- package/skills/kryso-shift/feedback.schema.json +35 -0
- package/skills/kryso-shift/feedback.sh +228 -0
- package/skills/kryso-shift/history-manifest.schema.json +331 -0
- package/skills/kryso-shift/keep-after.sh +55 -0
- package/skills/kryso-shift/measure.sh +611 -0
- package/skills/kryso-shift/merge-ready.sh +207 -0
- package/skills/kryso-shift/outcome.schema.json +16 -0
- package/skills/kryso-shift/pass-rules.md +8 -0
- package/skills/kryso-shift/profile.schema.json +42 -0
- package/skills/kryso-shift/reader.sh +692 -0
- package/skills/kryso-shift/reads.sh +151 -0
- package/skills/kryso-shift/reference/allowance.md +21 -0
- package/skills/kryso-shift/reference/driver.md +95 -0
- package/skills/kryso-shift/reference/measuring.md +67 -0
- package/skills/kryso-shift/reference/outputs.md +21 -0
- package/skills/kryso-shift/reference/pass-script.md +115 -0
- package/skills/kryso-shift/reference/reconcile-and-merge.md +55 -0
- package/skills/kryso-shift/reference/second-reader.md +9 -0
- package/skills/kryso-shift/reference/sweeps.md +83 -0
- package/skills/kryso-shift/repair.schema.json +14 -0
- package/skills/kryso-shift/report-template.html +679 -0
- package/skills/kryso-shift/report.py +389 -0
- package/skills/kryso-shift/report_fixture.py +65 -0
- package/skills/kryso-shift/reporting.md +58 -0
- package/skills/kryso-shift/result.sh +91 -0
- package/skills/kryso-shift/runner.sh +1178 -0
- package/skills/kryso-shift/ship-loop.sh +3977 -0
- package/skills/kryso-shift/ship-pass.sh +4987 -0
- package/skills/kryso-shift/steps.jq +19 -0
- package/skills/kryso-shift/workflow.mjs +830 -0
- package/skills/kryso-shift/workflows/default.json +22 -0
- package/skills/kryso-shift/workflows/ralph.json +13 -0
- package/skills/kryso-watch/SKILL.md +100 -0
- package/skills/kryso-watch/answer.schema.json +23 -0
- package/skills/kryso-watch/base-refs.sh +44 -0
- package/skills/kryso-watch/board.sh +58 -0
- package/skills/kryso-watch/reference/config.md +23 -0
- package/skills/kryso-watch/reference/outputs.md +30 -0
- package/skills/kryso-watch/reference/report.md +29 -0
- package/skills/kryso-watch/reference/scheduler.md +32 -0
- package/skills/kryso-watch/reference/settlement.md +29 -0
- package/skills/kryso-watch/reference/shift.md +44 -0
- package/skills/kryso-watch/reference/shim-limits.md +22 -0
- package/skills/kryso-watch/reference/triage.md +26 -0
- package/skills/kryso-watch/schema.jq +40 -0
- package/skills/kryso-watch/settle.schema.json +36 -0
- package/skills/kryso-watch/stage-common.sh +187 -0
- package/skills/kryso-watch/stages/report.sh +525 -0
- package/skills/kryso-watch/stages/settle.sh +722 -0
- package/skills/kryso-watch/stages/shift.sh +466 -0
- package/skills/kryso-watch/stages/triage.sh +379 -0
- package/skills/kryso-watch/tracker.sh +27 -0
- package/skills/kryso-watch/triage.schema.json +77 -0
- package/skills/kryso-watch/warden.launchd.plist +50 -0
- package/skills/kryso-watch/warden.schema.json +98 -0
- package/skills/kryso-watch/warden.sh +1004 -0
- package/bin/kryso.js +0 -11
|
@@ -0,0 +1,830 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// @ts-check
|
|
3
|
+
// workflow: the one resolver of a repository's workflows (ADR 0046). `kryso workflow` runs it,
|
|
4
|
+
// and the pass and the shift run it beside themselves, as they run every module here, before
|
|
5
|
+
// anything is claimed.
|
|
6
|
+
//
|
|
7
|
+
// show [name] [--ref R] [--repo DIR] [--json] [--built-in]
|
|
8
|
+
// the workflow resolved at a ref: .kryso/workflows/<name>.json read with git and applied
|
|
9
|
+
// over the built-in it extends, else the built-in of that name. The name defaults to
|
|
10
|
+
// `default`, so a repository with no .kryso/ resolves to the built-in default. With
|
|
11
|
+
// --built-in, kryso's own workflow of that name, whatever the repository holds.
|
|
12
|
+
// choose [--flag NAME] [--labels a,b,...]
|
|
13
|
+
// which workflow a pass runs, by the rule: a flag beats a label, a label beats the
|
|
14
|
+
// repository's default, and a workflow:ralph label beats a flag. Prints the name, what
|
|
15
|
+
// chose it and, when a label beat a flag, why, tab-separated.
|
|
16
|
+
// check FILE
|
|
17
|
+
// check one workflow file against the frozen schema's rules, as core's tests do.
|
|
18
|
+
// fetch [name] [--ref R] [--repo DIR]
|
|
19
|
+
// put each pin the resolved workflow names into kryso's store, ~/.kryso/skills, where it
|
|
20
|
+
// is not there yet, and print one line per pin: its stage, skill, source, path, commit,
|
|
21
|
+
// the skill's folder in the store and whether this run fetched it or found it stored.
|
|
22
|
+
// The pass runs it before the claim, so a pin it cannot fetch claims nothing.
|
|
23
|
+
// update [--repo DIR] [--dry-run]
|
|
24
|
+
// move each pin the repository's own workflow files name to the newest commit on its
|
|
25
|
+
// source's default branch that changed the skill's folder, through one pull request whose
|
|
26
|
+
// body holds each skill's diff, so a skill never changes silently. One line per pin, as
|
|
27
|
+
// fetch prints, then the pull request's URL. --dry-run prints the lines and the body and
|
|
28
|
+
// writes nothing. The built-in workflows' pins move with kryso, not here.
|
|
29
|
+
// pins [--repo DIR] [--offline]
|
|
30
|
+
// as JSON, each workflow the repository's files name at HEAD, whether it resolves, and each pin it
|
|
31
|
+
// runs: whether the store holds it and, for a pin the file itself names and unless
|
|
32
|
+
// --offline, the newest commit for its skill. kryso doctor reads it.
|
|
33
|
+
//
|
|
34
|
+
// The schema of record is packages/core/schemas/workflow/2.schema.json, and a file may still name
|
|
35
|
+
// version 1, which has no role. This module runs where
|
|
36
|
+
// core is not installed, so it checks a file itself, and core's test holds the two to the same
|
|
37
|
+
// verdicts over its fixtures. Rules the schema cannot hold are here alone: the fixed stages, the
|
|
38
|
+
// ids a change names, and the built-in a file extends.
|
|
39
|
+
|
|
40
|
+
import { createHash } from "node:crypto";
|
|
41
|
+
import { spawnSync } from "node:child_process";
|
|
42
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
43
|
+
import os from "node:os";
|
|
44
|
+
import path from "node:path";
|
|
45
|
+
import { fileURLToPath } from "node:url";
|
|
46
|
+
|
|
47
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
48
|
+
const BUILT_INS = path.join(HERE, "workflows");
|
|
49
|
+
const EX_USAGE = 64;
|
|
50
|
+
const EX_UNAVAILABLE = 69;
|
|
51
|
+
const EX_CANTCREAT = 73;
|
|
52
|
+
const EX_CONFIG = 78;
|
|
53
|
+
|
|
54
|
+
/** The four stages every workflow keeps, which no file may remove or replace. */
|
|
55
|
+
const FIXED = ["claim", "prove", "merge", "closeout"];
|
|
56
|
+
/** Built-in kinds a file may keep or remove, but not define. */
|
|
57
|
+
const BUILT_IN_ONLY = ["claim", "prove", "pr", "reconcile", "merge", "closeout"];
|
|
58
|
+
/** Built-in kinds a file may name in a stage of its own. */
|
|
59
|
+
const NAMED_KINDS = ["slice-loop", "repair"];
|
|
60
|
+
const READS = ["previous-attempt", "findings", "park-reason", "handoff"];
|
|
61
|
+
/** The roles a repository binds to a profile, as the glossary names them, and a judgement stage may take. */
|
|
62
|
+
const ROLES = ["plan", "build", "helper", "reader", "cross-reviewer"];
|
|
63
|
+
/** The file versions this resolver reads: version 2 adds a judgement stage's role. */
|
|
64
|
+
const VERSIONS = ["kryso-workflow/1", "kryso-workflow/2"];
|
|
65
|
+
/** Where a shift runs a workflow's shift stages: after each pass, and once at its end. */
|
|
66
|
+
const SHIFT_POINTS = ["after-pass", "end"];
|
|
67
|
+
const NAME = /^[a-z0-9][a-z0-9-]*$/;
|
|
68
|
+
const STAGE_ID = /^[a-z][a-z0-9-]*$/;
|
|
69
|
+
const SKILL = /^[a-z0-9][a-z0-9-]*(:[a-z0-9][a-z0-9-]*)?$/;
|
|
70
|
+
|
|
71
|
+
class Refusal extends Error {
|
|
72
|
+
/** @param {number} code @param {string} message */
|
|
73
|
+
constructor(code, message) {
|
|
74
|
+
super(message);
|
|
75
|
+
this.code = code;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// ---- the file's shape, as packages/core/schemas/workflow/2.schema.json states it -------------
|
|
80
|
+
|
|
81
|
+
/** @param {unknown} v @returns {v is Record<string, any>} */
|
|
82
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
83
|
+
|
|
84
|
+
/** @param {Record<string, unknown>} v @param {string} at @param {string[]} required @param {string[]} allowed */
|
|
85
|
+
function checkKeys(v, at, required, allowed) {
|
|
86
|
+
for (const key of required) if (!(key in v)) throw new Error(`${at} has no ${key}`);
|
|
87
|
+
for (const key of Object.keys(v)) if (!allowed.includes(key)) throw new Error(`${at} has ${key}, which a workflow does not take`);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** @param {unknown} v @param {RegExp} re @param {string} at @param {string} what */
|
|
91
|
+
function checkMatch(v, re, at, what) {
|
|
92
|
+
if (typeof v !== "string" || !re.test(v)) throw new Error(`${at} is ${JSON.stringify(v)}, not ${what}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param {unknown} v @param {string} at */
|
|
96
|
+
function checkStrings(v, at, min = 0) {
|
|
97
|
+
if (!Array.isArray(v) || v.length < min || !v.every((s) => typeof s === "string" && s.length > 0)) {
|
|
98
|
+
throw new Error(`${at} must be a list of ${min > 0 ? "one or more " : ""}non-empty strings`);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** @param {unknown} step @param {string} at */
|
|
103
|
+
function checkStep(step, at) {
|
|
104
|
+
if (!isObject(step)) throw new Error(`${at} must be an object`);
|
|
105
|
+
checkKeys(step, at, ["skill"], ["skill", "pin", "when", "evidence"]);
|
|
106
|
+
checkMatch(step.skill, SKILL, `${at}.skill`, "a skill name");
|
|
107
|
+
if ("pin" in step) {
|
|
108
|
+
const pin = step.pin;
|
|
109
|
+
if (!isObject(pin)) throw new Error(`${at}.pin must be an object`);
|
|
110
|
+
checkKeys(pin, `${at}.pin`, ["source", "path", "commit"], ["source", "path", "commit"]);
|
|
111
|
+
checkMatch(pin.source, /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/, `${at}.pin.source`, "<owner>/<repo>");
|
|
112
|
+
checkMatch(pin.path, /./, `${at}.pin.path`, "a path");
|
|
113
|
+
checkMatch(pin.commit, /^[0-9a-f]{40}$/, `${at}.pin.commit`, "a full commit");
|
|
114
|
+
}
|
|
115
|
+
if ("when" in step) {
|
|
116
|
+
const when = step.when;
|
|
117
|
+
if (!isObject(when) || Object.keys(when).length === 0) throw new Error(`${at}.when must name at least one field`);
|
|
118
|
+
checkKeys(when, `${at}.when`, [], ["seam", "label", "entry"]);
|
|
119
|
+
if ("seam" in when && !["tdd", "no-seam"].includes(/** @type {string} */ (when.seam))) throw new Error(`${at}.when.seam is ${JSON.stringify(when.seam)}, not tdd or no-seam`);
|
|
120
|
+
if ("label" in when) checkMatch(when.label, /./, `${at}.when.label`, "a label");
|
|
121
|
+
if ("entry" in when && !["issue", "description"].includes(/** @type {string} */ (when.entry))) throw new Error(`${at}.when.entry is ${JSON.stringify(when.entry)}, not issue or description`);
|
|
122
|
+
}
|
|
123
|
+
if ("evidence" in step) {
|
|
124
|
+
const ev = step.evidence;
|
|
125
|
+
if (!isObject(ev)) throw new Error(`${at}.evidence must be an object`);
|
|
126
|
+
checkKeys(ev, `${at}.evidence`, [], ["events", "receipts", "paths"]);
|
|
127
|
+
if ("events" in ev) {
|
|
128
|
+
if (!Array.isArray(ev.events)) throw new Error(`${at}.evidence.events must be a list`);
|
|
129
|
+
ev.events.forEach((e, i) => {
|
|
130
|
+
const where = `${at}.evidence.events[${i}]`;
|
|
131
|
+
if (!isObject(e)) throw new Error(`${where} must be an object`);
|
|
132
|
+
checkKeys(e, where, ["stage", "outcome"], ["stage", "outcome", "min"]);
|
|
133
|
+
checkMatch(e.stage, /^[A-Za-z][A-Za-z0-9_-]*$/, `${where}.stage`, "one word");
|
|
134
|
+
checkMatch(e.outcome, /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/, `${where}.outcome`, "one word");
|
|
135
|
+
if ("min" in e && !(Number.isInteger(e.min) && /** @type {number} */ (e.min) >= 1)) throw new Error(`${where}.min must be a whole number from 1`);
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
if ("receipts" in ev) checkStrings(ev.receipts, `${at}.evidence.receipts`);
|
|
139
|
+
if ("paths" in ev) checkStrings(ev.paths, `${at}.evidence.paths`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** A stage: in a file, a built-in-only kind is refused; in a built-in, every kind is a stage. A
|
|
144
|
+
* judgement stage takes a role only in a version 2 file or a built-in.
|
|
145
|
+
* @param {unknown} stage @param {string} at @param {boolean} inFile @param {boolean} [allowsRole] */
|
|
146
|
+
function checkStage(stage, at, inFile, allowsRole = true) {
|
|
147
|
+
if (!isObject(stage)) throw new Error(`${at} must be an object`);
|
|
148
|
+
checkMatch(stage.id, STAGE_ID, `${at}.id`, "a stage id");
|
|
149
|
+
const kind = stage.kind;
|
|
150
|
+
if (kind === "judgement") {
|
|
151
|
+
checkKeys(stage, at, ["id", "kind", "steps"], ["id", "kind", "profile", "reads", "steps", ...(allowsRole ? ["role"] : [])]);
|
|
152
|
+
if ("profile" in stage) checkMatch(stage.profile, /./, `${at}.profile`, "a profile name");
|
|
153
|
+
if ("role" in stage && !ROLES.includes(/** @type {string} */ (stage.role))) throw new Error(`${at}.role is ${JSON.stringify(stage.role)}, not ${ROLES.join(", ")}`);
|
|
154
|
+
if ("reads" in stage) {
|
|
155
|
+
const reads = stage.reads;
|
|
156
|
+
if (!Array.isArray(reads) || new Set(reads).size !== reads.length || !reads.every((r) => READS.includes(r))) {
|
|
157
|
+
throw new Error(`${at}.reads must list each of ${READS.join(", ")} at most once`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (!Array.isArray(stage.steps) || stage.steps.length === 0) throw new Error(`${at}.steps must list one step or more`);
|
|
161
|
+
stage.steps.forEach((s, i) => checkStep(s, `${at}.steps[${i}]`));
|
|
162
|
+
} else if (kind === "commands") {
|
|
163
|
+
checkKeys(stage, at, ["id", "kind", "commands"], ["id", "kind", "commands"]);
|
|
164
|
+
checkStrings(stage.commands, `${at}.commands`, 1);
|
|
165
|
+
} else if (NAMED_KINDS.includes(/** @type {string} */ (kind)) || (!inFile && BUILT_IN_ONLY.includes(/** @type {string} */ (kind)))) {
|
|
166
|
+
checkKeys(stage, at, ["id", "kind"], ["id", "kind"]);
|
|
167
|
+
} else if (BUILT_IN_ONLY.includes(/** @type {string} */ (kind))) {
|
|
168
|
+
throw new Error(`${at} defines a ${kind} stage, which only a built-in workflow carries`);
|
|
169
|
+
} else {
|
|
170
|
+
throw new Error(`${at}.kind is ${JSON.stringify(kind)}, not judgement, commands, ${NAMED_KINDS.join(" or ")}`);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** A file's shift stages: commands only, because the shift driver runs them and no model does.
|
|
175
|
+
* @param {unknown} shift */
|
|
176
|
+
function checkShift(shift) {
|
|
177
|
+
if (!isObject(shift)) throw new Error("shift must be an object");
|
|
178
|
+
checkKeys(shift, "shift", [], SHIFT_POINTS);
|
|
179
|
+
for (const at of SHIFT_POINTS) {
|
|
180
|
+
if (!(at in shift)) continue;
|
|
181
|
+
const stages = shift[at];
|
|
182
|
+
if (!Array.isArray(stages)) throw new Error(`shift.${at} must be a list`);
|
|
183
|
+
stages.forEach((s, i) => {
|
|
184
|
+
const where = `shift.${at}[${i}]`;
|
|
185
|
+
if (isObject(s) && s.kind !== "commands") throw new Error(`${where} is a ${JSON.stringify(s.kind)} stage, and a shift runs commands stages only`);
|
|
186
|
+
checkStage(s, where, true);
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** @param {unknown} file */
|
|
192
|
+
export function checkFile(file) {
|
|
193
|
+
if (!isObject(file)) throw new Error("a workflow file is one JSON object");
|
|
194
|
+
checkKeys(file, "the file", ["schema", "extends", "changes"], ["schema", "extends", "description", "changes", "shift"]);
|
|
195
|
+
if (!VERSIONS.includes(/** @type {string} */ (file.schema))) throw new Error(`schema is ${JSON.stringify(file.schema)}, not ${VERSIONS.map((v) => JSON.stringify(v)).join(" or ")}`);
|
|
196
|
+
const allowsRole = file.schema !== "kryso-workflow/1";
|
|
197
|
+
checkMatch(file.extends, NAME, "extends", "a workflow name");
|
|
198
|
+
if ("description" in file && typeof file.description !== "string") throw new Error("description must be a string");
|
|
199
|
+
if ("shift" in file) checkShift(file.shift);
|
|
200
|
+
if (!Array.isArray(file.changes)) throw new Error("changes must be a list");
|
|
201
|
+
file.changes.forEach((c, i) => {
|
|
202
|
+
const at = `changes[${i}]`;
|
|
203
|
+
if (!isObject(c)) throw new Error(`${at} must be an object`);
|
|
204
|
+
if ("remove" in c) {
|
|
205
|
+
checkKeys(c, at, ["remove"], ["remove"]);
|
|
206
|
+
checkMatch(c.remove, STAGE_ID, `${at}.remove`, "a stage id");
|
|
207
|
+
} else if ("replace" in c) {
|
|
208
|
+
checkKeys(c, at, ["replace", "with"], ["replace", "with"]);
|
|
209
|
+
checkMatch(c.replace, STAGE_ID, `${at}.replace`, "a stage id");
|
|
210
|
+
checkStage(c.with, `${at}.with`, true, allowsRole);
|
|
211
|
+
} else if ("insert" in c) {
|
|
212
|
+
const anchor = "before" in c ? "before" : "after";
|
|
213
|
+
checkKeys(c, at, ["insert", anchor], ["insert", anchor]);
|
|
214
|
+
checkMatch(c[anchor], STAGE_ID, `${at}.${anchor}`, "a stage id");
|
|
215
|
+
checkStage(c.insert, `${at}.insert`, true, allowsRole);
|
|
216
|
+
} else {
|
|
217
|
+
throw new Error(`${at} is not a remove, replace or insert`);
|
|
218
|
+
}
|
|
219
|
+
});
|
|
220
|
+
return /** @type {{ extends: string, changes: Record<string, any>[], shift?: Record<string, Record<string, any>[]> }} */ (file);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// ---- the built-ins and the resolution -------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
/** @returns {Map<string, { name: string, stages: Record<string, any>[] }>} */
|
|
226
|
+
function builtIns() {
|
|
227
|
+
const all = new Map();
|
|
228
|
+
for (const f of readdirSync(BUILT_INS).filter((f) => f.endsWith(".json")).sort()) {
|
|
229
|
+
const w = JSON.parse(readFileSync(path.join(BUILT_INS, f), "utf8"));
|
|
230
|
+
w.stages.forEach((/** @type {unknown} */ s, /** @type {number} */ i) => checkStage(s, `${f} stages[${i}]`, false));
|
|
231
|
+
all.set(w.name, w);
|
|
232
|
+
}
|
|
233
|
+
return all;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** JSON with every object's keys sorted and no spaces, which the hash is taken over.
|
|
237
|
+
* @param {unknown} v @returns {string} */
|
|
238
|
+
function canonical(v) {
|
|
239
|
+
if (Array.isArray(v)) return `[${v.map(canonical).join(",")}]`;
|
|
240
|
+
if (isObject(v)) return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canonical(v[k])}`).join(",")}}`;
|
|
241
|
+
return JSON.stringify(v);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Apply a file's changes, in order, over its base's stages.
|
|
245
|
+
* @param {Record<string, any>[]} base @param {string} baseSource @param {Record<string, any>[]} changes @param {string} file */
|
|
246
|
+
function apply(base, baseSource, changes, file) {
|
|
247
|
+
const stages = base.map((s) => ({ stage: s, source: baseSource }));
|
|
248
|
+
const index = (/** @type {string} */ id, /** @type {string} */ verb) => {
|
|
249
|
+
const i = stages.findIndex((s) => s.stage.id === id);
|
|
250
|
+
if (i < 0) throw new Error(`${verb} '${id}', which is not a stage of the workflow it changes (${stages.map((s) => s.stage.id).join(", ")})`);
|
|
251
|
+
return i;
|
|
252
|
+
};
|
|
253
|
+
const refuseDuplicateId = (/** @type {string} */ id, /** @type {number} */ except) => {
|
|
254
|
+
if (stages.some((s, i) => i !== except && s.stage.id === id)) throw new Error(`adds a second stage with the id '${id}'`);
|
|
255
|
+
};
|
|
256
|
+
for (const c of changes) {
|
|
257
|
+
if ("remove" in c || "replace" in c) {
|
|
258
|
+
const id = c.remove ?? c.replace;
|
|
259
|
+
const verb = "remove" in c ? "removes" : "replaces";
|
|
260
|
+
const i = index(id, verb);
|
|
261
|
+
if (FIXED.includes(id)) throw new Error(`${verb} '${id}', one of the stages every workflow keeps (${FIXED.join(", ")})`);
|
|
262
|
+
if ("remove" in c) {
|
|
263
|
+
stages.splice(i, 1);
|
|
264
|
+
} else {
|
|
265
|
+
if (BUILT_IN_ONLY.includes(stages[i].stage.kind)) throw new Error(`replaces '${id}', a built-in stage a workflow may keep or remove but not redefine`);
|
|
266
|
+
refuseDuplicateId(c.with.id, i);
|
|
267
|
+
stages[i] = { stage: c.with, source: file };
|
|
268
|
+
}
|
|
269
|
+
} else {
|
|
270
|
+
const anchor = c.before ?? c.after;
|
|
271
|
+
const i = index(anchor, `inserts '${c.insert.id}' ${"before" in c ? "before" : "after"}`);
|
|
272
|
+
if (("before" in c && anchor === "claim") || ("after" in c && anchor === "closeout")) {
|
|
273
|
+
throw new Error(`inserts '${c.insert.id}' ${"before" in c ? "before claim" : "after closeout"}, and a workflow's stages run between the two`);
|
|
274
|
+
}
|
|
275
|
+
refuseDuplicateId(c.insert.id, -1);
|
|
276
|
+
stages.splice("before" in c ? i : i + 1, 0, { stage: c.insert, source: file });
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
// The build stage maps to the build role by what it is, so a file cannot move it to another.
|
|
280
|
+
const build = stages.find((s) => s.stage.id === "build")?.stage;
|
|
281
|
+
if (build?.role !== undefined && build.role !== "build") throw new Error(`gives the build stage the role '${build.role}', and the build runs as the build role`);
|
|
282
|
+
return stages;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** A file's shift stages, whose ids are one namespace across both points, as a pass's stages are.
|
|
286
|
+
* @param {Record<string, Record<string, any>[]>} shift */
|
|
287
|
+
function checkShiftIds(shift) {
|
|
288
|
+
const seen = new Set();
|
|
289
|
+
for (const at of SHIFT_POINTS) {
|
|
290
|
+
for (const s of shift[at] ?? []) {
|
|
291
|
+
if (seen.has(s.id)) throw new Error(`adds a second shift stage with the id '${s.id}'`);
|
|
292
|
+
seen.add(s.id);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** @param {string[]} args @param {string} cwd */
|
|
298
|
+
function git(args, cwd) {
|
|
299
|
+
const r = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf8" });
|
|
300
|
+
return { ok: r.status === 0, out: (r.stdout ?? "").trim(), err: (r.stderr ?? "").trim() };
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** The workflow <name> resolved at <ref> in the repository at <repo>, or kryso's own workflow of
|
|
304
|
+
* that name when builtIn is set, so a caller can tell whether a repository changes it.
|
|
305
|
+
* @param {string} repo @param {string} ref @param {string} name */
|
|
306
|
+
export function resolve(repo, ref, name, builtIn = false) {
|
|
307
|
+
if (!NAME.test(name)) throw new Refusal(EX_USAGE, `'${name}' is not a workflow name: lowercase letters, digits and dashes`);
|
|
308
|
+
const top = git(["rev-parse", "--show-toplevel"], repo);
|
|
309
|
+
if (!top.ok) throw new Refusal(EX_UNAVAILABLE, `${repo} is not in a git repository`);
|
|
310
|
+
const commit = git(["rev-parse", "--verify", "-q", `${ref}^{commit}`], top.out);
|
|
311
|
+
if (!commit.ok) throw new Refusal(EX_USAGE, `the ref '${ref}' does not name a commit in ${top.out}`);
|
|
312
|
+
const known = builtIns();
|
|
313
|
+
const file = `.kryso/workflows/${name}.json`;
|
|
314
|
+
const shown = builtIn ? { ok: false, out: "", err: "" } : git(["show", `${commit.out}:${file}`], top.out);
|
|
315
|
+
let resolved;
|
|
316
|
+
if (shown.ok) {
|
|
317
|
+
const refuse = (/** @type {string} */ why) => new Refusal(EX_CONFIG, `${file} at ${ref}: ${why}`);
|
|
318
|
+
let parsed;
|
|
319
|
+
try {
|
|
320
|
+
parsed = JSON.parse(shown.out);
|
|
321
|
+
} catch (e) {
|
|
322
|
+
throw refuse(`not JSON: ${/** @type {Error} */ (e).message}`);
|
|
323
|
+
}
|
|
324
|
+
let body;
|
|
325
|
+
try {
|
|
326
|
+
body = checkFile(parsed);
|
|
327
|
+
} catch (e) {
|
|
328
|
+
throw refuse(`does not match the workflow schema: ${/** @type {Error} */ (e).message}`);
|
|
329
|
+
}
|
|
330
|
+
const base = known.get(body.extends);
|
|
331
|
+
if (!base) throw refuse(`extends '${body.extends}', which is not a built-in workflow (${[...known.keys()].join(", ")})`);
|
|
332
|
+
let stages;
|
|
333
|
+
try {
|
|
334
|
+
stages = apply(base.stages, `built-in:${base.name}`, body.changes, file);
|
|
335
|
+
checkShiftIds(body.shift ?? {});
|
|
336
|
+
} catch (e) {
|
|
337
|
+
throw refuse(/** @type {Error} */ (e).message);
|
|
338
|
+
}
|
|
339
|
+
resolved = { name, file, extends: base.name, stages, shift: body.shift ?? {} };
|
|
340
|
+
} else {
|
|
341
|
+
const base = known.get(name);
|
|
342
|
+
if (!base) {
|
|
343
|
+
throw new Refusal(EX_CONFIG, `no workflow named '${name}': ${file} is not at ${ref}, and kryso has no built-in of that name (${[...known.keys()].join(", ")})`);
|
|
344
|
+
}
|
|
345
|
+
resolved = { name, file: null, extends: null, stages: base.stages.map((s) => ({ stage: s, source: `built-in:${base.name}` })), shift: {} };
|
|
346
|
+
}
|
|
347
|
+
const stages = resolved.stages.map((s) => s.stage);
|
|
348
|
+
return {
|
|
349
|
+
schema: "kryso-workflow-resolved/2",
|
|
350
|
+
name: resolved.name,
|
|
351
|
+
hash: createHash("sha256").update(canonical(stages)).digest("hex"),
|
|
352
|
+
ref,
|
|
353
|
+
commit: commit.out,
|
|
354
|
+
file: resolved.file,
|
|
355
|
+
extends: resolved.extends,
|
|
356
|
+
stages,
|
|
357
|
+
sources: Object.fromEntries(resolved.stages.map((s) => [s.stage.id, s.source])),
|
|
358
|
+
shift: Object.fromEntries(SHIFT_POINTS.map((at) => [at, resolved.shift[at] ?? []])),
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// ---- pins and the store ----------------------------------------------------------------------
|
|
363
|
+
|
|
364
|
+
/** Every pin the workflow's judgement stages name, in stage and step order.
|
|
365
|
+
* @param {ReturnType<typeof resolve>} w */
|
|
366
|
+
export function pinsOf(w) {
|
|
367
|
+
return w.stages
|
|
368
|
+
.filter((s) => s.kind === "judgement")
|
|
369
|
+
.flatMap((s) => s.steps.filter((/** @type {Record<string, any>} */ st) => st.pin).map((/** @type {Record<string, any>} */ st) => ({ stage: s.id, skill: st.skill, ...st.pin })));
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Where a pin's source is fetched from: KRYSO_PIN_SOURCES, a URL or a directory that holds
|
|
373
|
+
* <owner>/<repo>.git, else GitHub.
|
|
374
|
+
* @param {string} source */
|
|
375
|
+
function sourceUrl(source) {
|
|
376
|
+
return `${(process.env.KRYSO_PIN_SOURCES || "https://github.com").replace(/\/+$/, "")}/${source}.git`;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/** Whether the tree at root holds the pin's skill: its path stays inside root and has a SKILL.md.
|
|
380
|
+
* @param {string} root @param {{ path: string }} pin */
|
|
381
|
+
const holds = (root, pin) => {
|
|
382
|
+
const rel = path.relative(root, path.join(root, pin.path));
|
|
383
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel) && existsSync(path.join(root, pin.path, "SKILL.md"));
|
|
384
|
+
};
|
|
385
|
+
|
|
386
|
+
/** The pin's entry in kryso's store, ~/.kryso/skills/<owner>/<repo>@<commit>/, and its skill's
|
|
387
|
+
* folder there, whether or not the store holds them yet.
|
|
388
|
+
* @param {{ skill: string, source: string, path: string, commit: string }} pin */
|
|
389
|
+
export function entryOf(pin) {
|
|
390
|
+
const [owner, repo] = pin.source.split("/");
|
|
391
|
+
if ([owner, repo].some((part) => /^\.+$/.test(part))) throw new Refusal(EX_CONFIG, `the pin ${pin.skill} names the source ${pin.source}, which is not <owner>/<repo>`);
|
|
392
|
+
const entry = path.join(os.homedir(), ".kryso", "skills", owner, `${repo}@${pin.commit}`);
|
|
393
|
+
return { entry, dir: path.join(entry, pin.path), repo };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** The pin's skill folder in kryso's store, fetched first when the store lacks its entry. An
|
|
397
|
+
* entry is one source at one commit, ~/.kryso/skills/<owner>/<repo>@<commit>/, written whole
|
|
398
|
+
* under a temporary name and renamed into place, so a reader never sees half of one, and never
|
|
399
|
+
* written again once it is there (ADR 0046).
|
|
400
|
+
* @param {{ skill: string, source: string, path: string, commit: string }} pin */
|
|
401
|
+
export function fetchPin(pin) {
|
|
402
|
+
const { entry, dir, repo } = entryOf(pin);
|
|
403
|
+
const at = `${pin.source} at ${pin.commit.slice(0, 12)}`;
|
|
404
|
+
const missing = () => new Refusal(EX_UNAVAILABLE, `the pin ${pin.skill} names ${pin.path}, which ${at} does not hold as a skill`);
|
|
405
|
+
if (existsSync(entry)) {
|
|
406
|
+
if (!holds(entry, pin)) throw missing();
|
|
407
|
+
return { dir, status: "stored" };
|
|
408
|
+
}
|
|
409
|
+
mkdirSync(path.dirname(entry), { recursive: true });
|
|
410
|
+
const tmp = mkdtempSync(path.join(path.dirname(entry), `.${repo}@${pin.commit}.`));
|
|
411
|
+
try {
|
|
412
|
+
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
|
|
413
|
+
for (const args of [["init", "-q"], ["fetch", "-q", "--depth", "1", sourceUrl(pin.source), pin.commit], ["-c", "advice.detachedHead=false", "checkout", "-q", "FETCH_HEAD"]]) {
|
|
414
|
+
const r = spawnSync("git", ["-C", tmp, ...args], { encoding: "utf8", env });
|
|
415
|
+
if (r.status !== 0) throw new Refusal(EX_UNAVAILABLE, `cannot fetch the pin ${pin.skill}, ${at}: ${(r.stderr ?? "").trim().split("\n")[0] || `git ${args[0]} failed`}`);
|
|
416
|
+
}
|
|
417
|
+
if (!holds(tmp, pin)) throw missing();
|
|
418
|
+
rmSync(path.join(tmp, ".git"), { recursive: true, force: true });
|
|
419
|
+
try {
|
|
420
|
+
renameSync(tmp, entry);
|
|
421
|
+
} catch (e) {
|
|
422
|
+
// Another pass wrote the entry first, and the one there stands.
|
|
423
|
+
if (!existsSync(entry)) throw e;
|
|
424
|
+
return { dir, status: "stored" };
|
|
425
|
+
}
|
|
426
|
+
return { dir, status: "fetched" };
|
|
427
|
+
} finally {
|
|
428
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** Which workflow a pass runs, and why.
|
|
433
|
+
* @param {string} flag @param {string[]} labels */
|
|
434
|
+
export function choose(flag, labels) {
|
|
435
|
+
const named = [...new Set(labels.filter((l) => l.startsWith("workflow:")))];
|
|
436
|
+
if (named.length > 1) throw new Refusal(EX_CONFIG, `two workflow labels, ${named.join(" and ")}, and a pass runs one workflow`);
|
|
437
|
+
const label = named.length === 1 ? named[0].slice("workflow:".length) : "";
|
|
438
|
+
// A ralph issue is a spec taken whole and never runs as one ticket, so its label beats a flag
|
|
439
|
+
// (the owner, 2026-12-01).
|
|
440
|
+
if (label === "ralph" && flag && flag !== "ralph") {
|
|
441
|
+
return { name: "ralph", by: "label", why: `the label workflow:ralph wins over --workflow ${flag}, because a ralph issue is a spec taken whole` };
|
|
442
|
+
}
|
|
443
|
+
if (flag) return { name: flag, by: "flag", why: "" };
|
|
444
|
+
if (label) return { name: label, by: "label", why: "" };
|
|
445
|
+
return { name: "default", by: "default", why: "" };
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// ---- moving pins: kryso workflow update, and what kryso doctor reads ---------------------------
|
|
449
|
+
|
|
450
|
+
/** GitHub refuses a pull request body past 65,536 characters, so the diffs stop short of it. */
|
|
451
|
+
const BODY_LIMIT = 60_000;
|
|
452
|
+
|
|
453
|
+
const firstLine = (/** @type {string} */ text) => text.trim().split("\n")[0] ?? "";
|
|
454
|
+
|
|
455
|
+
/** The repository's top-level path, or a refusal naming the directory.
|
|
456
|
+
* @param {string} repo */
|
|
457
|
+
function topOf(repo) {
|
|
458
|
+
const top = git(["rev-parse", "--show-toplevel"], repo);
|
|
459
|
+
if (!top.ok) throw new Refusal(EX_UNAVAILABLE, `${repo} is not in a git repository`);
|
|
460
|
+
return top.out;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
/** The repository's own workflow files at ref, by name, none when it has no .kryso/workflows/.
|
|
464
|
+
* @param {string} top @param {string} ref */
|
|
465
|
+
function workflowFiles(top, ref) {
|
|
466
|
+
const r = git(["ls-tree", "--name-only", `${ref}:.kryso/workflows`], top);
|
|
467
|
+
if (!r.ok) return [];
|
|
468
|
+
return r.out.split("\n").filter((f) => f.endsWith(".json")).sort().map((f) => ({ name: f.slice(0, -".json".length), file: `.kryso/workflows/${f}` }));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/** The pins a workflow file names itself, in the order its text holds them, with each one's
|
|
472
|
+
* stage and skill. A file's pins sit only in the judgement stages its changes add or put in place.
|
|
473
|
+
* @param {ReturnType<typeof checkFile>} body */
|
|
474
|
+
function ownPins(body) {
|
|
475
|
+
return body.changes.flatMap((c) => {
|
|
476
|
+
const stage = c.with ?? c.insert;
|
|
477
|
+
if (stage?.kind !== "judgement") return [];
|
|
478
|
+
return stage.steps.filter((/** @type {Record<string, any>} */ st) => st.pin).map((/** @type {Record<string, any>} */ st) => ({ stage: stage.id, skill: st.skill, ...st.pin }));
|
|
479
|
+
});
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
/** A bare clone of a pin's source, made once a run under tmp, or why it could not be read.
|
|
483
|
+
* @param {string} source @param {Map<string, { dir: string } | { why: string }>} clones @param {string} tmp */
|
|
484
|
+
function cloneOf(source, clones, tmp) {
|
|
485
|
+
let c = clones.get(source);
|
|
486
|
+
if (!c) {
|
|
487
|
+
const dir = path.join(tmp, `source-${clones.size}.git`);
|
|
488
|
+
// Without the blobs, which a log of one folder does not need and a diff fetches as it reads.
|
|
489
|
+
const r = spawnSync("git", ["clone", "-q", "--bare", "--filter=blob:none", sourceUrl(source), dir], { encoding: "utf8", env: { ...process.env, GIT_TERMINAL_PROMPT: "0" } });
|
|
490
|
+
c = r.status === 0 ? { dir } : { why: `cannot read ${source}: ${firstLine(r.stderr ?? "") || "git clone failed"}` };
|
|
491
|
+
clones.set(source, c);
|
|
492
|
+
}
|
|
493
|
+
return c;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** The newest commit on the pin's source's default branch that changed the skill's folder, and
|
|
497
|
+
* whether the pin is behind it. A pin already past that commit is current, at its own commit.
|
|
498
|
+
* @param {{ source: string, path: string, commit: string }} pin @param {Map<string, any>} clones @param {string} tmp
|
|
499
|
+
* @returns {{ newest: string, behind: boolean, clone: string } | { why: string }} */
|
|
500
|
+
function newestFor(pin, clones, tmp) {
|
|
501
|
+
const c = cloneOf(pin.source, clones, tmp);
|
|
502
|
+
if ("why" in c) return c;
|
|
503
|
+
const at = (/** @type {string[]} */ args) => git(args, c.dir);
|
|
504
|
+
const log = at(["log", "-1", "--format=%H", "HEAD", "--", pin.path]);
|
|
505
|
+
if (!log.ok || !log.out) return { why: `no commit on ${pin.source}'s default branch changed ${pin.path}` };
|
|
506
|
+
const newest = log.out;
|
|
507
|
+
if (newest === pin.commit) return { newest, behind: false, clone: c.dir };
|
|
508
|
+
if (!at(["cat-file", "-e", `${pin.commit}^{commit}`]).ok) return { why: `${pin.source} does not hold the pinned commit ${pin.commit.slice(0, 12)}, so no diff can show a move` };
|
|
509
|
+
if (at(["merge-base", "--is-ancestor", newest, pin.commit]).ok) return { newest: pin.commit, behind: false, clone: c.dir };
|
|
510
|
+
if (!at(["cat-file", "-e", `${newest}:${pin.path}/SKILL.md`]).ok) {
|
|
511
|
+
return { why: `${newest.slice(0, 12)}, the newest commit on ${pin.source}'s default branch that changed ${pin.path}, holds no skill there` };
|
|
512
|
+
}
|
|
513
|
+
return { newest, behind: true, clone: c.dir };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The pull request's body: for each skill that moves, where it is pinned and its diff between the
|
|
517
|
+
* two commits, fenced past any run of backticks the diff holds. Diffs that would take the body
|
|
518
|
+
* past GitHub's limit are named by the command that shows them instead.
|
|
519
|
+
* @param {{ file: string, stage: string, skill: string, source: string, path: string, commit: string, newest: string, clone: string }[]} moves
|
|
520
|
+
* @param {string} count how many pins move, in words */
|
|
521
|
+
function prBody(moves, count) {
|
|
522
|
+
/** @type {Map<string, typeof moves>} */
|
|
523
|
+
const bySkill = new Map();
|
|
524
|
+
for (const m of moves) {
|
|
525
|
+
const key = [m.source, m.path, m.commit, m.newest].join(" ");
|
|
526
|
+
bySkill.set(key, [...(bySkill.get(key) ?? []), m]);
|
|
527
|
+
}
|
|
528
|
+
let body = `\`kryso workflow update\` moves ${count} to the newest commit on the source's default branch that changed the skill's folder. Each skill's diff between the two commits follows, so what a pass runs changes only through this review.\n`;
|
|
529
|
+
for (const group of bySkill.values()) {
|
|
530
|
+
const m = group[0];
|
|
531
|
+
const where = group.map((g) => `${g.file}, stage ${g.stage}`).join("; ");
|
|
532
|
+
const head = `\n### ${m.skill}: ${m.source} ${m.path}, ${m.commit.slice(0, 12)} to ${m.newest.slice(0, 12)}\n\nPinned in ${where}.\n\n`;
|
|
533
|
+
const diff = git(["diff", "--no-color", "--no-ext-diff", m.commit, m.newest, "--", m.path], m.clone).out;
|
|
534
|
+
const fence = "`".repeat(Math.max(3, ...[...diff.matchAll(/`+/g)].map((r) => r[0].length + 1)));
|
|
535
|
+
const full = `${head}${fence}diff\n${diff}\n${fence}\n`;
|
|
536
|
+
body += body.length + full.length <= BODY_LIMIT ? full : `${head}The diff is too long for this body: \`git diff ${m.commit} ${m.newest} -- ${m.path}\` in ${m.source} shows it.\n`;
|
|
537
|
+
}
|
|
538
|
+
return body;
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** The repository's text of a workflow file with each moved pin's commit replaced. A file's
|
|
542
|
+
* "commit" keys are its pins' alone, so the nth one in its text is its nth pin.
|
|
543
|
+
* @param {string} text @param {{ commit: string, newest: string, behind: boolean }[]} rows the file's pins in order */
|
|
544
|
+
function withMovedCommits(text, rows) {
|
|
545
|
+
let i = 0;
|
|
546
|
+
const out = text.replace(/("commit"\s*:\s*")([0-9a-f]{40})"/g, (all, lead, commit) => {
|
|
547
|
+
const row = rows[i++];
|
|
548
|
+
if (!row || row.commit !== commit) throw new Error("the file's pins and its text disagree");
|
|
549
|
+
return row.behind ? `${lead}${row.newest}"` : all;
|
|
550
|
+
});
|
|
551
|
+
if (i !== rows.length) throw new Error("the file's pins and its text disagree");
|
|
552
|
+
return out;
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** kryso workflow update: what moves, then the pull request that moves it, or under dryRun the
|
|
556
|
+
* body it would open with.
|
|
557
|
+
* @param {string} repo @param {boolean} dryRun @param {(line: string) => void} say */
|
|
558
|
+
export function update(repo, dryRun, say) {
|
|
559
|
+
const top = topOf(repo);
|
|
560
|
+
const base = git(["symbolic-ref", "--short", "-q", "HEAD"], top);
|
|
561
|
+
if (!base.ok) throw new Refusal(EX_USAGE, `${top} is not on a branch, and the pull request needs one to merge into`);
|
|
562
|
+
const head = git(["rev-parse", "HEAD"], top).out;
|
|
563
|
+
const tmp = mkdtempSync(path.join(os.tmpdir(), "kryso-workflow-update-"));
|
|
564
|
+
try {
|
|
565
|
+
const clones = new Map();
|
|
566
|
+
/** @type {{ file: string, text: string, rows: any[] }[]} */
|
|
567
|
+
const files = [];
|
|
568
|
+
for (const { file } of workflowFiles(top, "HEAD")) {
|
|
569
|
+
// Untrimmed, so the moved file differs from it in its commits alone.
|
|
570
|
+
const text = spawnSync("git", ["-C", top, "show", `HEAD:${file}`], { encoding: "utf8" }).stdout ?? "";
|
|
571
|
+
let body;
|
|
572
|
+
try {
|
|
573
|
+
body = checkFile(JSON.parse(text));
|
|
574
|
+
} catch (e) {
|
|
575
|
+
throw new Refusal(EX_CONFIG, `${file} at HEAD: ${/** @type {Error} */ (e).message}`);
|
|
576
|
+
}
|
|
577
|
+
const rows = ownPins(body).map((pin) => {
|
|
578
|
+
const n = newestFor(pin, clones, tmp);
|
|
579
|
+
if ("why" in n) throw new Refusal(EX_UNAVAILABLE, `the pin ${pin.skill} in ${file}: ${n.why}`);
|
|
580
|
+
return { file, ...pin, ...n };
|
|
581
|
+
});
|
|
582
|
+
files.push({ file, text, rows });
|
|
583
|
+
}
|
|
584
|
+
const rows = files.flatMap((f) => f.rows);
|
|
585
|
+
for (const r of rows) say([r.file, r.stage, r.skill, r.source, r.path, r.commit, r.newest, r.behind ? "moves" : "current"].join("\t"));
|
|
586
|
+
if (rows.length === 0) {
|
|
587
|
+
say("kryso workflow update: no workflow file in .kryso/workflows/ pins a skill, so no pull request was opened; the built-in workflows' pins move with kryso");
|
|
588
|
+
return 0;
|
|
589
|
+
}
|
|
590
|
+
const moves = rows.filter((r) => r.behind);
|
|
591
|
+
if (moves.length === 0) {
|
|
592
|
+
say("kryso workflow update: no pin has a newer commit for its skill, so no pull request was opened");
|
|
593
|
+
return 0;
|
|
594
|
+
}
|
|
595
|
+
const count = `${moves.length} pin${moves.length === 1 ? "" : "s"}`;
|
|
596
|
+
const title = moves.length === 1 ? "chore(kryso): move 1 workflow pin to its skill's newest commit" : `chore(kryso): move ${count} of the workflows to their skills' newest commits`;
|
|
597
|
+
const body = prBody(moves, count);
|
|
598
|
+
if (dryRun) {
|
|
599
|
+
say(`\n${title}\n\n${body}`);
|
|
600
|
+
return 0;
|
|
601
|
+
}
|
|
602
|
+
const upstream = git(["rev-parse", "-q", "--verify", `refs/remotes/origin/${base.out}^{commit}`], top);
|
|
603
|
+
if (upstream.ok && upstream.out !== head) {
|
|
604
|
+
throw new Refusal(EX_USAGE, `${base.out} is at ${head.slice(0, 12)} and origin/${base.out} at ${upstream.out.slice(0, 12)}, so the pull request would carry other commits: push or pull first`);
|
|
605
|
+
}
|
|
606
|
+
// One branch for one set of moves, so a second run over the same pins finds the first's.
|
|
607
|
+
const digest = createHash("sha256").update(moves.map((m) => [m.file, m.stage, m.skill, m.commit, m.newest].join(" ")).join("\n")).digest("hex");
|
|
608
|
+
const branch = `kryso/workflow-update-${digest.slice(0, 12)}`;
|
|
609
|
+
if ([`refs/heads/${branch}`, `refs/remotes/origin/${branch}`].some((ref) => git(["rev-parse", "-q", "--verify", ref], top).ok)) {
|
|
610
|
+
throw new Refusal(EX_CANTCREAT, `the branch ${branch} already holds these moves, from an earlier run: open its pull request, or delete the branch to start again`);
|
|
611
|
+
}
|
|
612
|
+
const step = (/** @type {string[]} */ args, /** @type {string} */ cwd) => {
|
|
613
|
+
const r = git(args, cwd);
|
|
614
|
+
if (!r.ok) throw new Refusal(EX_UNAVAILABLE, `git ${args[0]} failed: ${firstLine(r.err)}`);
|
|
615
|
+
};
|
|
616
|
+
// In a worktree of its own, so the checkout and its branch stay as they were.
|
|
617
|
+
const wt = path.join(tmp, "worktree");
|
|
618
|
+
step(["worktree", "add", "-q", "-b", branch, wt, head], top);
|
|
619
|
+
let pushed = false;
|
|
620
|
+
try {
|
|
621
|
+
const changed = files.filter((f) => f.rows.some((r) => r.behind));
|
|
622
|
+
for (const f of changed) writeFileSync(path.join(wt, f.file), withMovedCommits(f.text, f.rows));
|
|
623
|
+
step(["add", "--", ...changed.map((f) => f.file)], wt);
|
|
624
|
+
step(["commit", "-q", "-m", title], wt);
|
|
625
|
+
step(["push", "-q", "origin", branch], top);
|
|
626
|
+
pushed = true;
|
|
627
|
+
} finally {
|
|
628
|
+
git(["worktree", "remove", "--force", wt], top);
|
|
629
|
+
if (!pushed) git(["branch", "-D", branch], top);
|
|
630
|
+
}
|
|
631
|
+
const bodyFile = path.join(tmp, "body.md");
|
|
632
|
+
writeFileSync(bodyFile, body);
|
|
633
|
+
const pr = spawnSync("gh", ["pr", "create", "--base", base.out, "--head", branch, "--title", title, "--body-file", bodyFile], { cwd: top, encoding: "utf8" });
|
|
634
|
+
if (pr.status !== 0) {
|
|
635
|
+
throw new Refusal(EX_UNAVAILABLE, `pushed ${branch}, but gh pr create failed: ${firstLine(pr.stderr ?? "") || `it exited ${pr.status}`}; open the pull request from that branch`);
|
|
636
|
+
}
|
|
637
|
+
say(`kryso workflow update: moved ${count}, opened ${(pr.stdout ?? "").trim().split("\n").at(-1)}`);
|
|
638
|
+
return 0;
|
|
639
|
+
} finally {
|
|
640
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
/** kryso workflow pins: each workflow the repository's files name at ref, whether it resolves,
|
|
645
|
+
* and each pin it runs, with whether the store holds it and, for a pin the file names itself,
|
|
646
|
+
* whether its source has a newer commit for its skill, unknown under offline.
|
|
647
|
+
* @param {string} repo @param {string} ref @param {boolean} offline */
|
|
648
|
+
export function pins(repo, ref, offline) {
|
|
649
|
+
const top = topOf(repo);
|
|
650
|
+
const tmp = mkdtempSync(path.join(os.tmpdir(), "kryso-workflow-pins-"));
|
|
651
|
+
try {
|
|
652
|
+
const clones = new Map();
|
|
653
|
+
const workflows = workflowFiles(top, ref).map(({ name, file }) => {
|
|
654
|
+
try {
|
|
655
|
+
const w = resolve(top, ref, name);
|
|
656
|
+
return {
|
|
657
|
+
name,
|
|
658
|
+
file,
|
|
659
|
+
pins: pinsOf(w).map((pin) => {
|
|
660
|
+
const { entry, dir } = entryOf(pin);
|
|
661
|
+
const own = w.sources[pin.stage] === file;
|
|
662
|
+
const row = { ...pin, own, store: dir, stored: existsSync(entry) && holds(entry, pin) };
|
|
663
|
+
if (!own) return row;
|
|
664
|
+
if (offline) return { ...row, unknown: "--offline reads no source" };
|
|
665
|
+
const n = newestFor(pin, clones, tmp);
|
|
666
|
+
return "why" in n ? { ...row, unknown: n.why } : { ...row, newest: n.newest, behind: n.behind };
|
|
667
|
+
}),
|
|
668
|
+
};
|
|
669
|
+
} catch (e) {
|
|
670
|
+
if (!(e instanceof Refusal)) throw e;
|
|
671
|
+
return { name, file, error: e.message };
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
return { workflows };
|
|
675
|
+
} finally {
|
|
676
|
+
rmSync(tmp, { recursive: true, force: true });
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// ---- the command ------------------------------------------------------------------------------
|
|
681
|
+
|
|
682
|
+
const USAGE = `Usage: kryso workflow show [name] [--ref R] [--repo DIR] [--json] [--built-in]
|
|
683
|
+
kryso workflow check FILE
|
|
684
|
+
kryso workflow choose [--flag NAME] [--labels a,b,...]
|
|
685
|
+
kryso workflow fetch [name] [--ref R] [--repo DIR]
|
|
686
|
+
kryso workflow update [--repo DIR] [--dry-run]
|
|
687
|
+
kryso workflow pins [--repo DIR] [--offline]
|
|
688
|
+
|
|
689
|
+
show print the workflow a pass on this repository would run: the
|
|
690
|
+
repository's .kryso/workflows/<name>.json at the ref, applied over
|
|
691
|
+
the built-in it extends, else kryso's built-in of that name. The
|
|
692
|
+
name defaults to default, so a repository with no .kryso/ runs
|
|
693
|
+
the built-in default
|
|
694
|
+
check check one workflow file against the workflow schema's rules,
|
|
695
|
+
and exit 78 with the reason when it fails
|
|
696
|
+
choose print the workflow a pass chooses from its --workflow and the
|
|
697
|
+
issue's labels, what chose it and, when a label beat the flag,
|
|
698
|
+
why, tab-separated. The pass and the shift run it
|
|
699
|
+
fetch put each skill the workflow pins into kryso's store,
|
|
700
|
+
~/.kryso/skills, where it is not there yet, and print one line a
|
|
701
|
+
pin: stage, skill, source, path, commit, its folder in the store,
|
|
702
|
+
and fetched or stored, tab-separated. A pin the store already
|
|
703
|
+
holds is never fetched again. KRYSO_PIN_SOURCES fetches from
|
|
704
|
+
another host or a directory in place of GitHub
|
|
705
|
+
update move each pin the repository's .kryso/workflows/ files name to
|
|
706
|
+
the newest commit on its source's default branch that changed
|
|
707
|
+
the skill's folder, through one pull request whose body holds
|
|
708
|
+
each skill's diff. Prints one line a pin: file, stage, skill,
|
|
709
|
+
source, path, commit, new commit, and moves or current,
|
|
710
|
+
tab-separated. Opens no pull request when nothing moves. Runs
|
|
711
|
+
from the checkout's branch, which the pull request merges into
|
|
712
|
+
pins print as JSON each workflow the repository's files name, whether
|
|
713
|
+
it resolves, and each pin it runs: whether the store holds it
|
|
714
|
+
and whether its source has a newer commit. kryso doctor reads it
|
|
715
|
+
|
|
716
|
+
Options:
|
|
717
|
+
--ref R the ref to read the repository's workflows at (default HEAD).
|
|
718
|
+
A pass reads its base
|
|
719
|
+
--repo DIR the repository (default the current directory)
|
|
720
|
+
--json print the resolved workflow as JSON, to
|
|
721
|
+
packages/core/schemas/workflow-resolved/2.schema.json
|
|
722
|
+
--built-in show kryso's own workflow of that name, not the repository's
|
|
723
|
+
--dry-run update: print the moves and the pull request's body, and
|
|
724
|
+
write nothing
|
|
725
|
+
--offline pins: read no source, so whether a pin is behind is unknown
|
|
726
|
+
-h, --help print this help
|
|
727
|
+
`;
|
|
728
|
+
|
|
729
|
+
/** @param {ReturnType<typeof resolve>} w */
|
|
730
|
+
function render(w) {
|
|
731
|
+
const from = w.file ? `${w.file}, extending the built-in ${w.extends}` : `the built-in ${w.name}`;
|
|
732
|
+
const lines = [`workflow ${w.name} from ${from}, at ${w.ref} (${w.commit.slice(0, 12)})`, `hash ${w.hash}`, ""];
|
|
733
|
+
const width = Math.max(...w.stages.map((s) => s.id.length)) + 2;
|
|
734
|
+
for (const s of w.stages) {
|
|
735
|
+
lines.push(` ${s.id.padEnd(width)}${s.kind.padEnd(12)}${w.sources[s.id]}`);
|
|
736
|
+
const detail =
|
|
737
|
+
s.kind === "judgement"
|
|
738
|
+
? s.steps.map((/** @type {Record<string, any>} */ st) => `${st.skill}${st.when ? ` when ${Object.entries(st.when).map(([k, v]) => `${k}=${v}`).join(" ")}` : ""}`).join(", ")
|
|
739
|
+
: s.kind === "commands"
|
|
740
|
+
? s.commands.join("; ")
|
|
741
|
+
: "";
|
|
742
|
+
if (detail) lines.push(` ${" ".repeat(width)}${detail}`);
|
|
743
|
+
}
|
|
744
|
+
for (const [at, said] of [["after-pass", "after each pass"], ["end", "at the end of the shift"]]) {
|
|
745
|
+
for (const s of w.shift[at]) lines.push(` ${said}: ${s.id}, ${s.commands.join("; ")}`);
|
|
746
|
+
}
|
|
747
|
+
return `${lines.join("\n")}\n`;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** @param {string[]} argv */
|
|
751
|
+
function main(argv) {
|
|
752
|
+
const [verb, ...rest] = argv;
|
|
753
|
+
if (verb === undefined || verb === "-h" || verb === "--help") {
|
|
754
|
+
process.stdout.write(USAGE);
|
|
755
|
+
return verb === undefined ? EX_USAGE : 0;
|
|
756
|
+
}
|
|
757
|
+
/** @type {Record<string, string | boolean>} */
|
|
758
|
+
const opts = {};
|
|
759
|
+
const words = [];
|
|
760
|
+
for (let i = 0; i < rest.length; i++) {
|
|
761
|
+
const a = rest[i];
|
|
762
|
+
if (a === "-h" || a === "--help") {
|
|
763
|
+
process.stdout.write(USAGE);
|
|
764
|
+
return 0;
|
|
765
|
+
}
|
|
766
|
+
if (a === "--json") opts.json = true;
|
|
767
|
+
else if (a === "--built-in") opts.builtIn = true;
|
|
768
|
+
else if (a === "--dry-run") opts.dryRun = true;
|
|
769
|
+
else if (a === "--offline") opts.offline = true;
|
|
770
|
+
else if (["--ref", "--repo", "--flag", "--labels"].includes(a)) {
|
|
771
|
+
if (i + 1 >= rest.length) throw new Refusal(EX_USAGE, `${a} needs a value`);
|
|
772
|
+
opts[a.slice(2)] = rest[++i];
|
|
773
|
+
} else if (a.startsWith("-")) throw new Refusal(EX_USAGE, `unknown option ${a}`);
|
|
774
|
+
else words.push(a);
|
|
775
|
+
}
|
|
776
|
+
if (verb === "show") {
|
|
777
|
+
if (words.length > 1) throw new Refusal(EX_USAGE, `show takes one workflow name, got ${words.join(" ")}`);
|
|
778
|
+
const w = resolve(String(opts.repo ?? process.cwd()), String(opts.ref ?? "HEAD"), words[0] ?? "default", opts.builtIn === true);
|
|
779
|
+
process.stdout.write(opts.json ? `${JSON.stringify(w, null, 2)}\n` : render(w));
|
|
780
|
+
return 0;
|
|
781
|
+
}
|
|
782
|
+
if (verb === "fetch") {
|
|
783
|
+
if (words.length > 1) throw new Refusal(EX_USAGE, `fetch takes one workflow name, got ${words.join(" ")}`);
|
|
784
|
+
const w = resolve(String(opts.repo ?? process.cwd()), String(opts.ref ?? "HEAD"), words[0] ?? "default");
|
|
785
|
+
for (const pin of pinsOf(w)) {
|
|
786
|
+
const got = fetchPin(pin);
|
|
787
|
+
process.stdout.write(`${[pin.stage, pin.skill, pin.source, pin.path, pin.commit, got.dir, got.status].join("\t")}\n`);
|
|
788
|
+
}
|
|
789
|
+
return 0;
|
|
790
|
+
}
|
|
791
|
+
if (verb === "update" || verb === "pins") {
|
|
792
|
+
if (words.length > 0) throw new Refusal(EX_USAGE, `${verb} reads every workflow file, and takes no name, got ${words.join(" ")}`);
|
|
793
|
+
const repo = String(opts.repo ?? process.cwd());
|
|
794
|
+
if (verb === "update") return update(repo, opts.dryRun === true, (line) => process.stdout.write(`${line}\n`));
|
|
795
|
+
if (opts.ref !== undefined) throw new Refusal(EX_USAGE, "pins reads HEAD, and takes no --ref");
|
|
796
|
+
process.stdout.write(`${JSON.stringify(pins(repo, "HEAD", opts.offline === true), null, 2)}\n`);
|
|
797
|
+
return 0;
|
|
798
|
+
}
|
|
799
|
+
if (verb === "choose") {
|
|
800
|
+
const labels = String(opts.labels ?? "").split(",").filter(Boolean);
|
|
801
|
+
const c = choose(String(opts.flag ?? ""), labels);
|
|
802
|
+
process.stdout.write(`${c.name}\t${c.by}\t${c.why}\n`);
|
|
803
|
+
return 0;
|
|
804
|
+
}
|
|
805
|
+
if (verb === "check") {
|
|
806
|
+
if (words.length !== 1) throw new Refusal(EX_USAGE, "check takes one file");
|
|
807
|
+
let parsed;
|
|
808
|
+
try {
|
|
809
|
+
parsed = JSON.parse(readFileSync(words[0], "utf8"));
|
|
810
|
+
checkFile(parsed);
|
|
811
|
+
} catch (e) {
|
|
812
|
+
throw new Refusal(EX_CONFIG, `${words[0]}: ${/** @type {Error} */ (e).message}`);
|
|
813
|
+
}
|
|
814
|
+
return 0;
|
|
815
|
+
}
|
|
816
|
+
throw new Refusal(EX_USAGE, `unknown verb '${verb}'`);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// Through the real path, because a module run by a path with a link in it, such as /var on macOS,
|
|
820
|
+
// has a URL that names the target, and a plain comparison would run nothing and exit 0.
|
|
821
|
+
if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
822
|
+
try {
|
|
823
|
+
process.exitCode = main(process.argv.slice(2));
|
|
824
|
+
} catch (e) {
|
|
825
|
+
if (!(e instanceof Refusal)) throw e;
|
|
826
|
+
process.stderr.write(`kryso workflow: ${e.message}\n`);
|
|
827
|
+
if (e.code === EX_USAGE) process.stderr.write("kryso workflow --help lists the options\n");
|
|
828
|
+
process.exitCode = e.code;
|
|
829
|
+
}
|
|
830
|
+
}
|