slicekit 0.0.1 → 0.1.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 +252 -3
- package/bin/slicekit.js +4 -0
- package/package.json +21 -4
- package/src/adapters/githost/errors.js +17 -0
- package/src/adapters/githost/fixture.js +136 -0
- package/src/adapters/githost/gh-json.js +99 -0
- package/src/adapters/githost/github.js +127 -0
- package/src/adapters/githost/index.js +12 -0
- package/src/adapters/tracker/errors.js +53 -0
- package/src/adapters/tracker/fixture.js +71 -0
- package/src/adapters/tracker/github-issues.js +65 -0
- package/src/adapters/tracker/index.js +14 -0
- package/src/baseline.js +109 -0
- package/src/build/commit.js +201 -0
- package/src/build/decline.js +81 -0
- package/src/build/finish.js +155 -0
- package/src/build/order.js +158 -0
- package/src/build/overlap.js +173 -0
- package/src/build/parallel.js +50 -0
- package/src/build/pr.js +263 -0
- package/src/build/record.js +28 -0
- package/src/build/red.js +207 -0
- package/src/build/review.js +123 -0
- package/src/build/sync.js +47 -0
- package/src/build/verdict.js +410 -0
- package/src/build/worktree.js +169 -0
- package/src/check/ci-event.js +52 -0
- package/src/check/context.js +129 -0
- package/src/check/index.js +140 -0
- package/src/check/rules/.gitkeep +0 -0
- package/src/check/rules/ci-body.js +22 -0
- package/src/check/rules/ci-title.js +43 -0
- package/src/check/rules/citations.js +224 -0
- package/src/check/rules/commands.js +146 -0
- package/src/check/rules/coverage.js +248 -0
- package/src/check/rules/hooks.js +58 -0
- package/src/check/rules/journal.js +17 -0
- package/src/check/rules/layout.js +56 -0
- package/src/check/rules/managed.js +31 -0
- package/src/check/rules/queue.js +106 -0
- package/src/check/rules/references.js +249 -0
- package/src/check/rules/style.js +177 -0
- package/src/check/rules/trailer.js +67 -0
- package/src/cli/baseline.js +66 -0
- package/src/cli/branch.js +86 -0
- package/src/cli/build.js +239 -0
- package/src/cli/check.js +40 -0
- package/src/cli/decide.js +59 -0
- package/src/cli/gaps.js +73 -0
- package/src/cli/hook.js +28 -0
- package/src/cli/index.js +83 -0
- package/src/cli/init.js +96 -0
- package/src/cli/instructions.js +63 -0
- package/src/cli/intake.js +107 -0
- package/src/cli/journal.js +82 -0
- package/src/cli/plan.js +29 -0
- package/src/cli/pr.js +83 -0
- package/src/cli/process.js +59 -0
- package/src/cli/ready-label.js +119 -0
- package/src/cli/review.js +64 -0
- package/src/cli/spec.js +31 -0
- package/src/cli/stage.js +37 -0
- package/src/cli/state.js +106 -0
- package/src/cli/status.js +108 -0
- package/src/cli/update.js +62 -0
- package/src/cli/workflow.js +48 -0
- package/src/config.js +203 -0
- package/src/decisions.js +289 -0
- package/src/evidence.js +27 -0
- package/src/fs.js +38 -0
- package/src/gaps.js +271 -0
- package/src/git.js +209 -0
- package/src/githooks.js +37 -0
- package/src/hook-cli.js +63 -0
- package/src/hooks/io.js +205 -0
- package/src/hooks/paths.js +82 -0
- package/src/hooks/pre-bash.js +715 -0
- package/src/hooks/pre-compact.js +139 -0
- package/src/hooks/pre-edit.js +170 -0
- package/src/hooks/session-end.js +118 -0
- package/src/hooks/session-start.js +209 -0
- package/src/hooks/shapes.js +103 -0
- package/src/hooks/stop.js +37 -0
- package/src/hooks/subagent-marker.js +88 -0
- package/src/hooks/subagent-start.js +100 -0
- package/src/hooks/subagent-stop.js +106 -0
- package/src/ids.js +43 -0
- package/src/init.js +276 -0
- package/src/instructions.js +235 -0
- package/src/intake.js +409 -0
- package/src/journal.js +326 -0
- package/src/lock.js +35 -0
- package/src/markdown.js +155 -0
- package/src/paths.js +33 -0
- package/src/plan.js +25 -0
- package/src/pr.js +73 -0
- package/src/prbody.js +266 -0
- package/src/ready-label.js +107 -0
- package/src/redact.js +33 -0
- package/src/render/compare.js +23 -0
- package/src/render/entry.js +101 -0
- package/src/render/index.js +27 -0
- package/src/render/managed.js +128 -0
- package/src/render/manifest.js +24 -0
- package/src/render/settings.js +76 -0
- package/src/render/update.js +151 -0
- package/src/slicefile.js +173 -0
- package/src/spec-verify.js +58 -0
- package/src/stage.js +325 -0
- package/src/state/build.js +156 -0
- package/src/state/covers.js +58 -0
- package/src/state/index.js +191 -0
- package/src/state/sync.js +64 -0
- package/src/state/transitions.js +282 -0
- package/src/verdict.js +203 -0
- package/src/which.js +37 -0
- package/src/workflow.js +177 -0
- package/src/worktrees.js +68 -0
- package/templates/claude-code/agents/auditor.md +7 -0
- package/templates/claude-code/agents/designer.md +7 -0
- package/templates/claude-code/agents/developer.md +7 -0
- package/templates/claude-code/agents/fixer.md +7 -0
- package/templates/claude-code/agents/ops.md +7 -0
- package/templates/claude-code/agents/reviewer.md +7 -0
- package/templates/claude-code/commands/slicekit-audit.md +7 -0
- package/templates/claude-code/commands/slicekit-build.md +7 -0
- package/templates/claude-code/commands/slicekit-gaps.md +6 -0
- package/templates/claude-code/commands/slicekit-intake.md +7 -0
- package/templates/claude-code/commands/slicekit-ops.md +7 -0
- package/templates/claude-code/commands/slicekit-plan.md +6 -0
- package/templates/claude-code/commands/slicekit-release.md +7 -0
- package/templates/claude-code/commands/slicekit-review.md +7 -0
- package/templates/claude-code/commands/slicekit-specify.md +6 -0
- package/templates/claude-code/commands/slicekit.md +7 -0
- package/templates/claude-code/hooks.json +90 -0
- package/templates/claude-code/manifest.json +171 -0
- package/templates/claude-code/skills/slicekit-ids/SKILL.md +16 -0
- package/templates/claude-code/skills/slicekit-loop/SKILL.md +23 -0
- package/templates/claude-code/skills/slicekit-writing/SKILL.md +24 -0
- package/templates/docs/BUILD.md +5 -0
- package/templates/docs/decisions.md +15 -0
- package/templates/docs/intake/.keep +0 -0
- package/templates/docs/observability.md +25 -0
- package/templates/docs/phases/.keep +0 -0
- package/templates/docs/platform.md +25 -0
- package/templates/docs/releases/.keep +0 -0
- package/templates/docs/runbook.md +21 -0
- package/templates/docs/spec/00-overview.md +8 -0
- package/templates/docs/spec/contracts/.keep +0 -0
- package/templates/docs/spec/gaps.md +6 -0
- package/templates/docs/spec/stack.md +3 -0
- package/templates/githooks/pre-commit +59 -0
- package/templates/githooks/pre-merge-commit +59 -0
- package/templates/githooks/prepare-commit-msg +74 -0
- package/templates/instructions/agents/auditor.md +33 -0
- package/templates/instructions/agents/designer.md +21 -0
- package/templates/instructions/agents/developer.md +49 -0
- package/templates/instructions/agents/fixer.md +41 -0
- package/templates/instructions/agents/ops.md +21 -0
- package/templates/instructions/agents/reviewer.md +63 -0
- package/templates/instructions/commands/build.md +234 -0
- package/templates/instructions/commands/gaps.md +65 -0
- package/templates/instructions/commands/intake.md +90 -0
- package/templates/instructions/commands/plan.md +60 -0
- package/templates/instructions/commands/review.md +117 -0
- package/templates/instructions/commands/specify.md +49 -0
- package/templates/style.json +11 -0
- package/templates/workflow/pins.json +6 -0
- package/templates/workflow/slicekit.yml +110 -0
package/src/journal.js
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// The session journal (03 REQ-3.8, D-32, D-34, D-36): append-only, hash-chained files under
|
|
2
|
+
// `.slicekit/journal/`, one per branch per clone, named `<branch-part>--<clone-id>.log`, each its own
|
|
3
|
+
// chain from `prev=genesis`. Two branches, or two clones on one branch, never append to the same file,
|
|
4
|
+
// so merging never conflicts and never breaks a chain. One line per session end:
|
|
5
|
+
//
|
|
6
|
+
// <iso> actor=<a> slice=<id|-> stage=<s> commits=<sha7,…|-> verdicts=<ids|-> decisions=<ids|-> prev=<hash|genesis> hash=<sha256>
|
|
7
|
+
//
|
|
8
|
+
// `hash` is the SHA-256 of the line up to and including `prev=<…>`. Values carry no spaces and no `=`:
|
|
9
|
+
// every value is masked with redact() first, then whitespace and `=` become `_`.
|
|
10
|
+
//
|
|
11
|
+
// What is protected: a mid-chain edit is caught by the chain (verifyJournal); shortening or removing a
|
|
12
|
+
// committed file is caught against the default branch (appendOnlyProblems); lines not yet committed are
|
|
13
|
+
// not protected. Nothing here repairs a journal.
|
|
14
|
+
import { execFileSync } from 'node:child_process';
|
|
15
|
+
import crypto from 'node:crypto';
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { GitError, assertRef, currentBranch, git, isRepo, resolveCommit } from './git.js';
|
|
19
|
+
import { toPosix } from './hooks/paths.js';
|
|
20
|
+
import { LOCK_WAIT_MS, sleep, withFileLock } from './lock.js';
|
|
21
|
+
import { kitPaths } from './paths.js';
|
|
22
|
+
import { redact } from './redact.js';
|
|
23
|
+
|
|
24
|
+
export const GENESIS = 'genesis';
|
|
25
|
+
export const NO_CLONE = 'no-clone';
|
|
26
|
+
const FIELDS = ['actor', 'slice', 'stage', 'commits', 'verdicts', 'decisions'];
|
|
27
|
+
const LISTS = new Set(['commits', 'verdicts', 'decisions']);
|
|
28
|
+
const LINE = /^(\S+) actor=(\S+) slice=(\S+) stage=(\S+) commits=(\S+) verdicts=(\S+) decisions=(\S+) prev=(genesis|[0-9a-f]{64}) hash=([0-9a-f]{64})$/;
|
|
29
|
+
const CLONE_ID = /^[0-9a-f]{8}$/;
|
|
30
|
+
|
|
31
|
+
const LOCK_BUDGET_MS = 2_000;
|
|
32
|
+
|
|
33
|
+
export class JournalError extends Error {
|
|
34
|
+
constructor(message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.name = 'JournalError';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const dirOf = (root, cfg) => kitPaths(root, cfg ?? { docsRoot: 'docs' }).journalDir;
|
|
41
|
+
|
|
42
|
+
export const hashLine = (text) => crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
43
|
+
|
|
44
|
+
// A branch name as the first part of a file name: `/` → `__`, anything outside [A-Za-z0-9._-] → `_`.
|
|
45
|
+
// When that changed the name, or the name is longer than 80 characters, it is cut to 60 and gets `-`
|
|
46
|
+
// and the first 8 hex of the raw name's SHA-256, so `feature/a` and `feature__a` never share a file.
|
|
47
|
+
export function branchPart(branch) {
|
|
48
|
+
const raw = String(branch);
|
|
49
|
+
const clean = raw.replace(/\//g, '__').replace(/[^A-Za-z0-9._-]/g, '_');
|
|
50
|
+
if (clean === raw && raw.length <= 80) return clean;
|
|
51
|
+
return `${clean.slice(0, 60)}-${hashLine(raw).slice(0, 8)}`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// The branch whose file a session at root appends to: its name, `detached`, or `no-branch` outside a repo.
|
|
55
|
+
export function journalBranch(root) {
|
|
56
|
+
try {
|
|
57
|
+
return currentBranch(root) ?? 'detached';
|
|
58
|
+
} catch (e) {
|
|
59
|
+
if (e instanceof GitError) return 'no-branch';
|
|
60
|
+
throw e;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function cloneIdFile(root) {
|
|
65
|
+
try {
|
|
66
|
+
return path.join(path.resolve(root, git(root, ['rev-parse', '--git-common-dir'])), 'slicekit', 'clone-id');
|
|
67
|
+
} catch (e) {
|
|
68
|
+
if (e instanceof GitError) return null;
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function readId(file) {
|
|
74
|
+
try {
|
|
75
|
+
const id = fs.readFileSync(file, 'utf8').trim();
|
|
76
|
+
return CLONE_ID.test(id) ? id : null;
|
|
77
|
+
} catch {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// This clone's id: 8 random hex characters kept at `<git-common-dir>/slicekit/clone-id`, so the
|
|
83
|
+
// worktrees of one clone share it. `no-clone` outside git. With create false, null when it is not made
|
|
84
|
+
// yet; with create true it is made once (wx), and a process that loses the race reads the winner's.
|
|
85
|
+
export function cloneId(root, { create = false } = {}) {
|
|
86
|
+
const file = cloneIdFile(root);
|
|
87
|
+
if (file === null) return NO_CLONE;
|
|
88
|
+
const have = readId(file);
|
|
89
|
+
if (have || !create) return have;
|
|
90
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
91
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
92
|
+
try {
|
|
93
|
+
fs.writeFileSync(file, `${id}\n`, { flag: 'wx' });
|
|
94
|
+
return id;
|
|
95
|
+
} catch (e) {
|
|
96
|
+
if (e.code !== 'EEXIST') throw e;
|
|
97
|
+
}
|
|
98
|
+
const deadline = Date.now() + LOCK_BUDGET_MS;
|
|
99
|
+
for (;;) {
|
|
100
|
+
const won = readId(file);
|
|
101
|
+
if (won) return won;
|
|
102
|
+
if (Date.now() >= deadline) throw new JournalError(`${toPosix(file)} holds no clone id`);
|
|
103
|
+
sleep(LOCK_WAIT_MS);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// The file this clone appends to for branch; null when the clone has no id yet and create is false.
|
|
108
|
+
export function journalFile(root, branch, cfg, { create = false } = {}) {
|
|
109
|
+
const id = cloneId(root, { create });
|
|
110
|
+
return id === null ? null : path.join(dirOf(root, cfg), `${branchPart(branch)}--${id}.log`);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function value(v) {
|
|
114
|
+
const s = redact(String(v ?? '')).replace(/[\s=]/g, '_');
|
|
115
|
+
return s === '' ? '-' : s;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function list(v) {
|
|
119
|
+
const items = (Array.isArray(v) ? v : v == null || v === '' || v === '-' ? [] : [v])
|
|
120
|
+
.map((x) => value(x).replace(/,/g, '_')).filter((x) => x !== '-');
|
|
121
|
+
return items.length === 0 ? '-' : [...new Set(items)].sort().join(',');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// The text the hash covers: the line up to and including `prev=<…>`.
|
|
125
|
+
export function lineBody(fields, prev, at) {
|
|
126
|
+
const parts = FIELDS.map((k) => `${k}=${LISTS.has(k) ? list(fields[k]) : value(fields[k])}`);
|
|
127
|
+
return `${value(at)} ${parts.join(' ')} prev=${prev}`;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// -> {at, actor, slice, stage, commits[], verdicts[], decisions[], prev, hash, body}, or null.
|
|
131
|
+
export function parseLine(text) {
|
|
132
|
+
const m = LINE.exec(String(text).replace(/\r$/, ''));
|
|
133
|
+
if (!m) return null;
|
|
134
|
+
const split = (s) => (s === '-' ? [] : s.split(','));
|
|
135
|
+
const [, at, actor, slice, stage, commits, verdicts, decisions, prev, hash] = m;
|
|
136
|
+
const body = m[0].slice(0, m[0].lastIndexOf(' hash='));
|
|
137
|
+
return { at, actor, slice, stage, commits: split(commits), verdicts: split(verdicts), decisions: split(decisions), prev, hash, body };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// One file's text: {lines, brokenAt}. The first line whose hash or prev link does not hold is the break;
|
|
141
|
+
// a last line with no newline (a torn write) is a break at its own number.
|
|
142
|
+
function verifyText(text) {
|
|
143
|
+
if (text === '') return { lines: 0, brokenAt: null };
|
|
144
|
+
const parts = text.split('\n');
|
|
145
|
+
const torn = parts.at(-1) !== '';
|
|
146
|
+
const complete = parts.slice(0, -1);
|
|
147
|
+
let prev = GENESIS;
|
|
148
|
+
for (let i = 0; i < complete.length; i++) {
|
|
149
|
+
const p = parseLine(complete[i]);
|
|
150
|
+
if (!p || p.prev !== prev || hashLine(p.body) !== p.hash) return { lines: complete.length, brokenAt: i + 1 };
|
|
151
|
+
prev = p.hash;
|
|
152
|
+
}
|
|
153
|
+
return { lines: complete.length, brokenAt: torn ? complete.length + 1 : null };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export const NO_BASE = 'journal: no base to compare against (fetch the default branch with full history)';
|
|
157
|
+
export const brokenMessage = (file, n) => `journal chain broken at line ${n} of ${file}`;
|
|
158
|
+
const unexpectedMessage = (name) => `unexpected entry ${name} in .slicekit/journal/`;
|
|
159
|
+
|
|
160
|
+
// Every regular `*.log` file directly under .slicekit/journal/, by name, whatever the name. Anything else
|
|
161
|
+
// there (another name, a directory, a link) except a `*.lock` is a problem. Never writes.
|
|
162
|
+
// -> {ok, lines, brokenAt, file, message, problems: [{file, line, message}], files: [{file, lines, brokenAt}]};
|
|
163
|
+
// `file` and `brokenAt` name the first chain break, `message` the first problem.
|
|
164
|
+
export function verifyJournal(root, cfg) {
|
|
165
|
+
const dir = dirOf(root, cfg);
|
|
166
|
+
const relDir = toPosix(path.relative(root, dir));
|
|
167
|
+
let entries = [];
|
|
168
|
+
try {
|
|
169
|
+
entries = fs.readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
170
|
+
} catch (e) {
|
|
171
|
+
if (e.code !== 'ENOENT' && e.code !== 'ENOTDIR') throw e;
|
|
172
|
+
}
|
|
173
|
+
const files = [];
|
|
174
|
+
const problems = [];
|
|
175
|
+
let first = null;
|
|
176
|
+
for (const d of entries) {
|
|
177
|
+
const rel = `${relDir}/${d.name}`;
|
|
178
|
+
if (!(d.isFile() && d.name.endsWith('.log'))) {
|
|
179
|
+
if (!(d.isFile() && d.name.endsWith('.lock'))) problems.push({ file: rel, line: 0, message: unexpectedMessage(d.name) });
|
|
180
|
+
continue;
|
|
181
|
+
}
|
|
182
|
+
const r = verifyText(fs.readFileSync(path.join(dir, d.name), 'utf8'));
|
|
183
|
+
files.push({ file: rel, lines: r.lines, brokenAt: r.brokenAt });
|
|
184
|
+
if (r.brokenAt !== null) {
|
|
185
|
+
problems.push({ file: rel, line: r.brokenAt, message: brokenMessage(rel, r.brokenAt) });
|
|
186
|
+
first ??= { file: rel, brokenAt: r.brokenAt };
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
ok: problems.length === 0,
|
|
191
|
+
lines: files.reduce((n, f) => n + f.lines, 0),
|
|
192
|
+
brokenAt: first?.brokenAt ?? null,
|
|
193
|
+
file: first?.file ?? null,
|
|
194
|
+
message: problems[0]?.message ?? null,
|
|
195
|
+
problems,
|
|
196
|
+
files,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function gitBytes(root, args) {
|
|
201
|
+
try {
|
|
202
|
+
return execFileSync('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 1 << 28 });
|
|
203
|
+
} catch (e) {
|
|
204
|
+
throw new GitError(args, String(e.stderr ?? e.message).trim());
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
const lf = (buf) => Buffer.from(buf.toString('latin1').replace(/\r\n/g, '\n'), 'latin1');
|
|
208
|
+
|
|
209
|
+
function resolves(root, ref) {
|
|
210
|
+
try {
|
|
211
|
+
return resolveCommit(root, assertRef(ref)) !== null;
|
|
212
|
+
} catch (e) {
|
|
213
|
+
if (e instanceof GitError) return false;
|
|
214
|
+
throw e;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Append-only against git: every journal file at the merge base of HEAD and `against` (default: the
|
|
219
|
+
// default branch, local, else origin's) must still exist in the working tree and start with the base
|
|
220
|
+
// copy's bytes (CRLF read as LF). [] outside a repo. When the ref or the merge base does not exist: []
|
|
221
|
+
// locally, and with ci one problem saying so (a CI checkout without the default branch's history).
|
|
222
|
+
// root may sit below the git top level; the files reported are relative to root.
|
|
223
|
+
// -> [{file, line, message}] with message `journal file <f> was shortened or removed since <ref>`.
|
|
224
|
+
export function appendOnlyProblems(root, cfg, { against, ci = false } = {}) {
|
|
225
|
+
if (!isRepo(root)) return [];
|
|
226
|
+
const relDir = toPosix(path.relative(root, dirOf(root, cfg)));
|
|
227
|
+
const noBase = () => (ci ? [{ file: relDir, line: 0, message: NO_BASE }] : []);
|
|
228
|
+
const def = cfg?.defaultBranch ?? 'main';
|
|
229
|
+
const candidates = against != null ? [against] : [def, `origin/${def}`];
|
|
230
|
+
const ref = candidates.find((r) => resolves(root, r));
|
|
231
|
+
if (ref === undefined) return noBase();
|
|
232
|
+
let base;
|
|
233
|
+
try {
|
|
234
|
+
base = git(root, ['merge-base', 'HEAD', ref]);
|
|
235
|
+
} catch (e) {
|
|
236
|
+
if (e instanceof GitError) return noBase();
|
|
237
|
+
throw e;
|
|
238
|
+
}
|
|
239
|
+
// --full-name lists paths from the top level, as `git show <base>:<path>` takes them; the prefix
|
|
240
|
+
// (root's place below the top level) maps each back to root.
|
|
241
|
+
const prefix = git(root, ['rev-parse', '--show-prefix']);
|
|
242
|
+
const listed = git(root, ['ls-tree', '-r', '--full-name', '--name-only', base, '--', `${relDir}/`]);
|
|
243
|
+
const out = [];
|
|
244
|
+
for (const full of listed === '' ? [] : listed.split('\n')) {
|
|
245
|
+
if (!full.endsWith('.log') || !full.startsWith(prefix)) continue;
|
|
246
|
+
const rel = full.slice(prefix.length);
|
|
247
|
+
const was = lf(gitBytes(root, ['show', `${base}:${full}`]));
|
|
248
|
+
let now = null;
|
|
249
|
+
try {
|
|
250
|
+
now = lf(fs.readFileSync(path.join(root, ...rel.split('/'))));
|
|
251
|
+
} catch {
|
|
252
|
+
now = null;
|
|
253
|
+
}
|
|
254
|
+
if (now === null || now.length < was.length || !now.subarray(0, was.length).equals(was)) {
|
|
255
|
+
out.push({ file: rel, line: 0, message: `journal file ${rel} was shortened or removed since ${ref}` });
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return out;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function readIfAny(file) {
|
|
262
|
+
if (file === null) return '';
|
|
263
|
+
try {
|
|
264
|
+
return fs.readFileSync(file, 'utf8');
|
|
265
|
+
} catch (e) {
|
|
266
|
+
if (e.code === 'ENOENT') return '';
|
|
267
|
+
throw e;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// The text's last line (the one before the final newline), or null for an empty text.
|
|
272
|
+
function lastLine(text) {
|
|
273
|
+
if (text === '') return null;
|
|
274
|
+
const parts = text.split('\n');
|
|
275
|
+
return parts.length >= 2 ? parts.at(-2) : null;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// The last line of this clone's file for branch, parsed; null when there is none or it does not parse.
|
|
279
|
+
export function readLast(root, branch = journalBranch(root), cfg) {
|
|
280
|
+
const text = readIfAny(journalFile(root, branch, cfg));
|
|
281
|
+
if (text !== '' && !text.endsWith('\n')) return null;
|
|
282
|
+
const line = lastLine(text);
|
|
283
|
+
return line === null ? null : parseLine(line);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function withLock(file, fn, budgetMs) {
|
|
287
|
+
return withFileLock(`${file}.lock`, fn, {
|
|
288
|
+
budgetMs,
|
|
289
|
+
busy: () => new JournalError(`could not lock ${toPosix(file)}: another slicekit is appending`),
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
function writeAll(fd, text) {
|
|
294
|
+
const buf = Buffer.from(text, 'utf8');
|
|
295
|
+
let off = 0;
|
|
296
|
+
while (off < buf.length) off += fs.writeSync(fd, buf, off, buf.length - off);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// Appends one line to this clone's file for branch, under a lock, and returns it (no newline). Refuses a
|
|
300
|
+
// file whose last line is torn or is not a journal line (a blank line included): the chain is never
|
|
301
|
+
// continued from a guess.
|
|
302
|
+
export function appendJournal(root, fields, { branch = journalBranch(root), now = new Date(), cfg, budgetMs = LOCK_BUDGET_MS } = {}) {
|
|
303
|
+
const file = journalFile(root, branch, cfg, { create: true });
|
|
304
|
+
const shown = toPosix(path.relative(root, file));
|
|
305
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
306
|
+
return withLock(file, () => {
|
|
307
|
+
const text = readIfAny(file);
|
|
308
|
+
if (text !== '' && !text.endsWith('\n')) throw new JournalError(`${shown} ends in a torn line; not appending`);
|
|
309
|
+
const last = lastLine(text);
|
|
310
|
+
let prev = GENESIS;
|
|
311
|
+
if (last !== null) {
|
|
312
|
+
const p = parseLine(last);
|
|
313
|
+
if (!p) throw new JournalError(`${shown} last line does not parse; not appending`);
|
|
314
|
+
prev = p.hash;
|
|
315
|
+
}
|
|
316
|
+
const body = lineBody(fields, prev, now.toISOString());
|
|
317
|
+
const line = `${body} hash=${hashLine(body)}`;
|
|
318
|
+
const fd = fs.openSync(file, 'a');
|
|
319
|
+
try {
|
|
320
|
+
writeAll(fd, `${line}\n`);
|
|
321
|
+
} finally {
|
|
322
|
+
fs.closeSync(fd);
|
|
323
|
+
}
|
|
324
|
+
return line;
|
|
325
|
+
}, budgetMs);
|
|
326
|
+
}
|
package/src/lock.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// One lock file per guarded file: `wx` creates it or fails, so one holder at a time. A lock older than
|
|
2
|
+
// LOCK_STALE_MS is taken as left by a dead process and removed. The journal and the slice state use it.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
|
|
5
|
+
export const LOCK_WAIT_MS = 10;
|
|
6
|
+
export const LOCK_STALE_MS = 30_000;
|
|
7
|
+
|
|
8
|
+
export const sleep = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
9
|
+
|
|
10
|
+
// Runs fn while holding `lock`, waiting up to budgetMs for it; then throws busy() (an Error).
|
|
11
|
+
export function withFileLock(lock, fn, { budgetMs, busy }) {
|
|
12
|
+
const deadline = Date.now() + budgetMs;
|
|
13
|
+
let fd;
|
|
14
|
+
for (;;) {
|
|
15
|
+
try {
|
|
16
|
+
fd = fs.openSync(lock, 'wx');
|
|
17
|
+
break;
|
|
18
|
+
} catch (e) {
|
|
19
|
+
if (e.code !== 'EEXIST' && e.code !== 'EPERM' && e.code !== 'EACCES') throw e;
|
|
20
|
+
try {
|
|
21
|
+
if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.unlinkSync(lock);
|
|
22
|
+
} catch {
|
|
23
|
+
// the holder released it between the attempt and the stat; try again
|
|
24
|
+
}
|
|
25
|
+
if (Date.now() >= deadline) throw busy();
|
|
26
|
+
sleep(LOCK_WAIT_MS);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
return fn();
|
|
31
|
+
} finally {
|
|
32
|
+
fs.closeSync(fd);
|
|
33
|
+
fs.rmSync(lock, { force: true });
|
|
34
|
+
}
|
|
35
|
+
}
|
package/src/markdown.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { ID } from './ids.js';
|
|
2
|
+
|
|
3
|
+
export function lines(text) {
|
|
4
|
+
return text.replace(/^/, '').replace(/\r\n/g, '\n').split('\n');
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
const FENCE = /^\s*(```|~~~)/;
|
|
8
|
+
|
|
9
|
+
// Yields [line, number] for every line outside fenced code blocks (1-based).
|
|
10
|
+
export function* prose(text) {
|
|
11
|
+
let inFence = false;
|
|
12
|
+
const all = lines(text);
|
|
13
|
+
for (let i = 0; i < all.length; i++) {
|
|
14
|
+
if (FENCE.test(all[i])) {
|
|
15
|
+
inFence = !inFence;
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
if (!inFence) yield [all[i], i + 1];
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function headings(text) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const [line, n] of prose(text)) {
|
|
25
|
+
const m = /^(#{1,6})\s+(.*?)\s*#*\s*$/.exec(line);
|
|
26
|
+
if (m) out.push({ level: m[1].length, text: m[2], line: n });
|
|
27
|
+
}
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function frontMatter(text) {
|
|
32
|
+
const all = lines(text);
|
|
33
|
+
const plain = all.join('\n');
|
|
34
|
+
if (all[0] !== '---') return { data: {}, body: plain };
|
|
35
|
+
const end = all.indexOf('---', 1);
|
|
36
|
+
if (end === -1) return { data: {}, body: plain };
|
|
37
|
+
const data = {};
|
|
38
|
+
let listKey = null;
|
|
39
|
+
for (const line of all.slice(1, end)) {
|
|
40
|
+
const item = /^\s*-\s+(.*)$/.exec(line);
|
|
41
|
+
if (item && listKey) {
|
|
42
|
+
data[listKey].push(item[1].trim());
|
|
43
|
+
continue;
|
|
44
|
+
}
|
|
45
|
+
const kv = /^([^:\s][^:]*):\s*(.*)$/.exec(line);
|
|
46
|
+
if (!kv) continue;
|
|
47
|
+
const [, key, value] = kv;
|
|
48
|
+
if (value === '') {
|
|
49
|
+
listKey = key;
|
|
50
|
+
data[key] = [];
|
|
51
|
+
} else {
|
|
52
|
+
listKey = null;
|
|
53
|
+
const list = /^\[(.*)\]$/.exec(value.trim());
|
|
54
|
+
data[key] = list ? list[1].split(',').map((s) => s.trim()).filter((s) => s !== '') : value.trim();
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { data, body: all.slice(end + 1).join('\n') };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// A table row's cells. A `\|` is a pipe inside its cell, not a cell break, and is read as `|`.
|
|
61
|
+
export const tableCells = (row) =>
|
|
62
|
+
row
|
|
63
|
+
.replace(/^\s*\|/, '')
|
|
64
|
+
.replace(/(?<!\\)\|\s*$/, '')
|
|
65
|
+
.split(/(?<!\\)\|/)
|
|
66
|
+
.map((c) => c.trim().replace(/\\\|/g, '|'));
|
|
67
|
+
const cells = tableCells;
|
|
68
|
+
const isRow = (l) => /^\s*\|.*\|\s*$/.test(l);
|
|
69
|
+
const isDivider = (l) => /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(l);
|
|
70
|
+
|
|
71
|
+
export function tables(text) {
|
|
72
|
+
const all = lines(text);
|
|
73
|
+
const fenced = [];
|
|
74
|
+
let inFence = false;
|
|
75
|
+
for (const l of all) {
|
|
76
|
+
if (FENCE.test(l)) {
|
|
77
|
+
inFence = !inFence;
|
|
78
|
+
fenced.push(true);
|
|
79
|
+
} else {
|
|
80
|
+
fenced.push(inFence);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const out = [];
|
|
84
|
+
for (let i = 0; i < all.length - 1; i++) {
|
|
85
|
+
if (!fenced[i] && !fenced[i + 1] && isRow(all[i]) && isDivider(all[i + 1])) {
|
|
86
|
+
const rows = [];
|
|
87
|
+
let j = i + 2;
|
|
88
|
+
while (j < all.length && !fenced[j] && isRow(all[j])) rows.push(cells(all[j++]));
|
|
89
|
+
out.push({ line: i + 1, header: cells(all[i]), rows });
|
|
90
|
+
i = j - 1;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// A link target: one level of balanced parentheses (`a(b).md`), then an optional title.
|
|
97
|
+
const LINK = /\[[^\]]*\]\(\s*((?:[^()\s]|\([^()\s]*\))+)(?:\s+(?:"[^"]*"|'[^']*'))?\s*\)/g;
|
|
98
|
+
const CODE_SPAN = /`[^`]*`/g;
|
|
99
|
+
|
|
100
|
+
// The line with every inline code span blanked to spaces, so columns are unchanged.
|
|
101
|
+
export const blankCodeSpans = (line) => line.replace(CODE_SPAN, (m) => ' '.repeat(m.length));
|
|
102
|
+
|
|
103
|
+
// A path written on Windows reads the same as one written anywhere else.
|
|
104
|
+
export const toSlashes = (p) => p.replace(/\\/g, '/');
|
|
105
|
+
|
|
106
|
+
// A target the reader cannot resolve to one file of repository content: a URL, a `<placeholder>`,
|
|
107
|
+
// a glob, or anything under `.git/` or `node_modules/`.
|
|
108
|
+
export function isPathLike(target) {
|
|
109
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(target) || target.includes('://') || /[<>*?{}]/.test(target)) return false;
|
|
110
|
+
const first = toSlashes(target).replace(/^(\.?\/)+/, '').split('/')[0];
|
|
111
|
+
return first !== '.git' && first !== 'node_modules';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A backticked token that names a repo path: a separator, a letter, and either a trailing
|
|
115
|
+
// separator or a final segment with an extension. One leading dot is part of the name, so `.bin`
|
|
116
|
+
// has no extension while `.eslintrc.cjs` has `cjs`.
|
|
117
|
+
function looksLikePath(token) {
|
|
118
|
+
const p = toSlashes(token);
|
|
119
|
+
if (!p.includes('/') || !/[A-Za-z]/.test(p) || !isPathLike(p)) return false;
|
|
120
|
+
return p.endsWith('/') || /^[^.][^/]*\.[A-Za-z0-9]+$/.test(p.split('/').at(-1).replace(/^\./, ''));
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// A reference-style link definition, `[ref]: target "title"`, its target optionally in `<>`. A
|
|
124
|
+
// footnote (`[^1]: text`) is not one.
|
|
125
|
+
const DEFINITION = /^\s{0,3}\[(?!\^)[^\]]+\]:\s*(?:<([^>\s]+)>|(\S+))/;
|
|
126
|
+
|
|
127
|
+
// Paths, anchors and ids outside fenced code. A link written inside a code span is not a link; a
|
|
128
|
+
// reference-style link (`[t][ref]`) is checked at its definition line. A path says whether it came
|
|
129
|
+
// from a link or a code span (`via`); an anchor carries the file it points into.
|
|
130
|
+
export function refs(text) {
|
|
131
|
+
const out = [];
|
|
132
|
+
const idRe = new RegExp(
|
|
133
|
+
`\\b(?:${ID.req}|${ID.sliceAddr}|${ID.decision}|${ID.gap}|${ID.contract})\\b`,
|
|
134
|
+
'g',
|
|
135
|
+
);
|
|
136
|
+
for (const [line, n] of prose(text)) {
|
|
137
|
+
const outsideCode = blankCodeSpans(line);
|
|
138
|
+
const def = DEFINITION.exec(outsideCode);
|
|
139
|
+
const targets = [...outsideCode.matchAll(LINK)].map((m) => m[1]);
|
|
140
|
+
if (def) targets.push(def[1] ?? def[2]);
|
|
141
|
+
for (const target of targets) {
|
|
142
|
+
if (target.startsWith('#') || !isPathLike(target)) continue;
|
|
143
|
+
const hash = target.indexOf('#');
|
|
144
|
+
const file = hash === -1 ? target : target.slice(0, hash);
|
|
145
|
+
const anchor = hash === -1 ? '' : target.slice(hash + 1);
|
|
146
|
+
if (file) out.push({ kind: 'path', value: file, via: 'link', line: n });
|
|
147
|
+
if (file && anchor) out.push({ kind: 'anchor', value: anchor, file, line: n });
|
|
148
|
+
}
|
|
149
|
+
for (const m of line.matchAll(/`([^`\s]+)`/g)) {
|
|
150
|
+
if (looksLikePath(m[1])) out.push({ kind: 'path', value: m[1], via: 'code', line: n });
|
|
151
|
+
}
|
|
152
|
+
for (const m of line.matchAll(idRe)) out.push({ kind: 'id', value: m[0], line: n });
|
|
153
|
+
}
|
|
154
|
+
return out;
|
|
155
|
+
}
|
package/src/paths.js
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
export function kitPaths(root, cfg) {
|
|
4
|
+
const kit = path.join(root, '.slicekit');
|
|
5
|
+
const docs = path.join(root, cfg.docsRoot);
|
|
6
|
+
const spec = path.join(docs, 'spec');
|
|
7
|
+
return {
|
|
8
|
+
kit,
|
|
9
|
+
config: path.join(kit, 'config.json'),
|
|
10
|
+
state: path.join(kit, 'state'),
|
|
11
|
+
baselines: path.join(kit, 'baselines'),
|
|
12
|
+
journalDir: path.join(kit, 'journal'),
|
|
13
|
+
graph: path.join(kit, 'graph'),
|
|
14
|
+
workspace: path.join(kit, 'workspace.json'),
|
|
15
|
+
docs,
|
|
16
|
+
intake: path.join(docs, 'intake'),
|
|
17
|
+
decisions: path.join(docs, 'decisions.md'),
|
|
18
|
+
spec,
|
|
19
|
+
contracts: path.join(spec, 'contracts'),
|
|
20
|
+
gaps: path.join(spec, 'gaps.md'),
|
|
21
|
+
stack: path.join(spec, 'stack.md'),
|
|
22
|
+
platform: path.join(docs, 'platform.md'),
|
|
23
|
+
observability: path.join(docs, 'observability.md'),
|
|
24
|
+
runbook: path.join(docs, 'runbook.md'),
|
|
25
|
+
phases: path.join(docs, 'phases'),
|
|
26
|
+
releases: path.join(docs, 'releases'),
|
|
27
|
+
build: path.join(root, 'BUILD.md'),
|
|
28
|
+
claude: path.join(root, '.claude'),
|
|
29
|
+
githooks: path.join(root, '.githooks'),
|
|
30
|
+
workflow: path.join(root, '.github', 'workflows', 'slicekit.yml'),
|
|
31
|
+
gitignore: path.join(root, '.gitignore'),
|
|
32
|
+
};
|
|
33
|
+
}
|
package/src/plan.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
// What stops `/slicekit plan` (REQ-2.5): a clarification marker anywhere in the spec, contracts and
|
|
2
|
+
// stack.md included, or a gap scan that is not done (REQ-1.7).
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { exists, listFiles, readText } from './fs.js';
|
|
5
|
+
import { kitPaths } from './paths.js';
|
|
6
|
+
import { StageError, clarificationMarkers, requireStage } from './stage.js';
|
|
7
|
+
|
|
8
|
+
// Each blocker as one line: first every marker as `<file>:<line> clarification marker: <text>`,
|
|
9
|
+
// files in sorted order, then the refusal of the first stage up to the gap scan that is not done.
|
|
10
|
+
export function planBlockers(root, cfg) {
|
|
11
|
+
const dir = kitPaths(root, cfg).spec;
|
|
12
|
+
const blockers = [];
|
|
13
|
+
const files = exists(dir) ? listFiles(dir, { ext: '.md' }).sort() : [];
|
|
14
|
+
for (const f of files) {
|
|
15
|
+
const name = path.relative(root, path.join(dir, f)).split(path.sep).join('/');
|
|
16
|
+
for (const m of clarificationMarkers(readText(path.join(dir, f)))) blockers.push(`${name}:${m.line} clarification marker: ${m.text}`);
|
|
17
|
+
}
|
|
18
|
+
try {
|
|
19
|
+
requireStage(root, cfg, 'gap-scan');
|
|
20
|
+
} catch (e) {
|
|
21
|
+
if (!(e instanceof StageError)) throw e;
|
|
22
|
+
blockers.push(e.message);
|
|
23
|
+
}
|
|
24
|
+
return blockers;
|
|
25
|
+
}
|
package/src/pr.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
// Opening a pull request (02 REQ-2.10, REQ-2.1): the one path every command takes to put its work up
|
|
2
|
+
// for review. Everything that can refuse does so before anything is committed or pushed: the branch
|
|
3
|
+
// and where it would push, the base, the paths, the pull request already open for the branch (one
|
|
4
|
+
// per kind of change, so its title and base must match), and the body as the CI body rule judges it
|
|
5
|
+
// under that pull request's real title. A branch with an open pull request gets that pull request's
|
|
6
|
+
// body updated, never a second pull request.
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { EXEMPT_TITLE } from './check/ci-event.js';
|
|
10
|
+
import { assertRef, commitPaths, currentBranch, git, pushBranch, pushTarget } from './git.js';
|
|
11
|
+
import { prBodyProblems } from './prbody.js';
|
|
12
|
+
|
|
13
|
+
export class PrError extends Error {
|
|
14
|
+
constructor(message, code = 1) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.name = 'PrError';
|
|
17
|
+
this.code = code;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// A slice pull request opens as a draft (the build loop marks it ready once review clears it); a
|
|
22
|
+
// `[spec] ` or `[plan] ` pull request opens ready for review. `draft: true` forces a draft.
|
|
23
|
+
export const opensAsDraft = (title) => !EXEMPT_TITLE.test(title);
|
|
24
|
+
|
|
25
|
+
const NOT_INSIDE = '--paths must name files or folders inside the repository, not the root';
|
|
26
|
+
|
|
27
|
+
// Each path, read from `root` as git reads it, must name something below the repository's top.
|
|
28
|
+
function assertInside(root, paths) {
|
|
29
|
+
const real = (p) => fs.realpathSync.native(p);
|
|
30
|
+
const top = real(git(root, ['rev-parse', '--show-toplevel']));
|
|
31
|
+
const here = real(root);
|
|
32
|
+
for (const p of paths) {
|
|
33
|
+
const rel = path.relative(top, path.resolve(here, p));
|
|
34
|
+
if (rel === '' || rel === '..' || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) throw new PrError(NOT_INSIDE, 2);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// -> { number, url, created, committed }. `commit: {message, paths}` commits only those paths;
|
|
39
|
+
// `committed` is the new commit's SHA, or null when they held nothing to commit. `base` defaults to
|
|
40
|
+
// the default branch; given, it must match an open pull request's base. Throws PrError (code 1 or
|
|
41
|
+
// 2), GitError or GitHostError.
|
|
42
|
+
export function openOrUpdate(root, cfg, host, { title, body, base, commit, draft } = {}) {
|
|
43
|
+
if (typeof title !== 'string' || title.trim() === '' || /[\r\n]/.test(title)) throw new PrError('the title must be one non-empty line', 2);
|
|
44
|
+
const baseGiven = base !== undefined;
|
|
45
|
+
const into = assertRef(baseGiven ? base : cfg.defaultBranch);
|
|
46
|
+
const branch = currentBranch(root);
|
|
47
|
+
if (branch === null) throw new PrError('HEAD is detached; open a pull request from a work branch');
|
|
48
|
+
const protectedBranches = cfg.protectedBranches ?? [];
|
|
49
|
+
const isProtected = (b) => b === cfg.defaultBranch || protectedBranches.includes(b);
|
|
50
|
+
const { target } = pushTarget(root);
|
|
51
|
+
for (const b of [branch, target]) if (isProtected(b)) throw new PrError(`open a pull request from a work branch, not ${b}`);
|
|
52
|
+
if (into === target) throw new PrError(`--base ${into} is the branch being pushed; name the branch it merges into`, 2);
|
|
53
|
+
if (commit) assertInside(root, commit.paths);
|
|
54
|
+
|
|
55
|
+
const open = host.pullRequestForBranch(target, { base: baseGiven ? into : undefined });
|
|
56
|
+
let judged = title;
|
|
57
|
+
if (open) {
|
|
58
|
+
judged = host.getPullRequest(open.number).title;
|
|
59
|
+
if (judged !== title) throw new PrError(`pull request #${open.number} is titled "${judged}"; open one per kind of change`);
|
|
60
|
+
if (baseGiven && open.base && open.base !== into) throw new PrError(`pull request #${open.number} targets ${open.base}, not ${into}`);
|
|
61
|
+
}
|
|
62
|
+
const problems = prBodyProblems(judged, body, cfg);
|
|
63
|
+
if (problems.length > 0) throw new PrError(problems.join('\n'));
|
|
64
|
+
|
|
65
|
+
const committed = commit ? commitPaths(root, commit.paths, commit.message) : undefined;
|
|
66
|
+
pushBranch(root, { protectedBranches, defaultBranch: cfg.defaultBranch });
|
|
67
|
+
if (open) {
|
|
68
|
+
host.updatePullRequestBody(open.number, body);
|
|
69
|
+
return { number: open.number, url: open.url, created: false, committed };
|
|
70
|
+
}
|
|
71
|
+
const made = host.openPullRequest({ branch: target, base: into, title, body, draft: draft === true || opensAsDraft(title) });
|
|
72
|
+
return { number: made.number, url: made.url, created: true, committed };
|
|
73
|
+
}
|