codeassembly-guidance 0.0.0 → 0.1.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 (204) hide show
  1. package/.meta/changelog.json +563 -0
  2. package/CHANGELOG.md +134 -0
  3. package/LICENSE +7 -0
  4. package/README.md +165 -1
  5. package/content/_partials/README.md +192 -0
  6. package/content/_partials/code-descriptions.md +4 -0
  7. package/content/_partials/code-style.md +7 -0
  8. package/content/_partials/comment-discipline.md +89 -0
  9. package/content/_partials/concision.md +3 -0
  10. package/content/_partials/diff-audit-checklist.md +9 -0
  11. package/content/_partials/file-access.md +4 -0
  12. package/content/_partials/live-repo-writes.md +13 -0
  13. package/content/_partials/plain-speech-calibration.md +66 -0
  14. package/content/_partials/plain-speech.md +13 -0
  15. package/content/_partials/prose-line-breaks.md +3 -0
  16. package/content/_partials/record-marker.md +1 -0
  17. package/content/_partials/reduced-object-relative.md +28 -0
  18. package/content/_partials/shell-commands.md +3 -0
  19. package/content/_partials/target-file-set-resolution.md +22 -0
  20. package/content/_partials/technical-recommendations.md +5 -0
  21. package/content/_partials/test-structure-audit-checklist.md +7 -0
  22. package/content/_partials/ticket-assessment-baseline.md +12 -0
  23. package/content/_partials/ticket-assessment.md +202 -0
  24. package/content/_partials/work-type-choice.md +13 -0
  25. package/content/codeassembly-content.yaml +49 -0
  26. package/content/collections/all.md +11 -0
  27. package/content/collections/atlassian.md +16 -0
  28. package/content/collections/recommended.md +34 -0
  29. package/content/collections/triage.md +77 -0
  30. package/content/collections/williamthorsen.md +25 -0
  31. package/content/guidance/README.md +22 -0
  32. package/content/guidance/_harnesses/claude/CLAUDE.md +6 -0
  33. package/content/guidance/_harnesses/rovo/AGENTS.md +5 -0
  34. package/content/guidance/_harnesses/rovo/codeassembly-guidance.md +4 -0
  35. package/content/guidance/rulebooks/accessibility-conventions.md +20 -0
  36. package/content/guidance/rulebooks/codeassembly-content-specification.md +161 -0
  37. package/content/guidance/rulebooks/command-output-conventions.md +14 -0
  38. package/content/guidance/rulebooks/commit-conventions.md +72 -0
  39. package/content/guidance/rulebooks/generated-content-policy.md +10 -0
  40. package/content/guidance/rulebooks/live-worktree-policy.md +18 -0
  41. package/content/guidance/rulebooks/readme-conventions.md +74 -0
  42. package/content/guidance/rulebooks/shared-data-conventions.md +14 -0
  43. package/content/guidance/rulebooks/shell-conventions.md +279 -0
  44. package/content/guidance/rulebooks/williamthorsen-code-layout-preferences.md +102 -0
  45. package/content/guidance/rulebooks/williamthorsen-collaboration-preferences.md +58 -0
  46. package/content/guidance/rulebooks/williamthorsen-comment-preferences.md +30 -0
  47. package/content/guidance/rulebooks/williamthorsen-subagent-model-preferences.md +15 -0
  48. package/content/guidance/rulebooks/williamthorsen-ticketing-preferences.md +22 -0
  49. package/content/guidance/rulebooks/williamthorsen-tooling-preferences.md +36 -0
  50. package/content/guidance/rulebooks/williamthorsen-typescript-preferences.md +90 -0
  51. package/content/guidance/rulebooks/williamthorsen-workflow-preferences.md +58 -0
  52. package/content/guidance/rulebooks/williamthorsen-writing-preferences.md +80 -0
  53. package/content/guidance/shared/AGENTS.md +43 -0
  54. package/content/scripts/README.md +41 -0
  55. package/content/scripts/describe-change.mjs +165 -0
  56. package/content/scripts/get-ticket-id.sh +131 -0
  57. package/content/scripts/manage-jira-ticket.mjs +209 -0
  58. package/content/scripts/resolve-frontmatter.sh +540 -0
  59. package/content/scripts/resolve-review-run.mjs +12 -0
  60. package/content/scripts/select-lede-exemplars.mjs +208 -0
  61. package/content/skills/_data/action-items.md +83 -0
  62. package/content/skills/_data/artifact-conventions.md +969 -0
  63. package/content/skills/_data/bitbucket-pr-access.md +89 -0
  64. package/content/skills/_data/branch-format.md +34 -0
  65. package/content/skills/_data/change-record.md +163 -0
  66. package/content/skills/_data/complexity-classification.md +58 -0
  67. package/content/skills/_data/concision.md +23 -0
  68. package/content/skills/_data/deployed-file-provenance.md +46 -0
  69. package/content/skills/_data/design-priorities.md +76 -0
  70. package/content/skills/_data/gh-body-file.md +30 -0
  71. package/content/skills/_data/git-commands.md +39 -0
  72. package/content/skills/_data/naming-conventions.md +50 -0
  73. package/content/skills/_data/pr-resolution.md +25 -0
  74. package/content/skills/_data/pr-source-resolution.md +36 -0
  75. package/content/skills/_data/recommendation-gradient.md +90 -0
  76. package/content/skills/_data/scope-and-deferral.md +83 -0
  77. package/content/skills/_data/spike-conventions.md +89 -0
  78. package/content/skills/_data/ticket-evaluation.md +13 -0
  79. package/content/skills/_data/ticket-id-extraction.md +43 -0
  80. package/content/skills/_data/ticket-source-resolution.md +147 -0
  81. package/content/skills/_data/title-templates.md +624 -0
  82. package/content/skills/_data/title-voice.md +17 -0
  83. package/content/skills/_data/work-types.json +168 -0
  84. package/content/skills/_partials/acceptance-criteria-scaffold.md +15 -0
  85. package/content/skills/_partials/action-items.md +22 -0
  86. package/content/skills/_partials/bitbucket-delete-both-refusal.md +3 -0
  87. package/content/skills/_partials/commit-title-rendering.md +14 -0
  88. package/content/skills/_partials/gh-body-file.md +22 -0
  89. package/content/skills/_partials/nested-list-indent.md +9 -0
  90. package/content/skills/_partials/next-steps-after-plan.md +99 -0
  91. package/content/skills/_partials/next-steps-after-review.md +350 -0
  92. package/content/skills/_partials/option-format.md +84 -0
  93. package/content/skills/_partials/plan-template.md +97 -0
  94. package/content/skills/_partials/split-launch-prompts.md +5 -0
  95. package/content/skills/_partials/split-ticket-compose.md +5 -0
  96. package/content/skills/_partials/split-ticket-create.md +3 -0
  97. package/content/skills/_partials/ticket-and-plan-completeness.md +33 -0
  98. package/content/skills/_partials/ticket-concision.md +18 -0
  99. package/content/skills/_partials/ticket-criteria-conventions.md +7 -0
  100. package/content/skills/_partials/ticket-placement.md +14 -0
  101. package/content/skills/_partials/ticket-skeleton-tiers.md +6 -0
  102. package/content/skills/_partials/ticket-skeleton.md +13 -0
  103. package/content/skills/add-change-record/SKILL.md +136 -0
  104. package/content/skills/add-test-ids/SKILL.md +51 -0
  105. package/content/skills/align-ticket-with-implementation/SKILL.md +115 -0
  106. package/content/skills/anti-patterns/SKILL.md +57 -0
  107. package/content/skills/assess-ticket/SKILL.md +46 -0
  108. package/content/skills/assess-ticket/next-steps-after-assessment.md +98 -0
  109. package/content/skills/brainstorming/SKILL.md +107 -0
  110. package/content/skills/capture-event/SKILL.md +108 -0
  111. package/content/skills/capture-event/capture-event.mjs +216 -0
  112. package/content/skills/capture-feedback/SKILL.md +71 -0
  113. package/content/skills/capture-lede-decision/SKILL.md +163 -0
  114. package/content/skills/capture-lede-decision/capture-lede-decision.mjs +231 -0
  115. package/content/skills/classify-complexity/SKILL.md +92 -0
  116. package/content/skills/collaborate/SKILL.md +86 -0
  117. package/content/skills/condense-branch/SKILL.md +83 -0
  118. package/content/skills/create-bitbucket-pr/SKILL.md +87 -0
  119. package/content/skills/create-commit/SKILL.md +65 -0
  120. package/content/skills/create-devlog/SKILL.md +108 -0
  121. package/content/skills/create-gh-pr/SKILL.md +106 -0
  122. package/content/skills/create-pr/SKILL.md +150 -0
  123. package/content/skills/create-ticket/SKILL.md +350 -0
  124. package/content/skills/derive-session-context/derive-session-context.mjs +148 -0
  125. package/content/skills/design-and-plan/SKILL.md +194 -0
  126. package/content/skills/development-workflows/SKILL.md +41 -0
  127. package/content/skills/get-ticket-id/SKILL.md +67 -0
  128. package/content/skills/groom-backlog/SKILL.md +245 -0
  129. package/content/skills/groom-backlog/groom-backlog.mjs +106 -0
  130. package/content/skills/implement-plan/SKILL.md +164 -0
  131. package/content/skills/index-prototypes/SKILL.md +145 -0
  132. package/content/skills/index-prototypes/index-prototypes.mjs +328 -0
  133. package/content/skills/kb-add/SKILL.md +156 -0
  134. package/content/skills/kb-add/kb-add.mjs +216 -0
  135. package/content/skills/kb-curate/SKILL.md +117 -0
  136. package/content/skills/kb-curate/kb-curate.mjs +213 -0
  137. package/content/skills/kb-edit/SKILL.md +128 -0
  138. package/content/skills/kb-edit/kb-edit.mjs +219 -0
  139. package/content/skills/kb-retrieve/SKILL.md +100 -0
  140. package/content/skills/kb-retrieve/kb-retrieve.mjs +206 -0
  141. package/content/skills/kb-retrieve-events/SKILL.md +98 -0
  142. package/content/skills/kb-retrieve-events/kb-retrieve-events.mjs +206 -0
  143. package/content/skills/kb-update-events/SKILL.md +77 -0
  144. package/content/skills/kb-update-events/kb-update-events.mjs +215 -0
  145. package/content/skills/merge-bb-pr/SKILL.md +136 -0
  146. package/content/skills/merge-gh-pr/SKILL.md +167 -0
  147. package/content/skills/merge-gh-pr/merge-gh-pr.mjs +10 -0
  148. package/content/skills/merge-pr/SKILL.md +368 -0
  149. package/content/skills/migrate-feedback-memories/SKILL.md +136 -0
  150. package/content/skills/migrate-feedback-memories/feedback-memories.mjs +161 -0
  151. package/content/skills/people-report/SKILL.md +208 -0
  152. package/content/skills/plan/SKILL.md +87 -0
  153. package/content/skills/prepare-prototype-brief/SKILL.md +126 -0
  154. package/content/skills/pull-from-backlog/SKILL.md +83 -0
  155. package/content/skills/pull-from-backlog/pull-from-backlog.mjs +208 -0
  156. package/content/skills/refine-plan/SKILL.md +259 -0
  157. package/content/skills/respond-to-review/SKILL.md +292 -0
  158. package/content/skills/review-bb-pr/SKILL.md +161 -0
  159. package/content/skills/review-branch/SKILL.md +301 -0
  160. package/content/skills/review-criteria/SKILL.md +108 -0
  161. package/content/skills/review-gh-pr/SKILL.md +155 -0
  162. package/content/skills/review-gh-pr/select-pr-ticket.mjs +8 -0
  163. package/content/skills/review-permissions/SKILL.md +39 -0
  164. package/content/skills/review-pr/SKILL.md +123 -0
  165. package/content/skills/revise-comments/SKILL.md +115 -0
  166. package/content/skills/revise-prose/SKILL.md +197 -0
  167. package/content/skills/revise-prose/revise-prose.mjs +229 -0
  168. package/content/skills/save-artifact/SKILL.md +69 -0
  169. package/content/skills/save-plan/SKILL.md +55 -0
  170. package/content/skills/software-engineering/SKILL.md +74 -0
  171. package/content/skills/streamline-guidance/SKILL.md +174 -0
  172. package/content/skills/streamline-guidance/streamline-guidance.mjs +211 -0
  173. package/content/skills/summarize-change/SKILL.md +308 -0
  174. package/content/skills/summarize-chat/SKILL.md +100 -0
  175. package/content/skills/systematic-debugging/SKILL.md +308 -0
  176. package/content/skills/systematic-debugging/condition-based-waiting-example.ts +160 -0
  177. package/content/skills/systematic-debugging/condition-based-waiting.md +122 -0
  178. package/content/skills/systematic-debugging/defense-in-depth.md +130 -0
  179. package/content/skills/systematic-debugging/find-polluter.sh +68 -0
  180. package/content/skills/systematic-debugging/root-cause-tracing.md +185 -0
  181. package/content/skills/systematic-debugging/test-academic.md +16 -0
  182. package/content/skills/systematic-debugging/test-pressure-1.md +67 -0
  183. package/content/skills/systematic-debugging/test-pressure-2.md +77 -0
  184. package/content/skills/systematic-debugging/test-pressure-3.md +77 -0
  185. package/content/skills/testing-conventions/SKILL.md +168 -0
  186. package/content/skills/testing-conventions/mistakes.md +1 -0
  187. package/content/skills/typescript-testing-conventions/SKILL.md +129 -0
  188. package/content/skills/update-jira-ticket/SKILL.md +245 -0
  189. package/content/skills/update-jira-ticket/update-jira-ticket.mjs +9 -0
  190. package/content/skills/update-project-guidance/SKILL.md +300 -0
  191. package/content/skills/upgrade-dependencies/SKILL.md +139 -0
  192. package/content/skills/wrap-up/SKILL.md +431 -0
  193. package/content/subagents/_data/claude.yaml +19 -0
  194. package/content/subagents/_data/rovo.yaml +31 -0
  195. package/content/subagents/canary.md +11 -0
  196. package/content/subagents/entry-drafter.md +187 -0
  197. package/content/subagents/handoff-reviewer.md +75 -0
  198. package/content/subagents/plan-reviewer.md +184 -0
  199. package/content/subagents/plan-reviser.md +88 -0
  200. package/content/subagents/prose-reviser.md +130 -0
  201. package/content/subagents/ticket-assessor.md +139 -0
  202. package/package.json +70 -2
  203. package/schemas/preferences.v1.json +294 -0
  204. package/schemas/work-types.v1.json +142 -0
@@ -0,0 +1,328 @@
1
+ import { createRequire as __cjsCreateRequire } from 'node:module';
2
+ const require = __cjsCreateRequire(import.meta.url);
3
+ var G=Object.defineProperty;var i=(e,t)=>G(e,"name",{value:t,configurable:!0});import{realpathSync as B}from"node:fs";import{mkdir as pe,readFile as me,writeFile as he}from"node:fs/promises";import y from"node:path";import g from"node:process";import{fileURLToPath as be}from"node:url";function R(e){return e instanceof Error||Object.prototype.toString.call(e)==="[object Error]"}i(R,"isError");function x(e){try{return R(e)&&typeof e.message=="string"&&e.message!==""?e.message:String(e)}catch{return"[unstringifiable value]"}}i(x,"describeError");function M(e,t){let r=[],n=[];for(let o=0;o<e.length;o+=1){let s=e[o];if(s===void 0)continue;if(!s.startsWith("--")){r.push(s);continue}let c=H(s,t);if(c===null)throw new Error(`unknown flag: ${s}`);let{spec:d,inlineValue:a}=c;if(!d.takesValue){if(a!==null)throw new Error(`--${d.name} does not take a value`);n.push({name:d.name,value:null});continue}if(a!==null){n.push({name:d.name,value:a});continue}let l=e[o+1]??null;if(l===null||l.startsWith("--"))throw new Error(`--${d.name} requires a value`);n.push({name:d.name,value:l}),o+=1}return{positionals:r,flags:n}}i(M,"scanFlags");function P(e){let t={};for(let{name:r,value:n}of e)n!==null&&(t[r]=n);return t}i(P,"valueFlagMap");function H(e,t){for(let r of t)for(let n of[r.name,...r.aliases??[]]){let o=`--${n}`;if(e===o)return{spec:r,inlineValue:null};if(e.startsWith(`${o}=`))return{spec:r,inlineValue:e.slice(o.length+1)}}return null}i(H,"matchFlag");function Y(e,t){return T(e)&&e.code===t}i(Y,"isErrorCode");function p(e){return Y(e,"ENOENT")}i(p,"isEnoent");function $(e){return T(e)&&!Array.isArray(e)}i($,"isRecord");function T(e){return typeof e=="object"&&e!==null}i(T,"isObject");import{copyFile as J,mkdir as X,readFile as Q}from"node:fs/promises";import j from"node:path";var C=Buffer.from([137,80,78,71,13,10,26,10]);async function I(e){let t;try{t=await Q(e.sourcePath)}catch(o){if(p(o))return{ok:!1,error:"screenshot-not-found",message:`no screenshot at ${e.sourcePath}`};throw o}if(!t.subarray(0,C.length).equals(C))return{ok:!1,error:"not-png",message:`${e.sourcePath} is not a PNG file`};let r=j.join("shots",`${e.slug}-v${e.version}.png`),n=j.join(e.setDir,r);return await X(j.dirname(n),{recursive:!0}),await J(e.sourcePath,n),{ok:!0,shot:r}}i(I,"intakeScreenshot");import{mkdir as Z,readFile as ee,rename as te,rm as re,writeFile as ne}from"node:fs/promises";import V from"node:path";import ie from"node:process";var O="manifest.json",oe=/^[a-z0-9][a-z0-9-]{0,39}$/;function _(e){return oe.test(e)}i(_,"isValidSlug");function L(e){let t=new Map;for(let r of e.entries){let n=t.get(r.slug);(n===void 0||r.version>n.version)&&t.set(r.slug,r)}return t.values().toArray()}i(L,"listLatestEntries");function F(e,t){let r=e?.entries??[],n=0;for(let o of r)o.slug===t&&o.version>n&&(n=o.version);return n+1}i(F,"nextVersion");async function k(e){let t=q(e),r;try{r=await ee(t,"utf8")}catch(o){if(p(o))return{kind:"missing"};throw o}let n;try{n=JSON.parse(r)}catch{return{kind:"invalid",message:`${t} is not valid JSON`}}return ae(n)?{kind:"ok",manifest:n}:{kind:"invalid",message:`${t} does not have the manifest layout`}}i(k,"readManifest");function q(e){return V.join(e,O)}i(q,"resolveManifestPath");async function A(e,t){await Z(e,{recursive:!0});let r=q(e),n=V.join(e,`.${O}.${ie.pid}.${Date.now()}.tmp`);try{await ne(n,`${JSON.stringify(t,null,2)}
4
+ `,"utf8"),await te(n,r)}catch(o){throw await re(n,{force:!0}),o}return r}i(A,"writeManifest");function ae(e){return $(e)?typeof e.title=="string"&&(e.indexUrl===null||typeof e.indexUrl=="string")&&Array.isArray(e.entries)&&e.entries.every(t=>se(t)):!1}i(ae,"isManifest");function se(e){return $(e)?typeof e.slug=="string"&&typeof e.version=="number"&&Number.isSafeInteger(e.version)&&typeof e.registeredAt=="string"&&typeof e.title=="string"&&typeof e.url=="string"&&v(e.source)&&v(e.lens)&&Array.isArray(e.inputs)&&e.inputs.every(t=>typeof t=="string")&&v(e.description)&&v(e.shot):!1}i(se,"isManifestEntry");function v(e){return e===null||typeof e=="string"}i(v,"isNullableString");var ce="verdicts";var W=`(() => {
5
+ 'use strict';
6
+ const COLLECTION = '${ce}';
7
+ const grid = document.getElementById('grid');
8
+ const summary = document.getElementById('summary');
9
+ const status = document.getElementById('status');
10
+ const showRejected = document.getElementById('show-rejected');
11
+ const rejectedToggle = document.getElementById('rejected-toggle');
12
+ const shortcuts = document.getElementById('shortcuts');
13
+ const cards = Array.from(grid.querySelectorAll('.card'));
14
+ const bySlug = new Map(cards.map((card) => [card.dataset.slug, card]));
15
+ const rankLimit = cards.length;
16
+ const queues = new Map();
17
+ const state = { db: null, writable: false, refused: false, verdicts: new Map() };
18
+
19
+ function readVerdict(slug) {
20
+ return state.verdicts.get(slug) || { rejected: false, rank: null, winner: false, updatedAt: '' };
21
+ }
22
+
23
+ function normalizeVerdict(data) {
24
+ const rank = Number.isInteger(data.rank) && data.rank >= 1 && data.rank <= rankLimit ? data.rank : null;
25
+ return {
26
+ rejected: data.rejected === true,
27
+ rank,
28
+ winner: data.winner === true,
29
+ updatedAt: typeof data.updatedAt === 'string' ? data.updatedAt : '',
30
+ };
31
+ }
32
+
33
+ // Two documents can claim the win between the two writes of a winner change; the later claim wins.
34
+ function resolveWinner() {
35
+ let winner = null;
36
+ for (const [slug, verdict] of state.verdicts) {
37
+ if (verdict.winner && !verdict.rejected && (winner === null || verdict.updatedAt > winner.updatedAt)) {
38
+ winner = { slug, updatedAt: verdict.updatedAt };
39
+ }
40
+ }
41
+ return winner === null ? null : winner.slug;
42
+ }
43
+
44
+ function buildSortKey(card, winner) {
45
+ const slug = card.dataset.slug;
46
+ const verdict = readVerdict(slug);
47
+ let group = 2;
48
+ if (verdict.rejected) group = 3;
49
+ else if (slug === winner) group = 0;
50
+ else if (verdict.rank !== null) group = 1;
51
+ return [group, verdict.rank === null ? 0 : verdict.rank, card.dataset.registered];
52
+ }
53
+
54
+ function compareKeys(left, right) {
55
+ for (let index = 0; index < left.length; index += 1) {
56
+ if (left[index] < right[index]) return -1;
57
+ if (left[index] > right[index]) return 1;
58
+ }
59
+ return 0;
60
+ }
61
+
62
+ function setStatus(message) {
63
+ status.textContent = message;
64
+ }
65
+
66
+ function renderBadges(card, verdict, isWinner) {
67
+ const badges = card.querySelector('[data-role="badges"]');
68
+ badges.replaceChildren();
69
+ const add = (text, variant) => {
70
+ const badge = document.createElement('span');
71
+ badge.className = 'badge' + (variant ? ' ' + variant : '');
72
+ badge.textContent = text;
73
+ badges.append(badge);
74
+ };
75
+ if (isWinner) add('Winner', 'winner');
76
+ if (verdict.rank !== null) add('Rank ' + verdict.rank, '');
77
+ if (verdict.rejected) add('Rejected', 'rejected');
78
+ }
79
+
80
+ function render() {
81
+ const winner = resolveWinner();
82
+ const focused = document.activeElement;
83
+ const shownOrder = Array.from(grid.children);
84
+ const sorted = cards.slice().sort((left, right) => compareKeys(buildSortKey(left, winner), buildSortKey(right, winner)));
85
+ for (const card of sorted) grid.append(card);
86
+ if (focused instanceof HTMLElement && focused !== document.activeElement && grid.contains(focused)) {
87
+ focused.focus({ preventScroll: true });
88
+ }
89
+
90
+ const showControls = state.db !== null && state.writable;
91
+ let rejectedCount = 0;
92
+ let rankedCount = 0;
93
+ for (const card of cards) {
94
+ const slug = card.dataset.slug;
95
+ const verdict = readVerdict(slug);
96
+ const isWinner = slug === winner;
97
+ if (verdict.rejected) rejectedCount += 1;
98
+ if (verdict.rank !== null && !verdict.rejected) rankedCount += 1;
99
+ card.classList.toggle('is-winner', isWinner);
100
+ card.classList.toggle('is-rejected', verdict.rejected);
101
+ card.hidden = verdict.rejected && !showRejected.checked;
102
+ renderBadges(card, verdict, isWinner);
103
+
104
+ const controls = card.querySelector('[data-role="controls"]');
105
+ controls.hidden = !showControls;
106
+ for (const control of controls.querySelectorAll('button, select')) control.disabled = state.refused;
107
+ controls.querySelector('[data-action="reject"]').setAttribute('aria-pressed', String(verdict.rejected));
108
+ controls.querySelector('[data-action="winner"]').setAttribute('aria-pressed', String(isWinner));
109
+ controls.querySelector('[data-action="rank"]').value = verdict.rank === null ? '' : String(verdict.rank);
110
+ }
111
+
112
+ // Keep keyboard focus where the viewer was when a verdict hides the focused card: on its neighbor in the order
113
+ // shown before this render.
114
+ const focusedCard = focused instanceof Element ? focused.closest('.card') : null;
115
+ if (focusedCard && focusedCard.hidden) {
116
+ const index = shownOrder.indexOf(focusedCard);
117
+ const neighbor =
118
+ shownOrder.slice(index + 1).find((card) => !card.hidden) ||
119
+ shownOrder.slice(0, index).reverse().find((card) => !card.hidden);
120
+ if (neighbor) neighbor.focus({ preventScroll: true });
121
+ }
122
+
123
+ const parts = [cards.length + (cards.length === 1 ? ' prototype' : ' prototypes')];
124
+ if (state.db !== null) {
125
+ const winnerCard = winner === null ? null : bySlug.get(winner);
126
+ parts.push(winnerCard ? 'winner: ' + winnerCard.dataset.title : 'no winner yet');
127
+ parts.push(rankedCount + ' ranked', rejectedCount + ' rejected');
128
+ }
129
+ summary.textContent = parts.join(' \xB7 ');
130
+ }
131
+
132
+ function canAct() {
133
+ return state.db !== null && state.writable && !state.refused;
134
+ }
135
+
136
+ function writeVerdict(slug, verdict) {
137
+ const previous = queues.get(slug) || Promise.resolve();
138
+ const next = previous.then(() => state.db.collection(COLLECTION).doc(slug).set(verdict));
139
+ queues.set(slug, next.catch(() => undefined));
140
+ return next;
141
+ }
142
+
143
+ function handleWriteError(error) {
144
+ const code = error && typeof error === 'object' ? error.code : undefined;
145
+ if (code === 'invalid_argument' || code === 'not_granted' || code === 'revoked') {
146
+ state.refused = true;
147
+ setStatus('This view cannot change verdicts, so they are shown read-only.');
148
+ } else if (code === 'quota_exceeded') {
149
+ setStatus('The verdict store is full, so this verdict was not saved.');
150
+ } else {
151
+ setStatus('The verdict was not saved. Try again in a moment.');
152
+ }
153
+ render();
154
+ }
155
+
156
+ async function applyVerdict(slug, patch) {
157
+ const verdict = Object.assign({}, readVerdict(slug), patch, { updatedAt: new Date().toISOString() });
158
+ try {
159
+ await writeVerdict(slug, verdict);
160
+ return true;
161
+ } catch (error) {
162
+ handleWriteError(error);
163
+ return false;
164
+ }
165
+ }
166
+
167
+ async function toggleReject(slug) {
168
+ if (!canAct()) return;
169
+ const verdict = readVerdict(slug);
170
+ await applyVerdict(slug, verdict.rejected ? { rejected: false } : { rejected: true, rank: null, winner: false });
171
+ }
172
+
173
+ async function setRank(slug, rank) {
174
+ if (!canAct()) return;
175
+ await applyVerdict(slug, { rank, rejected: false });
176
+ }
177
+
178
+ async function toggleWinner(slug) {
179
+ if (!canAct()) return;
180
+ if (resolveWinner() === slug) {
181
+ await applyVerdict(slug, { winner: false });
182
+ return;
183
+ }
184
+ if (!(await applyVerdict(slug, { winner: true, rejected: false }))) return;
185
+ for (const [other, verdict] of state.verdicts) {
186
+ if (other !== slug && verdict.winner) await applyVerdict(other, { winner: false });
187
+ }
188
+ }
189
+
190
+ // A row is the run of visible cards that share the first card's top edge.
191
+ function countColumns(visible) {
192
+ const top = visible[0].offsetTop;
193
+ return Math.max(1, visible.filter((card) => card.offsetTop === top).length);
194
+ }
195
+
196
+ function moveFocus(card, key) {
197
+ const visible = Array.from(grid.querySelectorAll('.card')).filter((candidate) => !candidate.hidden);
198
+ const index = visible.indexOf(card);
199
+ if (index === -1) return;
200
+ const columns = countColumns(visible);
201
+ const steps = { ArrowLeft: -1, ArrowRight: 1, ArrowUp: -columns, ArrowDown: columns };
202
+ const target = visible[index + steps[key]];
203
+ if (target) target.focus();
204
+ }
205
+
206
+ grid.addEventListener('click', (event) => {
207
+ const button = event.target instanceof Element ? event.target.closest('button[data-action]') : null;
208
+ if (!button) return;
209
+ const slug = button.closest('.card').dataset.slug;
210
+ if (button.dataset.action === 'reject') void toggleReject(slug);
211
+ if (button.dataset.action === 'winner') void toggleWinner(slug);
212
+ });
213
+
214
+ grid.addEventListener('change', (event) => {
215
+ const select = event.target instanceof Element ? event.target.closest('select[data-action="rank"]') : null;
216
+ if (!select) return;
217
+ void setRank(select.closest('.card').dataset.slug, select.value === '' ? null : Number(select.value));
218
+ });
219
+
220
+ showRejected.addEventListener('change', render);
221
+
222
+ document.addEventListener('keydown', (event) => {
223
+ if (event.defaultPrevented || event.altKey || event.ctrlKey || event.metaKey) return;
224
+ const target = event.target instanceof Element ? event.target : null;
225
+ if (target && target.closest('input, select, textarea, [contenteditable]')) return;
226
+ const card = target ? target.closest('.card') : null;
227
+ const key = event.key;
228
+ if (key.startsWith('Arrow')) {
229
+ // Arrows move between cards only from a focused card, so the page scrolls as usual elsewhere.
230
+ if (!event.shiftKey && target && target.classList.contains('card')) {
231
+ event.preventDefault();
232
+ moveFocus(target, key);
233
+ }
234
+ return;
235
+ }
236
+ if (!card || !canAct()) return;
237
+ const slug = card.dataset.slug;
238
+ if (key === 'x') void toggleReject(slug);
239
+ else if (key === 'w') void toggleWinner(slug);
240
+ else if (/^[1-9]$/.test(key) && Number(key) <= rankLimit) void setRank(slug, Number(key));
241
+ else return;
242
+ event.preventDefault();
243
+ });
244
+
245
+ async function connect() {
246
+ const claude = window.claude;
247
+ if (!claude || typeof claude.use !== 'function') {
248
+ setStatus('Verdicts are available only in the Claude viewer.');
249
+ return;
250
+ }
251
+ const [db, user] = await Promise.all([claude.use('db'), claude.use('user')]);
252
+ if (!db) {
253
+ setStatus('Verdicts are not available in this view.');
254
+ return;
255
+ }
256
+ state.db = db;
257
+ const canWrite = user ? await user.can('data.write') : null;
258
+ state.writable = canWrite !== false;
259
+ rejectedToggle.hidden = false;
260
+ shortcuts.hidden = !state.writable;
261
+ if (!state.writable) setStatus('You can see the verdicts but not change them.');
262
+ db.collection(COLLECTION).onSnapshot(
263
+ (snapshot) => {
264
+ const verdicts = new Map();
265
+ for (const doc of snapshot.docs) {
266
+ const data = doc.data();
267
+ if (bySlug.has(doc.id) && data) verdicts.set(doc.id, normalizeVerdict(data));
268
+ }
269
+ state.verdicts = verdicts;
270
+ render();
271
+ },
272
+ () => setStatus('Verdicts stopped updating. Reload the page to see the latest.'),
273
+ );
274
+ render();
275
+ }
276
+
277
+ render();
278
+ connect().catch(() => setStatus('Verdicts could not be loaded.'));
279
+ })();
280
+ `;var de=["accent","chip","control-border","on-accent","page","reject-bg","reject-text","surface","text","text-muted","winner-bg","winner-border","winner-text"],le={dark:{accent:"#8cb6ff",chip:"#2a2f39","control-border":"#8790a3","on-accent":"#0b1730",page:"#111317","reject-bg":"#3f1717","reject-text":"#ffb8b8",surface:"#1b1e25",text:"#e7e9ee","text-muted":"#b0b6c3","winner-bg":"#3b2d06","winner-border":"#d9a43a","winner-text":"#ffd98a"},light:{accent:"#1d5bbf",chip:"#e9ecf1","control-border":"#6b7385","on-accent":"#ffffff",page:"#f4f5f7","reject-bg":"#fbe4e4","reject-text":"#8f1d1d",surface:"#ffffff",text:"#1b1f27","text-muted":"#4a5160","winner-bg":"#fff1c9","winner-border":"#a06c00","winner-text":"#5c3d00"}};function E(e){return de.map(t=>`--${t}: ${le[e][t]};`).join(" ")}i(E,"renderTokenDeclarations");var U=12e6,S=16e6;function z(e){let t=f(e.title),r=e.cards.length;return[`<title>${t}</title>`,`<style>${ge()}</style>`,"<main>","<header>",`<h1>${t}</h1>`,`<p class="summary" id="summary">${r} ${r===1?"prototype":"prototypes"}</p>`,"</header>",'<div class="toolbar">','<label class="toggle" id="rejected-toggle" hidden><input type="checkbox" id="show-rejected" checked> Show rejected</label>','<p class="hint" id="shortcuts" hidden>On a focused card: <kbd>\u2190</kbd> <kbd>\u2192</kbd> <kbd>\u2191</kbd> <kbd>\u2193</kbd> move between cards \xB7 <kbd>x</kbd> reject \xB7 <kbd>w</kbd> winner \xB7 <kbd>1\u20139</kbd> rank</p>','<p class="status" id="status" role="status" aria-live="polite"></p>',"</div>",'<div class="grid" id="grid">',...e.cards.map(n=>fe(n,r)),"</div>","</main>",`<script>${W}</script>`,""].join(`
281
+ `)}i(z,"renderIndexPage");function f(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}i(f,"escapeHtml");function ue(e){let t=Date.parse(e);if(Number.isNaN(t))return e;let r=new Date(t).toISOString();return`${r.slice(0,10)} ${r.slice(11,16)} UTC`}i(ue,"formatTimestamp");function fe(e,t){let{entry:r}=e,n=f(r.slug),o=f(r.title),s=f(r.url),c=`title-${n}`,d=e.shot===null?`<span class="placeholder">No screenshot for v${r.version}</span>`:`<img src="data:image/png;base64,${e.shot.toString("base64")}" alt="Screenshot of ${o}">`,a=[...r.lens===null?[]:[`<li class="chip">Lens: ${f(r.lens)}</li>`],...r.inputs.map(h=>`<li class="chip">${f(h)}</li>`)],l=Array.from({length:t},(h,b)=>`<option value="${b+1}">${b+1}</option>`);return[`<article class="card" tabindex="0" aria-labelledby="${c}" data-slug="${n}" data-title="${o}" data-registered="${f(r.registeredAt)}">`,`<a class="thumb" href="${s}" target="_blank" rel="noopener" tabindex="-1" aria-hidden="true">${d}</a>`,'<div class="body">','<div class="badges" data-role="badges"></div>',`<h2 id="${c}"><a href="${s}" target="_blank" rel="noopener">${o}</a></h2>`,`<p class="meta">${n} \xB7 v${r.version} \xB7 ${f(ue(r.registeredAt))}</p>`,...a.length===0?[]:[`<ul class="chips">${a.join("")}</ul>`],...r.description===null?[]:[`<p class="description">${f(r.description)}</p>`],'<div class="controls" data-role="controls" hidden>',`<button type="button" data-action="reject" aria-pressed="false" aria-describedby="${c}">Reject</button>`,`<label class="rank">Rank <select data-action="rank" aria-describedby="${c}"><option value="">None</option>${l.join("")}</select></label>`,`<button type="button" data-action="winner" aria-pressed="false" aria-describedby="${c}">Winner</button>`,"</div>","</div>","</article>"].join(`
282
+ `)}i(fe,"renderCard");function ge(){return`
283
+ :root { color-scheme: light; ${E("light")} }
284
+ @media (prefers-color-scheme: dark) {
285
+ :root:not([data-theme="light"]) { color-scheme: dark; ${E("dark")} }
286
+ }
287
+ :root[data-theme="dark"] { color-scheme: dark; ${E("dark")} }
288
+ * { box-sizing: border-box; }
289
+ body { margin: 0; background: var(--page); color: var(--text); font: 15px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
290
+ main { max-width: 1280px; margin: 0 auto; padding: 24px 16px 48px; }
291
+ h1 { font-size: 24px; line-height: 1.25; margin: 0 0 4px; }
292
+ img { max-width: 100%; }
293
+ [hidden] { display: none !important; }
294
+ .summary, .hint, .status { margin: 0; color: var(--text-muted); font-size: 13px; }
295
+ .toolbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 20px; margin: 12px 0 20px; }
296
+ .toggle { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; }
297
+ .toggle input { width: 18px; height: 18px; accent-color: var(--accent); }
298
+ kbd { font: 600 13px ui-monospace, SFMono-Regular, Menlo, monospace; color: var(--text); background: var(--chip); border-radius: 4px; padding: 0 4px; }
299
+ .grid { display: grid; gap: 16px; grid-template-columns: repeat(auto-fill, minmax(min(480px, 100%), 1fr)); }
300
+ .card { display: flex; flex-direction: column; background: var(--surface); border: 1px solid var(--control-border); border-radius: 10px; overflow: hidden; }
301
+ .card.is-winner { border: 3px solid var(--winner-border); }
302
+ .card:focus-visible, a:focus-visible, button:focus-visible, select:focus-visible, input:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
303
+ .thumb { display: block; aspect-ratio: 16 / 10; background: var(--chip); }
304
+ .thumb img { display: block; width: 100%; height: 100%; object-fit: cover; object-position: top; }
305
+ .card.is-rejected .thumb img { opacity: 0.4; filter: grayscale(1); }
306
+ .placeholder { display: flex; align-items: center; justify-content: center; height: 100%; padding: 8px; color: var(--text-muted); font-size: 13px; }
307
+ .body { display: flex; flex: 1; flex-direction: column; gap: 6px; padding: 12px 14px 14px; }
308
+ .card h2 { margin: 0; font-size: 17px; line-height: 1.3; }
309
+ .card h2 a { color: var(--accent); }
310
+ .meta { margin: 0; color: var(--text-muted); font-size: 13px; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
311
+ .chips { display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; list-style: none; }
312
+ .chip { padding: 2px 8px; border-radius: 999px; background: var(--chip); color: var(--text); font-size: 13px; }
313
+ .description { margin: 0; }
314
+ .badges { display: flex; flex-wrap: wrap; gap: 6px; }
315
+ .badges:empty { display: none; }
316
+ .badge { padding: 2px 8px; border-radius: 6px; background: var(--chip); color: var(--text); font-size: 13px; font-weight: 600; }
317
+ .badge.winner { background: var(--winner-bg); color: var(--winner-text); }
318
+ .badge.rejected { background: var(--reject-bg); color: var(--reject-text); }
319
+ .controls { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: auto; padding-top: 8px; }
320
+ .rank { display: inline-flex; align-items: center; gap: 6px; font-size: 14px; }
321
+ button, select { min-height: 32px; padding: 4px 10px; border: 1px solid var(--control-border); border-radius: 6px; background: var(--surface); color: var(--text); font: inherit; font-size: 14px; cursor: pointer; }
322
+ button[aria-pressed="true"] { border-color: var(--accent); background: var(--accent); color: var(--on-accent); }
323
+ button:disabled, select:disabled { cursor: not-allowed; }
324
+ @media (prefers-reduced-motion: reduce) { * { scroll-behavior: auto !important; transition: none !important; } }
325
+ `}i(ge,"renderStyles");var N=["record-index","register","render"],xe=new Set(N),ye=[{name:"description",takesValue:!0},{name:"inputs",takesValue:!0},{name:"lens",takesValue:!0},{name:"out",takesValue:!0},{name:"screenshot",takesValue:!0},{name:"set-dir",takesValue:!0},{name:"set-title",takesValue:!0},{name:"slug",takesValue:!0},{name:"source",takesValue:!0},{name:"title",takesValue:!0},{name:"url",takesValue:!0}],we={"record-index":{required:["set-dir","url"],optional:[]},register:{required:["set-dir","slug","title","url"],optional:["description","inputs","lens","screenshot","set-title","source"]},render:{required:["out","set-dir"],optional:[]}};async function ve(){try{let e=await ke({argv:g.argv.slice(2),now:new Date});g.stdout.write(`${JSON.stringify(e,null,2)}
326
+ `),e.ok||(g.exitCode=1)}catch(e){g.stderr.write(`index-prototypes: ${x(e)}
327
+ `),g.exit(1)}}i(ve,"main");$e()&&await ve();async function ke(e){let t;try{t=Ee(e.argv)}catch(n){return u("invalid-args",x(n))}let r=y.resolve(m(t.values,"set-dir"));switch(t.command){case"record-index":return Ne(r,m(t.values,"url"));case"register":return Re(r,t.values,e.now);case"render":return Me(r,y.resolve(m(t.values,"out")));default:{let n=t.command;throw new Error(`unhandled command: ${String(n)}`)}}}i(ke,"runIndexPrototypes");function Ee(e){let{positionals:t,flags:r}=M(e,ye),[n,o]=t;if(n===void 0)throw new Error(`a command is required: ${N.join(", ")}`);if(!Se(n))throw new Error(`unknown command "${n}"; expected one of ${N.join(", ")}`);if(o!==void 0)throw new Error(`unexpected argument: ${o}`);let s=P(r),{required:c,optional:d}=we[n];for(let[a,l]of Object.entries(s)){if(!c.includes(a)&&!d.includes(a))throw new Error(`${n} does not take --${a}`);if(l==="")throw new Error(`--${a} requires a value`)}for(let a of c)if(s[a]===void 0)throw new Error(`${n} requires --${a}`);return{command:n,values:s}}i(Ee,"parseArgs");function u(e,t){return{ok:!1,error:e,message:t}}i(u,"fail");function Se(e){return xe.has(e)}i(Se,"isCommand");function $e(){let e=g.argv[1];if(e===void 0)return!1;try{return B(be(import.meta.url))===B(e)}catch(t){return g.stderr.write(`index-prototypes: warning: could not determine entry point: ${x(t)}
328
+ `),!1}}i($e,"isEntryPoint");function D(e){try{let{protocol:t}=new URL(e);return t==="https:"||t==="http:"}catch{return!1}}i(D,"isWebUrl");function je(e){return e===void 0?[]:e.split(",").map(t=>t.trim()).filter(t=>t!=="")}i(je,"parseInputs");async function Ae(e){try{return await me(e)}catch(t){if(p(t))return null;throw t}}i(Ae,"readShot");async function Ne(e,t){if(!D(t))return u("invalid-url",`--url "${t}" is not an http or https URL`);let r=await k(e);return r.kind==="missing"?u("manifest-not-found",`no manifest in ${e}; register a prototype first`):r.kind==="invalid"?u("invalid-manifest",r.message):{ok:!0,command:"record-index",manifestPath:await A(e,{...r.manifest,indexUrl:t}),indexUrl:t}}i(Ne,"recordIndex");async function Re(e,t,r){let n=m(t,"slug");if(!_(n))return u("invalid-slug",`slug "${n}" must match [a-z0-9][a-z0-9-]{0,39}`);let o=m(t,"url");if(!D(o))return u("invalid-url",`--url "${o}" is not an http or https URL`);let s=await k(e);if(s.kind==="invalid")return u("invalid-manifest",s.message);let c=s.kind==="ok"?s.manifest:null,d=t["set-title"]??c?.title;if(d===void 0)return u("missing-set-title","the first registration in a set requires --set-title");let a=F(c,n),l=null,h=t.screenshot;if(h!==void 0){let w=await I({sourcePath:y.resolve(h),setDir:e,slug:n,version:a});if(!w.ok)return u(w.error,w.message);l=w.shot}let b={slug:n,version:a,registeredAt:r.toISOString(),title:m(t,"title"),url:o,source:t.source??null,lens:t.lens??null,inputs:je(t.inputs),description:t.description??null,shot:l},K={title:d,indexUrl:c?.indexUrl??null,entries:[...c?.entries??[],b]};return{ok:!0,command:"register",manifestPath:await A(e,K),entry:b}}i(Re,"register");async function Me(e,t){let r=await k(e);if(r.kind==="missing")return u("manifest-not-found",`no manifest in ${e}; register a prototype first`);if(r.kind==="invalid")return u("invalid-manifest",r.message);let{manifest:n}=r,o=[],s=[];for(let a of L(n)){let l=a.shot===null?null:await Ae(y.join(e,a.shot));a.shot!==null&&l===null&&s.push(a.slug),o.push({entry:a,shot:l})}let c=z({title:n.title,cards:o}),d=Buffer.byteLength(c,"utf8");return d>S?u("page-too-large",`the page is ${d} bytes, over the ${S}-byte artifact cap`):(await pe(y.dirname(t),{recursive:!0}),await he(t,c,"utf8"),{ok:!0,command:"render",path:t,bytes:d,cards:o.length,title:n.title,indexUrl:n.indexUrl,missingShots:s,...d>U&&{warning:`the page is ${d} bytes, approaching the ${S}-byte artifact cap`}})}i(Me,"render");function m(e,t){let r=e[t];if(r===void 0)throw new Error(`--${t} is missing after parsing`);return r}i(m,"requireFlag");export{Ee as parseArgs,ke as runIndexPrototypes};
@@ -0,0 +1,156 @@
1
+ ---
2
+ name: kb-add
3
+ description: Capture a new note into the knowledge base via agent-mediated classification with a confirm-by-default flow and an --auto escape hatch
4
+ user-invocable: true
5
+ ---
6
+
7
+ # Capture a new knowledge-base note
8
+
9
+ Add a new note to the knowledge base. A bundled helper does the mechanical work: It resolves which knowledge base to write to, reports that base's declared structure, generates UTC dates, canonicalizes known-alias tags, composes a typed assertion record, writes the file atomically under the KB's assertions root (`content/assertions/`), and records the note's folder in the base's taxonomy. You do the judgment work: Pick the topic folder, the Diátaxis label, the title, and the tags; run `kb-retrieve` to find related notes; and compose the body, including cross-references when they aid comprehension.
10
+
11
+ The split is deliberate: The helper is narrow and mechanical; the classification and composition are wide and judgment-driven. Treat the helper as a guardrail (it refuses a title that cannot be a filename and will not overwrite an existing file), not as a classifier.
12
+
13
+ **Announce at start:** "Using kb-add to capture {short description of the note}."
14
+
15
+ ## Arguments
16
+
17
+ | Argument | Description | Required |
18
+ | ---------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
19
+ | `--auto` | Skip the proposal step and record any domain that the write declares under `provisional:`. See [Modes](#modes). | No |
20
+ | `--diataxis` | The note's Diátaxis label (e.g. `howto`, `concept`, `reference`, `tutorial`). | No |
21
+ | `--domain-description` | One-line description for a domain that the write declares. Takes prose, not a path; the path comes from `--folder`. Without it the domain is declared bare. | No |
22
+ | `--folder` | Topic subpath beneath the assertions root (`content/assertions/`). The helper supplies the `assertions/` segment; pass the topic only. Defaults to `content/assertions/` itself. | No |
23
+ | `--kb` | Knowledge base name, or `@default` for the registry default. Overrides `.kb/` discovery; the registry default is reachable only via `--kb @default`. | No |
24
+ | `--survey` | Report the destination's shape and exit. Takes `--kb` alone; writes nothing and does not read stdin. See [step 2](#2-survey-the-destination-kb). | No |
25
+ | `--tags` | Comma-separated tag list. Known aliases are canonicalized at write time. | No |
26
+ | `--title` | The note title; also doubles as the filename. | Yes |
27
+
28
+ A value-bearing flag accepts both `--diataxis howto` and `--diataxis=howto`. The note body is read from stdin to EOF; an empty body is allowed when a stub note is appropriate.
29
+
30
+ ### KB selection
31
+
32
+ By default the helper writes to the knowledge base discovered by walking up from the current directory for a `.kb/` folder. When the walk does not discover a `.kb/` and the caller does not pass `--kb`, the helper refuses to write rather than guessing a destination. `--kb <name>` names a specific entry from the merged `kb.yaml` registry and overrides discovery; `--kb @default` is the only way to reach the registry's `default_kb`. The chosen KB is shown in the proposal so that the user can redirect the write via `--kb` if it is wrong.
33
+
34
+ ## Runtime dependencies
35
+
36
+ - **`node` ≥ 24**: The bundled helper inherits the Node version floor of `@williamthorsen/kb`.
37
+
38
+ ## Modes
39
+
40
+ - **Default mode**: Gather context, propose placement and body, present the proposal to the user, write only after confirmation.
41
+ - **Auto mode (`--auto`)**: Gather context, pick the best inference, write silently. The agent never asks clarifying questions in this mode.
42
+
43
+ `--auto` does two jobs. It tells you to skip the proposal step, and it is passed through to the helper, which then records any domain that the write declares under `provisional:` rather than `domains:`; an unconfirmed placement is by definition unreviewed, and the taxonomy should say so.
44
+
45
+ ## Placement
46
+
47
+ The declared taxonomy is the primary placement signal; the folders found on disk by the survey corroborate it. A folder containing notes outside every declared domain is drift: Report it rather than quietly writing another note into it.
48
+
49
+ Treat the taxonomy as a strong prior, not a hard constraint. When a note's topic is in the long tail, rely on the tags for retrieval and place the note in the nearest domain that genuinely fits; do not force it into an ill-fitting folder to avoid proposing a new one, and do not create a domain per note.
50
+
51
+ A new domain is warranted by intent, not by note count: Propose one when the user means to keep that domain, however few notes it will contain. Name it to match the form of the domains reported by the survey, since the name is durable structure that later captures reuse. In auto mode, do not create a top-level domain: A new top-level domain changes the structure of the base and needs confirmation.
52
+
53
+ Folders serve human browsing and tags serve machine retrieval, so a folder name that restates a tag is expected rather than redundant. Do not contort either list to keep them orthogonal.
54
+
55
+ When two declared domains both fit, prefer the reviewed one: A domain reported with `provisional: true` was declared but never reviewed, and adding to it enlarges an unreviewed domain.
56
+
57
+ ## Process
58
+
59
+ ### 1. Gather context
60
+
61
+ Read the note content from the conversation or, if the user pointed to one, from a file. Identify the topic, the intent (procedural vs explanatory vs reference-style), and any obvious entities (libraries, tools, concepts).
62
+
63
+ ### 2. Survey the destination KB
64
+
65
+ Run the helper in survey mode, passing the same `--kb` that the write will use:
66
+
67
+ ```bash
68
+ node {harness_home_dir}/skills/kb-add/kb-add.mjs --survey [--kb <name>]
69
+ ```
70
+
71
+ It reports:
72
+
73
+ - `kb`: The knowledge base to which the write will resolve, by the same rules.
74
+ - `taxonomyPath`: The `.kb/taxonomy.yaml` from which the domains came.
75
+ - `domains`: Each declared domain with its `description`, its `provisional` flag, and the `noteCount` at or beneath it.
76
+ - `undeclaredFolders`: Folders containing notes outside every declared domain.
77
+
78
+ Then read a representative sample of notes from the folder most likely to fit the new note's topic. The survey does not read any note bodies, so the sample, not the survey, reveals the title conventions and the live tag vocabulary already in use.
79
+
80
+ ### 3. Cross-reference via kb-retrieve
81
+
82
+ Invoke the `{skill:kb-retrieve}` skill on the note's topic terms. Read the top-ranked candidates; they are the inputs for your cross-referencing decisions in step 5. This step is mandatory in both default and auto modes: The proposal should always either embed cross-references or explicitly note that none are warranted.
83
+
84
+ ### 4. Classify
85
+
86
+ Pick the placement and metadata:
87
+
88
+ - **Folder**: A topic subpath under `content/assertions/`, chosen per [Placement](#placement) (a declared domain when one fits, a new one when the topic is genuinely new to the KB).
89
+ - **Diátaxis label**: The note's Diátaxis classification (the default vocabulary is `howto`, `concept`, `reference`, `tutorial`).
90
+ - **Title**: A concise, descriptive title. For `diataxis: howto`, propose imperative-led titles ("Configure pnpm workspaces") not interrogative ones ("How do I configure pnpm workspaces?"). The title is also the filename; keep it within a sane length and avoid filesystem-hostile characters.
91
+ - **Tags**: Topic and category tags drawn from existing tag vocabulary when possible. Known aliases will be canonicalized at write time by the helper.
92
+
93
+ ### 5. Compose the body
94
+
95
+ Write the note body. Embed cross-references inline when the reference contributes at the point of mention; group tangential references under a `## See also` heading at the end. Prefer file-relative or KB-relative links.
96
+
97
+ ### 6. Present the proposal (default mode)
98
+
99
+ In default mode, present the proposed KB, folder, Diátaxis label, title, tags, and body to the user. Name the domain that the folder matched, that domain's description, and the taxonomy file from which they came, so that the user can see what the placement was measured against. When the folder is a new domain, name it as new and propose the description that you will pass as `--domain-description`. When the survey reported an undeclared folder bearing on the choice, say so. Wait for confirmation or a redirect. In auto mode, skip this step.
100
+
101
+ <!-- include: ../_partials/action-items.md / -->
102
+
103
+ ### 7. Invoke the helper
104
+
105
+ Pipe the composed body to the bundled helper. A heredoc keeps multi-line bodies legible without the quoting and escaping that `echo "$BODY"` requires once the note contains backticks, blank lines, or shell metacharacters:
106
+
107
+ ```bash
108
+ cat <<'EOF' | node {harness_home_dir}/skills/kb-add/kb-add.mjs \
109
+ --diataxis <label> --title "<title>" \
110
+ [--kb <name>] [--folder <topic-subpath>] \
111
+ [--tags <comma,separated>] [--domain-description "<description>"] [--auto]
112
+ <note body, may span multiple lines and contain any characters>
113
+ EOF
114
+ ```
115
+
116
+ A worked example:
117
+
118
+ ```bash
119
+ cat <<'EOF' | node {harness_home_dir}/skills/kb-add/kb-add.mjs \
120
+ --diataxis howto --title "Configure pnpm workspaces" \
121
+ --folder engineering/tooling --tags "pnpm,workspaces"
122
+ Configure pnpm workspaces by adding a `pnpm-workspace.yaml` at the repo
123
+ root that lists each package directory under `packages:`.
124
+ EOF
125
+ ```
126
+
127
+ The helper prints a JSON object to stdout:
128
+
129
+ - `ok: true` with `path`, `kb`, `record`, `originalTags`, `canonicalTags`, and `placement` on success.
130
+ - `ok: false` with `error`, `message`, and optional `details` on a recoverable failure.
131
+
132
+ ### 8. Handle the result
133
+
134
+ On `ok: true`, report the written path and the canonicalization audit trail. When `canonicalTags` differs from `originalTags`, report which tags were canonicalized so that the user can confirm the change matches their intent.
135
+
136
+ Then report the placement:
137
+
138
+ - `placement.domain` names the domain that contains the note. A `null` value means the note was written to the assertions root, not under any domain, and outside the scope of the taxonomy rules; say so, and offer to move it under a domain.
139
+ - `placement.added` lists the domains declared by this capture, each with the block in which it was declared. Name them, and flag every one with `provisional: true` as awaiting review.
140
+ - `placement.warning` means the note was written but its folder could not be declared. Report the message; `kb check` will report the folder as `taxonomy.undeclared` on its next run.
141
+ - An absent `placement` means the store does not contain a `.kb/taxonomy.yaml` and so has not adopted a taxonomy. Nothing was declared, and nothing is wrong.
142
+
143
+ In auto mode, the user learns of an undeclared folder found by the survey from the completion report; include it there.
144
+
145
+ On `ok: false`, act on the `error` code:
146
+
147
+ - `no-kb-resolvable`: The explicit `--kb <name>` did not match any entry in the `kb.yaml` registry. Report the message and propose a corrected name (or, in auto mode, fail visibly with the categorical reason).
148
+ - `missing-destination`: The helper did not discover a `.kb/`, and the invocation did not pass `--kb`. Ask the user where the note should go, passing `--kb <name>` for a specific KB or `--kb @default` for the registry default (or, in auto mode, fail visibly with the categorical reason).
149
+ - `no-default`: `--kb @default` was given but `kb.yaml` does not configure a `default_kb`. Report the message; have the user name a KB explicitly or configure a default.
150
+ - `invalid-args` / `invalid-title`: Report the helper's message and propose a corrected invocation.
151
+ - `invalid-config`: A survey found a malformed `.kb/config.yaml` or `.kb/taxonomy.yaml`. The message names the file; report it and have the user repair it before capturing.
152
+ - `collision`: A note already exists at the target path. Decide whether to re-title, append the new material to the existing note (read it first, then write a follow-up edit), or abort.
153
+
154
+ ## Completion
155
+
156
+ A written note at the reported path, conforming to the assertion record contract, plus the canonicalization audit trail so that the user can verify which alias tags were rewritten, and the domain under which the note was placed along with any domain declared by the capture.