polydeukes 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/README.ko.md +14 -28
  2. package/README.md +14 -28
  3. package/dist/baseline.d.ts +37 -1
  4. package/dist/baseline.js +68 -1
  5. package/dist/bin.d.ts +3 -4
  6. package/dist/bin.js +73 -90
  7. package/dist/covenant/bash-line.d.ts +130 -0
  8. package/dist/covenant/bash-line.js +566 -0
  9. package/dist/covenant/declaration-engine.d.ts +108 -0
  10. package/dist/covenant/declaration-engine.js +415 -0
  11. package/dist/covenant/discipline.d.ts +103 -0
  12. package/dist/covenant/discipline.js +667 -0
  13. package/dist/covenant/dispatch.d.ts +153 -0
  14. package/dist/covenant/dispatch.js +237 -0
  15. package/dist/covenant/extract-steps.d.ts +122 -0
  16. package/dist/covenant/extract-steps.js +0 -0
  17. package/dist/covenant/mention.d.ts +117 -0
  18. package/dist/covenant/mention.js +209 -0
  19. package/dist/covenant/module.d.ts +25 -0
  20. package/dist/covenant/module.js +23 -0
  21. package/dist/covenant/mutation-rules.d.ts +40 -0
  22. package/dist/covenant/mutation-rules.js +146 -0
  23. package/dist/covenant/relations.d.ts +46 -0
  24. package/dist/covenant/relations.js +68 -0
  25. package/dist/covenant/run-covenant.d.ts +95 -0
  26. package/dist/covenant/run-covenant.js +164 -0
  27. package/dist/covenant/self-mod.d.ts +55 -0
  28. package/dist/covenant/self-mod.js +84 -0
  29. package/dist/covenant/shell-evidence.d.ts +38 -0
  30. package/dist/covenant/shell-evidence.js +247 -0
  31. package/dist/covenant/shell-mod.d.ts +84 -0
  32. package/dist/covenant/shell-mod.js +213 -0
  33. package/dist/covenant/supply.d.ts +54 -0
  34. package/dist/covenant/supply.js +50 -0
  35. package/dist/covenant/transcript-mod.d.ts +60 -0
  36. package/dist/covenant/transcript-mod.js +254 -0
  37. package/dist/covenant/ttl-witness.d.ts +47 -0
  38. package/dist/covenant/ttl-witness.js +80 -0
  39. package/dist/covenant-check.d.ts +72 -39
  40. package/dist/covenant-check.js +260 -121
  41. package/dist/diff-ir.d.ts +28 -0
  42. package/dist/diff-ir.js +310 -0
  43. package/dist/docs/README.ko.md +8 -8
  44. package/dist/docs/README.md +8 -8
  45. package/dist/docs/catalog.json +44 -28
  46. package/dist/docs/concepts/judgment.ko.md +2 -2
  47. package/dist/docs/concepts/judgment.md +2 -2
  48. package/dist/docs/how-to/configure-project.ko.md +16 -16
  49. package/dist/docs/how-to/configure-project.md +15 -12
  50. package/dist/docs/how-to/connect-surfaces.ko.md +39 -34
  51. package/dist/docs/how-to/connect-surfaces.md +36 -33
  52. package/dist/docs/how-to/write-disciplines.ko.md +61 -6
  53. package/dist/docs/how-to/write-disciplines.md +62 -6
  54. package/dist/docs/index.json +607 -373
  55. package/dist/docs/reference/cli/covenant-check.ko.md +112 -65
  56. package/dist/docs/reference/cli/covenant-check.md +114 -59
  57. package/dist/docs/reference/cli/docs.ko.md +2 -2
  58. package/dist/docs/reference/cli/docs.md +2 -2
  59. package/dist/docs/reference/cli/explain.ko.md +14 -9
  60. package/dist/docs/reference/cli/explain.md +15 -10
  61. package/dist/docs/reference/cli/init.ko.md +52 -52
  62. package/dist/docs/reference/cli/init.md +43 -55
  63. package/dist/docs/reference/configuration/index.ko.md +171 -66
  64. package/dist/docs/reference/configuration/index.md +178 -71
  65. package/dist/docs/reference/packages/adapter-claude-code.ko.md +38 -11
  66. package/dist/docs/reference/packages/adapter-claude-code.md +38 -14
  67. package/dist/docs/reference/packages/adapter-grok.ko.md +77 -0
  68. package/dist/docs/reference/packages/adapter-grok.md +79 -0
  69. package/dist/docs/reference/packages/core.ko.md +49 -3
  70. package/dist/docs/reference/packages/core.md +54 -5
  71. package/dist/docs/reference/packages/polydeukes.ko.md +138 -77
  72. package/dist/docs/reference/packages/polydeukes.md +146 -81
  73. package/dist/docs/reference/packages/sdk-ts.ko.md +161 -0
  74. package/dist/docs/reference/packages/sdk-ts.md +164 -0
  75. package/dist/docs/troubleshooting.ko.md +17 -15
  76. package/dist/docs/troubleshooting.md +18 -14
  77. package/dist/docs/tutorials/first-judgment.ko.md +2 -2
  78. package/dist/docs/tutorials/first-judgment.md +2 -2
  79. package/dist/explain.d.ts +1 -1
  80. package/dist/explain.js +37 -22
  81. package/dist/load-config.d.ts +1 -1
  82. package/dist/load-config.js +1 -1
  83. package/dist/pre-state-reader.d.ts +1 -1
  84. package/dist/pre-state-reader.js +1 -1
  85. package/dist/scaffold-project.d.ts +2 -2
  86. package/dist/scaffold-project.js +9 -3
  87. package/dist/schema/polydeukes.schema.json +12 -0
  88. package/dist/worktree-reader.d.ts +19 -0
  89. package/dist/worktree-reader.js +30 -0
  90. package/package.json +3 -17
  91. package/dist/claude-code-hook.d.ts +0 -79
  92. package/dist/claude-code-hook.js +0 -372
  93. package/dist/claude-code.d.ts +0 -6
  94. package/dist/claude-code.js +0 -6
  95. package/dist/covenant-module.d.ts +0 -25
  96. package/dist/covenant-module.js +0 -42
  97. package/dist/docs/reference/packages/adapter-git.ko.md +0 -101
  98. package/dist/docs/reference/packages/adapter-git.md +0 -108
  99. package/dist/docs/reference/packages/covenant.ko.md +0 -115
  100. package/dist/docs/reference/packages/covenant.md +0 -123
  101. package/dist/index.d.ts +0 -22
  102. package/dist/index.js +0 -21
  103. package/dist/init-claude-code.d.ts +0 -52
  104. package/dist/init-claude-code.js +0 -586
  105. package/dist/init-grok.d.ts +0 -51
  106. package/dist/init-grok.js +0 -242
@@ -1,586 +0,0 @@
1
- /**
2
- * `initClaudeCode` — the session-surface installer.
3
- *
4
- * One command wires a project into the session surface: prove the package resolves, run the
5
- * shared project-side scaffold ({@link scaffoldProject}), then add what this distribution
6
- * path owns — the delegator hook file, its `.claude/settings.json` registration, the
7
- * discipline file that tells an agent the docs query exists, and the classification skill
8
- * that turns a described problem into a config entry.
9
- *
10
- * Preflight comes first and nothing is written before it clears. A generated hook whose
11
- * import can never resolve blocks every call through its own fail-closed catch, and a tree
12
- * that also has no config and no valve to open cannot be edited back into shape from inside
13
- * the session.
14
- *
15
- * Nothing existing is overwritten. The settings file in particular is merged, never
16
- * replaced: a consumer's other PreToolUse registrations and permissions are live
17
- * configuration, and replacing them would disarm every other tool they wired. A grok JSON
18
- * whose command still names the grok mjs is rewritten to this hook's command so the two
19
- * installers do not leave two spawn strings.
20
- */
21
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
22
- import { findPackageJSON } from 'node:module';
23
- import { dirname, join } from 'node:path';
24
- import { MUTATING_TOOLS, SHELL_TOOLS } from '@polydeukes/adapter-claude-code';
25
- import { isPlainObject } from '@polydeukes/core';
26
- import { TOPICS } from './docs-query.js';
27
- import { retargetGrokHookCommandToClaude } from './init-grok.js';
28
- import { CONFIG_FILENAMES } from './load-config.js';
29
- import { scaffoldProject } from './scaffold-project.js';
30
- /** The published entry point the generated hook loads the judge through. */
31
- const HOOK_SPECIFIER = 'polydeukes/claude-code';
32
- /** The registration artifacts, as `projectRoot`-relative paths (the report vocabulary). */
33
- const HOOK_RELATIVE = '.claude/hooks/covenant-pretooluse.mjs';
34
- const SETTINGS_RELATIVE = '.claude/settings.json';
35
- const DISCOVERY_RELATIVE = '.claude/rules/polydeukes.md';
36
- const SKILL_RELATIVE = '.claude/skills/discipline-draft/SKILL.md';
37
- /**
38
- * The command the host spawns, and the string our registration is recognized by: the same
39
- * command already present means already registered. A registration keyed on anything else
40
- * would be re-added on every run, and the host would then spawn the judge twice per call —
41
- * every verdict and every telemetry row doubled.
42
- */
43
- const HOOK_COMMAND = `node "$CLAUDE_PROJECT_DIR"/${HOOK_RELATIVE}`;
44
- /** Which calls reach the judge — the adapter's own vocabulary, never a copy of it. */
45
- const HOOK_MATCHER = [...MUTATING_TOOLS, ...SHELL_TOOLS].join('|');
46
- /**
47
- * The generated hook. It carries no assembly at all, so upgrading the package upgrades the
48
- * judge without regenerating this file.
49
- */
50
- const GENERATED_HOOK = `#!/usr/bin/env node
51
- /**
52
- * Polydeukes PreToolUse covenant hook — generated by \`pdks init claude-code\`.
53
- *
54
- * A delegator and nothing more: the judgment assembly lives in the \`polydeukes\` package as
55
- * \`runClaudeCodeHook\`, reached here through its session subpath. The package barrel would
56
- * work too and is the wrong door — its re-exports are eager, so every session call would
57
- * load the commit surface and its git adapter alongside the judge it actually needs.
58
- *
59
- * \`repoRoot\` comes from this file's own location, never from the working directory. A hook
60
- * is spawned with whatever directory the agent happened to hold, and what config discovery
61
- * and the protection list need is the project that CONTAINS this hook — always \`../..\`
62
- * from here.
63
- *
64
- * fail-closed: \`runClaudeCodeHook\` translates every failure it can reach into exit 2 with
65
- * one blocked record. This catch answers only for what it cannot reach — the package failing
66
- * to resolve or load at all (never installed, or installed without a build) — where no
67
- * telemetry writer exists yet. Recovery is installing the package again.
68
- */
69
-
70
- import { dirname, join } from 'node:path';
71
- import { fileURLToPath } from 'node:url';
72
-
73
- const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
74
-
75
- try {
76
- const { runClaudeCodeHook } = await import('${HOOK_SPECIFIER}');
77
- const { exitCode } = await runClaudeCodeHook({ repoRoot });
78
- // Assign and let the process end naturally instead of process.exit(): an explicit exit
79
- // can preempt a buffered stderr write on platforms with async pipes, dropping the break
80
- // reason the agent needs to read.
81
- process.exitCode = exitCode;
82
- } catch (error) {
83
- console.error(\`covenant hook failed closed: \${error?.message ?? error}\`);
84
- process.exitCode = 2;
85
- }
86
- `;
87
- /** What a session is about to do, per topic — the correspondence the generated file carries. */
88
- const DOCS_TOPIC_PURPOSE = {
89
- install: 'install Polydeukes, or wire another surface into this project',
90
- config: 'edit `polydeukes.config.*` — every key and what reads it',
91
- discipline: 'add or change a `disciplines` entry',
92
- covenant: 'explain a verdict, or why a surface failed closed',
93
- witness: 'open a blocked call in person',
94
- };
95
- /**
96
- * The generated discipline file — the discovery path that gets the query surface called. A
97
- * query an agent never learns about is a query that does not exist. One scoped file costs
98
- * nothing while it waits: `paths` frontmatter keeps it out of context until a Polydeukes
99
- * path is in play.
100
- *
101
- * Both the command forms and the topic names come from the shipped surface itself — a file
102
- * naming a query that exits 2 fails the agent once, and it never calls the command again.
103
- */
104
- const GENERATED_DISCOVERY = `---
105
- paths:
106
- ${CONFIG_FILENAMES.map((name) => ` - "${name}"`).join('\n')}
107
- - ".claude/**"
108
- ---
109
-
110
- # Polydeukes — query the installed docs
111
-
112
- This project is judged by Polydeukes, and the matching documentation ships inside the
113
- installed package. \`pdks docs\` answers offline, from the same version that does the
114
- judging; a web search answers from whichever release it indexed.
115
-
116
- Run \`pdks docs\` for the topic list, \`pdks docs <topic>\` for topic content,
117
- \`pdks docs search "locale key pairing"\` to find a section, or
118
- \`pdks docs show write-disciplines\` to retrieve the guide. Add \`--lang ko\` for Korean.
119
-
120
- A local install puts the bin in \`node_modules/.bin\`, which a plain shell does not have on
121
- PATH. If \`pdks\` is not found, run \`./node_modules/.bin/pdks docs <topic>\` — or your package
122
- manager's exec form — from the project root.
123
-
124
- | Before you | Run |
125
- | --- | --- |
126
- ${TOPICS.map((topic) => `| ${DOCS_TOPIC_PURPOSE[topic]} | \`pdks docs ${topic}\` |`).join('\n')}
127
- `;
128
- /**
129
- * The generated classification skill — the procedure that turns a described problem into a
130
- * registered entry. A classification procedure an agent never learns about is one that never
131
- * runs, so it ships as an artifact of the install rather than as prose in a README.
132
- *
133
- * Its advise-consumption section is the delivery path for advised rows: the session surface
134
- * lets an advised call through with exit 0, and the reason never reaches the model at call
135
- * time — reading the telemetry log at task boundaries is the only way it arrives.
136
- */
137
- export const GENERATED_SKILL = `---
138
- name: discipline-draft
139
- description: Turn a described discipline problem into a registered entry in polydeukes.config — a judged entry when the declaration grammar and observed evidence can express it, a draft entry otherwise. Use when the user describes a recurring problem they want promised away ("I keep...", "stop X from happening", "we should never...", "how do I enforce Y").
140
- ---
141
-
142
- # discipline-draft — from a problem description to a registered discipline
143
-
144
- This project is judged by Polydeukes. A discipline starts as prose and climbs a ladder —
145
- \`draft\` (registered, read, never judged) → \`advise\` (judged, recorded, never stops a call) →
146
- \`block\` (stops the call; the user's explicit choice, never the default). This skill walks a
147
- problem description down to the right first rung and registers it.
148
-
149
- ## Procedure
150
-
151
- ### 1. Restate the problem as a promise
152
-
153
- Rewrite the description as one sentence of the form "X must not happen" or "when A happens,
154
- B must also happen". If the sentence needs "unless" more than once, split it into two
155
- promises and classify each separately.
156
-
157
- ### 2. Classify the shape
158
-
159
- Choose from the current catalogue, then check whether the intended surface can supply the
160
- required evidence. A mechanism name constrains the declaration; it does not implement the
161
- promise by itself. The extracted axes and body relations must be subsets of the admitted
162
- sets below. Scope filtering is separate from the extracted axes.
163
-
164
- | Mechanism | Admitted axes | Body relations | Evidence or structural condition |
165
- | --- | --- | --- | --- |
166
- | \`pairing\` | \`world\` | \`equal\` | Compare supplied files or channels; extract keys when values may differ. |
167
- | \`companion\` | \`change\`, \`world\` | \`implies\` | Compare presence by key; a multi-file promise needs the observed change set. |
168
- | \`monotonic-order\` | \`change\`, \`world\` | \`ordered\` | Extract a sequence with an explicit comparison field; order is not presence. |
169
- | \`fingerprint-sync\` | \`world\` | \`equal\` | Compare supplied stamps; no generator or compiler runs during judgment. |
170
- | \`producer-owned\` | \`actor\` | \`empty\`, \`nonEmpty\` | Requires host-provided actor evidence, not an artifact's self-reported producer. |
171
- | \`self-absolution-ban\` | \`change\` | \`unchanged\`, \`empty\` | Extract protected fields or path changes; choose creation/deletion supply explicitly. |
172
- | \`actor-scope\` | \`actor\` | \`empty\`, \`nonEmpty\` | Requires a proven actor; a missing actor is not proof of the main session. |
173
- | \`precedent\` | \`history\`, \`world\` | \`nonEmpty\` | Requires an observed earlier call in a transcript or supplied channel. |
174
- | \`phase-order\` | \`history\` | \`ordered\` | Compare observed call ordinals; missing phases need a separate presence promise. |
175
- | \`turn-locality\` | \`history\` | \`nonEmpty\` | Requires observed turns and time or ordinal boundaries. |
176
- | \`stated-ground\` | \`history\` | \`nonEmpty\` | Can require recorded text, not establish whether its reasoning is sound. |
177
- | \`controlled-vocabulary\` | \`change\`, \`world\` | \`subset\` | Extract values and an explicit allowed set. |
178
- | \`naming\` | \`change\` | \`empty\`, \`nonEmpty\` | Scope must read \`target.path\`; match the intended name pattern. |
179
- | \`added-only\` | \`change\` | \`empty\` | Compare pre/post extractions and judge only newly added matches. |
180
- | \`one-way-marker\` | \`change\` | \`subset\` | Existing markers must remain in the extracted post-change set. |
181
- | \`delegated-scope\` | — | — | Reserved for a definition-time evaluator; not accepted in current declarations. |
182
- | \`scoped-valve\` | \`change\`, \`actor\`, \`world\`, \`history\` | \`empty\`, \`nonEmpty\`, \`equal\`, \`subset\`, \`implies\`, \`ordered\`, \`unchanged\` | Requires a \`witness\` block expressing the exception condition. |
183
- | \`forbidden-command\` | \`change\` | \`empty\` | Scope must read \`command\`; a text pattern is not shell semantic analysis. |
184
-
185
- These four requests illustrate the classification boundary:
186
-
187
- | Request | Classification | Proof |
188
- | --- | --- | --- |
189
- | The English and Korean locale files must carry identical keys. | \`pairing\`, with two supplied files. | An unmatched key breaks; translated values may differ. |
190
- | Every status must belong to an allowed list. | \`controlled-vocabulary\`, with a supplied allowed set. | An unknown status breaks; an allowed status passes. |
191
- | A successful package lookup must precede a manifest edit. | \`precedent\`, with observed session history. | Failed or absent lookups break; an unavailable transcript is a supply case. |
192
- | A fresh benchmark must execute during judgment to prove a performance claim. | \`draft\`: the engine does not execute benchmarks. | Comparing an existing report would be a different promise. |
193
-
194
- Run \`pdks docs show write-disciplines\` for the key-pairing walkthrough and
195
- \`pdks docs show configuration --section disciplines\` for the declaration grammar.
196
- Use \`--lang ko\` for Korean; these commands read the installed version offline.
197
-
198
- An \`added-only\` declaration forgives existing occurrences — only what the edit adds breaks
199
- the promise. That is usually what you want: a discipline adopted today should not indict
200
- yesterday's code.
201
-
202
- One path-shaped promise takes no \`disciplines:\` entry at all: a path nobody may touch
203
- belongs in the top-level \`protectedPaths:\` list — its own config block, never an entry key.
204
-
205
- ### 3. Check the observation boundary
206
-
207
- Do not confuse an expressible relation with available evidence:
208
-
209
- - **Files outside the repository** — file-change protection observes the project root.
210
- Use the host's permission policy for comprehensive protection outside it. A command-text
211
- pattern may recognize a particular string, but does not observe all resulting writes.
212
- - **Writes by child processes** — arbitrary writes inside a test runner or script are not
213
- individually observed by the session surface. A commit comparison can observe the resulting
214
- files when they enter its selected diff; it does not recover the originating tool history.
215
- - **Missing history or actor channels** — choose the declaration's supply policy explicitly.
216
- Commit observations have no session transcript; \`supply: pass\` records a skip, not success.
217
- - **Fresh execution or semantic proof** — the engine compares supplied evidence. It does not
218
- run a new benchmark or prove that a written explanation is true. Preserve that unmet promise
219
- as a draft rather than silently replacing it with a weaker text check.
220
-
221
- ### 4a. Expressible now — register a judged entry
222
-
223
- Add the entry to the \`disciplines:\` array in \`polydeukes.config.yaml\`. Advise is the default
224
- landing — a break is recorded as \`advised\` and the call goes on — and the \`enforce: advise\`
225
- line below only spells that default out. NEVER write \`enforce: block\` from this skill:
226
- promotion to block is the user's own choice, made after the advise measurements have been
227
- read.
228
-
229
- The examples below are whole documents, so \`languages:\` — the schema's one required block —
230
- appears alongside the entry; in a config that already has one, copy the entry only.
231
-
232
- \`\`\`yaml
233
- languages:
234
- placeholder:
235
- productionGlob: 'src/**'
236
- testCmd: 'echo "set a verification command for {scope}"'
237
- disciplines:
238
- - id: 'no-focused-tests'
239
- why: 'a committed .only silently shrinks the suite to one test'
240
- declare:
241
- mechanism: 'added-only'
242
- scope: { source: 'target.path', include: ['^src/'] }
243
- supply: { pre: 'empty', post: 'empty' }
244
- extract:
245
- before:
246
- - { op: 'source', of: 'pre' }
247
- - { op: 'lines' }
248
- - { op: 'keyByPattern', re: '(\\.only\\()' }
249
- after:
250
- - { op: 'source', of: 'post' }
251
- - { op: 'lines' }
252
- - { op: 'keyByPattern', re: '(\\.only\\()' }
253
- added:
254
- - { op: 'onlyIn', of: 'after', notIn: 'before' }
255
- relate:
256
- - id: 'nothing-added'
257
- relation: { op: 'empty', of: 'added' }
258
- message: 'adds {key}: {value}'
259
- enforce: advise
260
- \`\`\`
261
-
262
- A command-line ban reads the fixed source \`command\` and scopes on it — the scope is part of
263
- the mechanism's shape, so a \`forbidden-command\` entry without it is refused at load time:
264
-
265
- \`\`\`yaml
266
- languages:
267
- placeholder:
268
- productionGlob: 'src/**'
269
- testCmd: 'echo "set a verification command for {scope}"'
270
- disciplines:
271
- - id: 'no-force-push'
272
- why: 'a force push rewrites history nobody reviewed'
273
- declare:
274
- mechanism: 'forbidden-command'
275
- scope: { source: 'command' }
276
- extract:
277
- hits:
278
- - { op: 'source', of: 'command' }
279
- - { op: 'lines' }
280
- - { op: 'matches', re: 'git push\\b.*--force(?![\\w-])' }
281
- relate:
282
- - { id: 'no-force', relation: { op: 'empty', of: 'hits' }, message: '{value}' }
283
- enforce: advise
284
- \`\`\`
285
-
286
- The following examples implement the first three classification cases. Both locale files and
287
- the allowed-status file must exist and contain valid JSON. File bindings use the proposed
288
- contents for a file changed by the current observation, not a second stale disk read.
289
-
290
- \`\`\`yaml
291
- languages:
292
- json:
293
- productionGlob: 'locales/**/*.json'
294
- testCmd: 'pnpm test'
295
- disciplines:
296
- - id: 'locale-key-parity'
297
- why: 'the ko and en locales must carry the same keys'
298
- declare:
299
- mechanism: 'pairing'
300
- scope: { source: 'target.path', include: ['^locales/(ko|en)[.]json$'] }
301
- sources:
302
- ko: { file: 'locales/ko.json' }
303
- en: { file: 'locales/en.json' }
304
- supply: { ko: 'error', en: 'error' }
305
- extract:
306
- koKeys: [{ op: 'source', of: 'ko' }, { op: 'json' }, { op: 'flattenKeys' }]
307
- enKeys: [{ op: 'source', of: 'en' }, { op: 'json' }, { op: 'flattenKeys' }]
308
- relate:
309
- - id: 'parity'
310
- relation: { op: 'equal', of: ['koKeys', 'enKeys'] }
311
- messageBySide:
312
- left: '{key} is in ko only'
313
- right: '{key} is in en only'
314
- enforce: advise
315
- \`\`\`
316
-
317
- \`\`\`yaml
318
- languages:
319
- json:
320
- productionGlob: '*.json'
321
- testCmd: 'pnpm test'
322
- disciplines:
323
- - id: 'status-vocabulary'
324
- why: 'statuses.json may contain only values listed in allowed-statuses.json'
325
- declare:
326
- mechanism: 'controlled-vocabulary'
327
- scope: { source: 'target.path', include: ['^statuses[.]json$'] }
328
- sources: { allowed: { file: 'allowed-statuses.json' } }
329
- supply: { post: 'error', allowed: 'error' }
330
- extract:
331
- selected: [{ op: 'source', of: 'post' }, { op: 'json' }, { op: 'items' }]
332
- permitted: [{ op: 'source', of: 'allowed' }, { op: 'json' }, { op: 'items' }]
333
- relate:
334
- - id: 'allowed-status'
335
- relation: { op: 'subset', of: 'selected', in: 'permitted' }
336
- message: 'unknown status: {value}'
337
- enforce: advise
338
- \`\`\`
339
-
340
- Here both status files are JSON arrays of strings. This declaration scopes on statuses.json;
341
- editing only the allowed list does not trigger it. Broaden the observation deliberately if
342
- changes to that list must recheck all dependent files.
343
-
344
- \`\`\`yaml
345
- languages:
346
- typescript:
347
- productionGlob: 'src/**'
348
- testCmd: 'pnpm test'
349
- disciplines:
350
- - id: 'manifest-needs-npm-view'
351
- why: 'a successful package lookup must precede a manifest edit'
352
- declare:
353
- mechanism: 'precedent'
354
- scope: { source: 'target.path', include: ['^(packages/[^/]+/)?package[.]json$'] }
355
- sources: { session: { transcript: true } }
356
- supply: { session: 'pass' }
357
- extract:
358
- npmView:
359
- - { op: 'source', of: 'session' }
360
- - { op: 'toolUses', names: ['Bash'] }
361
- - { op: 'filter', when: [{ field: 'succeeded', eq: true }] }
362
- - { op: 'select', path: 'args.command' }
363
- - { op: 'matches', re: '^npm view ' }
364
- relate:
365
- - id: 'npm-view'
366
- relation: { op: 'nonEmpty', of: 'npmView' }
367
- message: 'no successful npm view precedes this edit'
368
- enforce: advise
369
- \`\`\`
370
-
371
- The precedent example proves only that an observed successful Bash call starts with npm view;
372
- it does not prove that the lookup concerns the dependency being edited. The commit surface has
373
- no transcript and therefore skips this example by its explicit supply policy.
374
-
375
- **Write the regex yourself — the user states the promise, you author the pattern.** The
376
- pattern is the part users find hardest, so never hand the prose back and ask for one. Three
377
- authoring traps, each measured on a live config:
378
-
379
- - **A pattern answers a syntactic question only.** "Is this string a forbidden word" is
380
- syntax; "is this a new dependency version" is meaning, and a regex leaks both ways on a
381
- semantic question. When the question is semantic, narrow the declaration's own \`scope\`
382
- block to the files where any match IS a break, or accept "editing this file at all" as
383
- the trigger.
384
- - **\`^\` means what the preceding step left.** After a \`lines\` step a declaration's
385
- pattern sees one line at a time, so \`^\` anchors to that line; over an unsplit source it
386
- anchors to the whole text and matches the first line only. A ban over the command line
387
- puts \`lines\` before its \`matches\` for exactly that reason.
388
- - **Author both directions.** Before registering, write down one string the pattern must
389
- match and one nearby string it must not (\`only(\` vs \`only_helper(\`, a flag vs its
390
- substring). A pattern checked in only the breaking direction over-fires in review-proof
391
- ways.
392
-
393
- ### 4b. Not expressible yet — register a draft
394
-
395
- A draft is prose with a handle: \`id\`, \`why\`, and the literal marker \`draft: true\` — no other
396
- keys. It produces no judgment and no telemetry; \`pdks explain\` lists it as unpromoted.
397
- Record the intended promise and the exact missing capability inside \`why\`. Do not classify
398
- pairing, vocabulary, or history promises as drafts merely because they are absent from a short
399
- example list. Check the catalogue, extraction steps, and observation channel first. A reserved
400
- \`delegated-scope\` declaration cannot be registered as a judged entry.
401
-
402
- \`\`\`yaml
403
- languages:
404
- placeholder:
405
- productionGlob: 'src/**'
406
- testCmd: 'echo "set a verification command for {scope}"'
407
- disciplines:
408
- - id: 'benchmark-supports-performance-claim'
409
- why: 'a performance claim needs a fresh benchmark run during judgment; the engine cannot execute it'
410
- draft: true
411
- \`\`\`
412
-
413
- ### 5. Prove it fires, then close
414
-
415
- Run \`pdks explain\` and confirm the new entry is listed (a judged entry with its mechanism
416
- and surfaces; a draft as unpromoted).
417
-
418
- For a judged entry, registration is not the finish — a pattern that never fires protects
419
- nothing while looking installed. Fire it once for real, with the proof run the declaration's
420
- own mechanism can actually reach:
421
-
422
- | Mechanism | Break it once | The entry's id shows up in |
423
- | --- | --- | --- |
424
- | a file-reading one (\`added-only\`, \`naming\`, …) | one scratch edit matching the must-match direction | \`pdks covenant check --worktree\` output — the exit stays 0 at advise, the id is the proof |
425
- | \`forbidden-command\` | run one harmless command matching the pattern | the telemetry log tail — at advise the call proceeds and its row records the id |
426
- | \`precedent\` | one in-scope edit made without the required precedent | the telemetry log tail — a declaration reading the session judges on the session surface only (the commit surface has none, so its \`supply\` policy records it \`skipped\`) |
427
-
428
- Then undo the scratch break, repeat the same observation, and confirm a passing row for the
429
- must-NOT-match case. Silence alone may mean a scope miss, unchanged files, or unavailable evidence;
430
- check \`pdks explain\` and telemetry for \`config-fault\`, \`no-observation\`, or \`supply-pass\`. Close by telling the user which rung the entry landed on and
431
- that \`enforce: block\` is theirs to add later if the advise record earns it.
432
-
433
- ## Updating this skill without losing local edits
434
-
435
- An upgrade does not overwrite an existing skill; rerunning \`pdks init claude-code\` reports it
436
- skipped. Generate a fresh copy in a disposable project using the installed package, compare it
437
- with this file, and merge the changes you want. Keep a backup of local additions. Do not delete
438
- the existing skill to force regeneration in the working project.
439
-
440
- ## Reading the advise record
441
-
442
- An \`advised\` row means a promise was broken and the call went through anyway. Rows land in
443
- the telemetry log at the path configured by \`telemetry.logPath\` (default
444
- \`.polydeukes/roi.log\`). The hook's stderr note is not shown to you, so consult the log at
445
- task boundaries: before committing, or after a batch of edits, read the tail and act on any
446
- \`advised\` row — fix the break, or tell the user why it should stand. An advisory nobody
447
- reads measures nothing.
448
- `;
449
- /**
450
- * The default preflight: is `polydeukes` installed where `projectRoot` can reach it?
451
- *
452
- * ESM resolution specifically, because that is what the generated hook's `await import(...)`
453
- * runs; the CJS alternatives were measured disagreeing with it in both directions.
454
- * `findPackageJSON` is experimental in Node 24, so its behaviour can still change.
455
- */
456
- function resolveFromProjectRoot(projectRoot) {
457
- // Absence throws here rather than returning undefined (Node 24.18); the branch guards the
458
- // documented `string | undefined` return.
459
- const manifestPath = findPackageJSON('polydeukes', join(projectRoot, 'package.json'));
460
- if (manifestPath === undefined) {
461
- throw new Error('polydeukes is not installed where this project can reach it');
462
- }
463
- // Locating the package is not the question — `findPackageJSON` does not apply its exports
464
- // map, so a version predating the session subpath, or one whose dist was never built,
465
- // passes a bare-name check while the generated hook fails on every call. That tree cannot
466
- // be reopened with the witness token either, because an assembly crash lands before any
467
- // verdict.
468
- const manifest = JSON.parse(readFileSync(manifestPath, 'utf-8'));
469
- const subpath = isPlainObject(manifest) && isPlainObject(manifest.exports)
470
- ? manifest.exports[`./${HOOK_SPECIFIER.split('/')[1]}`]
471
- : undefined;
472
- const target = isPlainObject(subpath) ? subpath.import : undefined;
473
- if (typeof target !== 'string' || !existsSync(join(dirname(manifestPath), target))) {
474
- throw new Error(`the installed polydeukes does not expose '${HOOK_SPECIFIER}' — update or rebuild it`);
475
- }
476
- }
477
- /**
478
- * Is our PreToolUse command already in this settings object? Asked twice — before the merge
479
- * to stay idempotent, and after the write to prove the file took it.
480
- */
481
- function carriesRegistration(settings) {
482
- return (settings.hooks?.PreToolUse ?? []).some((entry) => (entry?.hooks ?? []).some((hook) => hook?.command === HOOK_COMMAND));
483
- }
484
- /** Write one generated artifact unless it is already there, recording which happened. */
485
- function writeIfAbsent(projectRoot, relative, contents, report) {
486
- const path = join(projectRoot, relative);
487
- if (existsSync(path)) {
488
- report.skipped.push(relative);
489
- return;
490
- }
491
- mkdirSync(dirname(path), { recursive: true });
492
- writeFileSync(path, contents);
493
- report.created.push(relative);
494
- }
495
- /**
496
- * Read the settings file, or an empty one when there is none yet. Belongs to preflight
497
- * rather than to the merge: parsing it later would leave a wired-but-unregistered tree —
498
- * delegator on disk, host never told to spawn it, every call unjudged with no telemetry row.
499
- */
500
- function readSettings(projectRoot) {
501
- const settingsPath = join(projectRoot, SETTINGS_RELATIVE);
502
- if (!existsSync(settingsPath)) {
503
- return {};
504
- }
505
- let parsed;
506
- try {
507
- parsed = JSON.parse(readFileSync(settingsPath, 'utf-8'));
508
- }
509
- catch (error) {
510
- throw new Error(`cannot parse ${SETTINGS_RELATIVE} in ${projectRoot} — fix it and re-run ` +
511
- `(${error instanceof Error ? error.message : String(error)})`);
512
- }
513
- return parsed;
514
- }
515
- /**
516
- * Add the PreToolUse registration to `.claude/settings.json`, keeping everything else the
517
- * file carries — other registrations, other hook events, and unrelated keys alike. A
518
- * settings file with no `hooks` key at all is the commonest consumer state (it exists for
519
- * permissions alone), so the nesting is created here rather than assumed.
520
- */
521
- function mergeSettings(projectRoot, settings, report) {
522
- const settingsPath = join(projectRoot, SETTINGS_RELATIVE);
523
- const preToolUse = settings.hooks?.PreToolUse ?? [];
524
- if (carriesRegistration(settings)) {
525
- // Not rewriting is the point: a re-serialization would rewrite a consumer's formatting
526
- // on every run, which is an overwrite by another name.
527
- report.skipped.push(SETTINGS_RELATIVE);
528
- return;
529
- }
530
- settings.hooks = {
531
- ...settings.hooks,
532
- PreToolUse: [
533
- ...preToolUse,
534
- { matcher: HOOK_MATCHER, hooks: [{ type: 'command', command: HOOK_COMMAND }] },
535
- ],
536
- };
537
- writeFileSync(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
538
- // Read the registration back rather than assuming the write carried it. The one outcome
539
- // this installer must never produce is a successful-looking run whose judge never spawns,
540
- // and the merge can drop the entry without failing — a settings file whose root is an
541
- // array takes the assignment as a non-index property and `JSON.stringify` discards it.
542
- // Checking the file instead of the shapes that reach it keeps the question finite: one
543
- // code path, asked after every write, whatever arrived.
544
- if (!carriesRegistration(JSON.parse(readFileSync(settingsPath, 'utf-8')))) {
545
- throw new Error(`${SETTINGS_RELATIVE} in ${projectRoot} did not take the PreToolUse registration — ` +
546
- 'the judge would never be spawned. Fix that file and re-run');
547
- }
548
- report.created.push(SETTINGS_RELATIVE);
549
- }
550
- /**
551
- * Install the session surface into `spec.projectRoot`, skipping whatever is already there
552
- * and reporting both halves per artifact.
553
- *
554
- * Throws before any write when the package cannot be resolved from that root or when two
555
- * config spellings already coexist there — both leave zero files. Translating a throw into
556
- * exit 2 with the install command is the bin's job.
557
- */
558
- export function initClaudeCode(spec) {
559
- const resolvePolydeukes = spec.resolvePolydeukes ?? resolveFromProjectRoot;
560
- try {
561
- resolvePolydeukes(spec.projectRoot);
562
- }
563
- catch (error) {
564
- // The message names the package because the user's next action is installing it — the
565
- // seam's own message cannot be relied on to say so. The original is carried through
566
- // rather than discarded: "not exposed" and "not installed" need different actions, and
567
- // an experimental resolver can fail for reasons that are neither.
568
- throw new Error(`cannot use 'polydeukes' from ${spec.projectRoot} — install or update it there first ` +
569
- "(e.g. 'npm install --save-dev polydeukes'), then run this command again: " +
570
- `${error instanceof Error ? error.message : String(error)}`);
571
- }
572
- // Every read that can fail is settled before the first write.
573
- const settings = readSettings(spec.projectRoot);
574
- const report = scaffoldProject(spec.projectRoot);
575
- writeIfAbsent(spec.projectRoot, HOOK_RELATIVE, GENERATED_HOOK, report);
576
- mergeSettings(spec.projectRoot, settings, report);
577
- // Written last, after the registration the hook needs to ever be spawned. Every write
578
- // between the hook file and that registration widens the window where a throw leaves a
579
- // delegator nothing invokes — a tree that looks installed and is judged by nothing. These
580
- // two artifacts are the ones whose absence costs only discoverability, so they go where
581
- // a failure costs least.
582
- writeIfAbsent(spec.projectRoot, DISCOVERY_RELATIVE, GENERATED_DISCOVERY, report);
583
- writeIfAbsent(spec.projectRoot, SKILL_RELATIVE, GENERATED_SKILL, report);
584
- retargetGrokHookCommandToClaude(spec.projectRoot);
585
- return report;
586
- }
@@ -1,51 +0,0 @@
1
- /**
2
- * `initGrok` — the Grok session-surface installer.
3
- *
4
- * Preflight first, then the shared project-side scaffold, then the generated hook and the
5
- * `.grok/hooks` JSON registration. When a Claude delegator is already on disk, the JSON
6
- * command names that file instead of planting a second one — two command strings would
7
- * spawn two judges per call.
8
- *
9
- * Nothing existing is overwritten, with one command-field exception: a grok JSON whose
10
- * `command` is still the grok-mjs string is rewritten to the Claude-hook command when that
11
- * Claude file is on disk — otherwise grok-then-claude leaves two command strings. Any entry
12
- * naming the Claude-hook command also takes the matcher of the `.claude/settings.json` entry
13
- * carrying that command, because the host collapses the two registrations only when command
14
- * and matcher are byte-identical; with no such entry the matcher stays. Timeout stays either
15
- * way, and a command that is not the grok-mjs string is left byte-identical.
16
- *
17
- * Rules and skills are not copied; `.claude/settings.json` is not written.
18
- */
19
- import { type ScaffoldReport } from './scaffold-project.ts';
20
- /** `initGrok` input — the target tree and the preflight seam. */
21
- export type InitGrokSpec = {
22
- /** Project root to install into — every write below is relative to it. */
23
- projectRoot: string;
24
- /**
25
- * Preflight seam: throws when the package cannot be resolved from the given root.
26
- * ABSENT uses the real resolution, anchored at that root and nowhere else — anchoring it
27
- * at the installer's own module would answer for the installer's install graph rather
28
- * than the target project's, which is precisely the case that must fail.
29
- */
30
- resolvePolydeukes?: (projectRoot: string) => void;
31
- };
32
- /**
33
- * Rewrite the grok JSON `command` from the grok-mjs string to the Claude-hook string.
34
- *
35
- * The Claude installer calls this after writing its delegator; this installer calls it on
36
- * re-run when that file is already on disk. Only the installer-generated grok-mjs command
37
- * is rewritten; any other string is the consumer's spawn target and the file is not touched.
38
- * Every entry naming the Claude-hook command — rewritten now or by an earlier install — takes
39
- * the matcher the Claude settings file registered that command under, so the host sees one
40
- * pair rather than two and a re-run converges. Parse failure leaves the file as it was —
41
- * existence is presence, not parse success.
42
- */
43
- export declare function retargetGrokHookCommandToClaude(projectRoot: string): void;
44
- /**
45
- * Install the Grok session surface into `spec.projectRoot`, skipping whatever is already
46
- * there and reporting both halves per artifact.
47
- *
48
- * Throws before any write when the package cannot be resolved from that root — that leaves
49
- * zero files. Translating a throw into exit 2 with the install command is the bin's job.
50
- */
51
- export declare function initGrok(spec: InitGrokSpec): ScaffoldReport;