@olegkoval/agent-skills 1.91.0 → 1.93.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/.github/prompts/self-critique.prompt.md +90 -232
- package/adapters/claude/olko-github-pr/skills/lekker-review/SKILL.md +13 -7
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +20 -15
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/run-log.mjs +21 -0
- package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/selftest.mjs +17 -1
- package/adapters/claude/olko-reflection/skills/self-critique/SKILL.md +90 -232
- package/adapters/claude/olko-reflection/skills/self-critique/references/rules.md +67 -0
- package/adapters/claude/olko-reflection/skills/self-critique/references/scoring.md +99 -0
- package/adapters/claude/olko-reflection/skills/self-critique/references/setup.md +62 -0
- package/adapters/claude/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
- package/adapters/claude/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
- package/adapters/claude/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
- package/adapters/cursor/olko-reflection/skills/self-critique/SKILL.md +90 -232
- package/adapters/cursor/olko-reflection/skills/self-critique/references/rules.md +67 -0
- package/adapters/cursor/olko-reflection/skills/self-critique/references/scoring.md +99 -0
- package/adapters/cursor/olko-reflection/skills/self-critique/references/setup.md +62 -0
- package/adapters/cursor/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
- package/adapters/cursor/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
- package/adapters/cursor/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
- package/adapters/grok/olko-reflection/skills/self-critique/SKILL.md +90 -232
- package/adapters/grok/olko-reflection/skills/self-critique/references/rules.md +67 -0
- package/adapters/grok/olko-reflection/skills/self-critique/references/scoring.md +99 -0
- package/adapters/grok/olko-reflection/skills/self-critique/references/setup.md +62 -0
- package/adapters/grok/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
- package/adapters/grok/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
- package/adapters/grok/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
- package/package.json +1 -1
- package/plugins/olko-apple-kit/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-creative/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-garmin-kit/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-git-tools/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-github-pr/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-github-pr/skills/lekker-review/README.md +18 -11
- package/plugins/olko-github-pr/skills/lekker-review/SKILL.md +13 -7
- package/plugins/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +20 -15
- package/plugins/olko-github-pr/skills/lekker-review/scripts/run-log.mjs +21 -0
- package/plugins/olko-github-pr/skills/lekker-review/scripts/selftest.mjs +17 -1
- package/plugins/olko-github-pr/skills/lekker-review/workflow.js +25 -2
- package/plugins/olko-obsidian/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-product/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-reflection/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-reflection/skills/self-critique/SKILL.md +90 -232
- package/plugins/olko-reflection/skills/self-critique/references/rules.md +67 -0
- package/plugins/olko-reflection/skills/self-critique/references/scoring.md +99 -0
- package/plugins/olko-reflection/skills/self-critique/references/setup.md +62 -0
- package/plugins/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
- package/plugins/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
- package/plugins/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
- package/plugins/olko-release/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-skill-meta/.claude-plugin/plugin.json +1 -1
- package/plugins/olko-web-ops/.claude-plugin/plugin.json +1 -1
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# Setup notes
|
|
2
|
+
|
|
3
|
+
## Standalone Cursor installation
|
|
4
|
+
|
|
5
|
+
Use the generated Cursor adapter or the full skill package, including its `scripts/` and
|
|
6
|
+
`references/` directories. Copying only `SKILL.md` is insufficient for this workflow, which calls
|
|
7
|
+
the bundled scripts.
|
|
8
|
+
|
|
9
|
+
## State directory
|
|
10
|
+
|
|
11
|
+
Each run writes to its own dated folder, outside any repository:
|
|
12
|
+
|
|
13
|
+
- root: `$SELF_CRITIQUE_STATE_DIR`, else `${XDG_STATE_HOME:-~/.local/state}/self-critique`
|
|
14
|
+
- per project: a folder named from the working directory, then one folder per run named from a UTC
|
|
15
|
+
timestamp (`2026-11-19T21-09-27`, with `-1`, `-2` on a same-second collision), mode 0700
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
RUN=$(node <skill>/scripts/run-store.mjs new --cwd "$PWD") # create and print the run folder
|
|
19
|
+
node <skill>/scripts/run-store.mjs latest --cwd "$PWD" # newest run folder
|
|
20
|
+
node <skill>/scripts/run-store.mjs history --cwd "$PWD" --limit 10 # first-answer score trend
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
A run folder holds `run.json`, `author-claims.json`, `critic-r<N>.json` and `ledger-v<N>.json`.
|
|
24
|
+
Ledgers contain candidate claim text, so keep them out of the repository tree.
|
|
25
|
+
|
|
26
|
+
## Optional: auto-offer via a Claude Code Stop hook
|
|
27
|
+
|
|
28
|
+
A hook is a shell command, so it cannot run this loop itself. What it can do is **nudge**: after a
|
|
29
|
+
substantial answer, it offers the review and you run the skill only if the user says yes.
|
|
30
|
+
|
|
31
|
+
The hook ships with this skill at `scripts/critique-nudge.mjs`. Register it as a `Stop` hook in your
|
|
32
|
+
Claude Code settings (`.claude/settings.json` for a team, `.claude/settings.local.json` for
|
|
33
|
+
yourself):
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"hooks": {
|
|
38
|
+
"Stop": [
|
|
39
|
+
{
|
|
40
|
+
"hooks": [
|
|
41
|
+
{
|
|
42
|
+
"type": "command",
|
|
43
|
+
"command": "node \"$CLAUDE_PROJECT_DIR/.claude/hooks/critique-nudge.mjs\"",
|
|
44
|
+
"timeout": 15
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
Copy `scripts/critique-nudge.mjs` to `.claude/hooks/critique-nudge.mjs` (or point the command at
|
|
54
|
+
wherever you keep it). After an answer whose final prose is at least 1500 characters, the hook blocks
|
|
55
|
+
the turn once and instructs the agent to append a one-line "critical-thinking review" offer, then
|
|
56
|
+
stop. Two loop guards keep it from firing forever: it does nothing when `stop_hook_active` is set, and
|
|
57
|
+
nothing when the answer already contains the offer phrase. On any malformed input it exits silently
|
|
58
|
+
and never blocks the user.
|
|
59
|
+
|
|
60
|
+
The 1500-character threshold is a heuristic with a known ceiling: it misses short but dense
|
|
61
|
+
tool-heavy turns. If that matters, extend the script to also count tool calls since the last user
|
|
62
|
+
message.
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { readFileSync } from 'node:fs'
|
|
2
|
+
import { parseArgs } from 'node:util'
|
|
2
3
|
import { pathToFileURL } from 'node:url'
|
|
3
4
|
|
|
4
5
|
export const PENALTIES = {
|
|
@@ -7,6 +8,7 @@ export const PENALTIES = {
|
|
|
7
8
|
unverifiable_load_bearing: 10,
|
|
8
9
|
unverifiable: 4,
|
|
9
10
|
inferred_accepted: 5,
|
|
11
|
+
inferred_accepted_load_bearing: 10,
|
|
10
12
|
missed_load_bearing: 15,
|
|
11
13
|
missed: 5,
|
|
12
14
|
only_critic_found: 5,
|
|
@@ -66,7 +68,7 @@ const claimPenalties = (c) => {
|
|
|
66
68
|
const byStatus = {
|
|
67
69
|
refuted: [lb ? 'refuted_load_bearing' : 'refuted'],
|
|
68
70
|
unverifiable: [lb ? 'unverifiable_load_bearing' : 'unverifiable'],
|
|
69
|
-
inferred: ['inferred_accepted'],
|
|
71
|
+
inferred: [lb ? 'inferred_accepted_load_bearing' : 'inferred_accepted'],
|
|
70
72
|
verified: c.origin === 'critic' ? ['only_critic_found'] : [],
|
|
71
73
|
}
|
|
72
74
|
return byStatus[c.status]
|
|
@@ -83,6 +85,102 @@ export const scoreLedger = (ledger) => {
|
|
|
83
85
|
return { score: Math.max(0, 100 - total), breakdown }
|
|
84
86
|
}
|
|
85
87
|
|
|
88
|
+
const asArray = (v) => (Array.isArray(v) ? v : v === undefined ? [] : [v])
|
|
89
|
+
|
|
90
|
+
const duplicateIdErrors = (ledger) => {
|
|
91
|
+
const ids = [...ledger.claims, ...ledger.missed].map((x) => x.id)
|
|
92
|
+
return [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))].map((id) => `duplicate id: ${id}`)
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Every author claim is accounted for, and every claim the author owns names it.
|
|
96
|
+
const authorErrors = (ledger, author) => {
|
|
97
|
+
if (!Array.isArray(author)) return ['author claims invalid: not an array']
|
|
98
|
+
const known = new Set(author.map((a) => a.id))
|
|
99
|
+
const used = new Set(ledger.claims.flatMap((c) => asArray(c.author_id)))
|
|
100
|
+
const perClaim = ledger.claims.flatMap((c, i) => {
|
|
101
|
+
const path = `claims[${i}]`
|
|
102
|
+
if (c.origin === 'critic') {
|
|
103
|
+
return c.author_id === undefined ? [] : [`${path}.author_id: origin critic must not name an author claim`]
|
|
104
|
+
}
|
|
105
|
+
return known.has(c.author_id) ? [] : [`${path}.author_id: origin ${c.origin} needs an author claim id, got ${c.author_id}`]
|
|
106
|
+
})
|
|
107
|
+
const dropped = [...known].filter((id) => !used.has(id)).map((id) => `author claim ${id} has no ledger entry`)
|
|
108
|
+
return [...perClaim, ...dropped]
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// critic maps a round label ("r1") to that round's raw critic JSON. A critic_ref is "r1:claims.0" or "r1:missed.2".
|
|
112
|
+
const criticRefs = (critic) =>
|
|
113
|
+
Object.entries(critic).flatMap(([label, out]) => [
|
|
114
|
+
...asArray(out?.claims).map((_, i) => `${label}:claims.${i}`),
|
|
115
|
+
...asArray(out?.missed).map((_, i) => `${label}:missed.${i}`),
|
|
116
|
+
])
|
|
117
|
+
|
|
118
|
+
const criticErrors = (ledger, critic) => {
|
|
119
|
+
if (!isRecord(critic)) return ['critic outputs invalid: not an object']
|
|
120
|
+
const valid = new Set(criticRefs(critic))
|
|
121
|
+
const entries = [
|
|
122
|
+
...ledger.claims.map((c, i) => [`claims[${i}]`, c]),
|
|
123
|
+
...ledger.missed.map((m, i) => [`missed[${i}]`, m]),
|
|
124
|
+
]
|
|
125
|
+
const used = new Set(entries.flatMap(([, e]) => asArray(e.critic_ref)))
|
|
126
|
+
const perEntry = entries.flatMap(([path, e]) => {
|
|
127
|
+
const refs = asArray(e.critic_ref)
|
|
128
|
+
const unknown = refs.filter((r) => !valid.has(r)).map((r) => `${path}.critic_ref: unknown ${r}`)
|
|
129
|
+
if (e.origin === 'author') {
|
|
130
|
+
return refs.length === 0 ? unknown : [...unknown, `${path}.critic_ref: origin author must not cite the critic`]
|
|
131
|
+
}
|
|
132
|
+
return refs.length === 0 ? [...unknown, `${path}.critic_ref: missing, name the critic item this entry came from`] : unknown
|
|
133
|
+
})
|
|
134
|
+
const dropped = [...valid].filter((r) => !used.has(r)).map((r) => `critic item ${r} has no ledger entry`)
|
|
135
|
+
return [...perEntry, ...dropped]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// A revision may add claims, never silently drop one.
|
|
139
|
+
const carryErrors = (ledger, prev) => {
|
|
140
|
+
const have = new Set(ledger.claims.map((c) => c.id))
|
|
141
|
+
return prev.claims.filter((c) => !have.has(c.id)).map((c) => `claim ${c.id} from the previous ledger is missing`)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export const integrityErrors = (ledger, { author, critic, prev } = {}) => [
|
|
145
|
+
...duplicateIdErrors(ledger),
|
|
146
|
+
...(author !== undefined ? authorErrors(ledger, author) : []),
|
|
147
|
+
...(critic !== undefined ? criticErrors(ledger, critic) : []),
|
|
148
|
+
...(prev ? carryErrors(ledger, prev) : []),
|
|
149
|
+
]
|
|
150
|
+
|
|
151
|
+
const isOpenClaim = (c) => c.status !== 'verified'
|
|
152
|
+
// A reasoning-only miss is not priced, but a load-bearing one still blocks the stop rule.
|
|
153
|
+
const isOpenMissed = (m) => m.checked_by !== 'inferred' || m.load_bearing
|
|
154
|
+
|
|
155
|
+
export const openDefects = (ledger) => ({
|
|
156
|
+
load_bearing:
|
|
157
|
+
ledger.claims.filter((c) => isOpenClaim(c) && c.load_bearing).length +
|
|
158
|
+
ledger.missed.filter((m) => isOpenMissed(m) && m.load_bearing).length,
|
|
159
|
+
other:
|
|
160
|
+
ledger.claims.filter((c) => isOpenClaim(c) && !c.load_bearing).length +
|
|
161
|
+
ledger.missed.filter((m) => isOpenMissed(m) && !m.load_bearing).length,
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
// The kept ledger is the ratchet winner across rounds; a later round wins ties.
|
|
165
|
+
const winnerIndex = (ledgers) =>
|
|
166
|
+
ledgers.reduce((best, l, i) => (scoreLedger(l).score >= scoreLedger(ledgers[best]).score ? i : best), 0)
|
|
167
|
+
|
|
168
|
+
// ledgers are in round order. done means the kept ledger has no load-bearing item left open.
|
|
169
|
+
export const statusOf = (ledgers) => {
|
|
170
|
+
const trajectory = ledgers.map((l) => scoreLedger(l).score)
|
|
171
|
+
const kept = winnerIndex(ledgers)
|
|
172
|
+
const open = openDefects(ledgers[kept])
|
|
173
|
+
return {
|
|
174
|
+
rounds: ledgers.length,
|
|
175
|
+
first_score: trajectory[0],
|
|
176
|
+
final_score: trajectory[kept],
|
|
177
|
+
kept: kept + 1,
|
|
178
|
+
trajectory,
|
|
179
|
+
open,
|
|
180
|
+
done: open.load_bearing === 0,
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
86
184
|
export const ratchet = (prev, next) => {
|
|
87
185
|
const p = scoreLedger(prev).score
|
|
88
186
|
const n = scoreLedger(next).score
|
|
@@ -99,7 +197,7 @@ const mk = (id, lb, status) => ({
|
|
|
99
197
|
receipt: 'anchor',
|
|
100
198
|
})
|
|
101
199
|
|
|
102
|
-
// 95 = 5 (one inferred); 72 = 10+10+4+4; 40 = 25+25+10
|
|
200
|
+
// 95 = 5 (one inferred, not load-bearing); 72 = 10+10+4+4; 40 = 25+25+10
|
|
103
201
|
const ANCHOR_LEDGERS = [
|
|
104
202
|
{ label: 'strong', claims: [mk('a1', false, 'inferred')] },
|
|
105
203
|
{ label: 'middling', claims: [mk('b1', false, 'refuted'), mk('b2', false, 'refuted'), mk('b3', false, 'unverifiable'), mk('b4', false, 'unverifiable')] },
|
|
@@ -129,30 +227,75 @@ const fail = (message) => {
|
|
|
129
227
|
process.exit(2)
|
|
130
228
|
}
|
|
131
229
|
|
|
132
|
-
const
|
|
133
|
-
let parsed
|
|
230
|
+
const readJson = (path) => {
|
|
134
231
|
try {
|
|
135
|
-
|
|
232
|
+
return JSON.parse(readFileSync(path, 'utf8'))
|
|
136
233
|
} catch (e) {
|
|
137
234
|
return fail(`cannot read ${path}: ${e.message}`)
|
|
138
235
|
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
const loadLedger = (path) => {
|
|
239
|
+
const parsed = readJson(path)
|
|
139
240
|
const errors = validateLedger(parsed)
|
|
140
241
|
if (errors.length > 0) return fail(errors.join('; '))
|
|
141
242
|
return parsed
|
|
142
243
|
}
|
|
143
244
|
|
|
245
|
+
const OPTIONS = {
|
|
246
|
+
author: { type: 'string' },
|
|
247
|
+
critic: { type: 'string', multiple: true },
|
|
248
|
+
prev: { type: 'string' },
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const criticFromFlags = (specs) => {
|
|
252
|
+
const pairs = specs.map((spec) => {
|
|
253
|
+
const at = spec.indexOf('=')
|
|
254
|
+
return at < 1 ? fail(`--critic needs <label>=<path>, got ${spec}`) : [spec.slice(0, at), spec.slice(at + 1)]
|
|
255
|
+
})
|
|
256
|
+
const repeated = pairs.map(([label]) => label).filter((label, i, all) => all.indexOf(label) !== i)
|
|
257
|
+
if (repeated.length > 0) fail(`--critic label repeated: ${[...new Set(repeated)].join(', ')}`)
|
|
258
|
+
return Object.fromEntries(pairs.map(([label, path]) => [label, readJson(path)]))
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const contextFrom = (flags, prevPath) => {
|
|
262
|
+
const given = flags.author !== undefined || flags.critic !== undefined || prevPath !== undefined
|
|
263
|
+
return {
|
|
264
|
+
given,
|
|
265
|
+
author: flags.author === undefined ? undefined : readJson(flags.author),
|
|
266
|
+
critic: flags.critic === undefined ? undefined : criticFromFlags(flags.critic),
|
|
267
|
+
prev: prevPath === undefined ? undefined : loadLedger(prevPath),
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
const checked = (ledger, context) => {
|
|
272
|
+
const errors = integrityErrors(ledger, context)
|
|
273
|
+
return errors.length > 0 ? fail(errors.join('; ')) : (context.given ? 'checked' : 'unchecked')
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const withIntegrity = (ledger, flags, prevPath) => ({ ledger, integrity: checked(ledger, contextFrom(flags, prevPath)) })
|
|
277
|
+
|
|
144
278
|
const COMMANDS = {
|
|
145
|
-
score: ([a]) =>
|
|
146
|
-
|
|
279
|
+
score: ([a], flags) => {
|
|
280
|
+
const { ledger, integrity } = withIntegrity(loadLedger(a), flags, flags.prev)
|
|
281
|
+
return { ...scoreLedger(ledger), integrity }
|
|
282
|
+
},
|
|
283
|
+
check: ([a], flags) => ({ ok: true, integrity: withIntegrity(loadLedger(a), flags, flags.prev).integrity }),
|
|
284
|
+
ratchet: ([a, b], flags) => {
|
|
285
|
+
const { ledger, integrity } = withIntegrity(loadLedger(b), flags, a)
|
|
286
|
+
return { ...ratchet(loadLedger(a), ledger), integrity }
|
|
287
|
+
},
|
|
288
|
+
status: (paths) => statusOf(paths.map(loadLedger)),
|
|
147
289
|
anchors: () => anchors(),
|
|
148
290
|
summary: ([a]) => summaryMarkdown(loadLedger(a)),
|
|
149
291
|
}
|
|
150
292
|
|
|
151
293
|
const main = (argv) => {
|
|
152
|
-
const [cmd, ...
|
|
294
|
+
const [cmd, ...rest] = argv
|
|
153
295
|
const run = COMMANDS[cmd]
|
|
154
296
|
if (!run) return fail(`unknown command: ${cmd}`)
|
|
155
|
-
const
|
|
297
|
+
const { values, positionals } = parseArgs({ args: rest, options: OPTIONS, allowPositionals: true })
|
|
298
|
+
const out = run(positionals, values)
|
|
156
299
|
process.stdout.write(typeof out === 'string' ? `${out}\n` : `${JSON.stringify(out, null, 2)}\n`)
|
|
157
300
|
}
|
|
158
301
|
|
|
@@ -9,6 +9,8 @@ import { fileURLToPath } from 'node:url';
|
|
|
9
9
|
const FENCE = '---';
|
|
10
10
|
const EVIDENCE_LINE = /^\s*-\s.*\b20\d\d-\d\d-\d\d\b/;
|
|
11
11
|
const DAY_MS = 86_400_000;
|
|
12
|
+
const RULE_STORE = 'self-critique';
|
|
13
|
+
const isOurs = (rule) => rule.metadata.rule_store === RULE_STORE;
|
|
12
14
|
|
|
13
15
|
const topLevelKey = (line) => /^([A-Za-z_][\w-]*):(?: (.*))?$/.exec(line);
|
|
14
16
|
const metaEntry = (line) => /^ {2}([A-Za-z_][\w-]*):(?: (.*))?$/.exec(line);
|
|
@@ -86,29 +88,48 @@ function readRuleFiles(dir) {
|
|
|
86
88
|
|
|
87
89
|
export const listRules = (dir) => readRuleFiles(dir).map((e) => e.rule);
|
|
88
90
|
|
|
89
|
-
|
|
90
|
-
|
|
91
|
+
// The replay pass reads only rules this workflow stored; { all: true } lists every rule with a name.
|
|
92
|
+
export const checklistMarkdown = (dir, { all = false } = {}) =>
|
|
93
|
+
listRules(dir)
|
|
94
|
+
.filter((r) => all || isOurs(r))
|
|
95
|
+
.map((r) => `- [${r.name}]: ${r.description}\n`)
|
|
96
|
+
.join('');
|
|
91
97
|
|
|
92
98
|
export function bumpFire(rule, isoDate) {
|
|
93
99
|
const fires = Number.parseInt(rule.metadata.fires ?? '0', 10) || 0;
|
|
94
|
-
|
|
100
|
+
// A rule that fires is one this workflow now counts, so it must also be one prune may propose.
|
|
101
|
+
return { ...rule, metadata: { ...rule.metadata, rule_store: RULE_STORE, fires: String(fires + 1), last_fired: isoDate } };
|
|
95
102
|
}
|
|
96
103
|
|
|
97
|
-
|
|
98
|
-
const
|
|
99
|
-
|
|
100
|
-
const updated = bumpFire(entry.rule, isoDate);
|
|
101
|
-
const target = path.join(dir, entry.file);
|
|
102
|
-
const temporary = path.join(dir, `.${entry.file}.${randomUUID()}.tmp`);
|
|
104
|
+
function writeRule(dir, file, rule) {
|
|
105
|
+
const target = path.join(dir, file);
|
|
106
|
+
const temporary = path.join(dir, `.${file}.${randomUUID()}.tmp`);
|
|
103
107
|
try {
|
|
104
|
-
fs.writeFileSync(temporary, serializeRule(
|
|
108
|
+
fs.writeFileSync(temporary, serializeRule(rule), { flag: 'wx', mode: fs.statSync(target).mode });
|
|
105
109
|
fs.renameSync(temporary, target);
|
|
106
110
|
} finally {
|
|
107
111
|
fs.rmSync(temporary, { force: true });
|
|
108
112
|
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function fire(dir, name, isoDate) {
|
|
116
|
+
const entry = readRuleFiles(dir).find((e) => e.rule.name === name);
|
|
117
|
+
if (!entry) throw new Error(`rule not found: ${name}`);
|
|
118
|
+
const updated = bumpFire(entry.rule, isoDate);
|
|
119
|
+
writeRule(dir, entry.file, updated);
|
|
109
120
|
return updated;
|
|
110
121
|
}
|
|
111
122
|
|
|
123
|
+
// One-off repair: a rule with a fire counter but no marker was counted yet never prunable.
|
|
124
|
+
export function adopt(dir) {
|
|
125
|
+
return readRuleFiles(dir).flatMap(({ file, rule }) => {
|
|
126
|
+
// Only a rule with no owner is adopted; a rule marked for another workflow keeps its marker.
|
|
127
|
+
if (rule.metadata.rule_store !== undefined || rule.metadata.fires === undefined) return [];
|
|
128
|
+
writeRule(dir, file, { ...rule, metadata: { ...rule.metadata, rule_store: RULE_STORE } });
|
|
129
|
+
return [rule.name];
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
|
|
112
133
|
const daysBetween = (fromIso, toIso) => (Date.parse(toIso) - Date.parse(fromIso)) / DAY_MS;
|
|
113
134
|
|
|
114
135
|
const ISO_DAY = /^\d{4}-\d{2}-\d{2}/;
|
|
@@ -129,7 +150,7 @@ export function pruneReason(rule, { idleDays, today, mtimeIso }) {
|
|
|
129
150
|
|
|
130
151
|
export function prune(dir, { idleDays, today }) {
|
|
131
152
|
return readRuleFiles(dir).flatMap(({ file, rule }) => {
|
|
132
|
-
if (rule
|
|
153
|
+
if (!isOurs(rule)) return [];
|
|
133
154
|
const mtimeIso = fs.statSync(path.join(dir, file)).mtime.toISOString().slice(0, 10);
|
|
134
155
|
const reason = pruneReason(rule, { idleDays, today, mtimeIso });
|
|
135
156
|
return reason ? [{ name: rule.name, reason }] : [];
|
|
@@ -170,7 +191,8 @@ function runCli(argv) {
|
|
|
170
191
|
const date = flags.date ?? todayIso();
|
|
171
192
|
const commands = {
|
|
172
193
|
list: () => JSON.stringify(listRules(dir).map(({ top, ...rule }) => rule), null, 2),
|
|
173
|
-
checklist: () => checklistMarkdown(dir).trimEnd(),
|
|
194
|
+
checklist: () => checklistMarkdown(dir, { all: flags.scope === 'all' }).trimEnd(),
|
|
195
|
+
adopt: () => JSON.stringify(adopt(dir), null, 2),
|
|
174
196
|
fire: () => {
|
|
175
197
|
const { top, ...rule } = fire(dir, positional[0], date);
|
|
176
198
|
return JSON.stringify(rule, null, 2);
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Per-run state for self-critique: one dated folder per run under a state dir, outside any repo.
|
|
3
|
+
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
4
|
+
import { createHash } from 'node:crypto'
|
|
5
|
+
import { homedir } from 'node:os'
|
|
6
|
+
import { join } from 'node:path'
|
|
7
|
+
import { parseArgs } from 'node:util'
|
|
8
|
+
import { pathToFileURL } from 'node:url'
|
|
9
|
+
import { statusOf, validateLedger } from './claim-ledger.mjs'
|
|
10
|
+
|
|
11
|
+
const RUN_NAME = /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}(-\d+)?$/
|
|
12
|
+
const LEDGER_FILE = /^ledger-v(\d+)\.json$/
|
|
13
|
+
|
|
14
|
+
export const stateRoot = (env = process.env) =>
|
|
15
|
+
env.SELF_CRITIQUE_STATE_DIR || join(env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'self-critique')
|
|
16
|
+
|
|
17
|
+
// The digest keeps /work/foo-bar and /work/foo/bar apart; the readable part is only for humans.
|
|
18
|
+
export const projectSlug = (cwd) => {
|
|
19
|
+
const readable = cwd.replace(/[^A-Za-z0-9]+/g, '-').replace(/^-+|-+$/g, '') || 'root'
|
|
20
|
+
return `${readable}-${createHash('sha256').update(cwd).digest('hex').slice(0, 8)}`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export const runId = (date) => date.toISOString().slice(0, 19).replaceAll(':', '-')
|
|
24
|
+
|
|
25
|
+
const projectDir = (root, cwd) => join(root, projectSlug(cwd))
|
|
26
|
+
|
|
27
|
+
const tryMkdir = (dir) => {
|
|
28
|
+
try {
|
|
29
|
+
mkdirSync(dir, { mode: 0o700 })
|
|
30
|
+
return true
|
|
31
|
+
} catch (e) {
|
|
32
|
+
if (e.code === 'EEXIST') return false
|
|
33
|
+
throw e
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const newRun = ({ root, cwd, now = new Date() }) => {
|
|
38
|
+
const project = projectDir(root, cwd)
|
|
39
|
+
mkdirSync(project, { recursive: true, mode: 0o700 })
|
|
40
|
+
const base = runId(now)
|
|
41
|
+
const dir = [base, ...Array.from({ length: 99 }, (_, i) => `${base}-${i + 1}`)]
|
|
42
|
+
.map((name) => join(project, name))
|
|
43
|
+
.find(tryMkdir)
|
|
44
|
+
if (!dir) throw new Error(`no free run folder for ${base}`)
|
|
45
|
+
writeFileSync(join(dir, 'run.json'), `${JSON.stringify({ project: cwd, started: now.toISOString() }, null, 2)}\n`)
|
|
46
|
+
return dir
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Timestamp first, then the collision suffix as a number, so -2 sorts before -10.
|
|
50
|
+
const SUFFIX = /^(.{19})(?:-(\d+))?$/
|
|
51
|
+
const runOrder = (a, b) => {
|
|
52
|
+
const [, ta, sa = '0'] = SUFFIX.exec(a)
|
|
53
|
+
const [, tb, sb = '0'] = SUFFIX.exec(b)
|
|
54
|
+
return ta === tb ? Number(sa) - Number(sb) : ta < tb ? -1 : 1
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const runNames = (project) => {
|
|
58
|
+
try {
|
|
59
|
+
return readdirSync(project).filter((n) => RUN_NAME.test(n)).sort(runOrder)
|
|
60
|
+
} catch (e) {
|
|
61
|
+
if (e.code === 'ENOENT') return []
|
|
62
|
+
throw e
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export const latestRun = ({ root, cwd }) => {
|
|
67
|
+
const project = projectDir(root, cwd)
|
|
68
|
+
const last = runNames(project).at(-1)
|
|
69
|
+
return last === undefined ? null : join(project, last)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const ledgerFiles = (dir) =>
|
|
73
|
+
readdirSync(dir)
|
|
74
|
+
.flatMap((f) => (LEDGER_FILE.test(f) ? [[Number(LEDGER_FILE.exec(f)[1]), f]] : []))
|
|
75
|
+
.sort((a, b) => a[0] - b[0])
|
|
76
|
+
.map(([, f]) => f)
|
|
77
|
+
|
|
78
|
+
const readLedger = (path) => {
|
|
79
|
+
try {
|
|
80
|
+
return JSON.parse(readFileSync(path, 'utf8'))
|
|
81
|
+
} catch {
|
|
82
|
+
return null
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export const summarizeRun = (dir) => {
|
|
87
|
+
const ledgers = ledgerFiles(dir).map((f) => readLedger(join(dir, f)))
|
|
88
|
+
if (ledgers.length === 0) return { rounds: 0 }
|
|
89
|
+
if (ledgers.some((l) => l === null || validateLedger(l).length > 0)) return { rounds: ledgers.length, invalid: true }
|
|
90
|
+
const { first_score, final_score, open } = statusOf(ledgers)
|
|
91
|
+
return { rounds: ledgers.length, first_score, final_score, open_load_bearing: open.load_bearing }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export const history = ({ root, cwd, limit = 10 }) => {
|
|
95
|
+
const project = projectDir(root, cwd)
|
|
96
|
+
return runNames(project)
|
|
97
|
+
.slice(-limit)
|
|
98
|
+
.map((name) => ({ run: name, ...summarizeRun(join(project, name)) }))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const cellOf = (v) => (v === undefined ? '-' : String(v))
|
|
102
|
+
|
|
103
|
+
const rowOf = (r) =>
|
|
104
|
+
`| ${[r.run, r.rounds, r.first_score, r.final_score, r.invalid ? 'invalid ledger' : r.open_load_bearing].map(cellOf).join(' | ')} |`
|
|
105
|
+
|
|
106
|
+
export const historyMarkdown = (rows) =>
|
|
107
|
+
[
|
|
108
|
+
'| run | rounds | first-answer score | final score | open load-bearing |',
|
|
109
|
+
'| --- | --- | --- | --- | --- |',
|
|
110
|
+
...rows.map(rowOf),
|
|
111
|
+
].join('\n')
|
|
112
|
+
|
|
113
|
+
const fail = (message) => {
|
|
114
|
+
process.stderr.write(`${JSON.stringify({ error: message })}\n`)
|
|
115
|
+
process.exit(2)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const COMMANDS = {
|
|
119
|
+
new: ({ cwd }) => newRun({ root: stateRoot(), cwd }),
|
|
120
|
+
latest: ({ cwd }) => latestRun({ root: stateRoot(), cwd }) ?? fail(`no runs yet for ${cwd}`),
|
|
121
|
+
history: ({ cwd, limit }) => historyMarkdown(history({ root: stateRoot(), cwd, limit: Number(limit ?? 10) })),
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const main = (argv) => {
|
|
125
|
+
const [cmd, ...rest] = argv
|
|
126
|
+
const run = COMMANDS[cmd]
|
|
127
|
+
if (!run) return fail(`usage: run-store.mjs ${Object.keys(COMMANDS).join('|')} --cwd <dir>`)
|
|
128
|
+
const { values } = parseArgs({ args: rest, options: { cwd: { type: 'string' }, limit: { type: 'string' } } })
|
|
129
|
+
if (values.cwd === undefined) return fail('--cwd is required')
|
|
130
|
+
process.stdout.write(`${run(values)}\n`)
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) main(process.argv.slice(2))
|