geneseed 5.1.1 → 5.3.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 (163) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +2 -2
  3. package/SHIPPED.md +1 -1
  4. package/adapters/opencode/README.md +4 -3
  5. package/adapters/opencode/plugins/geneseed-context.js +82 -29
  6. package/adapters/opencode/plugins/geneseed-guard.js +118 -8
  7. package/bin/geneseed-cli.mjs +64 -16
  8. package/bin/geneseed-hook.mjs +37 -3
  9. package/docs/concepts/exclusions.md +1 -1
  10. package/docs/concepts/factories.md +40 -6
  11. package/docs/concepts/footprint.md +1 -1
  12. package/docs/concepts/foreman-mode.md +2 -2
  13. package/docs/concepts/host-matrix.md +1 -1
  14. package/docs/concepts/loop-gates.md +1 -1
  15. package/docs/concepts/loops.md +2 -2
  16. package/docs/concepts/shared-tier.md +1 -1
  17. package/docs/design-history.md +140 -0
  18. package/docs/extending.md +54 -162
  19. package/docs/guides/run-a-factory.md +15 -2
  20. package/docs/guides/setup-doctrines.md +1 -1
  21. package/docs/guides/upgrade.md +2 -2
  22. package/docs/reference/factory-actions.md +6 -5
  23. package/docs/reference/troubleshoot-update.md +1 -1
  24. package/docs/understand/enforced-vs-asked.md +1 -1
  25. package/docs/web-ui.md +16 -3
  26. package/harness.config.json +1 -1
  27. package/js/README.md +10 -7
  28. package/js/build/args.mjs +10 -4
  29. package/js/build/bundle.mjs +122 -23
  30. package/js/build/driver.mjs +32 -12
  31. package/js/build/emit-claude.mjs +2 -1
  32. package/js/build/emit-common.mjs +2 -2
  33. package/js/build/emit-opencode.mjs +22 -10
  34. package/js/build/export.mjs +431 -0
  35. package/js/build/generate.mjs +3 -0
  36. package/js/build/render.mjs +44 -24
  37. package/js/build/source.mjs +6 -1
  38. package/js/cli-table.json +232 -57
  39. package/js/factory/cli.mjs +24 -5
  40. package/js/factory/graph.mjs +13 -9
  41. package/js/factory/metrics.mjs +93 -0
  42. package/js/factory/registry.mjs +37 -12
  43. package/js/factory/state.mjs +25 -6
  44. package/js/hosts/hooks-context.mjs +26 -1
  45. package/js/hosts/hooks-done.mjs +8 -2
  46. package/js/hosts/hooks-prims.mjs +52 -3
  47. package/js/hosts/hooks.mjs +155 -33
  48. package/js/hosts/hosts.mjs +2 -4
  49. package/js/hosts/installs.mjs +28 -0
  50. package/js/hosts/loss.mjs +25 -3
  51. package/js/hosts/native.mjs +30 -2
  52. package/js/hosts/owned.mjs +55 -1
  53. package/js/hosts/ownership-gate.mjs +5 -5
  54. package/js/hosts/settings.mjs +83 -33
  55. package/js/inspect/diff.mjs +16 -1
  56. package/js/inspect/doctor.mjs +7 -3
  57. package/js/inspect/excludes.mjs +18 -6
  58. package/js/inspect/status.mjs +35 -7
  59. package/js/inspect/validate.mjs +44 -21
  60. package/js/lib/managed-block.mjs +74 -0
  61. package/js/maintain/uninstall.mjs +85 -15
  62. package/js/maintain/update.mjs +31 -7
  63. package/js/ui/cli.mjs +34 -4
  64. package/js/ui/menu.mjs +1 -1
  65. package/js/ui/tui.mjs +11 -14
  66. package/js/web/actions.mjs +5 -0
  67. package/js/web/api.mjs +32 -11
  68. package/js/web/daemon.mjs +0 -1
  69. package/js/web/server.mjs +1 -0
  70. package/js/web/state.mjs +37 -16
  71. package/package.json +1 -1
  72. package/src/AGENT.md.tmpl +23 -17
  73. package/src/agents/_template.md +1 -1
  74. package/src/agents/advocate.md +1 -1
  75. package/src/agents/developer.md +12 -3
  76. package/src/agents/empiricist.md +1 -1
  77. package/src/agents/framer.md +1 -1
  78. package/src/agents/historian.md +1 -1
  79. package/src/agents/operator.md +1 -1
  80. package/src/agents/pragmatist.md +1 -1
  81. package/src/agents/researcher.md +1 -1
  82. package/src/agents/skeptic.md +1 -1
  83. package/src/agents/steward.md +1 -1
  84. package/src/agents/user-advocate.md +1 -1
  85. package/src/agents/visionary.md +1 -1
  86. package/src/bricks/intake.md +10 -3
  87. package/src/bricks/retro.md +13 -3
  88. package/src/doctrines/comms.md +1 -1
  89. package/src/doctrines/ops.md +1 -1
  90. package/src/doctrines/process.md +7 -5
  91. package/src/factories/analysis-to-build.json +1 -0
  92. package/src/factories/bug-report-to-fix.json +1 -0
  93. package/src/factories/issue-to-pr.json +1 -0
  94. package/src/laws/universal.md +2 -2
  95. package/src/modes/foreman.md +8 -14
  96. package/src/skills/commit.md +7 -2
  97. package/src/skills/debug.md +1 -1
  98. package/src/skills/diagram-design/SKILL.md +1 -1
  99. package/src/skills/diagram-design/VENDOR.md +3 -1
  100. package/src/skills/factory-forge.md +5 -3
  101. package/src/skills/factory.md +22 -1
  102. package/src/skills/geneseed.md +1 -1
  103. package/src/skills/handoff.md +1 -1
  104. package/src/skills/parallel-agents.md +1 -1
  105. package/src/skills/pipeline.md +6 -6
  106. package/src/skills/plan.md +7 -3
  107. package/src/skills/spring-testing.md +1 -1
  108. package/themes/biker.json +78 -78
  109. package/themes/commentator.json +81 -81
  110. package/themes/cyberpunk.json +79 -79
  111. package/themes/gamer.json +77 -77
  112. package/themes/imperial.json +82 -82
  113. package/themes/joker.json +79 -79
  114. package/themes/marvin.json +82 -82
  115. package/themes/mean.json +82 -82
  116. package/themes/military.json +78 -78
  117. package/themes/neutral.json +78 -78
  118. package/themes/pirate.json +79 -79
  119. package/themes/sports.json +79 -79
  120. package/themes/verstappen.json +78 -78
  121. package/themes/wizard.json +79 -79
  122. package/web/dist/assets/ActiveLoops-BJJN3P-V.js +1 -0
  123. package/web/dist/assets/Activity-CqJiquEq.js +1 -0
  124. package/web/dist/assets/ActivityDetail-BSzevynX.js +1 -0
  125. package/web/dist/assets/{Bonsai-hiG_gGNU.js → Bonsai-Bfpb6W-1.js} +1 -1
  126. package/web/dist/assets/{CopyButton-DUIUfNp6.js → CopyButton-ByIntFtB.js} +1 -1
  127. package/web/dist/assets/Dashboard-DBOEi9lQ.js +2 -0
  128. package/web/dist/assets/Docs-DvlMJhpu.js +5 -0
  129. package/web/dist/assets/Factories-Bpvv7L2H.js +1 -0
  130. package/web/dist/assets/{GreenhouseView-BKxy5apE.js → GreenhouseView-GpBsYn50.js} +1 -1
  131. package/web/dist/assets/Installs-BlGmVrFK.js +3 -0
  132. package/web/dist/assets/{JournalView-ChFitHjo.js → JournalView-iLuLrOxE.js} +1 -1
  133. package/web/dist/assets/Kits-DRwpxC-J.js +1 -0
  134. package/web/dist/assets/Laws-CZkiNOWQ.js +4 -0
  135. package/web/dist/assets/LibRows-DEHjIoD-.js +1 -0
  136. package/web/dist/assets/Library-B4K-1iNF.js +3 -0
  137. package/web/dist/assets/Loops-BWSzaW8E.js +2 -0
  138. package/web/dist/assets/{OperatorHudView-BO0aIKPL.js → OperatorHudView-BAXwCEvY.js} +1 -1
  139. package/web/dist/assets/Personal-Bp9nV4GR.js +2 -0
  140. package/web/dist/assets/Settings-CWWuaIp-.js +1 -0
  141. package/web/dist/assets/Tabs-CWeQTADL.js +1 -0
  142. package/web/dist/assets/index-CsAZq0BQ.css +1 -0
  143. package/web/dist/assets/index-How7SzDZ.js +6 -0
  144. package/web/dist/assets/usePoll-D5c_qIFZ.js +1 -0
  145. package/web/dist/index.html +2 -2
  146. package/web/dist/assets/ActiveLoops-BTHIaRhn.js +0 -1
  147. package/web/dist/assets/Activity-CpkBwpu7.js +0 -1
  148. package/web/dist/assets/ActivityDetail-DTPziZWM.js +0 -1
  149. package/web/dist/assets/Dashboard-Dnw6EyX7.js +0 -2
  150. package/web/dist/assets/Docs-BEET_l16.js +0 -5
  151. package/web/dist/assets/Factories-D6KXkfWw.js +0 -1
  152. package/web/dist/assets/Installs-CnFVlVD0.js +0 -3
  153. package/web/dist/assets/Kits-CcR-OlwQ.js +0 -1
  154. package/web/dist/assets/Laws-B1s5idOg.js +0 -4
  155. package/web/dist/assets/LibRows-BZgdbI1l.js +0 -1
  156. package/web/dist/assets/Library-x6TkkEVF.js +0 -3
  157. package/web/dist/assets/Loops-BH93KKxn.js +0 -2
  158. package/web/dist/assets/Personal-CE_0Vhh0.js +0 -2
  159. package/web/dist/assets/Settings-CbpZvVN_.js +0 -1
  160. package/web/dist/assets/Tabs-C2oW7oEj.js +0 -1
  161. package/web/dist/assets/index-BQwOmbor.js +0 -6
  162. package/web/dist/assets/index-CuIop_pO.css +0 -1
  163. package/web/dist/assets/usePoll-o8ul-Sog.js +0 -1
@@ -0,0 +1,431 @@
1
+ /**
2
+ * `geneseed export` — skills, agents and the constitution as catalogue entities, for a library
3
+ * that is not a Geneseed install.
4
+ *
5
+ * An install is a harness: a carrier, hooks, settings, memory. A shared library wants none of
6
+ * that. It wants one folder per entity, a description file a model reads and a governance file a
7
+ * pipeline reads, in the layout many such libraries have converged on:
8
+ *
9
+ * <skillsDir>/<name>/SKILL.md frontmatter `name` + `description`, nothing else
10
+ * <skillsDir>/<name>/metadata.yaml type, owner, maintainer, version, status, ...
11
+ * <skillsDir>/<name>/references/ the skill's side files
12
+ * <agentsDir>/<name>/AGENT.md the same frontmatter rule
13
+ * <agentsDir>/<name>/metadata.yaml
14
+ * <lawsDir>/<name>/LAWS.md the constitution's index, one entity
15
+ * <lawsDir>/<name>/<category>.md ontology, laws, and one file per doctrine pack
16
+ *
17
+ * ONE WAY. The source stays `src/`; an export is a render of it, as an install is. Nothing reads
18
+ * an exported folder back.
19
+ *
20
+ * THE PROFILE is where the receiving library's own rules go: the name prefix it demands, the
21
+ * owner and maintainer its metadata requires, its folder names. It is a JSON file the user keeps
22
+ * outside the package, because those values are theirs. This module names no library; without
23
+ * a profile it exports under the source names. A git checkout may carry one of its own,
24
+ * `export.profile.json` at the root (`DEFAULT_PROFILE`), which is the default there.
25
+ *
26
+ * WHAT CHANGES IN THE TEXT, and why each:
27
+ * - a reference to another exported entity is rewritten to the name it is exported under, and
28
+ * listed in `requires`, so the reader's installer can resolve it;
29
+ * - a skill's side files move under `references/`, and its pointers follow;
30
+ * - a skill loses its Self-improvement footer, which points at a notebook only an install has.
31
+ * An agent keeps the whole of its seven sections, step 0 and Self-improvement included: that
32
+ * shape is the contract a persona library reads;
33
+ * - host keys (`disable-model-invocation`, `disallowedTools`, ...) are not written at all.
34
+ * A citation of a law or doctrine stays the principle's name, and the entity `requires` the
35
+ * exported constitution, which is where that name is defined.
36
+ *
37
+ * NOT EXPORTED: an alias (a second name for one skill), the authoring templates, and a vendored
38
+ * folder skill. The last is a third party's folder shipped verbatim under its own licence and
39
+ * frontmatter; a library takes those from their upstream, not through this render.
40
+ *
41
+ * WRITES ARE CLAIM-ON-CREATE, as everywhere else: the export records what it wrote in
42
+ * `geneseed-export.json` at `--out`, overwrites and prunes only what a previous export recorded,
43
+ * and leaves a file it finds and did not write, named in the summary. So `--out` may be a
44
+ * checkout of the library itself.
45
+ */
46
+ import {
47
+ copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, rmdirSync, unlinkSync,
48
+ } from 'node:fs';
49
+ import path from 'node:path';
50
+
51
+ import {
52
+ agentDescription, isVendoredPath, skillDescription, stripSkillBodyLinks, pointSideFiles,
53
+ } from '../hosts/native.mjs';
54
+ import { ownedWithin } from '../hosts/owned.mjs';
55
+ import { lstripNewlines } from '../hosts/settings.mjs';
56
+ import { printErr, printOut, readText, writeText } from '../lib/fs.mjs';
57
+ import { relPosix } from '../lib/text.mjs';
58
+ import { renderAll } from './render.mjs';
59
+ import {
60
+ CREDIT_RE, ROOT, aliasesOf, loadKits, makeCfg, upstreamOf,
61
+ } from './source.mjs';
62
+ import { sourceFingerprint, sourceReleaseVersion } from './version.mjs';
63
+
64
+ export const EXPORT_MANIFEST = 'geneseed-export.json';
65
+ /**
66
+ * The checkout's own profile, read when `--profile` is not given: the maintainer's defaults for
67
+ * the library they publish to (the user asked for it to live in the repository, 2026-11). It is
68
+ * a git checkout's file and is not in the npm package's `files`, so an npm install exports
69
+ * under the source names unless a profile is passed. `--profile none` ignores it.
70
+ */
71
+ export const DEFAULT_PROFILE = path.join(ROOT, 'export.profile.json');
72
+
73
+ /** What a profile may say, with what an export without one uses. */
74
+ const PROFILE_DEFAULTS = {
75
+ prefix: '',
76
+ owner: null,
77
+ maintainer: null,
78
+ status: 'experimental',
79
+ compatibleTools: [],
80
+ skillsDir: 'skills',
81
+ agentsDir: 'agents/personas',
82
+ lawsDir: 'laws',
83
+ lawsName: 'laws',
84
+ laws: true,
85
+ only: null,
86
+ exclude: [],
87
+ keepSkillSelfImprovement: false,
88
+ };
89
+ const LIST_KEYS = ['compatibleTools', 'exclude'];
90
+ const NAME_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
91
+ const CITES_RE = /\{\{(?:LAW|DOCTRINE):[a-z0-9-]+\}\}/;
92
+
93
+ /** A refusal: the message is the whole of what the user needs, so no stack is printed. */
94
+ class ExportError extends Error {}
95
+
96
+ /**
97
+ * Read and check a profile. Every key is optional; an unknown key is refused by name, because a
98
+ * misspelt `prefx` would otherwise export every entity under the wrong name without a word.
99
+ */
100
+ export function loadProfile(file) {
101
+ if (!file) return { ...PROFILE_DEFAULTS };
102
+ let data;
103
+ try { data = JSON.parse(readFileSync(file, 'utf8')); } catch (e) {
104
+ throw new ExportError(`--profile ${file}: ${e.code === 'ENOENT' ? 'no such file' : `not JSON (${e.message})`}`);
105
+ }
106
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
107
+ throw new ExportError(`--profile ${file}: must hold one JSON object`);
108
+ }
109
+ const unknown = Object.keys(data).filter((k) => !Object.hasOwn(PROFILE_DEFAULTS, k));
110
+ if (unknown.length) {
111
+ throw new ExportError(`--profile ${file}: unknown key(s) ${unknown.join(', ')} — it takes `
112
+ + Object.keys(PROFILE_DEFAULTS).join(', '));
113
+ }
114
+ const p = { ...PROFILE_DEFAULTS, ...data };
115
+ for (const k of LIST_KEYS) {
116
+ if (!Array.isArray(p[k]) || p[k].some((v) => typeof v !== 'string')) {
117
+ throw new ExportError(`--profile ${file}: ${k} must be a list of strings`);
118
+ }
119
+ }
120
+ if (p.only !== null && (!Array.isArray(p.only) || p.only.some((v) => typeof v !== 'string'))) {
121
+ throw new ExportError(`--profile ${file}: only must be a list of strings, or absent`);
122
+ }
123
+ for (const k of ['skillsDir', 'agentsDir', 'lawsDir']) {
124
+ const v = p[k];
125
+ if (typeof v !== 'string' || !v || path.isAbsolute(v) || v.split(/[\\/]/).includes('..')) {
126
+ throw new ExportError(`--profile ${file}: ${k} must be a relative folder inside --out`);
127
+ }
128
+ }
129
+ if (typeof p.prefix !== 'string') throw new ExportError(`--profile ${file}: prefix must be a string`);
130
+ return p;
131
+ }
132
+
133
+ /** One YAML scalar. Double-quoted JSON is valid YAML, and the only safe spelling of `@handle`. */
134
+ const yamlStr = (s) => JSON.stringify(String(s));
135
+
136
+ /**
137
+ * `metadata.yaml`: the governance half, which a pipeline reads and a model never does. Keys in
138
+ * a fixed order, a key written only when it has a value, so two exports of one source are
139
+ * byte-identical. `name` and `description` are passed only for the constitution: a skill's and
140
+ * an agent's live in the frontmatter, and a library's schema may refuse them here.
141
+ */
142
+ function metadataYaml(m) {
143
+ const lines = [];
144
+ if (m.name) lines.push(`name: ${m.name}`);
145
+ lines.push(`type: ${m.type}`);
146
+ if (m.owner) lines.push(`owner: ${yamlStr(m.owner)}`);
147
+ if (m.maintainer) lines.push(`maintainer: ${yamlStr(m.maintainer)}`);
148
+ lines.push(`version: ${m.version}`, `status: ${m.status}`);
149
+ if (m.description) lines.push(`description: ${yamlStr(m.description)}`);
150
+ const list = (key, items) => {
151
+ if (!items.length) return;
152
+ lines.push(`${key}:`);
153
+ for (const it of items) lines.push(` - ${/^[a-z0-9][a-z0-9-]*$/.test(it) ? it : yamlStr(it)}`);
154
+ };
155
+ list('compatible-tools', m.compatibleTools);
156
+ if (m.origin) lines.push(`origin: ${yamlStr(m.origin)}`);
157
+ if (m.license) lines.push(`license: ${m.license}`);
158
+ list('requires', m.requires);
159
+ return `${lines.join('\n')}\n`;
160
+ }
161
+
162
+ const frontmatter = (name, description) => `---\nname: ${name}\ndescription: ${yamlStr(description)}\n---\n\n`;
163
+
164
+ /** The registry's row for one entity: its version and nothing else is read. */
165
+ function registryVersions() {
166
+ try {
167
+ return JSON.parse(readText(path.join(ROOT, 'registry.json'))).entities ?? {};
168
+ } catch { return {}; }
169
+ }
170
+
171
+ /**
172
+ * Rewrite every reference to another exported entity to its exported name, and collect them.
173
+ * Two spellings carry a reference in the sources: a Markdown link to the entity's spec
174
+ * (`[architect](architect.md)`, `[plan](skills/plan.md)`), and its name in backticks before the
175
+ * word skill or agent (the `explain-changes` skill). A name that is not exported is left as
176
+ * written and reported, so the reader is not sent to an entity the export never wrote.
177
+ */
178
+ function relink(text, self, names, requires, missing, known) {
179
+ const hit = (stem, whole) => {
180
+ if (stem === self.stem) return `\`${self.name}\``;
181
+ if (names.has(stem)) { requires.add(names.get(stem)); return `\`${names.get(stem)}\``; }
182
+ if (known.has(stem)) missing.add(stem);
183
+ return whole;
184
+ };
185
+ return text
186
+ .replace(/\[[^\]]+\]\((?:\.\.\/)?(?:(?:agents|skills)\/)?([a-z0-9][a-z0-9-]*)\.md(?:#[^)\s]*)?\)/g,
187
+ (whole, stem) => (names.has(stem) || known.has(stem) ? hit(stem, whole) : whole))
188
+ .replace(/`([a-z0-9][a-z0-9-]*)`(?=\s+(?:skill|agent)s?\b)/gi,
189
+ (whole, stem) => (names.has(stem) || known.has(stem) ? hit(stem, whole) : whole));
190
+ }
191
+
192
+ /**
193
+ * The body as a library reads it: the two authoring markers a host emit consumes are dropped
194
+ * (`aliases:` names skills this export does not write, `invocation:` is a host frontmatter key),
195
+ * and the title carries the exported name, which is the one the reader will look the entity up by.
196
+ */
197
+ function forLibrary(body, s) {
198
+ return body
199
+ .replace(/^[ \t]*<!--[ \t]*(?:aliases|invocation):[^>]*-->[ \t]*\n/gm, '')
200
+ .replace(new RegExp(`^(# [^\\n:]+: )${s.stem}[ \\t]*$`, 'm'), `$1${s.name}`);
201
+ }
202
+
203
+ /** A skill body without its Self-improvement footer, which is always the last section. */
204
+ function dropSelfImprovement(body) {
205
+ const at = body.search(/^## Self-improvement[ \t]*$/m);
206
+ return at < 0 ? body : `${body.slice(0, at).replace(/\s+$/, '')}\n`;
207
+ }
208
+
209
+ /** The upstreams a spec credits: `{ license, origin }`, the first key's licence winning. */
210
+ function creditsOf(sourceFile, src) {
211
+ let raw;
212
+ try { raw = readText(sourceFile); } catch { return {}; }
213
+ const ups = [...raw.matchAll(CREDIT_RE)].map(([, key]) => upstreamOf(key, src)).filter(Boolean);
214
+ if (!ups.length) return {};
215
+ const repos = [...new Set(ups.map((u) => `https://github.com/${u.repo}`))];
216
+ return { license: ups[0].license, origin: repos.join(', ') };
217
+ }
218
+
219
+ /**
220
+ * Plan the export: every file as `{ rel, text | copy }`, plus what was left out and why. Pure
221
+ * over the source tree; `writeExport` is the half that touches `out`.
222
+ */
223
+ export function planExport({ profile = { ...PROFILE_DEFAULTS }, theme = 'neutral', kits = null } = {}) {
224
+ const cfg = makeCfg({ kits: kits ?? [...loadKits().keys()] });
225
+ // Full footprint: an exported entity is read on its own, with no carrier beside it to expand
226
+ // a lean line.
227
+ const { items } = renderAll(cfg, theme, { footprint: 'full' });
228
+ const srcRel = (it) => relPosix(cfg.src, it.src);
229
+ const versions = registryVersions();
230
+ const release = sourceReleaseVersion(cfg);
231
+
232
+ // The roster: flat specs under skills/ and agents/, minus templates and what the profile drops.
233
+ const wanted = (stem) => !profile.exclude.includes(stem) && (profile.only === null || profile.only.includes(stem));
234
+ const specs = [];
235
+ const known = new Set();
236
+ for (const it of items) {
237
+ if (it.text === null || it.licenceOf) continue;
238
+ const m = /^(skills|agents)\/([a-z0-9][a-z0-9-]*)\.md$/.exec(srcRel(it));
239
+ if (!m) continue;
240
+ known.add(m[2]);
241
+ if (wanted(m[2])) {
242
+ specs.push({ kind: m[1] === 'skills' ? 'skill' : 'persona', stem: m[2], it, name: `${profile.prefix}${m[2]}` });
243
+ }
244
+ }
245
+ const skipped = [];
246
+ const vendored = new Set(items.map(srcRel).filter(isVendoredPath).map((r) => r.split('/')[1]));
247
+ for (const dir of [...vendored].sort()) {
248
+ known.add(dir);
249
+ if (wanted(dir)) skipped.push(`${dir}: a vendored folder skill, shipped under its upstream's own layout and licence`);
250
+ }
251
+
252
+ const names = new Map();
253
+ const problems = [];
254
+ for (const s of specs) {
255
+ if (!NAME_RE.test(s.name) || s.name.length > 64) problems.push(`${s.name}: not a kebab-case name of at most 64 characters`);
256
+ names.set(s.stem, s.name);
257
+ }
258
+ const lawsName = `${profile.prefix}${profile.lawsName}`;
259
+ if (profile.laws && (!NAME_RE.test(lawsName) || lawsName.length > 64)) problems.push(`${lawsName}: not a kebab-case name of at most 64 characters`);
260
+ if (problems.length) throw new ExportError(`these names cannot be exported:\n ${problems.join('\n ')}`);
261
+
262
+ const files = [];
263
+ const entities = [];
264
+ const aliases = [];
265
+ const missing = new Map();
266
+ const base = { owner: profile.owner, maintainer: profile.maintainer, status: profile.status,
267
+ compatibleTools: profile.compatibleTools };
268
+
269
+ for (const s of specs.sort((a, b) => (a.name < b.name ? -1 : 1))) {
270
+ const dir = `${s.kind === 'skill' ? profile.skillsDir : profile.agentsDir}/${s.name}`;
271
+ const requires = new Set();
272
+ const gone = new Set();
273
+ const link = (text) => relink(text, s, names, requires, gone, known);
274
+ let body = forLibrary(lstripNewlines(s.it.text), s);
275
+ let description;
276
+ if (s.kind === 'skill') {
277
+ description = skillDescription(s.it.text);
278
+ body = stripSkillBodyLinks(link(pointSideFiles(body, s.stem, 'references')));
279
+ if (!profile.keepSkillSelfImprovement) body = dropSelfImprovement(body);
280
+ for (const side of items) {
281
+ const parts = srcRel(side).split('/');
282
+ if (side.licenceOf === s.stem) {
283
+ files.push({ rel: `${dir}/${path.posix.basename(side.rel)}`, copy: side.src });
284
+ } else if (side.text !== null && parts.length === 3 && parts[0] === 'skills' && parts[1] === s.stem) {
285
+ files.push({ rel: `${dir}/references/${parts[2]}`, text: stripSkillBodyLinks(link(side.text)) });
286
+ }
287
+ }
288
+ } else {
289
+ description = agentDescription(s.it.text);
290
+ body = link(body);
291
+ }
292
+ if (profile.laws && CITES_RE.test(readText(s.it.src))) requires.add(lawsName);
293
+ files.push({ rel: `${dir}/${s.kind === 'skill' ? 'SKILL.md' : 'AGENT.md'}`, text: frontmatter(s.name, description) + body });
294
+ files.push({ rel: `${dir}/metadata.yaml`, text: metadataYaml({
295
+ ...base, type: s.kind, requires: [...requires].sort(),
296
+ version: versions[`${s.kind === 'skill' ? 'skills' : 'agents'}/${s.stem}`]?.version ?? release,
297
+ ...creditsOf(s.it.src, cfg.src),
298
+ }) });
299
+ entities.push({ type: s.kind, name: s.name, source: srcRel(s.it), path: dir });
300
+ if (gone.size) missing.set(s.name, [...gone].sort());
301
+ aliases.push(...aliasesOf(s.it.text));
302
+ }
303
+
304
+ if (aliases.length) skipped.push(`${aliases.sort().join(', ')}: aliases, each a second name for a skill exported once`);
305
+
306
+ if (profile.laws) {
307
+ // The constitution, ONE FILE PER CATEGORY (the user asked, 2026-11: a reader looking for a
308
+ // doctrine pack should not scroll through the laws to find it): the ontology, the laws, and
309
+ // each doctrine pack, as the install ships them. `LAWS.md` is the index a reader opens
310
+ // first, naming each file and what it holds.
311
+ const dir = `${profile.lawsDir}/${lawsName}`;
312
+ const parts = [];
313
+ const packs = cfg.doctrines; // the pack order the carrier lists them in
314
+ for (const it of items) {
315
+ const m = /^(ontology|laws|doctrines)\/([a-z0-9-]+)\.md$/.exec(srcRel(it));
316
+ if (!m || it.text === null) continue;
317
+ const [, tier, stem] = m;
318
+ const body = stripSkillBodyLinks(lstripNewlines(it.text)).replace(/\s+$/, '');
319
+ const rules = (body.match(/^### /gm) || []).length;
320
+ // A rendered tier file opens on prose, with no title of its own: inside an install the
321
+ // carrier's section heading is its title. Standing alone it needs one.
322
+ const pack = /^\*\*(.+?)\*\* — (.+?)\.?$/m.exec(body);
323
+ const [title, what] = tier === 'doctrines'
324
+ ? [`Doctrines — ${pack?.[1] ?? stem}`, `${pack?.[2] ?? 'a doctrine pack'} (${rules} rules)`]
325
+ : tier === 'laws'
326
+ ? ['Laws', `the invariants, always in force (${rules} rules)`]
327
+ : ['Ontology', 'how the agent thinks, decides and behaves'];
328
+ const file = tier === 'doctrines' ? `doctrines-${stem}.md` : `${tier}.md`;
329
+ parts.push({ rank: ['ontology', 'laws'].indexOf(tier) >= 0 ? ['ontology', 'laws'].indexOf(tier) : 2 + packs.indexOf(stem), file, title, what });
330
+ files.push({ rel: `${dir}/${file}`, text: `# ${title}\n\n${body}\n` });
331
+ }
332
+ parts.sort((x, y) => x.rank - y.rank);
333
+ files.push({ rel: `${dir}/LAWS.md`, text: [
334
+ `# ${lawsName}`, '',
335
+ 'The constitution the skills and agents of this collection cite by principle name. One '
336
+ + 'file per category:', '',
337
+ ...parts.map((x) => `- \`${x.file}\` — ${x.title}: ${x.what}`), '',
338
+ ].join('\n') });
339
+ files.push({ rel: `${dir}/metadata.yaml`, text: metadataYaml({
340
+ ...base, type: 'laws', name: lawsName, requires: [], version: release,
341
+ description: 'The constitution the exported skills and agents cite by principle name: '
342
+ + 'the ontology, the laws and every doctrine pack, in full.',
343
+ }) });
344
+ entities.push({ type: 'laws', name: lawsName, source: 'laws/, ontology/, doctrines/', path: dir });
345
+ }
346
+
347
+ return {
348
+ files, entities, skipped, missing,
349
+ meta: { geneseed: release, fingerprint: sourceFingerprint(cfg), theme },
350
+ };
351
+ }
352
+
353
+ /** Remove now-empty directories from `dir` up to, never including, `out`. */
354
+ function pruneEmpty(dir, out) {
355
+ for (let d = dir; d !== out && d.startsWith(out + path.sep); d = path.dirname(d)) {
356
+ try { if (readdirSync(d).length) return; rmdirSync(d); } catch { return; }
357
+ }
358
+ }
359
+
360
+ /**
361
+ * Write a plan into `out`, claim-on-create. Returns `{ written, kept, pruned }`: `kept` is
362
+ * every file found at a destination that no previous export recorded, and left alone.
363
+ */
364
+ export function writeExport(plan, out) {
365
+ mkdirSync(out, { recursive: true });
366
+ let prior = [];
367
+ try {
368
+ const m = JSON.parse(readFileSync(path.join(out, EXPORT_MANIFEST), 'utf8'));
369
+ if (Array.isArray(m.files)) prior = m.files.filter((f) => typeof f === 'string');
370
+ } catch { /* a first export: nothing is recorded */ }
371
+ const mine = new Set(prior);
372
+ const now = new Set(plan.files.map((f) => f.rel));
373
+ const pruned = [];
374
+ for (const rel of ownedWithin(out, prior.filter((r) => !now.has(r)))) {
375
+ const victim = path.join(out, rel);
376
+ try { unlinkSync(victim); pruned.push(rel); pruneEmpty(path.dirname(victim), out); } catch { /* already gone */ }
377
+ }
378
+ const written = [];
379
+ const kept = [];
380
+ for (const f of plan.files) {
381
+ const dest = path.join(out, f.rel);
382
+ if (existsSync(dest) && !mine.has(f.rel)) { kept.push(f.rel); continue; }
383
+ mkdirSync(path.dirname(dest), { recursive: true });
384
+ if (f.copy) copyFileSync(f.copy, dest);
385
+ else writeText(dest, f.text);
386
+ written.push(f.rel);
387
+ }
388
+ writeText(path.join(out, EXPORT_MANIFEST), `${JSON.stringify({
389
+ _comment: 'Written by `geneseed export`. Lists the files that export wrote here, so the next '
390
+ + 'one replaces and prunes exactly those. A file not listed is yours and is never touched.',
391
+ ...plan.meta, entities: plan.entities, files: written.sort(),
392
+ }, null, 2)}\n`);
393
+ return { written, kept, pruned };
394
+ }
395
+
396
+ /** The `export` verb. */
397
+ export function cmdExport(args) {
398
+ if (!args.out) {
399
+ printErr('[export] --out <folder> is required: where the entity folders are written.\n');
400
+ return 2;
401
+ }
402
+ try {
403
+ const given = args.profile == null && existsSync(DEFAULT_PROFILE) ? DEFAULT_PROFILE : args.profile;
404
+ const profile = loadProfile(given === 'none' ? null : given);
405
+ if (given === DEFAULT_PROFILE) printOut(`[export] profile: ${DEFAULT_PROFILE} (--profile none to export without one)\n`);
406
+ const kits = args.kits == null ? null : String(args.kits).split(',').map((k) => k.trim()).filter((k) => k && k !== 'none');
407
+ const plan = planExport({ profile, theme: args.theme || 'neutral', kits });
408
+ const out = path.resolve(String(args.out));
409
+ const { written, kept, pruned } = writeExport(plan, out);
410
+ const count = (t) => plan.entities.filter((e) => e.type === t).length;
411
+ printOut(`[export] ${count('skill')} skill(s), ${count('persona')} agent(s)`
412
+ + `${count('laws') ? ', the constitution' : ''} -> ${out} (${written.length} file(s)`
413
+ + `${pruned.length ? `, ${pruned.length} pruned` : ''})\n`);
414
+ for (const line of plan.skipped) printOut(`[export] not exported — ${line}\n`);
415
+ for (const [name, stems] of plan.missing) {
416
+ printErr(`[export] WARN: ${name} refers to ${stems.join(', ')}, which this export leaves out\n`);
417
+ }
418
+ if (kept.length) {
419
+ printErr(`[export] WARN: kept ${kept.length} existing file(s) no earlier export wrote, and skipped `
420
+ + `the exported copy of each: ${kept.slice(0, 5).join(', ')}${kept.length > 5 ? `, and ${kept.length - 5} more` : ''}\n`);
421
+ }
422
+ if (!profile.owner || !profile.maintainer) {
423
+ printErr('[export] WARN: no owner or maintainer in the profile; metadata.yaml was written without one\n');
424
+ }
425
+ return 0;
426
+ } catch (e) {
427
+ if (!(e instanceof ExportError)) throw e;
428
+ printErr(`[export] ${e.message}\n`);
429
+ return 2;
430
+ }
431
+ }
@@ -105,6 +105,9 @@ export function cmdBuild(args) {
105
105
  // The bare switches `build` forwards (the gate switches): they take no value, so they are
106
106
  // not BUILD_FORWARD rows.
107
107
  for (const g of GATE_SWITCHES) if (args[g.arg]) argv.push(g.flag);
108
+ if (args.force) argv.push('--force');
109
+ // Forwarded like `--force`: a one-shot flag of the generator, with no `GATE_SWITCHES` row.
110
+ if (args.pruneGates) argv.push('--prune-gates');
108
111
  return driverMain(argv);
109
112
  }
110
113
 
@@ -35,7 +35,7 @@ import { parseJson } from '../lib/json.mjs';
35
35
  import { normcase, comparePaths } from '../lib/paths.mjs';
36
36
  // `js/build/source.mjs` imports nothing but node builtins, so this direction cannot cycle.
37
37
  import {
38
- CREDIT_RE, GATE_SWITCHES, PACK_ORDER, kitMembers, loadKits, readPackText, resolveCredits, resolveRuleIds, ruleCanon, upstreamOf,
38
+ CREDIT_RE, GATE_SWITCHES, PACK_ORDER, kitMembers, loadKits, readPackText, resolveCredits, resolveRuleIds, ruleCanon, titleKey, upstreamOf,
39
39
  } from './source.mjs';
40
40
  import { SHARED_TIER_LINE } from '../hosts/hosts.mjs';
41
41
  import { VENDORED_SKILL_DIRS } from '../hosts/native.mjs';
@@ -296,14 +296,41 @@ export function splitAtLawHeadings(text) {
296
296
  return out;
297
297
  }
298
298
 
299
- /** The pointer under §1 at lean. The laws' lean text itself is authored in LEAN blocks. */
300
- export function lawsPointer(theme, lawsPrefix = '') {
299
+ /**
300
+ * The one pointer at lean, closing §2 for both tiers: the laws' and the rules' lean text is
301
+ * authored in LEAN blocks, and this names where the complete text of each lives. It was two notes,
302
+ * one under each section, saying the same thing (owner decision D2, 2026-11-11).
303
+ */
304
+ export function briefPointer(theme, lawsPrefix = '', anyPack = true) {
301
305
  const law = theme.LAW ?? 'Law';
306
+ const doctrine = theme.DOCTRINE ?? 'Doctrine';
302
307
  const lawsDir = theme.DIR_LAWS ?? 'laws';
303
- return `> Each ${law} above is given in brief — the rule, not its reasoning. The `
304
- + `complete, binding text of every ${law} is in \`${lawsPrefix}${lawsDir}/universal.md\`; `
305
- + `read it whenever a ${law}'s application is unclear, and before any act touching `
306
- + 'secrets, deletion, git history, scope, or untrusted content.';
308
+ const dir = theme.DIR_DOCTRINES ?? 'doctrines';
309
+ // With no pack active only the laws are above; the packs' folder is still named, as it ships.
310
+ const above = anyPack ? `${law} and ${doctrine}` : law;
311
+ return `> Each ${above} above is given in brief — the rule, not its reasoning. `
312
+ + `The complete text is in \`${lawsPrefix}${lawsDir}/universal.md\` (binding) and in `
313
+ + `\`${lawsPrefix}${dir}/\` (every pack, active or not). Read the matching file whenever a rule's application `
314
+ + `is unclear; read \`${lawsPrefix}${lawsDir}/universal.md\` before any act touching secrets, `
315
+ + 'deletion, git history, scope, or untrusted content.';
316
+ }
317
+
318
+ /**
319
+ * LEAN DROPS THE VOICE'S HALF of each rule title and the italic epigraph under each § heading
320
+ * (owner decision D2, 2026-11-11). A theme spells a title `Arcana Sigillata · Sealed Secrets`;
321
+ * lean renders the principle alone, the name every citation already renders (`*Sealed
322
+ * Secrets*`), so one rule reads the same at its heading and where it is cited. Done here, on the
323
+ * unsubstituted tokens, so all fourteen voices follow without a theme edit. Keyed on the PER-FILE
324
+ * footprint: the on-disk `laws/`, `ontology/` and `doctrines/` render full even in a lean install,
325
+ * keep the voice, and are what `js/inspect/inventory.mjs` and the console parse.
326
+ */
327
+ const TITLE_TOKEN_RE = /\{\{((?:LEX|DOC)_[A-Z0-9_]+)\}\}/g;
328
+ const EPIGRAPH_LINE_RE = /^\*\{\{EPI_[A-Z_]+\}\}\*\n\n/gm;
329
+ function leanVoice(text, src) {
330
+ text = text.replace(EPIGRAPH_LINE_RE, '');
331
+ if (!text.includes('{{LEX_') && !text.includes('{{DOC_')) return text;
332
+ const names = new Map(ruleCanon(src).rules.map((r) => [titleKey(r.kind, r.id), r.name]));
333
+ return text.replace(TITLE_TOKEN_RE, (whole, key) => names.get(key) ?? whole);
307
334
  }
308
335
 
309
336
  /**
@@ -392,17 +419,14 @@ export function renderFile(cfg, filePath, theme, footprint = 'full', lawsPrefix
392
419
  if (normcase(target) === normcase(here) || visiting.has(normcase(target))) {
393
420
  return `<!-- CIRCULAR INCLUDE: ${rel} -->`;
394
421
  }
395
- let inner = renderFile(cfg, target, theme, footprint, lawsPrefix,
396
- new Set(visiting).add(normcase(here)), nativeCatalog)
422
+ return renderFile(cfg, target, theme, footprint, lawsPrefix,
423
+ new Set(visiting).add(normcase(here)), nativeCatalog)
397
424
  .replace(/\n+$/, ''); // `.rstrip("\n")`
398
- if (footprint === 'lean' && rel === 'laws/universal.md') {
399
- inner = `${inner}\n\n${lawsPointer(theme, lawsPrefix)}`;
400
- }
401
- return inner;
402
425
  });
403
426
 
404
427
  text = resolveCatalogs(text, nativeCatalog, cfg.excludeSkills ?? [], cfg);
405
428
  text = resolveLean(text, footprint);
429
+ if (footprint === 'lean') text = leanVoice(text, cfg.src);
406
430
  return substitute(text, theme);
407
431
  }
408
432
 
@@ -503,7 +527,8 @@ function dropExcludedRules(text, pack, excluded) {
503
527
  }
504
528
 
505
529
  function doctrinesBody(cfg, theme, active, footprint, lawsPrefix) {
506
- if (!active.length) return '';
530
+ // At lean the section still carries the one pointer with no pack active: it names the laws too.
531
+ if (!active.length) return footprint === 'lean' ? briefPointer(theme, lawsPrefix, false) : '';
507
532
  const excluded = new Set(cfg.excludeRules ?? []);
508
533
  const parts = active.map((name) => {
509
534
  const raw = dropExcludedRules(readPackText(path.join(cfg.src, 'doctrines', `${name}.md`)),
@@ -512,15 +537,10 @@ function doctrinesBody(cfg, theme, active, footprint, lawsPrefix) {
512
537
  // voice second. THE ORDER IS LOAD-BEARING — `resolveLean` reads HTML markers, and
513
538
  // substituting first would hand it prose in fourteen voices. The first-sentence cut is gone;
514
539
  // a rule's lean text is written in `src/doctrines/<pack>.md`, not measured out of its prose.
515
- return substitute(resolveLean(raw, footprint), theme).trim();
540
+ const text = resolveLean(raw, footprint);
541
+ return substitute(footprint === 'lean' ? leanVoice(text, cfg.src) : text, theme).trim();
516
542
  });
517
- if (footprint === 'lean') {
518
- const doctrine = theme.DOCTRINE ?? 'Doctrine';
519
- const dir = theme.DIR_DOCTRINES ?? 'doctrines';
520
- parts.push(`> Each ${doctrine} above is given in brief — the rule, not its reasoning. `
521
- + `The complete text of every pack, active or not, is in \`${lawsPrefix}${dir}/\`; read `
522
- + `the pack file whenever a ${doctrine}'s application is unclear.`);
523
- }
543
+ if (footprint === 'lean') parts.push(briefPointer(theme, lawsPrefix));
524
544
  return parts.join('\n\n');
525
545
  }
526
546
 
@@ -667,8 +687,8 @@ export function renderAll(cfg, themeName, {
667
687
  if (NOT_BUNDLED.has(sp[0])) continue;
668
688
  if (sp.length >= 2 && Object.hasOwn(off, sp[0]) && off[sp[0]].has(sp[1].replace(/\.md$/, ''))) continue;
669
689
  const outRel = destRel(themedRel(rel, theme)).split(path.sep).join('/'); // as_posix()
670
- // The on-disk `laws/`, `ontology/` and `doctrines/` are the "complete text" the two lean
671
- // pointers promise — §1's and the Doctrines section's. They render at full whatever the
690
+ // The on-disk `laws/`, `ontology/` and `doctrines/` are the "complete text" the lean
691
+ // pointer under the Doctrines section promises. They render at full whatever the
672
692
  // footprint; only what AGENT.md INLINES leans. `doctrines/` joined them when its rules got
673
693
  // authored LEAN blocks: before that a pack file carried no markers and shipped whole by
674
694
  // accident, which is a different thing from shipping whole by contract.
@@ -600,7 +600,8 @@ export const GATE_SWITCHES = [
600
600
  */
601
601
  export function makeCfg({
602
602
  posture = 'peer', mode = 'direct', trust = DEFAULT_PRESET, doctrines = PACK_ORDER,
603
- excludeRules = [], excludeSkills = [], kits = [], sharedTier = /** @type {boolean | string} */ (false), ...switches
603
+ excludeRules = [], excludeSkills = [], kits = [], sharedTier = /** @type {boolean | string} */ (false),
604
+ pruneGates = false, force = false, ...switches
604
605
  } = {}) {
605
606
  return {
606
607
  root: ROOT,
@@ -632,9 +633,13 @@ export function makeCfg({
632
633
  kits: Array.isArray(kits) ? [...kits] : [],
633
634
  // The shared tier read by a PROJECT install (`--shared-tier on`); `on` from the flag, a boolean from a read-back.
634
635
  sharedTier: sharedTier === true || sharedTier === 'on',
636
+ // `--force`, for this one build: only a literal `true` forces. Never an axis of the install.
637
+ force: force === true,
635
638
  // The gate switches (`GATE_SWITCHES`: `secretsGate`, `doneGate`, `deletionGate`), each armed
636
639
  // unless its `no*` arg says so in so many words: only a literal `true` disarms, so every
637
640
  // caller that never heard of a switch keeps the gate.
638
641
  ...Object.fromEntries(GATE_SWITCHES.map((g) => [g.key, switches[g.arg] !== true])),
642
+ // `--prune-gates`: only a literal `true`, so a caller that never heard of it prunes nothing.
643
+ pruneGates: pruneGates === true,
639
644
  };
640
645
  }