slicekit 0.3.3 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/init.js CHANGED
@@ -23,6 +23,8 @@ const IGNORE_RULES = [
23
23
  { rule: '.slicekit/.subagent-*', forms: new Set(['.slicekit/.subagent-*', '/.slicekit/.subagent-*']) },
24
24
  // The machine's own settings (D-43), such as a local test command: never part of the project.
25
25
  { rule: '.slicekit/local.json', forms: new Set(['.slicekit/local.json', '/.slicekit/local.json']) },
26
+ // The reports of `/slicekit ops` and `/slicekit audit` (D-57, D-58): written on one machine, never committed.
27
+ { rule: '.slicekit/reports/', forms: new Set(['.slicekit/reports/', '/.slicekit/reports/', '.slicekit/reports', '/.slicekit/reports']) },
26
28
  { rule: '!.slicekit/journal/', forms: new Set(['!.slicekit/journal/', '!/.slicekit/journal/']) },
27
29
  { rule: '!.slicekit/journal/*.log', forms: new Set(['!.slicekit/journal/*.log', '!/.slicekit/journal/*.log']) },
28
30
  { rule: '.slicekit/journal/*.lock', forms: new Set(['.slicekit/journal/*.lock', '/.slicekit/journal/*.lock']) },
@@ -40,6 +42,8 @@ const IGNORE_RULES = [
40
42
  const UNIGNORE_RULES = ['!.slicekit/journal/', '!.slicekit/journal/*.log', '.slicekit/journal/*.lock', '!.slicekit/journal-heads.log'];
41
43
  const UNIGNORE_PROBES = ['.slicekit/journal-heads.log', '.slicekit/journal/main--00000000.log'];
42
44
 
45
+ const REPORTS_RULE = '.slicekit/reports/';
46
+
43
47
  function ignoredByGit(root, rel) {
44
48
  try {
45
49
  git(root, ['check-ignore', '--quiet', '--no-index', rel]);
@@ -94,6 +98,21 @@ function reassertUnignores(root, file) {
94
98
  return { appended, note };
95
99
  }
96
100
 
101
+ // The ignore rule for the reports directory when the project lacks it, else null. `update` never
102
+ // writes the ignore file (REQ-5.6: managed blocks only), so it prints this line for a project
103
+ // initialised before the rule existed (P5/S-23 review H-4). In a git repository git decides whether
104
+ // a report is ignored; outside one, a line in any spelling init accepts counts.
105
+ export function missingReportsRule(root, cfg) {
106
+ const paths = kitPaths(root, cfg);
107
+ if (isRepo(root)) {
108
+ const report = path.relative(root, path.join(paths.reports, 'ops-1.md')).split(path.sep).join('/');
109
+ return ignoredByGit(root, report) ? null : REPORTS_RULE;
110
+ }
111
+ const { forms } = IGNORE_RULES.find((r) => r.rule === REPORTS_RULE);
112
+ const present = exists(paths.gitignore) ? fs.readFileSync(paths.gitignore, 'utf8').split(/\r?\n/).map((l) => l.trim()) : [];
113
+ return present.some((l) => forms.has(l)) ? null : REPORTS_RULE;
114
+ }
115
+
97
116
  // Hooks checked out with CRLF break sh (REQ-3.9).
98
117
  // Intake snapshots (S-10) are stored byte for byte, so git must not convert their line endings. The
99
118
  // pattern comes from kitPaths as S-10 builds it, so `./docs` and `docs` write the same line.
package/src/ops.js ADDED
@@ -0,0 +1,223 @@
1
+ // `slicekit ops` (REQ-2.13, D-57): what `/slicekit ops` hands the ops agent for a symptom, and the
2
+ // check of the report the agent replies with. Both read graph.json and files; neither runs git, calls
3
+ // the host or takes an action.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { history } from './graph/history.js';
7
+ import { indexGraph, loadGraph, normalisePath } from './graph/load.js';
8
+ import { GraphError, cmp, keyOf } from './graph/schema.js';
9
+ import { re } from './ids.js';
10
+ import { kitPaths } from './paths.js';
11
+ import { cellsOf, footerProblems, isDivider, isRow, lineExists, nextReport, reportSections } from './reports.js';
12
+
13
+ // A word naming more files than this is too broad to expand.
14
+ export const BROAD = 50;
15
+
16
+ const posix = (p) => p.split(path.sep).join('/');
17
+ const segmentsOf = (file) => file.toLowerCase().split(/[/._-]/).filter((s) => s !== '');
18
+
19
+ // The files a symptom names (D-57). Words are the runs of letters and digits of three or more
20
+ // characters, lower-cased, unique, in order; a word names each file one of whose path segments
21
+ // (split on `/`, `.`, `-`, `_`) equals it. A word naming more than BROAD files names none and is
22
+ // reported; so is a word naming no file. Each of `paths` names the files `slicekit history` would
23
+ // match for it. -> {files, words: [{word, files}], broad: [{word, count}], unmatched}
24
+ export function symptomFiles(index, symptom, paths = []) {
25
+ const all = index.byKind('file').map((n) => keyOf(n.id));
26
+ const bySegment = new Map();
27
+ for (const file of all) {
28
+ for (const s of new Set(segmentsOf(file))) {
29
+ if (!bySegment.has(s)) bySegment.set(s, []);
30
+ bySegment.get(s).push(file);
31
+ }
32
+ }
33
+ const found = new Set();
34
+ const words = [];
35
+ const broad = [];
36
+ const unmatched = [];
37
+ for (const word of new Set((String(symptom ?? '').match(/[A-Za-z0-9]{3,}/g) ?? []).map((w) => w.toLowerCase()))) {
38
+ const named = bySegment.get(word) ?? [];
39
+ if (named.length === 0) unmatched.push(word);
40
+ else if (named.length > BROAD) broad.push({ word, count: named.length });
41
+ else {
42
+ words.push({ word, files: [...named].sort(cmp) });
43
+ for (const f of named) found.add(f);
44
+ }
45
+ }
46
+ for (const p of paths) {
47
+ const want = normalisePath(p);
48
+ const dir = `${want}/`;
49
+ const named = want === '' || want === '.' ? all : all.filter((f) => f === want || f.startsWith(dir));
50
+ if (named.length === 0) throw new GraphError(2, `${p} is not in the graph`);
51
+ for (const f of named) found.add(f);
52
+ }
53
+ return { files: [...found].sort(cmp), words, broad, unmatched };
54
+ }
55
+
56
+ // The release record of the highest phase, as its repository-relative path; null when there is none.
57
+ function lastRelease(index) {
58
+ const phaseOf = (n) => Number(/^P(\d+)$/.exec(keyOf(n.id))?.[1] ?? -1);
59
+ const newest = [...index.byKind('release')].sort((a, b) => phaseOf(b) - phaseOf(a) || cmp(a.id, b.id))[0];
60
+ return newest ? String(newest.from ?? '').replace(/:\d+$/, '') || null : null;
61
+ }
62
+
63
+ // Everything the ops agent is handed for `symptom`. The report path is reserved last, so a symptom
64
+ // that names no file leaves no empty report behind. Paths are repository-relative.
65
+ export function opsContext(root, cfg, symptom, { paths = [] } = {}) {
66
+ const index = indexGraph(loadGraph(root, cfg));
67
+ const { files, broad, unmatched } = symptomFiles(index, symptom, paths);
68
+ if (files.length === 0) throw new GraphError(1, 'the symptom names no file in the graph; name one with --path <path>');
69
+ const p = kitPaths(root, cfg);
70
+ const rel = (file) => posix(path.relative(root, file));
71
+ const entries = history(index, files);
72
+ return {
73
+ report: nextReport(root, cfg, 'ops'),
74
+ symptom,
75
+ files,
76
+ broad,
77
+ unmatched,
78
+ history: entries,
79
+ runbook: rel(p.runbook),
80
+ observability: rel(p.observability),
81
+ missing: [p.runbook, p.observability].filter((f) => !fs.existsSync(f)).map(rel),
82
+ lastRelease: lastRelease(index),
83
+ };
84
+ }
85
+
86
+ export const OPS_SECTIONS = ['Likely slices and pull requests', 'First checks', 'Proposed actions'];
87
+
88
+ const FOOTER = /^(?:Skipped|Not checked):/;
89
+ const ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/;
90
+ const MARKED = /\((?:anyone|on-call|owner: [^()]*[^()\s][^()]*)\)[.\s]*$/;
91
+ const PR_REF = /(?<![\w&/#.-])([A-Za-z0-9._-]+)?#(\d+)\b/g;
92
+ const CITATION = /(?<![\w./-])([A-Za-z0-9_.][\w./-]*):(\d+)\b/g;
93
+
94
+ // The file extensions a path can end in without naming a file of the graph: the cited file may be
95
+ // missing, and its extension still says it was meant as a file.
96
+ const EXTENSIONS = new Set(
97
+ 'c cc cfg cjs conf cpp cs css csv env go gradle h hpp html ini java js json jsx kt lock log lua md mjs php properties proto ps1 py rb rs scss sh sql svelte swift tf toml ts tsx txt vue xml yaml yml'.split(' '),
98
+ );
99
+ const extensionOf = (file) => /\.([A-Za-z0-9]+)$/.exec(file.split('/').at(-1))?.[1].toLowerCase() ?? null;
100
+
101
+ // Whether the text before the colon of a `<path>:<line>` token in First checks makes it a citation
102
+ // (P5/S-23 review H-6), with a slash in it or without. It is one when the path is a file in the
103
+ // repository or a file of the graph, and when its last segment ends in a file extension: one of
104
+ // EXTENSIONS, or the extension of a file of the graph. A token that names no file and ends in no file
105
+ // extension, such as `localhost:8080`, `svc.internal/health:8080` or `registry/app:2`, is none.
106
+ function isCitation(root, index, file) {
107
+ if (file === '' || file === '.') return false;
108
+ if (index.node(`file:${file}`)) return true;
109
+ try {
110
+ if (fs.statSync(path.join(root, file)).isFile()) return true;
111
+ } catch {
112
+ // Not a file on disk: the extension decides.
113
+ }
114
+ const ext = extensionOf(file);
115
+ return ext !== null && (EXTENSIONS.has(ext) || index.byKind('file').some((n) => extensionOf(keyOf(n.id)) === ext));
116
+ }
117
+
118
+ const FENCE = /^\s*(```|~~~)/;
119
+ const SUBHEADING = /^\s{0,3}#{3,6}\s/;
120
+ const NO_MARK = 'who may take it: (anyone), (on-call) or (owner: <name>)';
121
+
122
+ // The actions of the Proposed actions section, in each form the section can hold one, as
123
+ // {first, marked, message}: `first` the action's first line number. A list item, with the lines that
124
+ // continue it (indented, or right under it), and a paragraph of plain lines are each one action,
125
+ // marked when the joined text ends with the mark. A table row is one action, marked when one of its
126
+ // cells ends with the mark; the header row and the divider are none. A sub-heading and a fenced
127
+ // block are no action. `ls` holds the section's lines that are not blank.
128
+ function actions(ls) {
129
+ const out = [];
130
+ let open = null;
131
+ let last = 0;
132
+ let fenced = false;
133
+ const start = (first, t) => {
134
+ open = { first, text: t.trimEnd(), item: ITEM.test(t) };
135
+ out.push(open);
136
+ };
137
+ ls.forEach(({ text: t, line }, i) => {
138
+ const adjacent = line === last + 1;
139
+ last = line;
140
+ if (FENCE.test(t)) {
141
+ fenced = !fenced;
142
+ open = null;
143
+ } else if (fenced || SUBHEADING.test(t)) {
144
+ open = null;
145
+ } else if (isRow(t)) {
146
+ open = null;
147
+ const header = ls[i + 1] && ls[i + 1].line === line + 1 && isDivider(ls[i + 1].text);
148
+ if (!header && !isDivider(t)) out.push({ first: line, row: cellsOf(t) });
149
+ } else if (ITEM.test(t)) {
150
+ start(line, t);
151
+ } else if (open && (adjacent || (open.item && /^\s+\S/.test(t)))) {
152
+ open.text += ` ${t.trim()}`;
153
+ } else {
154
+ start(line, t);
155
+ }
156
+ });
157
+ return out.map((a) =>
158
+ a.row
159
+ ? { first: a.first, marked: a.row.some((cell) => MARKED.test(cell)), message: `the action names in no cell ${NO_MARK}` }
160
+ : { first: a.first, marked: MARKED.test(a.text), message: `the action does not end with ${NO_MARK}` },
161
+ );
162
+ }
163
+
164
+ // A Proposed actions section that proposes no action is this one line.
165
+ const NONE = 'None.';
166
+
167
+ // The lines of a section above its first closing line, `Skipped:` or `Not checked:`, outside a fenced
168
+ // block. The closing lines end the section: a closing line that wraps, or a list under it, is no action.
169
+ function beforeFooter(ls) {
170
+ let fenced = false;
171
+ for (let i = 0; i < ls.length; i++) {
172
+ if (FENCE.test(ls[i].text)) fenced = !fenced;
173
+ else if (!fenced && FOOTER.test(ls[i].text)) return ls.slice(0, i);
174
+ }
175
+ return ls;
176
+ }
177
+
178
+ // What is wrong with an ops report, one `<rel>:<line> <message>` per problem (REQ-2.13): each of the
179
+ // three sections present and holding a line; every slice and pull request named in the first one in
180
+ // the graph; every `<file>:<line>` cited in First checks a line that exists; every proposed action,
181
+ // whether a list item, a plain line or a table row, marked by who may take it, up to the first closing
182
+ // line, or the one line `None.` for no action; the two closing lines.
183
+ export function opsReportProblems(root, index, rel, text) {
184
+ const out = [];
185
+ const sections = reportSections(text);
186
+ const content = (name, closed = false) => {
187
+ const section = sections.get(name.toLowerCase());
188
+ if (!section) {
189
+ out.push(`${rel}:1 no "## ${name}" section`);
190
+ return [];
191
+ }
192
+ const upTo = closed ? beforeFooter(section.lines) : section.lines;
193
+ const held = upTo.filter((l) => l.text.trim() !== '' && !FOOTER.test(l.text));
194
+ if (held.length === 0) out.push(`${rel}:${section.line} the "## ${name}" section is empty`);
195
+ return held;
196
+ };
197
+
198
+ for (const { text: l, line } of content(OPS_SECTIONS[0])) {
199
+ for (const addr of new Set(l.match(new RegExp(`\\b${re('sliceAddr').source}\\b`, 'g')) ?? [])) {
200
+ if (!index.node(`slice:${addr}`)) out.push(`${rel}:${line} ${addr} is not a slice in the graph`);
201
+ }
202
+ for (const ref of new Set([...l.matchAll(PR_REF)].map((m) => `${m[1] ?? ''}#${m[2]}`))) {
203
+ if (!index.find(ref)) out.push(`${rel}:${line} ${ref} is not a pull request in the graph`);
204
+ }
205
+ }
206
+
207
+ for (const { text: l, line } of content(OPS_SECTIONS[1])) {
208
+ for (const m of l.matchAll(CITATION)) {
209
+ const file = normalisePath(m[1]);
210
+ if (!isCitation(root, index, file)) continue;
211
+ if (!lineExists(root, file, Number(m[2]))) out.push(`${rel}:${line} ${m[1]}:${m[2]} is not a line of a file in the repository`);
212
+ }
213
+ }
214
+
215
+ const proposed = content(OPS_SECTIONS[2], true);
216
+ if (!(proposed.length === 1 && proposed[0].text.trim() === NONE)) {
217
+ for (const action of actions(proposed)) {
218
+ if (!action.marked) out.push(`${rel}:${action.first} ${action.message}`);
219
+ }
220
+ }
221
+
222
+ return [...out, ...footerProblems(rel, text)];
223
+ }
package/src/paths.js CHANGED
@@ -11,6 +11,7 @@ export function kitPaths(root, cfg) {
11
11
  baselines: path.join(kit, 'baselines'),
12
12
  journalDir: path.join(kit, 'journal'),
13
13
  graph: path.join(kit, 'graph'),
14
+ reports: path.join(kit, 'reports'),
14
15
  workspace: path.join(kit, 'workspace.json'),
15
16
  docs,
16
17
  intake: path.join(docs, 'intake'),
@@ -11,7 +11,9 @@
11
11
  // slices this run of the sync moved to `merged`. A sync with no such slice, and a config without
12
12
  // `release.auto`, set none. The version counts from package.json at the merge commit, never from
13
13
  // one an open sync pull request proposes. The rendered files follow the version (`update --yes`),
14
- // as `build render` would commit them.
14
+ // as `build render` would commit them. So do the rendered files of each folder under `examples/`
15
+ // that holds a rendered directory (D-95): the sync renders each one at the same version, as
16
+ // `update --yes` would in that folder, and its pull request carries those files.
15
17
  //
16
18
  // Where a slice begins: the oldest commit of the default branch's first-parent history that brings
17
19
  // its state file. For a merge commit or a squash merge that is the merge itself; for a rebase merge
@@ -35,7 +37,7 @@
35
37
  import fs from 'node:fs';
36
38
  import path from 'node:path';
37
39
  import { fileURLToPath } from 'node:url';
38
- import { CONFIG_PATH, ConfigError, releaseAutoError } from './config.js';
40
+ import { CONFIG_PATH, ConfigError, loadConfig, releaseAutoError } from './config.js';
39
41
  import { GitError, git } from './git.js';
40
42
  import { readText, writeText } from './fs.js';
41
43
  import { ID, stateFileName } from './ids.js';
@@ -271,15 +273,87 @@ function sliceBegins(root, cfg, merge) {
271
273
  return begins;
272
274
  }
273
275
 
274
- // The paths the release step may write: package.json, CHANGELOG.md and the files `update` renders.
275
- export function releasePaths(cfg) {
276
- return [PACKAGE, CHANGELOG, ...new Set([...entriesForShape(cfg.shape).map((e) => e.dest), SETTINGS]), RENDERED];
276
+ // The files `update` renders for a config, and the directory of their reference copies.
277
+ const renderPaths = (cfg) => [...new Set([...entriesForShape(cfg.shape).map((e) => e.dest), SETTINGS]), RENDERED];
278
+
279
+ export const EXAMPLES = 'examples';
280
+
281
+ // The folders under `examples/` that hold rendered files (D-95): each one with a directory of
282
+ // reference copies, `.slicekit/rendered`, and a config. As POSIX paths from the root, sorted. A
283
+ // folder before init, such as one a walkthrough starts from, holds neither and is not one of them.
284
+ export function exampleDirs(root) {
285
+ const dir = path.join(root, EXAMPLES);
286
+ if (!fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) return [];
287
+ const isDir = (p) => fs.existsSync(p) && fs.statSync(p).isDirectory();
288
+ return fs
289
+ .readdirSync(dir, { withFileTypes: true })
290
+ .filter((e) => e.isDirectory() && isDir(path.join(dir, e.name, RENDERED)) && fs.existsSync(path.join(dir, e.name, CONFIG_PATH)))
291
+ .map((e) => `${EXAMPLES}/${e.name}`)
292
+ .sort();
293
+ }
294
+
295
+ // The paths of the examples the release step may write: for each example, the files `update`
296
+ // renders for that example's own config and its reference copies. An example whose config cannot
297
+ // be read gives the paths every shape renders, so a file of it is still judged.
298
+ function examplePaths(root) {
299
+ const out = [];
300
+ for (const example of exampleDirs(root)) {
301
+ let paths;
302
+ try {
303
+ paths = renderPaths(loadExampleConfig(root, example));
304
+ } catch (e) {
305
+ if (!(e instanceof ConfigError)) throw e;
306
+ paths = [SETTINGS, RENDERED];
307
+ }
308
+ for (const p of paths) out.push(`${example}/${p}`);
309
+ }
310
+ return out;
311
+ }
312
+
313
+ // An example's config, read as it stands and migrated in memory (loadConfig writes nothing): the
314
+ // sync writes an example's rendered files and nothing else of it.
315
+ const loadExampleConfig = (root, example) => loadConfig(path.join(root, ...example.split('/')));
316
+
317
+ // The paths the release step may write: package.json, CHANGELOG.md, the files `update` renders
318
+ // and, given the root, the rendered files of each example under it (D-95).
319
+ export function releasePaths(cfg, root = null) {
320
+ return [PACKAGE, CHANGELOG, ...renderPaths(cfg), ...(root === null ? [] : examplePaths(root))];
277
321
  }
278
- export const isReleasePath = (cfg) => {
279
- const dests = new Set(releasePaths(cfg));
280
- return (f) => dests.has(f) || f.startsWith(`${RENDERED}/`);
322
+ export const isReleasePath = (cfg, root = null) => {
323
+ const paths = releasePaths(cfg, root);
324
+ const dests = new Set(paths);
325
+ const dirs = paths.filter((p) => p === RENDERED || p.endsWith(`/${RENDERED}`)).map((p) => `${p}/`);
326
+ return (f) => dests.has(f) || dirs.some((d) => f.startsWith(d));
281
327
  };
282
328
 
329
+ // The config of each example, read before the release step writes a file: [{ example, cfg }]. An
330
+ // example whose config does not load stops the step with one line naming its folder and the config
331
+ // problem, so the reader of the sync job's log knows which file to mend.
332
+ function exampleConfigs(root) {
333
+ return exampleDirs(root).map((example) => {
334
+ try {
335
+ return { example, cfg: loadExampleConfig(root, example) };
336
+ } catch (e) {
337
+ if (!(e instanceof ConfigError)) throw e;
338
+ throw new ReleaseError(`${example}: its config does not load (${e.message}); no version is set and no file is written`);
339
+ }
340
+ });
341
+ }
342
+
343
+ // Renders each example at `version`, as `update --yes` would in that folder: the files whose plan
344
+ // is changed or missing are written, an edited one is left, and the reference copies are that
345
+ // version's alone. Every example's config is read before the first one is rendered. Returns the
346
+ // examples rendered.
347
+ export function renderExamples(root, version, configs = exampleConfigs(root)) {
348
+ const out = [];
349
+ for (const { example, cfg } of configs) {
350
+ const dir = path.join(root, ...example.split('/'));
351
+ applyUpdate(dir, cfg, planUpdate(dir, cfg, { version }), { version });
352
+ out.push(example);
353
+ }
354
+ return out;
355
+ }
356
+
283
357
  function phaseName(phaseDir, phaseId) {
284
358
  for (const f of fs.readdirSync(phaseDir).filter((n) => n.endsWith('.md') && !/^S-\d+/.test(n)).sort()) {
285
359
  const p = parsePhaseFile(readText(path.join(phaseDir, f)));
@@ -349,9 +423,12 @@ export function onDefaultTip(root, cfg) {
349
423
  }
350
424
 
351
425
  // Writes what releaseFor computed: package.json's version, the changelog section, and the render at
352
- // that version (the kit's own checkout) or at the running kit's version (any other). `isKit` says
426
+ // that version (the kit's own checkout) or at the running kit's version (any other), of the
427
+ // repository's own files and then of each example under `examples/` (D-95). `isKit` says
353
428
  // which; it defaults to whether `root` is the kit's checkout. Returns the release, or null when
354
- // there is none or the files on disk already hold it (a second run on the same commit).
429
+ // there is none or the files on disk already hold it (a second run on the same commit). Every
430
+ // example's config is read first; one that does not load throws a ReleaseError naming the example,
431
+ // and package.json, CHANGELOG.md and every rendered file are left as they were.
355
432
  export function applyRelease(root, cfg, { merge = 'HEAD', isKit = isKitRoot(root) } = {}) {
356
433
  const release = releaseFor(root, cfg, { merge });
357
434
  if (release === null) return null;
@@ -363,9 +440,12 @@ export function applyRelease(root, cfg, { merge = 'HEAD', isKit = isKitRoot(root
363
440
  // the version computed and CHANGELOG.md on disk holds its section, an earlier run on this commit
364
441
  // wrote them: this run writes nothing and sets no version.
365
442
  if (versionOf(pkgText) === release.version && holdsSection(logText, release.version)) return null;
443
+ // Before the first write: an example whose config does not load refuses the release (ReleaseError).
444
+ const examples = exampleConfigs(root);
366
445
  writeText(pkg, setVersion(pkgText, release.version));
367
446
  writeText(log, prependSection(logText, release.section));
368
447
  const version = isKit ? release.version : kitVersion();
369
448
  applyUpdate(root, cfg, planUpdate(root, cfg, { version }), { version });
449
+ renderExamples(root, version, examples);
370
450
  return release;
371
451
  }
package/src/reports.js ADDED
@@ -0,0 +1,131 @@
1
+ // The reports of `/slicekit ops` and `/slicekit audit` (REQ-2.13, REQ-2.14, D-57, D-58): where the
2
+ // next one goes, and how a check reads one. A report lives under .slicekit/reports, which init's
3
+ // ignore rules cover, so writing one changes no tracked file.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { lines } from './markdown.js';
7
+ import { kitPaths } from './paths.js';
8
+
9
+ const posix = (p) => p.split(path.sep).join('/');
10
+ const FENCE = /^\s*(```|~~~)/;
11
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
12
+
13
+ // The next free report of `kind`, relative to the root with forward slashes:
14
+ // `.slicekit/reports/<kind>-<k>.md`, `k` one above the highest of that kind there, else 1. The path
15
+ // is reserved by creating the empty file with the exclusive flag, moving to the next `k` while
16
+ // another run holds it, so two runs at once never get one path. Nothing else is written.
17
+ export function nextReport(root, cfg, kind) {
18
+ const dir = kitPaths(root, cfg).reports;
19
+ fs.mkdirSync(dir, { recursive: true });
20
+ const name = new RegExp(`^${escapeRe(kind)}-(\\d+)\\.md$`);
21
+ let k = 1;
22
+ for (const entry of fs.readdirSync(dir)) {
23
+ const m = name.exec(entry);
24
+ if (m && Number(m[1]) >= k) k = Number(m[1]) + 1;
25
+ }
26
+ for (;;) {
27
+ const file = path.join(dir, `${kind}-${k}.md`);
28
+ try {
29
+ fs.closeSync(fs.openSync(file, 'wx'));
30
+ return posix(path.relative(root, file));
31
+ } catch (e) {
32
+ if (e.code !== 'EEXIST') throw e;
33
+ k++;
34
+ }
35
+ }
36
+ }
37
+
38
+ // The `##` sections of a report outside fenced blocks: lower-case heading -> {line, lines}, `line`
39
+ // the heading's 1-based line and `lines` every line after it, as {text, line}, up to the next `#` or
40
+ // `##` heading. The first section of a name wins.
41
+ export function reportSections(text) {
42
+ const out = new Map();
43
+ let fenced = false;
44
+ let current = null;
45
+ lines(text).forEach((raw, i) => {
46
+ if (FENCE.test(raw)) {
47
+ fenced = !fenced;
48
+ } else if (!fenced) {
49
+ const m = /^(#{1,2})\s+(.*?)\s*#*\s*$/.exec(raw);
50
+ if (m) {
51
+ current = null;
52
+ const key = m[2].toLowerCase();
53
+ if (m[1].length === 2 && !out.has(key)) {
54
+ current = { line: i + 1, lines: [] };
55
+ out.set(key, current);
56
+ }
57
+ return;
58
+ }
59
+ }
60
+ if (current) current.lines.push({ text: raw, line: i + 1 });
61
+ });
62
+ return out;
63
+ }
64
+
65
+ export const isRow = (l) => /^\s*\|.*\|\s*$/.test(l);
66
+ export const isDivider = (l) => /^\s*\|(\s*:?-+:?\s*\|)+\s*$/.test(l);
67
+ // A row's cells; a `\|` is a pipe inside its cell.
68
+ export const cellsOf = (row) =>
69
+ row
70
+ .replace(/^\s*\|/, '')
71
+ .replace(/(?<!\\)\|\s*$/, '')
72
+ .split(/(?<!\\)\|/)
73
+ .map((c) => c.trim().replace(/\\\|/g, '|'));
74
+
75
+ // The first table of the section `heading`: {header: {cells, line}, rows: [{cells, line}]}, or null
76
+ // when the section is missing or holds no table.
77
+ export function sectionTable(text, heading) {
78
+ const section = reportSections(text).get(heading.toLowerCase());
79
+ if (!section) return null;
80
+ const ls = section.lines;
81
+ for (let i = 0; i + 1 < ls.length; i++) {
82
+ if (!isRow(ls[i].text) || !isDivider(ls[i + 1].text)) continue;
83
+ const rows = [];
84
+ for (let j = i + 2; j < ls.length && isRow(ls[j].text); j++) rows.push({ cells: cellsOf(ls[j].text), line: ls[j].line });
85
+ return { header: { cells: cellsOf(ls[i].text), line: ls[i].line }, rows };
86
+ }
87
+ return null;
88
+ }
89
+
90
+ // The rows of the first table of the section `heading`, the header row dropped: [{cells, line}].
91
+ export function reportTable(text, heading) {
92
+ return sectionTable(text, heading)?.rows ?? [];
93
+ }
94
+
95
+ // Whether `<file>:<line>` names a line that exists: a file under the root with at least that many lines.
96
+ export function lineExists(root, file, line) {
97
+ const abs = path.resolve(root, file);
98
+ const rel = path.relative(root, abs);
99
+ if (rel === '' || rel.startsWith('..') || path.isAbsolute(rel)) return false;
100
+ let text;
101
+ try {
102
+ if (!fs.statSync(abs).isFile()) return false;
103
+ text = fs.readFileSync(abs, 'utf8');
104
+ } catch {
105
+ return false;
106
+ }
107
+ const all = text.split('\n');
108
+ const count = all.at(-1) === '' ? all.length - 1 : all.length;
109
+ return Number.isInteger(line) && line >= 1 && line <= count;
110
+ }
111
+
112
+ // One `<rel>:<line> <message>` per closing line the report lacks: `Skipped:` and `Not checked:`, each
113
+ // at the start of its own line.
114
+ export function footerProblems(rel, text) {
115
+ const all = lines(text);
116
+ const last = Math.max(1, all.at(-1) === '' ? all.length - 1 : all.length);
117
+ return ['Skipped:', 'Not checked:'].filter((label) => !all.some((l) => l.startsWith(label))).map((label) => `${rel}:${last} no "${label}" line`);
118
+ }
119
+
120
+ // The text of a report named on the command line, with its path as the messages print it. A path
121
+ // that is no file is `null` text.
122
+ export function readReport(root, given) {
123
+ const abs = path.resolve(root, given);
124
+ const rel = posix(path.relative(root, abs));
125
+ try {
126
+ return { rel, text: fs.readFileSync(abs, 'utf8').replace(/^/, '') };
127
+ } catch (e) {
128
+ if (e.code === 'ENOENT' || e.code === 'EISDIR') return { rel, text: null };
129
+ throw e;
130
+ }
131
+ }
package/src/state/sync.js CHANGED
@@ -74,7 +74,7 @@ export function syncFromHost(root, cfg, host) {
74
74
  // `slicekit sync open` (03 REQ-3.11, D-78, D-80): after status --sync --write on the default branch's
75
75
  // merge commit, the state change goes up for review instead of onto the default branch. The paths it
76
76
  // may carry are the state directory, BUILD.md and the journal heads log, and with release.auto the
77
- // files the release step writes (syncPaths, D-90); nothing else is staged. When
77
+ // files the release step writes, those of the examples included (syncPaths, D-90, D-95); nothing else is staged. When
78
78
  // none of them changed it opens nothing. Otherwise it commits them on `sync/<short sha>` (a new branch
79
79
  // from the merge commit), pushes that branch alone, opens `[sync] state after <short sha>` into the
80
80
  // default branch through C-1, and starts the kit's workflow on the branch with workflow_dispatch, since
@@ -98,11 +98,12 @@ export const syncTitle = (short) => `[sync] state after ${short}`;
98
98
  const posix = (p) => p.split(path.sep).join('/');
99
99
 
100
100
  // The paths a sync commit may carry, relative to the repository root. With release.auto, also the
101
- // files the release step writes: package.json, CHANGELOG.md and the rendered files (D-90).
101
+ // files the release step writes: package.json, CHANGELOG.md, the rendered files (D-90) and the
102
+ // rendered files of each example under examples/ (D-95).
102
103
  export function syncPaths(root, cfg) {
103
104
  const p = kitPaths(root, cfg);
104
105
  const state = [p.build, p.state, path.join(p.kit, 'journal-heads.log')].map((f) => posix(path.relative(root, f)));
105
- return cfg.release?.auto === true ? [...state, ...releasePaths(cfg)] : state;
106
+ return cfg.release?.auto === true ? [...state, ...releasePaths(cfg, root)] : state;
106
107
  }
107
108
 
108
109
  // git with ALLOW_PROTECTED_COMMIT taken out of the environment (REQ-3.11: the sync never sets it).
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: ops
3
- description: Reads the runbook and history for a symptom and writes a proposed-actions report; changes nothing.
4
- tools: Read, Grep, Glob, Write, Bash
3
+ description: Reads the runbook and history for a symptom and replies with a proposed-actions report; changes nothing.
4
+ tools: Read, Grep, Glob
5
5
  model: inherit
6
6
  ---
7
- Brief: run `{{cli}} instructions ops` and follow it. You never run a git command that commits, pushes or moves a branch; report and the command commits. End every reply with "Skipped:" and "Not checked:" lines.
7
+ Brief: run `{{cli}} instructions ops` and follow it. The start hook gives you that brief, since you hold no tool that runs a command or writes a file. Your reply is the report; you take no action you propose. End every reply with "Skipped:" and "Not checked:" lines.
@@ -1,11 +1,11 @@
1
1
  # Brief: auditor
2
2
 
3
- You compare what the documents claim with what the code, the tests and the CI history show, or, in gap mode, what the spec claims with what the intake and the decisions support. Every finding carries a citation on both sides: the claim's file and line, and the evidence's file and line, command or CI run. The command that spawned you commits what you write.
3
+ You compare what the documents claim with what the code, the tests and the CI history show, or, in gap mode, what the spec claims with what the intake and the decisions support. Every finding carries a citation on both sides: the claim's file and line, and the evidence's file and line, command or CI run. In gap mode the command commits what you record; an audit report is never committed.
4
4
 
5
5
  ## You write
6
6
 
7
7
  - In an audit, a report at the path the command gives you, with one row per claim: the claim, where it is written, the evidence, where it was found, and its status.
8
- - The status is one of three words. `holds`: the evidence agrees with the claim. `drifted`: the evidence contradicts it; name the commit that broke it, from the history the command gives you. `unverifiable`: you found no evidence either way; say why.
8
+ - The status is one of three words. `holds`: the evidence agrees with the claim. `drifted`: the evidence contradicts it; name the commit that broke it, one of the claim's candidate commits. `unverifiable`: you found no evidence either way; say why.
9
9
  - In gap mode, nothing but the rows you record with `{{cli}} gaps add` (see Gaps below). You write no file of your own.
10
10
 
11
11
  ## You never
@@ -14,6 +14,17 @@ You compare what the documents claim with what the code, the tests and the CI hi
14
14
  - Change the documents you audit. In an audit the gap goes in your report; in gap mode it goes in through `{{cli}} gaps add`.
15
15
  - Run git, except the read-only `git diff`, `git log`, `git show` and `git status`. You never commit or push; the command does that.
16
16
 
17
+ ## Audit
18
+
19
+ In an audit the command gives you the report path and the claims, each with its ID, its `<file>:<line>`, the files it names and its candidate commits: those that touched one of those files after the claim was written. The report holds one table under `## Claims`, one row per claim:
20
+
21
+ ```
22
+ | Claim | Where | Evidence | Found at | Status | Commit |
23
+ |---|---|---|---|---|---|
24
+ ```
25
+
26
+ Claim and Where are as the command printed them. Found at is the evidence's `<file>:<line>` or a command in backticks; an `unverifiable` row may leave it empty. Commit is empty unless the row is `drifted`: a `drifted` row names one of its claim's candidate commits, by seven or more characters of its SHA. When no candidate explains the contradiction, the row is `unverifiable`. The report ends with the same two closing lines as your reply.
27
+
17
28
  ## Gaps
18
29
 
19
30
  When `/slicekit gaps` spawns you, you are in gap mode: the claims are the spec under `<docsRoot>/spec/` and the evidence is the intake snapshots under `<docsRoot>/intake/` and `<docsRoot>/decisions.md`. You look for gaps between them. Each gap is one of five classes: