@olegkoval/agent-skills 1.90.0 → 1.92.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.
Files changed (54) hide show
  1. package/.github/prompts/self-critique.prompt.md +90 -232
  2. package/adapters/claude/olko-github-pr/skills/lekker-review/SKILL.md +25 -3
  3. package/adapters/claude/olko-github-pr/skills/lekker-review/references/codex-workflow.md +13 -0
  4. package/adapters/claude/olko-github-pr/skills/lekker-review/references/output-format.md +1 -0
  5. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +17 -6
  6. package/adapters/claude/olko-github-pr/skills/lekker-review/scripts/vendor-bridge.mjs +207 -0
  7. package/adapters/claude/olko-reflection/skills/self-critique/SKILL.md +90 -232
  8. package/adapters/claude/olko-reflection/skills/self-critique/references/rules.md +67 -0
  9. package/adapters/claude/olko-reflection/skills/self-critique/references/scoring.md +99 -0
  10. package/adapters/claude/olko-reflection/skills/self-critique/references/setup.md +62 -0
  11. package/adapters/claude/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
  12. package/adapters/claude/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
  13. package/adapters/claude/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
  14. package/adapters/cursor/olko-reflection/skills/self-critique/SKILL.md +90 -232
  15. package/adapters/cursor/olko-reflection/skills/self-critique/references/rules.md +67 -0
  16. package/adapters/cursor/olko-reflection/skills/self-critique/references/scoring.md +99 -0
  17. package/adapters/cursor/olko-reflection/skills/self-critique/references/setup.md +62 -0
  18. package/adapters/cursor/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
  19. package/adapters/cursor/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
  20. package/adapters/cursor/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
  21. package/adapters/grok/olko-reflection/skills/self-critique/SKILL.md +90 -232
  22. package/adapters/grok/olko-reflection/skills/self-critique/references/rules.md +67 -0
  23. package/adapters/grok/olko-reflection/skills/self-critique/references/scoring.md +99 -0
  24. package/adapters/grok/olko-reflection/skills/self-critique/references/setup.md +62 -0
  25. package/adapters/grok/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
  26. package/adapters/grok/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
  27. package/adapters/grok/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
  28. package/package.json +1 -1
  29. package/plugins/olko-apple-kit/.claude-plugin/plugin.json +1 -1
  30. package/plugins/olko-creative/.claude-plugin/plugin.json +1 -1
  31. package/plugins/olko-garmin-kit/.claude-plugin/plugin.json +1 -1
  32. package/plugins/olko-git-tools/.claude-plugin/plugin.json +1 -1
  33. package/plugins/olko-github-pr/.claude-plugin/plugin.json +1 -1
  34. package/plugins/olko-github-pr/skills/lekker-review/README.md +20 -0
  35. package/plugins/olko-github-pr/skills/lekker-review/SKILL.md +25 -3
  36. package/plugins/olko-github-pr/skills/lekker-review/fix-workflow.js +92 -9
  37. package/plugins/olko-github-pr/skills/lekker-review/references/codex-workflow.md +13 -0
  38. package/plugins/olko-github-pr/skills/lekker-review/references/output-format.md +1 -0
  39. package/plugins/olko-github-pr/skills/lekker-review/scripts/model-matrix.mjs +17 -6
  40. package/plugins/olko-github-pr/skills/lekker-review/scripts/vendor-bridge.mjs +207 -0
  41. package/plugins/olko-github-pr/skills/lekker-review/workflow.js +102 -15
  42. package/plugins/olko-obsidian/.claude-plugin/plugin.json +1 -1
  43. package/plugins/olko-product/.claude-plugin/plugin.json +1 -1
  44. package/plugins/olko-reflection/.claude-plugin/plugin.json +1 -1
  45. package/plugins/olko-reflection/skills/self-critique/SKILL.md +90 -232
  46. package/plugins/olko-reflection/skills/self-critique/references/rules.md +67 -0
  47. package/plugins/olko-reflection/skills/self-critique/references/scoring.md +99 -0
  48. package/plugins/olko-reflection/skills/self-critique/references/setup.md +62 -0
  49. package/plugins/olko-reflection/skills/self-critique/scripts/claim-ledger.mjs +152 -9
  50. package/plugins/olko-reflection/skills/self-critique/scripts/rule-store.mjs +34 -12
  51. package/plugins/olko-reflection/skills/self-critique/scripts/run-store.mjs +133 -0
  52. package/plugins/olko-release/.claude-plugin/plugin.json +1 -1
  53. package/plugins/olko-skill-meta/.claude-plugin/plugin.json +1 -1
  54. package/plugins/olko-web-ops/.claude-plugin/plugin.json +1 -1
@@ -0,0 +1,67 @@
1
+ # Turning a critique into a durable rule (Step 5 detail)
2
+
3
+ A score is a measurement, not an improvement. The improvement is the rule you write down, in a
4
+ place a future session actually reads, before you move on.
5
+
6
+ ## Write the shape, not the incident
7
+
8
+ The incident is the evidence; the shape is the rule. Ask what class of reasoning produced the
9
+ error, then name that class:
10
+
11
+ | Incident | Shape worth keeping |
12
+ | --- | --- |
13
+ | Called an endpoint a read because the path was a noun and a sibling module imported | A conclusion drawn from evidence that does not cover the claim |
14
+ | Priced an open design question as "small" in the same sentence that asked which design was wanted | Never attach a size to an answer you are simultaneously asking for |
15
+ | Described a batch from the one member that was checked | Check the risk-deciding field on every member before describing the set |
16
+
17
+ Broadening a rule's scope so it qualifies for a wider store is the failure mode to avoid: one
18
+ incident on one afternoon is not standing policy. Let the evidence decide where it lands.
19
+
20
+ ## Routing, in order, only one store
21
+
22
+ 1. The user's or project's agent memory: how to work with this user or this project.
23
+ 2. The repository's own `CLAUDE.md` / `AGENTS.md`: true only inside that codebase.
24
+ 3. A shared, cross-session store: holds across projects. Use `context-repo` to resolve it, or
25
+ `shared-knowledge-artifact` when several agents need to read the same ledger.
26
+
27
+ Before writing to shared persistence, redact the incident evidence, including when using
28
+ `context-repo` or `shared-knowledge-artifact`, while still including the incident and its dated
29
+ receipt. This does not apply to local agent memory or repository-rule writes.
30
+
31
+ ## Dedupe
32
+
33
+ Read the store first. If a rule of the same shape exists, add one dated evidence line to it instead
34
+ of creating a second entry, with at most three evidence lines per rule. A fourth incident means the
35
+ rule named the incident, not the shape: rewrite the rule text and keep the three most recent
36
+ evidence lines. Link related rules instead of restating them. When the memory directory exists, run
37
+ `node <skill>/scripts/rule-store.mjs evidence-check --dir <memory dir>` before writing and report
38
+ any rule it flags.
39
+
40
+ ## Identity and counters
41
+
42
+ Mark each rule stored by this workflow with `rule_store: self-critique` under `metadata:` in its
43
+ memory file's frontmatter. The replay pass reads only marked rules, and only marked rules are
44
+ pruning candidates. `fire` adds the marker itself, so a rule that has fired is always both counted
45
+ and prunable. A rule's `fires` and `last_fired` live under `metadata:` and are written only by
46
+ `fire`. Rules routed to `CLAUDE.md`, `AGENTS.md`, or the shared store are neither counted nor pruned.
47
+
48
+ Older rules may have a `fires` counter and no marker (counted, never prunable).
49
+ `node <skill>/scripts/rule-store.mjs adopt --dir <memory dir>` marks them. It edits memory files,
50
+ so tell the user before running it.
51
+
52
+ `rule-store.mjs checklist --dir <dir> --scope all` lists every named memory file, marked or not.
53
+ Use it only to find an unmarked rule that belongs to this workflow.
54
+
55
+ ## Prune pass
56
+
57
+ At the end of Step 5, only when a valid memory directory is available, run
58
+ `node <skill>/scripts/rule-store.mjs prune --dir <memory dir> --idle-days 60` and list the
59
+ candidates in the report under "Rules proposed for deletion". Never delete a rule without the
60
+ user's reply.
61
+
62
+ ## Close the loop
63
+
64
+ State in your report where the rule was written and what it says, so the user can veto it. A rule
65
+ the user has not seen is a rule they cannot correct. The honest test is not that a rule was written
66
+ but that the next task of the same class does not need this skill to catch the same thing. If it
67
+ does, the rule named the incident instead of the shape: rewrite it, do not add another.
@@ -0,0 +1,99 @@
1
+ # Scoring reference
2
+
3
+ The score is `100` minus penalties, floored at 0. It is computed by
4
+ `node <skill>/scripts/claim-ledger.mjs score <ledger>`, never by hand and never by the critic.
5
+
6
+ ## Penalties
7
+
8
+ | Finding | Points off |
9
+ | --- | --- |
10
+ | refuted, load-bearing | 25 |
11
+ | refuted | 10 |
12
+ | unverifiable, load-bearing | 10 |
13
+ | unverifiable | 4 |
14
+ | inferred, accepted, load-bearing | 10 |
15
+ | inferred, accepted | 5 |
16
+ | missed, load-bearing | 15 |
17
+ | missed | 5 |
18
+ | verified but found only by the critic | 5 |
19
+
20
+ An `inferred` missed item (`checked_by: inferred`) is never penalised. A non-load-bearing one is
21
+ not an open defect; a load-bearing one is, so it still blocks the stop rule until you verify it.
22
+
23
+ Why a load-bearing inferred claim costs 10: it used to cost 5, which made "inferred" cheaper than
24
+ "unverifiable" (10) for the same lack of evidence, so unverified claims drifted into the cheaper
25
+ bucket. Load-bearing means the user would act on it, so the two now cost the same.
26
+
27
+ The 5 points for "verified but found only by the critic" can never be revised away. That is why the
28
+ stop rule in `SKILL.md` does not use a score threshold.
29
+
30
+ ## Score anchors
31
+
32
+ Calibrate against these three ledgers (all claims `origin: both`;
33
+ `node <skill>/scripts/claim-ledger.mjs anchors` prints them as JSON).
34
+
35
+ **Strong, score 95**
36
+
37
+ | id | load_bearing | status | checked_by |
38
+ | --- | --- | --- | --- |
39
+ | a1 | no | inferred | inferred |
40
+
41
+ **Middling, score 72**
42
+
43
+ | id | load_bearing | status | checked_by |
44
+ | --- | --- | --- | --- |
45
+ | b1 | no | refuted | read |
46
+ | b2 | no | refuted | read |
47
+ | b3 | no | unverifiable | read |
48
+ | b4 | no | unverifiable | read |
49
+
50
+ **Weak, score 40**
51
+
52
+ | id | load_bearing | status | checked_by |
53
+ | --- | --- | --- | --- |
54
+ | c1 | yes | refuted | read |
55
+ | c2 | yes | refuted | read |
56
+ | c3 | yes | unverifiable | read |
57
+
58
+ ## Ledger shape
59
+
60
+ `version` is always `1`. `author_id` and `critic_ref` let the script cross-check the ledger.
61
+
62
+ ```json
63
+ { "version": 1,
64
+ "claims": [
65
+ { "id": "c1", "text": "...", "load_bearing": true, "origin": "both",
66
+ "author_id": "a1", "critic_ref": "r1:claims.0",
67
+ "status": "verified", "checked_by": "command", "receipt": "quoted output" },
68
+ { "id": "c2", "text": "...", "load_bearing": false, "origin": "critic",
69
+ "critic_ref": "r1:claims.1", "status": "inferred", "checked_by": "inferred" }
70
+ ],
71
+ "missed": [
72
+ { "id": "m1", "text": "...", "load_bearing": false, "checked_by": "read",
73
+ "critic_ref": "r1:missed.0" }
74
+ ] }
75
+ ```
76
+
77
+ - `origin`: `author` | `critic` | `both`
78
+ - `author_id`: the id from `author-claims.json`. Required when `origin` is `author` or `both`;
79
+ forbidden when it is `critic`.
80
+ - `critic_ref`: `"r<round>:claims.<index>"` or `"r<round>:missed.<index>"`, a string or an array,
81
+ pointing into the saved `critic-r<round>.json`. Required when `origin` is `critic` or `both`, and
82
+ on every `missed` entry; forbidden when `origin` is `author`.
83
+ - `status`: `verified` | `refuted` | `unverifiable` | `inferred`
84
+ - `checked_by`: `command` (run, output quoted) | `read` (file or record opened, quoted) |
85
+ `inferred` (reasoning only). Required on `missed` items too. A `verified` or `refuted` claim may
86
+ not use inferred evidence and requires a non-empty receipt.
87
+
88
+ ## Integrity checks
89
+
90
+ When `--author`, `--critic` or `--prev` is passed, the script also fails (exit 2) on:
91
+
92
+ - a duplicate id;
93
+ - an author claim with no ledger entry, or a ledger claim naming an unknown author claim;
94
+ - a critic item (any round) with no ledger entry, or a `critic_ref` that points at nothing;
95
+ - a claim id from the previous ledger that is missing from the new one (a revision may add claims,
96
+ never drop one).
97
+
98
+ Output carries `"integrity": "checked"` when any flag was given and `"unchecked"` otherwise. An
99
+ `unchecked` score is not a reportable score.
@@ -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 loadLedger = (path) => {
133
- let parsed
230
+ const readJson = (path) => {
134
231
  try {
135
- parsed = JSON.parse(readFileSync(path, 'utf8'))
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]) => scoreLedger(loadLedger(a)),
146
- ratchet: ([a, b]) => ratchet(loadLedger(a), loadLedger(b)),
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, ...args] = argv
294
+ const [cmd, ...rest] = argv
153
295
  const run = COMMANDS[cmd]
154
296
  if (!run) return fail(`unknown command: ${cmd}`)
155
- const out = run(args)
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
- export const checklistMarkdown = (dir) =>
90
- listRules(dir).map((r) => `- [${r.name}]: ${r.description}\n`).join('');
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
- return { ...rule, metadata: { ...rule.metadata, fires: String(fires + 1), last_fired: isoDate } };
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
- export function fire(dir, name, isoDate) {
98
- const entry = readRuleFiles(dir).find((e) => e.rule.name === name);
99
- if (!entry) throw new Error(`rule not found: ${name}`);
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(updated), { flag: 'wx', mode: fs.statSync(target).mode });
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.metadata.rule_store !== 'self-critique') return [];
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))