@erclx/canon 4.80.0 → 4.82.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 (39) hide show
  1. package/claude/.claude-plugin/plugin.json +1 -1
  2. package/claude/skills/design-extract/SKILL.md +5 -1
  3. package/claude/skills/sketch-design/REQUIREMENT.md +38 -0
  4. package/claude/skills/sketch-design/SKILL.md +92 -0
  5. package/claude/skills/teach-workspace/SKILL.md +23 -1
  6. package/claude/skills/teach-workspace/references/lesson-craft.md +11 -0
  7. package/docs/agents/commands.md +11 -5
  8. package/docs/agents/context-audit.md +1 -1
  9. package/docs/agents/context-classify.md +99 -0
  10. package/docs/agents/design-board.md +13 -11
  11. package/docs/agents/index.md +2 -1
  12. package/docs/agents/teach.md +16 -0
  13. package/docs/target-projects.md +15 -0
  14. package/docs/workflow/ai-workflow.md +4 -2
  15. package/docs/workflow/visual-design-workflow.md +1 -0
  16. package/governance/rules/claude/545-decisions.md +12 -0
  17. package/package.json +1 -1
  18. package/src/claude/cases/misc.ts +5 -0
  19. package/src/claude/seeds.ts +1 -0
  20. package/src/commands/claude.ts +26 -5
  21. package/src/commands/context.ts +425 -0
  22. package/src/commands/design.ts +24 -8
  23. package/src/commands/teach.ts +118 -0
  24. package/src/context/classify/extract.ts +450 -0
  25. package/src/context/classify/ollama.ts +172 -0
  26. package/src/context/classify/patterns.ts +114 -0
  27. package/src/context/classify/prompts.ts +73 -0
  28. package/src/context/classify/run.ts +348 -0
  29. package/src/context/classify/settings.ts +196 -0
  30. package/src/context/folders.ts +1 -0
  31. package/src/design/board.ts +130 -47
  32. package/src/project-root.ts +16 -0
  33. package/src/surface-root.ts +1 -0
  34. package/src/teach/render.ts +126 -0
  35. package/standards/decisions.md +100 -0
  36. package/standards/index.md +1 -0
  37. package/tooling/claude/reference.md +1 -0
  38. package/tooling/claude/seeds/CLAUDE.md +1 -0
  39. package/tooling/claude/seeds/canon/decisions/index.md +8 -0
@@ -0,0 +1,172 @@
1
+ /**
2
+ * The local Ollama backend: a reachability probe and one chat call per item.
3
+ *
4
+ * One chunk or section per call, never batched. The groundwork spike measured
5
+ * batching 16 hunks into a single call returning KEEP for every one, so a
6
+ * caller here (`run.ts`) invokes `chat` once per item rather than folding a
7
+ * set into one prompt.
8
+ */
9
+
10
+ export const DEFAULT_OLLAMA_BASE_URL = 'http://localhost:11434'
11
+
12
+ /**
13
+ * Nothing in the groundwork pins a request timeout: the spike scripts used a
14
+ * 600s ceiling meant for a batch research run, not a per-call budget for an
15
+ * interactive verb. 30s is chosen here as a deviation, wide enough that a
16
+ * shared GPU under another local session's load (measured coexisting at 12GB)
17
+ * still has room, while short enough that a `docs-fold` run does not hang
18
+ * indefinitely on a backend that stopped responding mid-call.
19
+ */
20
+ export const OLLAMA_TIMEOUT_MS = 30_000
21
+
22
+ /** Parsed straight off the model's own JSON, upper-cased for a loose model. */
23
+ export interface ParsedVerdict {
24
+ readonly verdict: string
25
+ readonly quote: string
26
+ readonly reason: string
27
+ }
28
+
29
+ export type ChatOutcome =
30
+ | {
31
+ readonly kind: 'ok'
32
+ readonly parsed: ParsedVerdict
33
+ readonly raw: string
34
+ }
35
+ | { readonly kind: 'unparsed'; readonly raw: string }
36
+ | { readonly kind: 'unreachable'; readonly message: string }
37
+ | { readonly kind: 'timeout' }
38
+
39
+ function describeError(error: unknown): string {
40
+ return error instanceof Error ? error.message : String(error)
41
+ }
42
+
43
+ function isTimeout(error: unknown): boolean {
44
+ return error instanceof DOMException && error.name === 'TimeoutError'
45
+ }
46
+
47
+ /**
48
+ * Reads the model's reply out of its own JSON body.
49
+ *
50
+ * Ported from `classify.py`'s `_parse`: find the first `{` and the last `}`,
51
+ * so a model that wraps its JSON in a sentence or a fence still parses. Diff
52
+ * mode returns a single `quote` string and sweep mode returns a `quotes`
53
+ * array, and both are read here since the caller decides which mode it asked
54
+ * for by which prompt it sent, not by which shape came back.
55
+ */
56
+ export function parseVerdictText(text: string): ParsedVerdict | undefined {
57
+ const start = text.indexOf('{')
58
+ const end = text.lastIndexOf('}')
59
+ if (start === -1 || end === -1 || end < start) return undefined
60
+
61
+ let data: unknown
62
+ try {
63
+ data = JSON.parse(text.slice(start, end + 1))
64
+ } catch {
65
+ return undefined
66
+ }
67
+
68
+ if (typeof data !== 'object' || data === null) return undefined
69
+ const record = data as Record<string, unknown>
70
+
71
+ const verdict = record.verdict
72
+ if (typeof verdict !== 'string' || verdict === '') return undefined
73
+
74
+ const quote =
75
+ typeof record.quote === 'string'
76
+ ? record.quote
77
+ : Array.isArray(record.quotes)
78
+ ? record.quotes.map((entry) => String(entry)).join(' | ')
79
+ : ''
80
+
81
+ const reason = typeof record.reason === 'string' ? record.reason : ''
82
+
83
+ return { verdict: verdict.toUpperCase(), quote, reason }
84
+ }
85
+
86
+ /**
87
+ * Whether the backend answers at all, checked before the real call so a
88
+ * per-item timeout is never the thing that discovers an unreachable Ollama.
89
+ */
90
+ export async function probeOllama(
91
+ baseUrl: string,
92
+ timeoutMs = OLLAMA_TIMEOUT_MS,
93
+ ): Promise<boolean> {
94
+ try {
95
+ const response = await fetch(`${baseUrl}/api/tags`, {
96
+ signal: AbortSignal.timeout(timeoutMs),
97
+ })
98
+ return response.ok
99
+ } catch {
100
+ return false
101
+ }
102
+ }
103
+
104
+ /**
105
+ * One chat call: JSON output format, temperature 0, thinking off.
106
+ *
107
+ * Thinking is always off. The groundwork spike measured it never catching a
108
+ * flag thinking-off missed, at roughly five times the latency, and in sweep
109
+ * mode it lost three real flags by reasoning itself past them. There is no
110
+ * option to turn it on here, matching the groundwork decision to defer that
111
+ * rather than build an unused knob.
112
+ */
113
+ export async function chat(opts: {
114
+ readonly baseUrl: string
115
+ readonly model: string
116
+ readonly system: string
117
+ readonly user: string
118
+ readonly timeoutMs?: number
119
+ }): Promise<ChatOutcome> {
120
+ const timeoutMs = opts.timeoutMs ?? OLLAMA_TIMEOUT_MS
121
+
122
+ let response: Response
123
+ try {
124
+ response = await fetch(`${opts.baseUrl}/api/chat`, {
125
+ method: 'POST',
126
+ headers: { 'Content-Type': 'application/json' },
127
+ body: JSON.stringify({
128
+ model: opts.model,
129
+ stream: false,
130
+ think: false,
131
+ format: 'json',
132
+ options: { temperature: 0, num_ctx: 16384 },
133
+ messages: [
134
+ { role: 'system', content: opts.system },
135
+ { role: 'user', content: opts.user },
136
+ ],
137
+ }),
138
+ signal: AbortSignal.timeout(timeoutMs),
139
+ })
140
+ } catch (error) {
141
+ if (isTimeout(error)) return { kind: 'timeout' }
142
+ return { kind: 'unreachable', message: describeError(error) }
143
+ }
144
+
145
+ if (!response.ok) {
146
+ return {
147
+ kind: 'unreachable',
148
+ message: `ollama returned ${response.status}`,
149
+ }
150
+ }
151
+
152
+ let body: unknown
153
+ try {
154
+ body = await response.json()
155
+ } catch (error) {
156
+ return { kind: 'unparsed', raw: describeError(error) }
157
+ }
158
+
159
+ const content =
160
+ typeof body === 'object' && body !== null
161
+ ? (body as { message?: { content?: unknown } }).message?.content
162
+ : undefined
163
+
164
+ if (typeof content !== 'string') {
165
+ return { kind: 'unparsed', raw: JSON.stringify(body) }
166
+ }
167
+
168
+ const parsed = parseVerdictText(content)
169
+ return parsed === undefined
170
+ ? { kind: 'unparsed', raw: content }
171
+ : { kind: 'ok', parsed, raw: content }
172
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Regex layer for the doc classifier, ported from the groundwork spike at
3
+ * `.canon/groundwork/93-canonical-doc-drift/scripts/heuristic.py`. It never
4
+ * needs a model installed, so it is the layer that always runs.
5
+ *
6
+ * Diff mode reads one changed chunk and answers KEEP, HISTORY, or MOVE. It
7
+ * never answers REPLACE, since telling a restated figure from a genuinely new
8
+ * one needs the section the hunk landed in, which the model layer reads and
9
+ * this one does not. Sweep mode reads one whole section and answers KEEP,
10
+ * REWRITE, or MOVE, collapsing REPLACE and HISTORY the way the sweep prompt
11
+ * does, since a section already carries its own history in view.
12
+ */
13
+
14
+ export type DiffVerdict = 'KEEP' | 'REPLACE' | 'HISTORY' | 'MOVE'
15
+ export type SweepVerdict = 'KEEP' | 'REWRITE' | 'MOVE'
16
+
17
+ export interface PatternVerdict<V extends string> {
18
+ readonly verdict: V
19
+ /** Absent on KEEP, since nothing decided against the text. */
20
+ readonly quote?: string
21
+ readonly reason: string
22
+ }
23
+
24
+ /**
25
+ * Narrates how a fact got here rather than stating it: a branch or PR name, a
26
+ * closed or retired marker, a review-pass story. Ported from
27
+ * `heuristic.py`'s `NARRATION` pattern with one change: the bare
28
+ * `on \d{4}-\d{2}-\d{2}` alternative is dropped.
29
+ *
30
+ * That alternative was measured to false-flag a gotcha ending "Measured at
31
+ * `<sha>` on <date>.", a dating anchor both prompts call correct on a current
32
+ * statement. Every tuned hunk the bare date branch caught also carries a
33
+ * narration verb elsewhere in the same text (`closed on`, `moved again`,
34
+ * `did not survive`), so dropping it costs no measured catch and removes the
35
+ * one measured false flag.
36
+ */
37
+ const NARRATION =
38
+ /moved (again|twice|on)|has since|at this branch|on `feat|Measured in PR|did not survive|the operator picked|picked arm|\barm \d|closed on|was retired|no longer|used to|\bround\b|a review pass|this pass/i
39
+
40
+ /**
41
+ * A source-file path inside prose, the shape of implementation detail landing
42
+ * on a surface that should describe layout and intent instead. Ported
43
+ * verbatim from `heuristic.py`.
44
+ */
45
+ const MECHANISM_IN_WIREFRAME = /`[\w./-]+\.(tsx?|py|css|spec\.ts)`/
46
+
47
+ function narrationQuote(text: string): string | undefined {
48
+ return text.match(NARRATION)?.[0]
49
+ }
50
+
51
+ /**
52
+ * Classifies one diff-mode chunk from its added text alone.
53
+ *
54
+ * `file` decides whether the wireframe-only MOVE test applies. A file argument
55
+ * rather than a boolean matches `run.ts`'s other call sites, which hold the
56
+ * path and not a pre-computed flag.
57
+ */
58
+ export function diffPatternVerdict(
59
+ file: string,
60
+ added: string,
61
+ ): PatternVerdict<DiffVerdict> {
62
+ const quote = narrationQuote(added)
63
+ if (quote !== undefined) {
64
+ return { verdict: 'HISTORY', quote, reason: 'narrates how this got here' }
65
+ }
66
+
67
+ if (file.includes('wireframes/')) {
68
+ const match = added.match(MECHANISM_IN_WIREFRAME)
69
+ if (match) {
70
+ return {
71
+ verdict: 'MOVE',
72
+ quote: match[0],
73
+ reason: 'names a source file, which is implementation detail',
74
+ }
75
+ }
76
+ }
77
+
78
+ return { verdict: 'KEEP', reason: 'no narration or wrong-surface pattern' }
79
+ }
80
+
81
+ /**
82
+ * Classifies one sweep-mode section from its whole body.
83
+ *
84
+ * REWRITE stands in for both REPLACE and HISTORY, matching `sweep-v1.md`'s
85
+ * own three-verdict vocabulary: a section already shows its own history in
86
+ * full view, so the model layer does not need the diff-mode split and the
87
+ * regex layer follows it.
88
+ */
89
+ export function sweepPatternVerdict(
90
+ file: string,
91
+ body: string,
92
+ ): PatternVerdict<SweepVerdict> {
93
+ const quote = narrationQuote(body)
94
+ if (quote !== undefined) {
95
+ return {
96
+ verdict: 'REWRITE',
97
+ quote,
98
+ reason: 'carries its own history rather than the current state alone',
99
+ }
100
+ }
101
+
102
+ if (file.includes('wireframes/')) {
103
+ const match = body.match(MECHANISM_IN_WIREFRAME)
104
+ if (match) {
105
+ return {
106
+ verdict: 'MOVE',
107
+ quote: match[0],
108
+ reason: 'names a source file, which is implementation detail',
109
+ }
110
+ }
111
+ }
112
+
113
+ return { verdict: 'KEEP', reason: 'no narration or wrong-surface pattern' }
114
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * System prompts and user-message builders for the model layer, ported
3
+ * verbatim as data from the groundwork spike at
4
+ * `.canon/groundwork/93-canonical-doc-drift/scripts/prompts/v3.md` (diff
5
+ * mode) and `sweep-v1.md` (sweep mode). Neither prompt text is invented here.
6
+ *
7
+ * Each prompt already states its own rules per canonical doc type inside one
8
+ * string, which is the shape the spike measured, so there is one prompt per
9
+ * mode rather than one per doc type.
10
+ */
11
+
12
+ export const DIFF_SYSTEM_PROMPT = `You review one hunk just added to a project's canonical documentation. The docs state the project AS IT STANDS NOW. Judge only the ADDED text.
13
+
14
+ File types and what they hold:
15
+ - context/<domain>.md: one domain's structure, decisions (choice + the alternative that lost), gotchas. No history of how the domain got here, no change numbers, branch names, or dates attached to a change.
16
+ - ARCHITECTURE.md: cross-domain decisions only, each a few sentences: what was chosen, over what, why. A measurement or mechanism specific to one domain belongs in that domain's context entry. Loaded every session, so weight matters.
17
+ - wireframes/<surface>.md: layout sketches, reachable states, exact on-screen copy, interaction intent. Would the line still be true if the surface were rebuilt in another framework? Component names, test files, pixel constants, and mechanism belong in context.
18
+ - DESIGN.md: tokens and visual rules, current state only.
19
+
20
+ Verdicts (pick exactly one):
21
+ - KEEP: states current design, a rule, copy, a decision with its rejected alternative, or a live gotcha, on the right surface.
22
+ - REPLACE: restates a fact or figure the existing section already carries ("moved again", "now", "the count moved", a newer number appended after an older one). The old statement should be rewritten in place, not appended to.
23
+ - HISTORY: narrates how things got here: which branch/PR changed what, "closed on", "did not survive", review-pass stories, pick-by-pick rounds. The current state is what belongs; the trail goes to the PR or a decision log.
24
+ - MOVE: correct content on the wrong surface (domain mechanism in ARCHITECTURE.md, implementation detail in a wireframe).
25
+
26
+ Return only JSON: {"verdict": "...", "quote": "<the shortest added phrase that decided it>", "reason": "<one sentence>"}
27
+
28
+ Decision checks, in order:
29
+ 1. If the hunk REMOVED text and the added text is the same statement rewritten (a table row, a figure, a sentence updated in place), that is the correct way to update: KEEP, unless the new wording itself narrates history.
30
+ 2. A trailing "Measured at <sha> on <date>" or a branch name does not make a sentence current. If the section already carries an earlier figure or statement on the same subject and the hunk removed nothing, the answer is REPLACE.
31
+ 3. Judge only what the added text says. Narration elsewhere in the section is not evidence about this hunk.
32
+ `
33
+
34
+ export const SWEEP_SYSTEM_PROMPT = `You review one whole section of a project's canonical documentation, as it stands today. The docs must state the project AS IT IS NOW, once, on the right surface.
35
+
36
+ File types and what they hold:
37
+ - context/<domain>.md: one domain's structure, decisions (choice + the alternative that lost), gotchas. No history of how the domain got here, no change numbers, branch names, or dates attached to a change.
38
+ - ARCHITECTURE.md: cross-domain decisions only, each a few sentences: what was chosen, over what, why. A measurement or mechanism specific to one domain belongs in that domain's context entry.
39
+ - wireframes/<surface>.md: layout, reachable states, exact on-screen copy, interaction intent. Would the line still be true if the surface were rebuilt in another framework? Component names, test files, and pixel constants belong in context.
40
+ - DESIGN.md: tokens and visual rules, current state only.
41
+ - REQUIREMENTS.md: problem, goals, non-goals, scope, constraints. Never measured results.
42
+
43
+ Verdicts (pick exactly one):
44
+ - KEEP: the section states the current design, rules, copy, or decisions once, on the right surface. A single commit anchor on a figure is fine.
45
+ - REWRITE: the section carries its own history: a figure followed by a later corrected figure, "superseded", "now", "moved", "no longer", "reverses the earlier reading", branch or PR narration, pick-by-pick rounds, a heading that narrates an event. The subject belongs here, but it must be restated as the current state.
46
+ - MOVE: the section, or most of it, belongs on another surface (results in requirements, one domain's mechanism in architecture, implementation detail in a wireframe).
47
+
48
+ Decision checks, in order:
49
+ 1. Judge what the text says, not how long it is. A long section that states current design once is KEEP.
50
+ 2. A trailing "Measured at <sha> on <date>" does not make a paragraph current if another paragraph in the section states an older value on the same subject.
51
+ 3. Short rationale for a current rule ("the form checks length itself because...") is KEEP. A story of the rounds that produced the rule is REWRITE.
52
+
53
+ Return only JSON: {"verdict": "...", "quotes": ["<up to three short phrases copied from the section that decided it>"], "reason": "<one sentence>"}
54
+ `
55
+
56
+ /** Ported from `classify.py`'s `_user_message`, the unmarked diff-mode branch. */
57
+ export function diffUserMessage(opts: {
58
+ readonly file: string
59
+ readonly removed: string
60
+ readonly added: string
61
+ readonly sectionAfter: string
62
+ }): string {
63
+ const removed = opts.removed === '' ? '(nothing)' : opts.removed
64
+ return `FILE: ${opts.file}\n\nREMOVED IN THIS HUNK:\n${removed}\n\nADDED IN THIS HUNK:\n${opts.added}\n\nTHE SECTION AFTER THE CHANGE (for context):\n${opts.sectionAfter}`
65
+ }
66
+
67
+ /** Ported from `classify.py`'s `_user_message`, the sweep-mode branch. */
68
+ export function sweepUserMessage(opts: {
69
+ readonly file: string
70
+ readonly body: string
71
+ }): string {
72
+ return `FILE: ${opts.file}\n\nSECTION:\n${opts.body}`
73
+ }