@inventarch/workspace-runtime 3.8.0 → 3.9.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 (131) hide show
  1. package/README.md +2 -2
  2. package/SPEC.md +11 -9
  3. package/dist/adapters.d.ts +2 -1
  4. package/dist/adapters.d.ts.map +1 -1
  5. package/dist/adapters.js +7 -4
  6. package/dist/adapters.js.map +1 -1
  7. package/dist/authoring-format.d.ts.map +1 -1
  8. package/dist/authoring-format.js +5 -4
  9. package/dist/authoring-format.js.map +1 -1
  10. package/dist/authoring-index.d.ts +5 -1
  11. package/dist/authoring-index.d.ts.map +1 -1
  12. package/dist/authoring-index.js +7 -5
  13. package/dist/authoring-index.js.map +1 -1
  14. package/dist/authoring-manifest.d.ts.map +1 -1
  15. package/dist/authoring-manifest.js +5 -4
  16. package/dist/authoring-manifest.js.map +1 -1
  17. package/dist/authoring-types.d.ts +4 -2
  18. package/dist/authoring-types.d.ts.map +1 -1
  19. package/dist/authoring.d.ts.map +1 -1
  20. package/dist/authoring.js +2 -1
  21. package/dist/authoring.js.map +1 -1
  22. package/dist/candidate.d.ts +7 -0
  23. package/dist/candidate.d.ts.map +1 -1
  24. package/dist/candidate.js +36 -24
  25. package/dist/candidate.js.map +1 -1
  26. package/dist/corpus.d.ts +7 -0
  27. package/dist/corpus.d.ts.map +1 -1
  28. package/dist/corpus.js +14 -1
  29. package/dist/corpus.js.map +1 -1
  30. package/dist/generate/agent-profile.d.ts.map +1 -1
  31. package/dist/generate/agent-profile.js +47 -16
  32. package/dist/generate/agent-profile.js.map +1 -1
  33. package/dist/generate/capability.d.ts.map +1 -1
  34. package/dist/generate/capability.js +6 -1
  35. package/dist/generate/capability.js.map +1 -1
  36. package/dist/generate/format.d.ts.map +1 -1
  37. package/dist/generate/format.js +1 -1
  38. package/dist/generate/format.js.map +1 -1
  39. package/dist/generate/index.d.ts +1 -1
  40. package/dist/generate/index.d.ts.map +1 -1
  41. package/dist/generate/index.js +1 -1
  42. package/dist/generate/index.js.map +1 -1
  43. package/dist/generate/playbook.d.ts.map +1 -1
  44. package/dist/generate/playbook.js +6 -1
  45. package/dist/generate/playbook.js.map +1 -1
  46. package/dist/generate/plugin.d.ts +1 -0
  47. package/dist/generate/plugin.d.ts.map +1 -1
  48. package/dist/generate/plugin.js +1 -0
  49. package/dist/generate/plugin.js.map +1 -1
  50. package/dist/generate/standalone-plugin.d.ts +26 -0
  51. package/dist/generate/standalone-plugin.d.ts.map +1 -0
  52. package/dist/generate/standalone-plugin.js +1616 -0
  53. package/dist/generate/standalone-plugin.js.map +1 -0
  54. package/dist/host-plugin/inventory.d.ts +1 -1
  55. package/dist/host-plugin/inventory.d.ts.map +1 -1
  56. package/dist/host-plugin/inventory.js +3 -1
  57. package/dist/host-plugin/inventory.js.map +1 -1
  58. package/dist/host-plugin/lower.d.ts +2 -1
  59. package/dist/host-plugin/lower.d.ts.map +1 -1
  60. package/dist/host-plugin/lower.js +10 -6
  61. package/dist/host-plugin/lower.js.map +1 -1
  62. package/dist/host-plugin/manifest.d.ts +6 -4
  63. package/dist/host-plugin/manifest.d.ts.map +1 -1
  64. package/dist/host-plugin/manifest.js +24 -4
  65. package/dist/host-plugin/manifest.js.map +1 -1
  66. package/dist/index.d.ts +3 -3
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +3 -3
  69. package/dist/index.js.map +1 -1
  70. package/dist/lifecycle-profile.d.ts +4 -2
  71. package/dist/lifecycle-profile.d.ts.map +1 -1
  72. package/dist/lifecycle-profile.js +29 -9
  73. package/dist/lifecycle-profile.js.map +1 -1
  74. package/dist/lifecycle-rows.d.ts +2 -1
  75. package/dist/lifecycle-rows.d.ts.map +1 -1
  76. package/dist/lifecycle-rows.js +3 -2
  77. package/dist/lifecycle-rows.js.map +1 -1
  78. package/dist/lifecycle-transport.d.ts +2 -1
  79. package/dist/lifecycle-transport.d.ts.map +1 -1
  80. package/dist/lifecycle-transport.js +6 -4
  81. package/dist/lifecycle-transport.js.map +1 -1
  82. package/dist/lifecycle.d.ts +12 -5
  83. package/dist/lifecycle.d.ts.map +1 -1
  84. package/dist/lifecycle.js +27 -8
  85. package/dist/lifecycle.js.map +1 -1
  86. package/dist/local-store.d.ts +2 -1
  87. package/dist/local-store.d.ts.map +1 -1
  88. package/dist/local-store.js +5 -4
  89. package/dist/local-store.js.map +1 -1
  90. package/dist/plain-format.d.ts +32 -0
  91. package/dist/plain-format.d.ts.map +1 -0
  92. package/dist/plain-format.js +32 -0
  93. package/dist/plain-format.js.map +1 -0
  94. package/dist/projection-codex.d.ts +4 -0
  95. package/dist/projection-codex.d.ts.map +1 -1
  96. package/dist/projection-codex.js +6 -1
  97. package/dist/projection-codex.js.map +1 -1
  98. package/dist/projection-format.d.ts +8 -4
  99. package/dist/projection-format.d.ts.map +1 -1
  100. package/dist/projection-format.js +14 -3
  101. package/dist/projection-format.js.map +1 -1
  102. package/dist/projection-host.d.ts +18 -3
  103. package/dist/projection-host.d.ts.map +1 -1
  104. package/dist/projection-host.js +113 -20
  105. package/dist/projection-host.js.map +1 -1
  106. package/dist/projections.d.ts +1 -1
  107. package/dist/projections.d.ts.map +1 -1
  108. package/dist/projections.js +9 -4
  109. package/dist/projections.js.map +1 -1
  110. package/dist/publication.d.ts +12 -1
  111. package/dist/publication.d.ts.map +1 -1
  112. package/dist/publication.js +48 -29
  113. package/dist/publication.js.map +1 -1
  114. package/dist/resource-context.d.ts.map +1 -1
  115. package/dist/resource-context.js +12 -3
  116. package/dist/resource-context.js.map +1 -1
  117. package/dist/resource-format.d.ts +2 -1
  118. package/dist/resource-format.d.ts.map +1 -1
  119. package/dist/resource-format.js.map +1 -1
  120. package/dist/resources.d.ts.map +1 -1
  121. package/dist/resources.js +2 -1
  122. package/dist/resources.js.map +1 -1
  123. package/dist/task-capture-format.d.ts +2 -1
  124. package/dist/task-capture-format.d.ts.map +1 -1
  125. package/dist/task-capture-format.js +5 -3
  126. package/dist/task-capture-format.js.map +1 -1
  127. package/dist/written-names.d.ts +9 -0
  128. package/dist/written-names.d.ts.map +1 -0
  129. package/dist/written-names.js +9 -0
  130. package/dist/written-names.js.map +1 -0
  131. package/package.json +9 -9
@@ -0,0 +1,1616 @@
1
+ import { isSelection } from '@inventarch/graph';
2
+ import { PHASES } from '@inventarch/language';
3
+ import { defaultActor, mandateAuthorityOf, requireMandatesAdmitted, rootWorkspace, RuntimeError, } from '@inventarch/runtime';
4
+ import { emitFrontmatter } from '../host-plugin/frontmatter.js';
5
+ import { HostPluginError } from '../host-plugin/errors.js';
6
+ import { MANIFESTS, NAME } from '../host-plugin/inventory.js';
7
+ import { pluginManifest } from '../host-plugin/manifest.js';
8
+ import { antigravityProseCatalog, claudeProseCatalog, codexProseCatalog, geminiProseCatalog, PROSE_EFFECT_TOOLS, } from '../projection-host.js';
9
+ import { capabilityClosure, fieldsOf, stated, textsAt, valuesAt } from './format.js';
10
+ import { HOOK_IDENTITY_LIMIT, HOOK_LIMIT, HOOK_SELECTION_LENGTH, HOOK_SELECTION_LIMIT, registrableHook, registrableSelection, } from './hook.js';
11
+ const PUBLIC_FLOOR_SYSTEMS = new Set([
12
+ 'agent-composition-system',
13
+ 'agent-system',
14
+ 'authoring-system',
15
+ 'compliance-system',
16
+ 'governance-system',
17
+ 'hook-authoring-system',
18
+ 'learning-system',
19
+ 'session-system',
20
+ 'template-system',
21
+ 'work-system',
22
+ 'workspace-system',
23
+ ]);
24
+ const LANES = ['work', 'knowledge', 'delivery'];
25
+ const LANE_DESCRIPTIONS = {
26
+ work: 'Work lane router for planning, milestones, tasks, decisions, and record governance workflows. Use when structuring, planning, or reviewing work and governance items.',
27
+ knowledge: 'Knowledge lane router for retrieving, explaining, placing, checking, and maintaining repository documentation and knowledge records. Use when answering questions or maintaining docs.',
28
+ delivery: 'Delivery lane router for designing, implementing, reviewing, and verifying engineering or architecture changes. Use when building, refactoring, diagnosing, or reviewing deliverables.',
29
+ };
30
+ const HOOK_TOOLS = new Map([
31
+ ['write', 'Write'],
32
+ ['edit', 'Edit'],
33
+ ['multiedit', 'MultiEdit'],
34
+ ]);
35
+ const jsonBytes = (value) => Buffer.from(`${JSON.stringify(value, null, 2)}\n`, 'utf8');
36
+ const utf8Bytes = (text) => Buffer.from(text, 'utf8');
37
+ const plainField = (text) => ({ kind: 'string', text, style: 'plain' });
38
+ function cleanLine(text) {
39
+ if (!text)
40
+ return '';
41
+ return text.replace(/\s+/g, ' ').trim();
42
+ }
43
+ function shortSummary(text, max = 220) {
44
+ const flat = cleanLine(text);
45
+ if (flat.length <= max)
46
+ return flat;
47
+ const sentence = flat.slice(0, max).match(/^.*?[.!?](?=\s|$)/)?.[0];
48
+ return sentence && sentence.length >= 32 ? sentence : `${flat.slice(0, max - 3).trimEnd()}...`;
49
+ }
50
+ function toPortableSlug(raw, fallback = 'ia-plugin') {
51
+ const cleaned = (raw ?? '')
52
+ .toLowerCase()
53
+ .replace(/[^a-z0-9-]+/g, '-')
54
+ .replace(/-+/g, '-')
55
+ .replace(/^[^a-z]+/, '')
56
+ .replace(/-$/, '')
57
+ .slice(0, 63)
58
+ .replace(/-$/, '');
59
+ return cleaned.length > 0 && NAME.test(cleaned) ? cleaned : fallback;
60
+ }
61
+ function toDisplayName(slug) {
62
+ return slug
63
+ .split('-')
64
+ .filter(Boolean)
65
+ .map((part) => (part === 'ia' || part === 'kb' ? part.toUpperCase() : part[0].toUpperCase() + part.slice(1)))
66
+ .join(' ');
67
+ }
68
+ function isLanguageFloorNode(node) {
69
+ if (node.band === 100)
70
+ return false;
71
+ const path = node.source.path.replaceAll('\\', '/');
72
+ const systemMatch = /(?:^|\/)\.ia\/src\/systems\/([^/]+)\//.exec(path);
73
+ if (systemMatch && PUBLIC_FLOOR_SYSTEMS.has(systemMatch[1]))
74
+ return true;
75
+ const releaseMatch = /(?:^|\/)\.ia\/src\/releases\/([^/]+)\.ia$/.exec(path);
76
+ if (releaseMatch) {
77
+ const stem = releaseMatch[1].replace(/-distribution$/, '');
78
+ if (stem === 'language' || PUBLIC_FLOOR_SYSTEMS.has(stem))
79
+ return true;
80
+ }
81
+ return false;
82
+ }
83
+ function isWorkspaceOrKitNode(node) {
84
+ return node.band >= 50 && !isLanguageFloorNode(node);
85
+ }
86
+ function portablePath(output) {
87
+ if (output === '' ||
88
+ output.startsWith('/') ||
89
+ output.includes('\\') ||
90
+ /^[A-Za-z]:/.test(output) ||
91
+ output.split('/').some((segment) => segment === '' || segment === '.' || segment === '..'))
92
+ throw new HostPluginError('IA-PLUGIN-PRODUCT', `${output} is not a portable plugin path`);
93
+ return output;
94
+ }
95
+ function hostToolsForEffects(host, effects) {
96
+ const digest = '0'.repeat(64);
97
+ const catalog = host === 'gemini'
98
+ ? geminiProseCatalog(digest)
99
+ : host === 'antigravity'
100
+ ? antigravityProseCatalog(digest)
101
+ : host === 'codex'
102
+ ? codexProseCatalog(digest)
103
+ : claudeProseCatalog(digest);
104
+ const byId = new Map(catalog.tools.map((tool) => [tool.id, tool.name]));
105
+ return [
106
+ ...new Set(effects
107
+ .flatMap((effect) => PROSE_EFFECT_TOOLS.get(effect) ?? [])
108
+ .map((id) => byId.get(id))
109
+ .filter((name) => name !== undefined)),
110
+ ];
111
+ }
112
+ function formatCompiledValue(value) {
113
+ if (value.kind === 'ref')
114
+ return `\`@${value.discriminator} ${value.name}\``;
115
+ if (value.kind === 'list')
116
+ return value.items.map(formatCompiledValue).filter(Boolean).join(', ');
117
+ return 'text' in value ? cleanLine(value.text) : '';
118
+ }
119
+ function renderRecordSummaryBlock(node) {
120
+ const says = cleanLine(textsAt(node, 'meaning.says')[0]);
121
+ const answers = cleanLine(textsAt(node, 'meaning.answers')[0]);
122
+ const lines = [`### \`${node.name}\` (\`@${node.discriminator}\`)`];
123
+ if (says)
124
+ lines.push('', says);
125
+ if (answers)
126
+ lines.push('', `- **Answers:** ${answers}`);
127
+ for (const section of node.sections) {
128
+ if (section.name === 'meaning')
129
+ continue;
130
+ for (const field of fieldsOf(node, section.name)) {
131
+ const formatted = formatCompiledValue(field.value);
132
+ if (formatted)
133
+ lines.push(`- **${section.name}.${field.key}:** ${formatted}`);
134
+ }
135
+ }
136
+ return lines;
137
+ }
138
+ function renderCellBullet(cell) {
139
+ const condition = cell.condition === undefined
140
+ ? ''
141
+ : ` *(when ${cell.condition.map((term) => `${cleanLine(term.axis)} = ${cleanLine(term.value)}`).join(' and ')})*`;
142
+ return `- **${cell.primitive}${cell.primary ? ' (primary)' : ''}**${condition}: ${cleanLine(cell.text)}`;
143
+ }
144
+ function collectNeighborhood(reader, within, seeds, nodesByIdentity) {
145
+ const visited = new Set(seeds.map((seed) => seed.identity));
146
+ let frontier = seeds.map((seed) => seed.identity);
147
+ for (let hop = 0; hop < 2 && frontier.length > 0; hop += 1) {
148
+ const next = [];
149
+ for (const id of frontier) {
150
+ for (const row of reader.directedView(id, { within })) {
151
+ if (!visited.has(row.counterpart) && nodesByIdentity.has(row.counterpart)) {
152
+ visited.add(row.counterpart);
153
+ next.push(row.counterpart);
154
+ }
155
+ }
156
+ }
157
+ frontier = next;
158
+ }
159
+ return visited;
160
+ }
161
+ function renderCapabilityReference(reader, within, host, capability, allRecords, nodesByIdentity, inlineBody) {
162
+ const resolveTarget = (value) => {
163
+ if (value.kind !== 'ref')
164
+ return undefined;
165
+ const resolved = reader.resolve(value, { within });
166
+ return resolved.ok ? nodesByIdentity.get(resolved.identity) : undefined;
167
+ };
168
+ const closure = capabilityClosure([{ kind: 'ref', discriminator: 'capability', name: capability.identity }], resolveTarget);
169
+ const caps = closure.length > 0 ? closure : [capability];
170
+ const playbooks = [
171
+ ...new Map(caps
172
+ .flatMap((cap) => valuesAt(cap, 'composition.playbooks').map(resolveTarget))
173
+ .filter((node) => node !== undefined && node.discriminator === 'playbook')
174
+ .map((node) => [node.identity, node])).values(),
175
+ ];
176
+ const explicitChecks = caps
177
+ .flatMap((cap) => valuesAt(cap, 'composition.checks').map(resolveTarget))
178
+ .filter((node) => node !== undefined && node.discriminator === 'check');
179
+ const neighborhood = collectNeighborhood(reader, within, [...caps, ...playbooks], nodesByIdentity);
180
+ const connected = (word) => allRecords
181
+ .filter((node) => node.discriminator === word && neighborhood.has(node.identity))
182
+ .sort((a, b) => (a.identity < b.identity ? -1 : 1));
183
+ // Also match authoring-guides or templates naming the capability's subject word (e.g. `decision-method` -> `decision`).
184
+ const subjectStem = capability.name.replace(/-method$/, '');
185
+ const authoringGuides = [
186
+ ...new Map([
187
+ ...connected('authoring-guide'),
188
+ ...allRecords.filter((node) => node.discriminator === 'authoring-guide' &&
189
+ (node.name === subjectStem || textsAt(node, 'authoring.target-word')[0] === subjectStem)),
190
+ ].map((node) => [node.identity, node])).values(),
191
+ ].sort((a, b) => (a.identity < b.identity ? -1 : 1));
192
+ const templates = [
193
+ ...new Map([
194
+ ...connected('template'),
195
+ ...allRecords.filter((node) => node.discriminator === 'template' && isWorkspaceOrKitNode(node) && neighborhood.has(node.identity)),
196
+ ].map((node) => [node.identity, node])).values(),
197
+ ].sort((a, b) => (a.identity < b.identity ? -1 : 1));
198
+ const checks = [
199
+ ...new Map([...explicitChecks, ...connected('check')].map((node) => [node.identity, node])).values(),
200
+ ].sort((a, b) => (a.identity < b.identity ? -1 : 1));
201
+ const governanceRules = allRecords
202
+ .filter((node) => (node.discriminator === 'law' || node.discriminator === 'principle' || node.discriminator === 'convention') &&
203
+ (neighborhood.has(node.identity) || isWorkspaceOrKitNode(node)))
204
+ .filter((node) => !isLanguageFloorNode(node) || neighborhood.has(node.identity))
205
+ .sort((a, b) => (a.identity < b.identity ? -1 : 1));
206
+ const effects = [...new Set(caps.flatMap((cap) => textsAt(cap, 'execution.effects')))];
207
+ const hostTools = hostToolsForEffects(host, effects);
208
+ const says = cleanLine(textsAt(capability, 'meaning.says')[0]);
209
+ const answers = cleanLine(textsAt(capability, 'meaning.answers')[0]);
210
+ const useWhen = cleanLine(textsAt(capability, 'invocation.use-when')[0]);
211
+ const argHint = cleanLine(textsAt(capability, 'invocation.argument-hint')[0]);
212
+ const lines = [
213
+ `# ${capability.name}`,
214
+ '',
215
+ '> Self-contained compiled OPAL method reference. Execute the phases and rules below directly using your native host tools; no runtime CLI or MCP server is required.',
216
+ '',
217
+ ];
218
+ if (says)
219
+ lines.push(says, '');
220
+ lines.push('## Overview', '');
221
+ lines.push(`- **Capability:** \`${capability.identity}\``);
222
+ if (answers)
223
+ lines.push(`- **Answers:** ${answers}`);
224
+ if (useWhen)
225
+ lines.push(`- **Use when:** ${useWhen}`);
226
+ if (argHint)
227
+ lines.push(`- **Arguments:** \`${argHint}\``);
228
+ lines.push(`- **Effects:** ${effects.length > 0 ? effects.map((e) => `\`${e}\``).join(', ') : 'none (read/inspection)'}`);
229
+ if (hostTools.length > 0)
230
+ lines.push(`- **Host tools:** ${hostTools.map((t) => `\`${t}\``).join(', ')}`);
231
+ if (inlineBody !== undefined) {
232
+ const trimmed = inlineBody.toString('utf8').trim();
233
+ if (trimmed.length > 0)
234
+ lines.push('', '## Instructions', '', trimmed);
235
+ }
236
+ for (const phase of PHASES) {
237
+ const phaseCells = playbooks.flatMap((pb) => {
238
+ const matching = pb.cells.filter((cell) => cell.phase === phase);
239
+ const ordered = [...matching.filter((c) => c.primary), ...matching.filter((c) => !c.primary)];
240
+ return ordered.map((cell) => ({ playbook: pb.name, cell }));
241
+ });
242
+ if (phaseCells.length === 0)
243
+ continue;
244
+ const title = phase[0].toUpperCase() + phase.slice(1);
245
+ lines.push('', `## ${title}`, '');
246
+ for (const { playbook, cell } of phaseCells) {
247
+ lines.push(`${renderCellBullet(cell)} *(\`${playbook}\`)*`);
248
+ }
249
+ }
250
+ if (governanceRules.length > 0) {
251
+ lines.push('', '## Governing Rules');
252
+ for (const rule of governanceRules.slice(0, 24)) {
253
+ lines.push('', ...renderRecordSummaryBlock(rule));
254
+ }
255
+ }
256
+ if (checks.length > 0) {
257
+ lines.push('', '## Verification Checks');
258
+ for (const check of checks) {
259
+ lines.push('', ...renderRecordSummaryBlock(check));
260
+ }
261
+ }
262
+ if (authoringGuides.length > 0) {
263
+ lines.push('', '## Authoring Guides');
264
+ for (const guide of authoringGuides) {
265
+ lines.push('', ...renderRecordSummaryBlock(guide));
266
+ }
267
+ }
268
+ if (templates.length > 0) {
269
+ lines.push('', '## Templates');
270
+ for (const tpl of templates) {
271
+ lines.push('', ...renderRecordSummaryBlock(tpl));
272
+ }
273
+ }
274
+ lines.push('');
275
+ return utf8Bytes(lines.join('\n'));
276
+ }
277
+ function renderRouterSkill(routerName, description, host, entries) {
278
+ const readTool = host === 'gemini' ? 'read_file' : host === 'antigravity' ? 'view_file' : 'Read';
279
+ const fields = [
280
+ { key: 'name', value: plainField(routerName) },
281
+ { key: 'description', value: plainField(shortSummary(description, 240)) },
282
+ ];
283
+ const tableRows = entries.map((entry) => {
284
+ const refPath = `references/${toPortableSlug(entry.capability.name, 'capability')}.md`;
285
+ const summary = shortSummary(entry.summary, 140).replaceAll('|', '\\|');
286
+ return `| \`${entry.activity}\` | \`${entry.capability.name}\` | ${summary || 'Compiled method packet'} | \`${refPath}\` |`;
287
+ });
288
+ const body = [
289
+ ...(host === 'codex' ? ['**Codex:** Read `CODEX.md` at the plugin root for Codex-specific conventions.', ''] : []),
290
+ `# ${toDisplayName(routerName)} Router`,
291
+ '',
292
+ shortSummary(description, 300),
293
+ '',
294
+ '## Progressive Disclosure Workflow',
295
+ '',
296
+ `1. Match the user's request to the closest activity or capability in the routing table below.`,
297
+ `2. Use \`${readTool}\` to read the matching \`references/<capability>.md\` file inside this skill folder.`,
298
+ '3. Execute the compiled Orient, Plan, Act, and Learn steps and governing checks directly with your native tools.',
299
+ '',
300
+ '## Routing Table',
301
+ '',
302
+ '| Activity | Capability | When to Use | Reference |',
303
+ '| --- | --- | --- | --- |',
304
+ ...tableRows,
305
+ '',
306
+ ].join('\n');
307
+ return Buffer.concat([utf8Bytes(emitFrontmatter(fields)), utf8Bytes(`\n${body}`)]);
308
+ }
309
+ function renderRulesMarkdown(title, rules) {
310
+ const laws = rules.filter((r) => r.discriminator === 'law');
311
+ const principles = rules.filter((r) => r.discriminator === 'principle');
312
+ const conventions = rules.filter((r) => r.discriminator === 'convention');
313
+ const lines = [
314
+ `# ${title} Governance Rules`,
315
+ '',
316
+ 'Compiled workspace laws, principles, and conventions enforced while working in this project.',
317
+ ];
318
+ const addGroup = (heading, items) => {
319
+ if (items.length === 0)
320
+ return;
321
+ lines.push('', `## ${heading}`);
322
+ for (const item of items)
323
+ lines.push('', ...renderRecordSummaryBlock(item));
324
+ };
325
+ addGroup('Laws', laws);
326
+ addGroup('Principles', principles);
327
+ addGroup('Conventions', conventions);
328
+ lines.push('');
329
+ return utf8Bytes(lines.join('\n'));
330
+ }
331
+ function standaloneHookOf(node) {
332
+ if (node.discriminator !== 'hook' || !isWorkspaceOrKitNode(node))
333
+ return null;
334
+ if (!registrableHook(node.identity) || node.identity.length > HOOK_IDENTITY_LIMIT)
335
+ return null;
336
+ const event = textsAt(node, 'hook.event')[0];
337
+ const rawTools = textsAt(node, 'hook.tools');
338
+ const paths = textsAt(node, 'hook.paths');
339
+ const message = textsAt(node, 'hook.message')[0];
340
+ if (event?.toLowerCase() !== 'pretooluse')
341
+ return null;
342
+ if (rawTools.length === 0 || rawTools.some((t) => !HOOK_TOOLS.has(t.toLowerCase())))
343
+ return null;
344
+ if (paths.length === 0 ||
345
+ paths.length > HOOK_SELECTION_LIMIT ||
346
+ paths.some((p) => p.length > HOOK_SELECTION_LENGTH || !isSelection(p) || !registrableSelection(p)))
347
+ return null;
348
+ if (!message || message.trim() === '')
349
+ return null;
350
+ return {
351
+ identity: node.identity,
352
+ tools: [...new Set(rawTools.map((t) => HOOK_TOOLS.get(t.toLowerCase())))],
353
+ paths,
354
+ message: cleanLine(message),
355
+ };
356
+ }
357
+ function compileMandateGuardModel(reader, within) {
358
+ try {
359
+ requireMandatesAdmitted(reader, within);
360
+ }
361
+ catch (error) {
362
+ return {
363
+ admissionRefusal: error instanceof Error ? error.message : String(error),
364
+ repositoryWorkspace: null,
365
+ rootWorkspace: null,
366
+ floorSystem: null,
367
+ declaredRoots: [],
368
+ declaredRootList: [],
369
+ systemsByFolder: {},
370
+ systems: {},
371
+ workspaces: {},
372
+ subagents: {},
373
+ mandates: [],
374
+ };
375
+ }
376
+ const read = { within };
377
+ const snapshot = reader.snapshot(read);
378
+ const nodes = new Map(snapshot.records.filter((node) => node.placement.kind !== 'runtime').map((node) => [node.identity, node]));
379
+ const rootOf = new Map(snapshot.membership.map((row) => [row.identity, row.root]));
380
+ const declaredRoots = reader.roots(read).map((row) => ({ root: row.root, workspace: row.workspace }));
381
+ const declaredRootList = [...new Set(declaredRoots.map((row) => row.root))];
382
+ const repoCandidate = reader.repositoryWorkspace(read);
383
+ const repositoryWorkspace = repoCandidate !== undefined && nodes.get(repoCandidate)?.discriminator === 'workspace' ? repoCandidate : null;
384
+ const rootWsCandidate = rootWorkspace(reader, read);
385
+ const resolvedRootWorkspace = rootWsCandidate !== undefined && nodes.get(rootWsCandidate)?.discriminator === 'workspace' ? rootWsCandidate : null;
386
+ const floorSeat = reader.resolveSeat('.ia/src/floor', read);
387
+ const floorSystem = floorSeat.by === 'system' ? (floorSeat.seat ?? null) : null;
388
+ const systemsByFolder = {};
389
+ for (const node of snapshot.records) {
390
+ if (node.discriminator !== 'system' || Object.hasOwn(systemsByFolder, node.name))
391
+ continue;
392
+ const sysSeat = reader.resolveSeat(`.ia/src/systems/${node.name}`, read);
393
+ if (sysSeat.by === 'system' && sysSeat.seat !== undefined) {
394
+ systemsByFolder[node.name] = sysSeat.seat;
395
+ }
396
+ }
397
+ const systems = {};
398
+ for (const node of nodes.values()) {
399
+ if (node.discriminator !== 'system')
400
+ continue;
401
+ systems[node.identity] = {
402
+ root: rootOf.get(node.identity) ?? '',
403
+ band: node.band,
404
+ };
405
+ }
406
+ const workspaces = {};
407
+ for (const node of nodes.values()) {
408
+ if (node.discriminator !== 'workspace')
409
+ continue;
410
+ const da = defaultActor(reader, within, node.identity);
411
+ workspaces[node.identity] = {
412
+ ownRoots: [...new Set(declaredRoots.filter((r) => r.workspace === node.identity).map((r) => r.root))],
413
+ actor: da.actor ?? null,
414
+ reason: da.reason ?? null,
415
+ refusal: da.refusal !== undefined ? { message: da.refusal.message, next: da.refusal.next } : null,
416
+ };
417
+ }
418
+ const targets = (identity, field, word) => reader
419
+ .directedView(identity, read)
420
+ .filter((row) => row.kind === 'field-ref' &&
421
+ row.direction === 'out' &&
422
+ row.field === field &&
423
+ nodes.get(row.counterpart)?.discriminator === word)
424
+ .map((row) => row.counterpart);
425
+ const profilesByName = new Map();
426
+ for (const node of nodes.values()) {
427
+ if (node.discriminator !== 'agent-profile' || node.band !== 100)
428
+ continue;
429
+ const list = profilesByName.get(node.name) ?? [];
430
+ list.push(node);
431
+ profilesByName.set(node.name, list);
432
+ }
433
+ const subagents = {};
434
+ for (const [name, list] of profilesByName.entries()) {
435
+ if (list.length !== 1)
436
+ continue;
437
+ const profile = list[0];
438
+ const agents = targets(profile.identity, 'composition.agent', 'agent');
439
+ subagents[name] = { profile: profile.identity, agent: agents.length === 1 ? agents[0] : null };
440
+ }
441
+ const statesKey = (node, sectionName, key) => node.sections
442
+ .filter((s) => s.name === sectionName)
443
+ .flatMap((s) => s.fields)
444
+ .some((c) => 'key' in c && c.key === key);
445
+ const statesValue = (node, sectionName, key) => node.sections
446
+ .filter((s) => s.name === sectionName)
447
+ .flatMap((s) => s.fields)
448
+ .some((c) => 'key' in c && c.key === key && !('value' in c && c.value.kind === 'list' && c.value.items.length === 0));
449
+ const coversOf = (node) => node.sections
450
+ .filter((s) => s.name === 'authority')
451
+ .flatMap((s) => s.fields)
452
+ .filter((c) => 'key' in c && c.key === 'covers')
453
+ .flatMap((c) => (c.value.kind === 'list' ? c.value.items : [c.value]))
454
+ .flatMap((v) => ('text' in v ? [v.text] : []));
455
+ const mandates = [...nodes.values()]
456
+ .filter((node) => node.discriminator === 'mandate' && node.band === 100)
457
+ .sort((a, b) => (a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0))
458
+ .map((node) => {
459
+ const root = rootOf.get(node.identity) ?? '';
460
+ const hasParticipant = statesKey(node, 'authority', 'participant');
461
+ const hasScopeOrCovers = statesValue(node, 'authority', 'scope') || statesValue(node, 'authority', 'covers');
462
+ const scopedWorkspaces = targets(node.identity, 'authority.scope', 'workspace');
463
+ const participantAgent = targets(node.identity, 'authority.participant', 'agent')[0] ?? null;
464
+ const rawCovers = coversOf(node);
465
+ try {
466
+ const authority = mandateAuthorityOf(node);
467
+ return {
468
+ identity: node.identity,
469
+ root,
470
+ band: node.band,
471
+ invalid: null,
472
+ participant: authority.participant === undefined ? null : (participantAgent ?? `@agent ${authority.participant}`),
473
+ participantAgent,
474
+ hasParticipant,
475
+ hasScopeOrCovers,
476
+ scopedWorkspaces,
477
+ covers: authority.covers ? [...authority.covers] : [...rawCovers],
478
+ moves: authority.moves ? [...authority.moves] : null,
479
+ };
480
+ }
481
+ catch (error) {
482
+ if (!(error instanceof RuntimeError))
483
+ throw error;
484
+ return {
485
+ identity: node.identity,
486
+ root,
487
+ band: node.band,
488
+ invalid: error.message,
489
+ participant: participantAgent,
490
+ participantAgent,
491
+ hasParticipant,
492
+ hasScopeOrCovers,
493
+ scopedWorkspaces,
494
+ covers: [...rawCovers],
495
+ moves: null,
496
+ };
497
+ }
498
+ });
499
+ return {
500
+ admissionRefusal: null,
501
+ repositoryWorkspace,
502
+ rootWorkspace: resolvedRootWorkspace,
503
+ floorSystem,
504
+ declaredRoots,
505
+ declaredRootList,
506
+ systemsByFolder,
507
+ systems,
508
+ workspaces,
509
+ subagents,
510
+ mandates,
511
+ };
512
+ }
513
+ const JS_UNSAFE_ESCAPES = {
514
+ '<': '\\u003c',
515
+ '>': '\\u003e',
516
+ '\u2028': '\\u2028',
517
+ '\u2029': '\\u2029',
518
+ };
519
+ function jsLiteral(value, indent) {
520
+ return JSON.stringify(value, null, indent).replace(/[<>\u2028\u2029]/g, (ch) => JS_UNSAFE_ESCAPES[ch] ?? ch);
521
+ }
522
+ function renderStandaloneGuardScript(host, rules, model) {
523
+ const source = `#!/usr/bin/env node
524
+ // Standalone zero-dependency @hook and @mandate path guard compiled by ia project --product plugin.
525
+ import { lstatSync, realpathSync, statSync } from 'node:fs';
526
+ import { dirname, isAbsolute, join, parse, relative, resolve, sep } from 'node:path';
527
+
528
+ const HOST = ${jsLiteral(host)};
529
+ const RULES = ${jsLiteral(rules, 2)};
530
+ const MODEL = ${jsLiteral(model, 2)};
531
+ const DECLARED_ROOT_SET = new Set(MODEL.declaredRootList);
532
+ const AGENT_LIMIT = 512;
533
+ const ESCAPES = new RegExp('\\\\u001b(?:\\\\[[0-?]*[ -/]*[@-~]|\\\\][^\\\\u0007\\\\u001b]*(?:\\\\u0007|\\\\u001b\\\\\\\\)?|[@-_])', 'g');
534
+ const CONTROLS = new RegExp('[\\\\u0000-\\\\u001f\\\\u007f-\\\\u009f\\\\u061c\\\\u200e\\\\u200f\\\\u2028\\\\u2029\\\\u202a-\\\\u202e\\\\u2066-\\\\u2069]', 'g');
535
+ const ALL_ONES = 2n ** 64n - 1n;
536
+
537
+ function printable(text) {
538
+ return String(text).replace(ESCAPES, '').replace(CONTROLS, ' ').slice(0, 4096);
539
+ }
540
+
541
+ function caseFold(name) {
542
+ return name
543
+ .normalize('NFC')
544
+ .split('\\u0131')
545
+ .map((part) => part.toLowerCase().toUpperCase().toLowerCase().normalize('NFC'))
546
+ .join('\\u0131');
547
+ }
548
+
549
+ function fold(value) {
550
+ if (process.platform === 'win32') return value.toLowerCase();
551
+ return process.platform === 'darwin' ? caseFold(value) : value;
552
+ }
553
+
554
+ function isPlainObject(value) {
555
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
556
+ }
557
+
558
+ function validFilePath(value) {
559
+ return typeof value === 'string' && value.trim().length > 0 && !value.includes('\\0');
560
+ }
561
+
562
+ function streamed(filePath) {
563
+ const rest = filePath.replace(/^[\\\\/]{2}[?.][\\\\/]/, '').replace(/^[A-Za-z]:/, '');
564
+ return rest.includes(':');
565
+ }
566
+
567
+ function selectionSegments(selection) {
568
+ const text = String(selection).replaceAll('\\\\', '/');
569
+ if (text === '' || text.startsWith('/') || /^[A-Za-z]:/.test(text)) return undefined;
570
+ const segments = (text.endsWith('/') ? text + '**' : text).split('/');
571
+ return segments.some((s) => s === '' || s === '.' || s === '..') ? undefined : segments;
572
+ }
573
+
574
+ function pathSegments(relPath) {
575
+ const text = String(relPath).replaceAll('\\\\', '/');
576
+ if (text.startsWith('/') || /^[A-Za-z]:/.test(text)) return undefined;
577
+ if (text === '') return [];
578
+ const segments = text.split('/');
579
+ return segments.some((s) => s === '' || s === '.' || s === '..') ? undefined : segments;
580
+ }
581
+
582
+ function wildcard(pattern, text, star, accepts) {
583
+ let p = 0;
584
+ let t = 0;
585
+ let starAt = -1;
586
+ let resume = 0;
587
+ while (t < text.length) {
588
+ if (p < pattern.length && !star(pattern[p]) && accepts(pattern[p], text[t])) {
589
+ p += 1;
590
+ t += 1;
591
+ } else if (p < pattern.length && star(pattern[p])) {
592
+ starAt = p;
593
+ p += 1;
594
+ resume = t;
595
+ } else if (starAt >= 0) {
596
+ p = starAt + 1;
597
+ resume += 1;
598
+ t = resume;
599
+ } else {
600
+ return false;
601
+ }
602
+ }
603
+ while (p < pattern.length && star(pattern[p])) p += 1;
604
+ return p === pattern.length;
605
+ }
606
+
607
+ function segmentAccepts(pattern, segment) {
608
+ return wildcard([...pattern], [...segment], (c) => c === '*', (c, d) => c === '?' || c === d);
609
+ }
610
+
611
+ function selects(selection, relPath) {
612
+ const pattern = selectionSegments(fold(selection));
613
+ const target = pathSegments(fold(relPath));
614
+ return pattern !== undefined && target !== undefined && wildcard(pattern, target, (s) => s === '**', segmentAccepts);
615
+ }
616
+
617
+ function linked(absPath) {
618
+ const absolute = resolve(absPath);
619
+ const volume = parse(absolute).root;
620
+ let current = volume;
621
+ for (const part of absolute.slice(volume.length).split(/[\\\\/]/).filter(Boolean)) {
622
+ current = join(current, part);
623
+ let isLink = false;
624
+ try {
625
+ isLink = lstatSync(current).isSymbolicLink();
626
+ } catch (error) {
627
+ if (['ENOENT', 'ENOTDIR'].includes(error?.code ?? '')) return false;
628
+ throw error;
629
+ }
630
+ if (isLink) return true;
631
+ }
632
+ return false;
633
+ }
634
+
635
+ function unaliased(targetPath, realPath) {
636
+ if (targetPath === realPath) return true;
637
+ if (process.platform === 'win32') return resolve(targetPath).toLowerCase() === realPath.toLowerCase() && !linked(resolve(targetPath));
638
+ return targetPath === resolve(targetPath) && !linked(targetPath);
639
+ }
640
+
641
+ function physical(targetPath) {
642
+ try {
643
+ lstatSync(targetPath);
644
+ } catch (error) {
645
+ if (error?.code !== 'ENOENT') throw error;
646
+ const parent = dirname(targetPath);
647
+ if (parent === targetPath) throw error;
648
+ return resolve(physical(parent), relative(parent, targetPath));
649
+ }
650
+ return realpathSync.native(targetPath);
651
+ }
652
+
653
+ function sameFile(a, b) {
654
+ try {
655
+ const left = statSync(a, { bigint: true, throwIfNoEntry: false });
656
+ const right = statSync(b, { bigint: true, throwIfNoEntry: false });
657
+ if (!left || !right) return false;
658
+ if (left.ino !== 0n && left.ino !== ALL_ONES && right.ino !== 0n && right.ino !== ALL_ONES) {
659
+ return left.dev === right.dev && left.ino === right.ino;
660
+ }
661
+ return realpathSync.native(a) === realpathSync.native(b);
662
+ } catch {
663
+ return fold(resolve(a)) === fold(resolve(b));
664
+ }
665
+ }
666
+
667
+ function local(rootPath, targetPath) {
668
+ const rel = relative(fold(rootPath), fold(targetPath));
669
+ return isAbsolute(rel) || rel === '..' || rel.startsWith('..' + sep) ? undefined : rel.replaceAll('\\\\', '/');
670
+ }
671
+
672
+ function anchored(rootPath, targetPath) {
673
+ for (let current = targetPath; ; ) {
674
+ if (sameFile(current, rootPath)) return local(current, targetPath);
675
+ const parent = dirname(current);
676
+ if (parent === current) return undefined;
677
+ current = parent;
678
+ }
679
+ }
680
+
681
+ function installation(relPath) {
682
+ return relPath === '.ia/distributions.lock.json' || relPath === '.ia/distributions' || relPath.startsWith('.ia/distributions/');
683
+ }
684
+
685
+ function callerOf(event) {
686
+ if (!isPlainObject(event)) return HOST;
687
+ if (event.hook_event_name === 'BeforeTool') return 'gemini';
688
+ if (isPlainObject(event.toolCall)) return 'antigravity';
689
+ if (event.hook_event_name === 'PreToolUse') return 'claude';
690
+ return HOST;
691
+ }
692
+
693
+ function normalizeEvent(event) {
694
+ if (!isPlainObject(event)) return null;
695
+ if (isPlainObject(event.toolCall)) {
696
+ const ev = event.hookEventName ?? event.hook_event_name;
697
+ if (ev !== undefined && ev !== 'PreToolUse') return null;
698
+ const call = event.toolCall;
699
+ const name = call.name;
700
+ const tool =
701
+ name === 'write_to_file' || name === 'write_file'
702
+ ? 'Write'
703
+ : name === 'replace_file_content' || name === 'edit_file'
704
+ ? 'Edit'
705
+ : name === 'multi_replace_file_content'
706
+ ? 'MultiEdit'
707
+ : null;
708
+ const args = call.args;
709
+ if (!tool || !isPlainObject(args)) return null;
710
+ if (name === 'multi_replace_file_content' && !Array.isArray(args.ReplacementChunks)) return null;
711
+ const filePath = args.TargetFile ?? args.Path ?? args.AbsolutePath;
712
+ if (!validFilePath(filePath)) return null;
713
+ const workspacePaths = Array.isArray(event.workspacePaths)
714
+ ? event.workspacePaths.filter((p) => typeof p === 'string' && p.trim().length > 0)
715
+ : [];
716
+ return {
717
+ caller: 'antigravity',
718
+ tool,
719
+ filePath,
720
+ cwd: typeof event.cwd === 'string' && event.cwd.trim() ? event.cwd : workspacePaths[0],
721
+ workspacePaths,
722
+ agentId: event.agent_id ?? event.agentId,
723
+ agentType: event.agent_type ?? event.agentType,
724
+ };
725
+ }
726
+ if (event.hook_event_name === 'BeforeTool') {
727
+ const tool = event.tool_name === 'write_file' ? 'Write' : event.tool_name === 'replace' ? 'Edit' : null;
728
+ if (!tool || !isPlainObject(event.tool_input) || !validFilePath(event.tool_input.file_path)) return null;
729
+ return {
730
+ caller: 'gemini',
731
+ tool,
732
+ filePath: event.tool_input.file_path,
733
+ cwd: event.cwd,
734
+ workspacePaths: [],
735
+ agentId: event.agent_id,
736
+ agentType: event.agent_type,
737
+ };
738
+ }
739
+ if (
740
+ event.hook_event_name === 'PreToolUse' &&
741
+ ['Write', 'Edit', 'MultiEdit'].includes(String(event.tool_name)) &&
742
+ isPlainObject(event.tool_input) &&
743
+ validFilePath(event.tool_input.file_path) &&
744
+ !(event.tool_name === 'MultiEdit' && !Array.isArray(event.tool_input.edits))
745
+ ) {
746
+ return {
747
+ caller: 'claude',
748
+ tool: event.tool_name,
749
+ filePath: event.tool_input.file_path,
750
+ cwd: event.cwd,
751
+ workspacePaths: [],
752
+ agentId: event.agent_id,
753
+ agentType: event.agent_type,
754
+ };
755
+ }
756
+ return null;
757
+ }
758
+
759
+ function findIaAncestor(startDir) {
760
+ for (let current = resolve(startDir); ; ) {
761
+ try {
762
+ const st = lstatSync(join(current, '.ia', 'src'), { throwIfNoEntry: false });
763
+ if (st && st.isDirectory() && !st.isSymbolicLink()) return current;
764
+ } catch {
765
+ // keep walking
766
+ }
767
+ const parent = dirname(current);
768
+ if (parent === current) return undefined;
769
+ current = parent;
770
+ }
771
+ }
772
+
773
+ function resolveRootPath(normalized) {
774
+ const rootArgIdx = process.argv.indexOf('--root');
775
+ if (rootArgIdx >= 0 && typeof process.argv[rootArgIdx + 1] === 'string' && process.argv[rootArgIdx + 1]) {
776
+ const explicit = process.argv[rootArgIdx + 1];
777
+ if (!isAbsolute(explicit)) throw new Error('Binding requires an absolute fixed project root');
778
+ const base = resolve(explicit);
779
+ const real = realpathSync.native(base);
780
+ if (!unaliased(base, real)) throw new Error('Project root is aliased');
781
+ return { rawRoot: base, base: real };
782
+ }
783
+ if (normalized.caller === 'claude' && typeof process.env.CLAUDE_PROJECT_DIR === 'string' && process.env.CLAUDE_PROJECT_DIR.trim()) {
784
+ const envRoot = resolve(process.env.CLAUDE_PROJECT_DIR);
785
+ return { rawRoot: envRoot, base: realpathSync.native(envRoot) };
786
+ }
787
+ if (normalized.workspacePaths.length > 0) {
788
+ const chosen = normalized.workspacePaths.find((ws) => isAbsolute(ws) && isAbsolute(normalized.filePath) && local(resolve(ws), resolve(normalized.filePath)) !== undefined) ?? normalized.workspacePaths[0];
789
+ if (typeof chosen === 'string' && isAbsolute(chosen)) {
790
+ const wsRoot = resolve(chosen);
791
+ return { rawRoot: wsRoot, base: realpathSync.native(wsRoot) };
792
+ }
793
+ }
794
+ if (typeof normalized.cwd === 'string' && isAbsolute(normalized.cwd)) {
795
+ const cwdResolved = resolve(normalized.cwd);
796
+ const iaRoot = findIaAncestor(cwdResolved) ?? cwdResolved;
797
+ return { rawRoot: iaRoot, base: realpathSync.native(iaRoot) };
798
+ }
799
+ throw new Error('Binding requires an absolute workspace root or cwd');
800
+ }
801
+
802
+ function resolveEditTarget(normalized) {
803
+ if (process.platform === 'win32' && streamed(normalized.filePath)) {
804
+ throw new Error('A path naming an alternate data stream or a drive-relative path is refused');
805
+ }
806
+ const { rawRoot, base } = resolveRootPath(normalized);
807
+ const rawPath = normalized.filePath;
808
+ if (!isAbsolute(rawPath)) {
809
+ if (typeof normalized.cwd !== 'string' || !isAbsolute(normalized.cwd) || local(base, physical(resolve(normalized.cwd))) === undefined) {
810
+ throw new Error('Relative input requires cwd inside the fixed root');
811
+ }
812
+ }
813
+ let target;
814
+ if (isAbsolute(rawPath)) {
815
+ const resolvedFile = resolve(rawPath);
816
+ const relFromRawRoot = rawRoot !== base ? local(rawRoot, resolvedFile) : undefined;
817
+ target = relFromRawRoot !== undefined && !linked(rawRoot) ? resolve(base, relFromRawRoot) : resolvedFile;
818
+ } else {
819
+ const effectiveCwd = process.platform === 'win32' ? resolve(normalized.cwd) : physical(resolve(normalized.cwd));
820
+ const relCwd = rawRoot !== base ? local(rawRoot, effectiveCwd) : undefined;
821
+ const baseCwd = relCwd !== undefined ? resolve(base, relCwd) : effectiveCwd;
822
+ target = resolve(baseCwd, rawPath);
823
+ }
824
+ const actual = physical(target);
825
+ const lexical = local(base, target);
826
+ const physicalPath = local(base, actual);
827
+ const spellings = [lexical, physicalPath];
828
+ if (lexical === undefined && physicalPath === undefined) {
829
+ spellings.push(anchored(base, target), anchored(base, actual));
830
+ }
831
+ return { base, target, actual, spellings };
832
+ }
833
+
834
+ function reaches(from, to) {
835
+ return from === '' || from === to || to.startsWith(from + '/');
836
+ }
837
+
838
+ function systemFolderOf(withTrailingSlash) {
839
+ const m =
840
+ /^(\\.ia\\/(?:(?:(?:adopted|open)\\/[a-z][a-z0-9-]*|distributions\\/store)\\/[a-f0-9]{64}\\/\\.ia\\/)?src\\/systems\\/([^/]+))\\//.exec(
841
+ withTrailingSlash,
842
+ ) ?? /^((?!\\.ia\\/)(?:[^/]+\\/)+\\.ia\\/src\\/systems\\/([^/]+))\\//.exec(withTrailingSlash);
843
+ return m ? m[2] : undefined;
844
+ }
845
+
846
+ function resolveSeat(relPath) {
847
+ const segs = pathSegments(relPath);
848
+ if (segs === undefined) return { path: relPath, unknown: 'outside' };
849
+ const canonical = segs.join('/');
850
+ const folder = systemFolderOf(canonical + '/');
851
+ const system =
852
+ folder !== undefined
853
+ ? (Object.hasOwn(MODEL.systemsByFolder, folder) ? MODEL.systemsByFolder[folder] : undefined)
854
+ : reaches('.ia/src/floor', canonical)
855
+ ? (MODEL.floorSystem ?? undefined)
856
+ : undefined;
857
+ const longest = MODEL.declaredRoots.find((d) => reaches(d.root, canonical))?.root;
858
+ const declarers =
859
+ longest === undefined
860
+ ? []
861
+ : [...new Set(MODEL.declaredRoots.filter((d) => d.root === longest).map((d) => d.workspace))];
862
+ const repoWs = canonical.split('/').includes('.ia') ? undefined : (MODEL.repositoryWorkspace ?? undefined);
863
+ if (system !== undefined) return { path: canonical, seat: system, by: 'system' };
864
+ if (declarers.length > 1) return { path: canonical, by: 'shared', declarers };
865
+ if (declarers.length === 1) return { path: canonical, seat: declarers[0], by: 'root' };
866
+ if (repoWs !== undefined) return { path: canonical, seat: repoWs, by: 'repository' };
867
+ return { path: canonical, unknown: 'undeclared' };
868
+ }
869
+
870
+ function holds(ownRoots, recordRoot, recordBand) {
871
+ return (
872
+ recordBand === 10 ||
873
+ recordBand === 90 ||
874
+ (ownRoots.length > 0 ? ownRoots.includes(recordRoot) : !DECLARED_ROOT_SET.has(recordRoot))
875
+ );
876
+ }
877
+
878
+ function workspaceOf(seatIdentity) {
879
+ if (!seatIdentity) return MODEL.rootWorkspace ?? undefined;
880
+ if (Object.hasOwn(MODEL.workspaces, seatIdentity)) return seatIdentity;
881
+ const sys = Object.hasOwn(MODEL.systems, seatIdentity) ? MODEL.systems[seatIdentity] : undefined;
882
+ if (sys === undefined) return MODEL.rootWorkspace ?? undefined;
883
+ const holder = MODEL.declaredRoots.find((d) => reaches(d.root, sys.root))?.workspace;
884
+ return [MODEL.rootWorkspace ?? undefined, holder].find(
885
+ (at) =>
886
+ at !== undefined &&
887
+ Object.hasOwn(MODEL.workspaces, at) &&
888
+ holds(MODEL.workspaces[at].ownRoots, sys.root, sys.band),
889
+ );
890
+ }
891
+
892
+ function seatedWorkspace(relPath) {
893
+ const res = resolveSeat(relPath);
894
+ if (res.by !== 'shared') return workspaceOf(res.seat);
895
+ const own = MODEL.repositoryWorkspace;
896
+ return own !== null && Object.hasOwn(MODEL.workspaces, own) && res.declarers.includes(own) ? own : undefined;
897
+ }
898
+
899
+ function governingWorkspace(relPath) {
900
+ return (
901
+ seatedWorkspace(relPath) ?? resolveSeat(relPath).declarers?.find((d) => Object.hasOwn(MODEL.workspaces, d))
902
+ );
903
+ }
904
+
905
+ function governingMandatesFor(relPath, ws, actor) {
906
+ const seat = resolveSeat(relPath);
907
+ const declarers = seat.by === 'shared' ? seat.declarers.filter((d) => Object.hasOwn(MODEL.workspaces, d)) : [];
908
+ const shared = declarers.length > 0 ? declarers : undefined;
909
+ const effWs = ws ?? workspaceOf(seat.seat);
910
+ const inside = (m) =>
911
+ shared !== undefined
912
+ ? shared.some((d) => holds(MODEL.workspaces[d].ownRoots, m.root, m.band))
913
+ : holds(
914
+ effWs !== undefined && Object.hasOwn(MODEL.workspaces, effWs) ? MODEL.workspaces[effWs].ownRoots : [],
915
+ m.root,
916
+ m.band,
917
+ );
918
+ const governs = (m) => {
919
+ const scoped =
920
+ shared !== undefined
921
+ ? ws !== undefined && shared.every((d) => m.scopedWorkspaces.includes(d))
922
+ : ws !== undefined && m.scopedWorkspaces.includes(ws);
923
+ const claims = m.covers.some((sel) => selects(sel, seat.path ?? relPath));
924
+ if (shared !== undefined) return m.hasScopeOrCovers && (scoped || claims);
925
+ if (m.hasScopeOrCovers) return scoped || claims;
926
+ return actor === undefined ? m.hasParticipant : m.participantAgent === actor;
927
+ };
928
+ const matched = MODEL.mandates.filter((m) => inside(m) && governs(m));
929
+ for (const m of matched) {
930
+ if (m.invalid !== null) {
931
+ const err = new Error(m.invalid);
932
+ err.mandateIdentity = m.identity;
933
+ throw err;
934
+ }
935
+ }
936
+ return matched.map((m) => ({
937
+ ...m,
938
+ ...(actor === undefined ? {} : { binds: m.participant === null || m.participantAgent === actor }),
939
+ }));
940
+ }
941
+
942
+ function resolveActing(normalized, ws) {
943
+ const { agentId, agentType } = normalized;
944
+ if (agentId !== undefined) {
945
+ if (typeof agentId !== 'string' || agentId === '' || agentId.length > AGENT_LIMIT) {
946
+ return { refusal: 'the subagent event carries a malformed agent_id', subagent: true };
947
+ }
948
+ if (typeof agentType !== 'string' || agentType === '' || agentType.length > AGENT_LIMIT) {
949
+ return { refusal: 'the subagent event names no agent_type', subagent: true };
950
+ }
951
+ const entry = Object.hasOwn(MODEL.subagents, agentType) ? MODEL.subagents[agentType] : undefined;
952
+ if (!entry) {
953
+ return { refusal: \`subagent \${agentType} matches no single authored @agent-profile of that name\`, subagent: true };
954
+ }
955
+ if (!entry.agent) {
956
+ return { refusal: \`\${entry.profile} names no admitted composition.agent\`, subagent: true };
957
+ }
958
+ return { agent: entry.agent, as: \`subagent \${agentType} acts as \${entry.agent} (\${entry.profile})\` };
959
+ }
960
+ if (ws === undefined || !MODEL.workspaces[ws]) {
961
+ return { as: 'the main session has no default actor: no @workspace holds this path' };
962
+ }
963
+ const wsInfo = MODEL.workspaces[ws];
964
+ if (wsInfo.refusal) {
965
+ return { refusal: wsInfo.refusal.message, next: wsInfo.refusal.next, subagent: false };
966
+ }
967
+ return wsInfo.actor === null
968
+ ? { as: \`the main session has no default actor: \${wsInfo.reason}\` }
969
+ : { agent: wsInfo.actor, as: \`the main session acts as \${wsInfo.actor}\` };
970
+ }
971
+
972
+ function governanceCmd(seat) {
973
+ return \`ia position --seat \${seat} --shape governance\`;
974
+ }
975
+
976
+ function evaluateProfileAuthor(mandates) {
977
+ if (mandates.length === 0) return {};
978
+ const whom = (m) => (m.participant === null ? m.identity : \`\${m.identity} binds \${m.participant}\`);
979
+ const judged = mandates.map((m) => ({
980
+ authority: m,
981
+ refusal: m.moves !== null && !m.moves.includes('Synthesis')
982
+ ? { message: \`\${m.identity} allows \${m.moves.join(', ')}; author needs Synthesis\`, next: governanceCmd(m.identity) }
983
+ : undefined,
984
+ }));
985
+ const binding = judged.filter(({ authority }) => authority.binds !== false);
986
+ if (binding.length === 0) {
987
+ return {
988
+ refusal: {
989
+ message: \`no mandate that governs here binds the acting @agent: \${mandates.map(whom).join('; ')}\`,
990
+ next: governanceCmd(mandates[0].identity),
991
+ },
992
+ };
993
+ }
994
+ const named = binding.filter(({ authority }) => authority.participant !== null).map(({ authority }) => authority);
995
+ const participants = new Set(named.map((a) => a.participant));
996
+ if (participants.size > 1) {
997
+ return {
998
+ refusal: {
999
+ message: \`the mandates that govern here bind \${participants.size} participants and name no acting @agent: \${named.map(whom).join('; ')}\`,
1000
+ next: governanceCmd(named[0].identity),
1001
+ },
1002
+ };
1003
+ }
1004
+ const unbound = named.filter((a) => a.binds === undefined);
1005
+ if (unbound.length > 0) {
1006
+ return {
1007
+ refusal: {
1008
+ message: \`a governing mandate names a participant but no acting @agent was established: \${unbound.map(whom).join('; ')}\`,
1009
+ next: governanceCmd(unbound[0].identity),
1010
+ },
1011
+ };
1012
+ }
1013
+ if (binding.every(({ refusal }) => refusal !== undefined)) {
1014
+ return {
1015
+ refusal: {
1016
+ message: \`\${binding.map(({ authority }) => \`\${authority.identity} allows \${authority.moves.join(', ')}\`).join('; ')}; author needs Synthesis\`,
1017
+ next: governanceCmd(binding[0].authority.identity),
1018
+ },
1019
+ };
1020
+ }
1021
+ return {};
1022
+ }
1023
+
1024
+ function evaluateRule(rule, paths, normalized) {
1025
+ const formatDeny = (code, why, next) => ({
1026
+ allowed: false,
1027
+ code,
1028
+ message: \`\${rule.message} (\${rule.identity}: \${why}) Next: \${next}\`,
1029
+ });
1030
+ if (MODEL.admissionRefusal !== null) {
1031
+ return formatDeny('IA-HOOK-MANDATE-UNAVAILABLE', \`the mandates that govern this edit cannot be read: \${MODEL.admissionRefusal}\`, 'ia report');
1032
+ }
1033
+ try {
1034
+ const ws = seatedWorkspace(paths[0]);
1035
+ const locate = (actor) => {
1036
+ const found = new Map();
1037
+ for (const p of paths) {
1038
+ const gws = ws ?? governingWorkspace(p);
1039
+ for (const m of governingMandatesFor(p, gws, actor)) {
1040
+ if (!found.has(m.identity)) found.set(m.identity, m);
1041
+ }
1042
+ }
1043
+ return [...found.values()].sort((a, b) => (a.identity < b.identity ? -1 : a.identity > b.identity ? 1 : 0));
1044
+ };
1045
+ const actor = resolveActing(normalized, ws);
1046
+ const governing = locate(undefined);
1047
+ const seat = governing[0]?.identity ?? ws;
1048
+ const first = seat === undefined ? 'ia position --shape governance' : governanceCmd(seat);
1049
+ if (actor.refusal !== undefined && actor.subagent) {
1050
+ return formatDeny('IA-HOOK-IDENTITY-UNAVAILABLE', actor.refusal, first);
1051
+ }
1052
+ if (governing.length === 0) return { allowed: true };
1053
+ if (actor.refusal !== undefined) {
1054
+ return formatDeny('IA-HOOK-IDENTITY-UNAVAILABLE', actor.refusal, actor.next ?? first);
1055
+ }
1056
+ let verdict;
1057
+ if (actor.agent === undefined) {
1058
+ const named = governing.find((m) => m.participant !== null);
1059
+ if (named !== undefined) {
1060
+ return formatDeny('IA-HOOK-IDENTITY-UNAVAILABLE', \`\${actor.as}; \${named.identity} binds \${named.participant}\`, governanceCmd(named.identity));
1061
+ }
1062
+ verdict = evaluateProfileAuthor(governing);
1063
+ } else {
1064
+ verdict = evaluateProfileAuthor(locate(actor.agent));
1065
+ }
1066
+ if (verdict.refusal !== undefined) {
1067
+ return formatDeny('IA-HOOK-NOT-MANDATED', \`\${actor.as}; \${verdict.refusal.message}\`, verdict.refusal.next);
1068
+ }
1069
+ return { allowed: true };
1070
+ } catch (error) {
1071
+ const next = error?.mandateIdentity ? governanceCmd(error.mandateIdentity) : 'ia report';
1072
+ return formatDeny('IA-HOOK-MANDATE-UNAVAILABLE', \`the mandates that govern this edit cannot be read: \${error?.message ?? String(error)}\`, next);
1073
+ }
1074
+ }
1075
+
1076
+ function respondDeny(caller, code, message) {
1077
+ const reason = printable(\`\${code}: \${message}\`);
1078
+ if (caller === 'gemini' || caller === 'antigravity') {
1079
+ process.stdout.write(JSON.stringify({ decision: 'deny', reason }) + '\\n');
1080
+ return;
1081
+ }
1082
+ process.stdout.write(
1083
+ JSON.stringify({
1084
+ hookSpecificOutput: {
1085
+ hookEventName: 'PreToolUse',
1086
+ permissionDecision: 'deny',
1087
+ permissionDecisionReason: reason,
1088
+ },
1089
+ }) + '\\n',
1090
+ );
1091
+ }
1092
+
1093
+ function respondAllow(caller) {
1094
+ if (caller === 'antigravity' || caller === 'gemini') {
1095
+ process.stdout.write(JSON.stringify({ decision: 'allow' }) + '\\n');
1096
+ }
1097
+ }
1098
+
1099
+ const chunks = [];
1100
+ let totalBytes = 0;
1101
+ for await (const chunk of process.stdin) {
1102
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk), 'utf8');
1103
+ totalBytes += buf.byteLength;
1104
+ if (totalBytes > 1024 * 1024) {
1105
+ respondDeny(HOST, 'IA-HOOK-INPUT-INVALID', 'Input exceeds 1 MiB');
1106
+ process.exit(0);
1107
+ }
1108
+ chunks.push(buf);
1109
+ }
1110
+
1111
+ let parsed;
1112
+ try {
1113
+ const raw = Buffer.concat(chunks).toString('utf8');
1114
+ if (!raw.trim()) {
1115
+ respondDeny(HOST, 'IA-HOOK-INPUT-INVALID', 'Expected a PreToolUse file edit event');
1116
+ process.exit(0);
1117
+ }
1118
+ parsed = JSON.parse(raw);
1119
+ } catch {
1120
+ respondDeny(HOST, 'IA-HOOK-INPUT-INVALID', 'Invalid JSON input');
1121
+ process.exit(0);
1122
+ }
1123
+
1124
+ const caller = callerOf(parsed);
1125
+ const normalized = normalizeEvent(parsed);
1126
+ if (!normalized) {
1127
+ respondDeny(caller, 'IA-HOOK-INPUT-INVALID', 'Expected a PreToolUse file edit event');
1128
+ process.exit(0);
1129
+ }
1130
+
1131
+ let edit;
1132
+ try {
1133
+ edit = resolveEditTarget(normalized);
1134
+ } catch (error) {
1135
+ respondDeny(caller, 'IA-HOOK-PATH-UNSAFE', error?.message ?? String(error));
1136
+ process.exit(0);
1137
+ }
1138
+
1139
+ if (edit.spellings.some((s) => s !== undefined && installation(s))) {
1140
+ respondDeny(caller, 'IA-HOOK-PROJECTION-MANAGED', 'Use the owning command for generated installation state');
1141
+ process.exit(0);
1142
+ }
1143
+
1144
+ const paths = [...new Set([edit.spellings[1], edit.spellings[0], ...edit.spellings.slice(2)])].filter(
1145
+ (s) => s !== undefined,
1146
+ );
1147
+ if (paths.length === 0) {
1148
+ respondAllow(caller);
1149
+ process.exit(0);
1150
+ }
1151
+
1152
+ try {
1153
+ const linkedStat = lstatSync(edit.actual, { throwIfNoEntry: false });
1154
+ if (linkedStat !== undefined && linkedStat.isFile() && linkedStat.nlink > 1) {
1155
+ respondDeny(caller, 'IA-HOOK-PATH-UNSAFE', 'A file with more than one link is refused: another of its names may be guarded');
1156
+ process.exit(0);
1157
+ }
1158
+ } catch (error) {
1159
+ respondDeny(caller, 'IA-HOOK-PATH-UNSAFE', error?.message ?? String(error));
1160
+ process.exit(0);
1161
+ }
1162
+
1163
+ for (const rule of RULES) {
1164
+ const selected =
1165
+ rule.tools.includes(normalized.tool) &&
1166
+ paths.some((p) => rule.paths.some((sel) => selects(sel, p)));
1167
+ if (!selected) continue;
1168
+ if (!unaliased(edit.target, edit.actual)) {
1169
+ respondDeny(caller, 'IA-HOOK-PATH-UNSAFE', 'Selected path has an aliased ancestor or target');
1170
+ process.exit(0);
1171
+ }
1172
+ const decision = evaluateRule(rule, paths, normalized);
1173
+ if (!decision.allowed) {
1174
+ respondDeny(caller, decision.code, decision.message);
1175
+ process.exit(0);
1176
+ }
1177
+ }
1178
+
1179
+ respondAllow(caller);
1180
+ `;
1181
+ return utf8Bytes(source);
1182
+ }
1183
+ function renderHookManifest(host) {
1184
+ if (host === 'claude') {
1185
+ return {
1186
+ path: 'hooks/hooks.json',
1187
+ bytes: jsonBytes({
1188
+ hooks: {
1189
+ PreToolUse: [
1190
+ {
1191
+ matcher: 'Write|Edit|MultiEdit',
1192
+ hooks: [
1193
+ {
1194
+ type: 'command',
1195
+ command: 'node "${CLAUDE_PLUGIN_ROOT}/scripts/guard.mjs"',
1196
+ timeout: 10,
1197
+ },
1198
+ ],
1199
+ },
1200
+ ],
1201
+ },
1202
+ }),
1203
+ };
1204
+ }
1205
+ if (host === 'gemini') {
1206
+ return {
1207
+ path: 'hooks/hooks.json',
1208
+ bytes: jsonBytes({
1209
+ hooks: {
1210
+ BeforeTool: [
1211
+ {
1212
+ matcher: '^(write_file|replace)$',
1213
+ hooks: [
1214
+ {
1215
+ name: 'ia-guard',
1216
+ type: 'command',
1217
+ command: 'node "${extensionPath}/scripts/guard.mjs"',
1218
+ timeout: 10000,
1219
+ },
1220
+ ],
1221
+ },
1222
+ ],
1223
+ },
1224
+ }),
1225
+ };
1226
+ }
1227
+ if (host === 'antigravity') {
1228
+ return {
1229
+ path: 'hooks.json',
1230
+ bytes: jsonBytes({
1231
+ 'ia-guard': {
1232
+ PreToolUse: [
1233
+ {
1234
+ matcher: 'write_to_file|replace_file_content|multi_replace_file_content|write_file|edit_file',
1235
+ hooks: [
1236
+ {
1237
+ type: 'command',
1238
+ command: 'node ./scripts/guard.mjs',
1239
+ timeout: 10,
1240
+ },
1241
+ ],
1242
+ },
1243
+ ],
1244
+ },
1245
+ }),
1246
+ };
1247
+ }
1248
+ return null;
1249
+ }
1250
+ function renderAgentMarkdown(reader, within, host, profile, nodesByIdentity, inlineBody) {
1251
+ if (host === 'codex')
1252
+ return null;
1253
+ const resolveTarget = (value) => {
1254
+ if (value.kind !== 'ref')
1255
+ return undefined;
1256
+ const resolved = reader.resolve(value, { within });
1257
+ return resolved.ok ? nodesByIdentity.get(resolved.identity) : undefined;
1258
+ };
1259
+ const caps = capabilityClosure(valuesAt(profile, 'composition.capabilities'), resolveTarget);
1260
+ const effects = [...new Set(caps.flatMap((cap) => textsAt(cap, 'execution.effects')))];
1261
+ // Default to read tools when a profile inspects without mutating effects.
1262
+ const effectiveTools = hostToolsForEffects(host, effects.length > 0 ? effects : ['read']);
1263
+ if (effectiveTools.length === 0)
1264
+ return null;
1265
+ const one = (field) => textsAt(profile, field)[0];
1266
+ const fields = host === 'antigravity'
1267
+ ? [
1268
+ { key: 'name', value: plainField(toPortableSlug(profile.name, 'agent')) },
1269
+ {
1270
+ key: 'description',
1271
+ value: plainField(shortSummary(one('meaning.says') ?? `Use this agent for ${profile.name}.`, 240)),
1272
+ },
1273
+ { key: 'subagent', value: { kind: 'boolean', value: true } },
1274
+ { key: 'mainAgent', value: { kind: 'boolean', value: false } },
1275
+ { key: 'tools', value: { kind: 'list', items: effectiveTools } },
1276
+ ]
1277
+ : host === 'gemini'
1278
+ ? [
1279
+ { key: 'name', value: plainField(toPortableSlug(profile.name, 'agent')) },
1280
+ {
1281
+ key: 'description',
1282
+ value: plainField(shortSummary(one('meaning.says') ?? `Use this agent for ${profile.name}.`, 240)),
1283
+ },
1284
+ { key: 'tools', value: { kind: 'list', items: effectiveTools } },
1285
+ ...(one('execution.model-profile') === undefined
1286
+ ? []
1287
+ : [{ key: 'model', value: plainField(one('execution.model-profile')) }]),
1288
+ ]
1289
+ : [
1290
+ { key: 'name', value: plainField(toPortableSlug(profile.name, 'agent')) },
1291
+ {
1292
+ key: 'description',
1293
+ value: plainField(shortSummary(one('meaning.says') ?? `Use this agent for ${profile.name}.`, 240)),
1294
+ },
1295
+ { key: 'tools', value: plainField(effectiveTools.join(', ')) },
1296
+ ...(one('execution.model-profile') === undefined
1297
+ ? []
1298
+ : [{ key: 'model', value: plainField(one('execution.model-profile')) }]),
1299
+ ...(one('presentation.color') === undefined
1300
+ ? []
1301
+ : [{ key: 'color', value: plainField(one('presentation.color')) }]),
1302
+ ...(one('execution.effort') === undefined
1303
+ ? []
1304
+ : [{ key: 'effort', value: plainField(one('execution.effort')) }]),
1305
+ ];
1306
+ if (inlineBody !== undefined) {
1307
+ return Buffer.concat([utf8Bytes(emitFrontmatter(fields)), inlineBody]);
1308
+ }
1309
+ const voice = valuesAt(profile, 'composition.voice')
1310
+ .map(resolveTarget)
1311
+ .find((n) => n?.discriminator === 'voice');
1312
+ const mandate = valuesAt(profile, 'composition.mandate')
1313
+ .map(resolveTarget)
1314
+ .find((n) => n?.discriminator === 'mandate');
1315
+ const bodyLines = [
1316
+ '',
1317
+ `# ${profile.name}`,
1318
+ '',
1319
+ cleanLine(one('meaning.says')) || `Specialized agent profile for ${profile.name}.`,
1320
+ ];
1321
+ if (voice) {
1322
+ const tone = cleanLine(textsAt(voice, 'voice.tone')[0]);
1323
+ const style = cleanLine(textsAt(voice, 'voice.style')[0]);
1324
+ bodyLines.push('', '## Voice');
1325
+ if (tone)
1326
+ bodyLines.push(`- **Tone:** ${tone}`);
1327
+ if (style)
1328
+ bodyLines.push(`- **Style:** ${style}`);
1329
+ }
1330
+ if (mandate) {
1331
+ const moves = textsAt(mandate, 'authority.moves');
1332
+ const covers = textsAt(mandate, 'authority.covers');
1333
+ bodyLines.push('', '## Mandate');
1334
+ if (moves.length > 0)
1335
+ bodyLines.push(`- **Allowed moves:** ${moves.join(', ')}`);
1336
+ if (covers.length > 0)
1337
+ bodyLines.push(`- **Scope:** ${covers.map((c) => `\`${c}\``).join(', ')}`);
1338
+ }
1339
+ if (caps.length > 0) {
1340
+ bodyLines.push('', '## Capabilities');
1341
+ for (const cap of caps) {
1342
+ bodyLines.push(`- \`${cap.name}\`: ${shortSummary(textsAt(cap, 'meaning.says')[0], 180)}`);
1343
+ }
1344
+ }
1345
+ bodyLines.push('');
1346
+ return Buffer.concat([utf8Bytes(emitFrontmatter(fields)), utf8Bytes(bodyLines.join('\n'))]);
1347
+ }
1348
+ function selectBindingRow(value, precedence) {
1349
+ if (!Array.isArray(value))
1350
+ return value;
1351
+ if (value.length <= 1)
1352
+ return value[0];
1353
+ const ranked = value
1354
+ .map((row) => ({ row, rank: row.kit ? precedence.indexOf(row.kit) : -1 }))
1355
+ .filter((entry) => entry.rank >= 0)
1356
+ .sort((a, b) => a.rank - b.rank);
1357
+ return ranked[0]?.row ?? value[0];
1358
+ }
1359
+ /**
1360
+ * Compiles any seated workspace or kit workspace into a zero-IA-dependency standalone plugin for `options.host`
1361
+ * (`claude`, `codex`, `gemini`, or `antigravity`).
1362
+ */
1363
+ export function compileStandalonePlugin(reader, within, options) {
1364
+ const { host } = options;
1365
+ const records = reader.records({ within });
1366
+ const nodesByIdentity = new Map(records.map((node) => [node.identity, node]));
1367
+ const resources = options.resources ?? [];
1368
+ const assets = options.assets ?? [];
1369
+ const authored = (word) => records
1370
+ .filter((node) => node.discriminator === word && node.band === 100)
1371
+ .sort((a, b) => (a.identity < b.identity ? -1 : 1));
1372
+ const active = (word) => records
1373
+ .filter((node) => node.discriminator === word && isWorkspaceOrKitNode(node))
1374
+ .sort((a, b) => (a.identity < b.identity ? -1 : 1));
1375
+ const one = (node, field) => node === undefined ? undefined : textsAt(node, field)[0];
1376
+ const productDist = authored('distribution').find((node) => stated(node, 'product.name'));
1377
+ const anyDist = productDist ?? authored('distribution')[0];
1378
+ const workspaceNode = authored('workspace')[0];
1379
+ const systemNode = authored('system')[0];
1380
+ const rawName = one(productDist, 'product.name') ??
1381
+ workspaceNode?.name ??
1382
+ systemNode?.name ??
1383
+ anyDist?.name.replace(/-distribution$/, '') ??
1384
+ options.fallbackName ??
1385
+ 'ia-plugin';
1386
+ const pluginName = toPortableSlug(rawName, 'ia-plugin');
1387
+ const displayName = one(productDist, 'product.display-name') ?? toDisplayName(pluginName);
1388
+ const version = one(productDist, 'product.version') ?? one(systemNode, 'head.version') ?? options.fallbackVersion ?? '0.1.0';
1389
+ const description = shortSummary(one(productDist, 'product.description') ??
1390
+ one(workspaceNode, 'meaning.says') ??
1391
+ one(anyDist, 'meaning.says') ??
1392
+ one(systemNode, 'head.describes') ??
1393
+ options.fallbackDescription ??
1394
+ `Standalone ${host} plugin compiled from ${pluginName}.`, 240);
1395
+ const author = one(productDist, 'product.author') ?? options.fallbackAuthor ?? 'InventArch';
1396
+ const product = {
1397
+ name: pluginName,
1398
+ displayName,
1399
+ version,
1400
+ description,
1401
+ author,
1402
+ license: one(productDist, 'product.license') ?? 'Apache-2.0',
1403
+ keywords: productDist && stated(productDist, 'product.keywords') ? textsAt(productDist, 'product.keywords') : undefined,
1404
+ shortDescription: one(productDist, 'product.short-description'),
1405
+ category: one(productDist, 'product.category'),
1406
+ };
1407
+ const out = [];
1408
+ const add = (path, bytes) => {
1409
+ const clean = portablePath(path);
1410
+ if (out.some((file) => file.path === clean))
1411
+ throw new HostPluginError('IA-PLUGIN-PRODUCT', `Two sources render ${clean}`);
1412
+ out.push(Object.freeze({ path: clean, bytes }));
1413
+ };
1414
+ // 1. Host-native manifest.
1415
+ add(MANIFESTS[host], jsonBytes(pluginManifest(product, host)));
1416
+ // 2. Capabilities -> either <=4 inline-body skills (when lowered with inline bodies and no lane bindings)
1417
+ // or bounded progressive-disclosure router skills (<=4 model-invocable skills total) + OPAL references/*.md.
1418
+ const allCapabilities = active('capability').filter((cap) => {
1419
+ const mode = one(cap, 'invocation.mode');
1420
+ return mode !== 'none' && mode !== 'delegated';
1421
+ });
1422
+ const capByName = new Map();
1423
+ for (const cap of allCapabilities) {
1424
+ const prev = capByName.get(cap.name);
1425
+ if (!prev || cap.band >= prev.band)
1426
+ capByName.set(cap.name, cap);
1427
+ }
1428
+ const uniqueCapabilities = [...capByName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
1429
+ const inlineBodyOf = (identity) => resources.find((r) => r.owner === identity && r.role === 'body' && r.delivery === 'inline')?.bytes;
1430
+ const hasSeatBindings = options.bindings !== undefined && Object.keys(options.bindings).length > 0;
1431
+ const hasAdoptedKitCapabilities = allCapabilities.some((cap) => cap.band < 100);
1432
+ const allHaveInlineBodies = uniqueCapabilities.length > 0 && uniqueCapabilities.every((cap) => inlineBodyOf(cap.identity) !== undefined);
1433
+ const inferSeatedLane = (cap) => {
1434
+ const src = cap.source.path.replaceAll('\\', '/');
1435
+ const name = cap.name;
1436
+ if (name === 'method-vocabulary')
1437
+ return { lane: 'knowledge', activity: 'vocabulary' };
1438
+ if (src.includes('/ia-kb/') || name.startsWith('kb-')) {
1439
+ const activity = name === 'kb-knowledge' ? 'knowledge (default)' : name.replace(/^kb-/, '');
1440
+ return { lane: 'knowledge', activity };
1441
+ }
1442
+ if (src.includes('/ia-method/') || name === 'method-operate' || name.endsWith('-method')) {
1443
+ const activity = name === 'method-operate' ? 'work (default)' : name.replace(/-method$/, '');
1444
+ return { lane: 'work', activity };
1445
+ }
1446
+ if (src.includes('/ia-authoring') ||
1447
+ src.includes('/ia-engineering') ||
1448
+ src.includes('/ia-architecture') ||
1449
+ name.startsWith('authoring-') ||
1450
+ name.startsWith('engineering-') ||
1451
+ name.startsWith('architecture-') ||
1452
+ name.startsWith('delivery-')) {
1453
+ const activity = name === 'authoring' || name === 'ia-authoring'
1454
+ ? 'delivery (default)'
1455
+ : name.replace(/^(?:ia-authoring-|authoring-|engineering-|architecture-|delivery-)/, '');
1456
+ return { lane: 'delivery', activity };
1457
+ }
1458
+ return null;
1459
+ };
1460
+ if (!hasSeatBindings && !hasAdoptedKitCapabilities && uniqueCapabilities.length <= 4 && allHaveInlineBodies) {
1461
+ for (const cap of uniqueCapabilities) {
1462
+ const mode = one(cap, 'invocation.mode');
1463
+ const fields = [
1464
+ { key: 'name', value: plainField(toPortableSlug(cap.name, 'skill')) },
1465
+ { key: 'description', value: plainField(shortSummary(one(cap, 'meaning.says') ?? '', 240)) },
1466
+ ...(mode === 'user'
1467
+ ? [{ key: 'disable-model-invocation', value: { kind: 'boolean', value: true } }]
1468
+ : []),
1469
+ ...(one(cap, 'invocation.argument-hint') === undefined
1470
+ ? []
1471
+ : [{ key: 'argument-hint', value: plainField(one(cap, 'invocation.argument-hint')) }]),
1472
+ ];
1473
+ add(`skills/${toPortableSlug(cap.name, 'skill')}/SKILL.md`, Buffer.concat([utf8Bytes(emitFrontmatter(fields)), inlineBodyOf(cap.identity)]));
1474
+ for (const ref of resources.filter((r) => r.owner === cap.identity && r.delivery === 'installed-reference')) {
1475
+ add(ref.output, ref.bytes);
1476
+ }
1477
+ }
1478
+ }
1479
+ else if (uniqueCapabilities.length > 0) {
1480
+ const seatedMode = hasSeatBindings || (workspaceNode !== undefined && hasAdoptedKitCapabilities);
1481
+ if (seatedMode) {
1482
+ const precedence = options.precedence ?? [];
1483
+ const mergedKeys = new Map();
1484
+ for (const [key, row] of Object.entries(options.recommendedBindings ?? {})) {
1485
+ mergedKeys.set(key, row);
1486
+ }
1487
+ for (const [key, raw] of Object.entries(options.bindings ?? {})) {
1488
+ const chosen = selectBindingRow(raw, precedence);
1489
+ if (chosen !== undefined)
1490
+ mergedKeys.set(key, chosen);
1491
+ }
1492
+ const laneEntries = { work: [], knowledge: [], delivery: [] };
1493
+ const assignedCaps = new Set();
1494
+ for (const [key, row] of [...mergedKeys.entries()].sort(([a], [b]) => (a < b ? -1 : 1))) {
1495
+ const dot = key.indexOf('.');
1496
+ if (dot <= 0)
1497
+ continue;
1498
+ const lane = key.slice(0, dot);
1499
+ if (!LANES.includes(lane))
1500
+ continue;
1501
+ const cap = capByName.get(row.capability);
1502
+ if (!cap)
1503
+ continue;
1504
+ const activity = key.slice(dot + 1) === '*' ? `${lane} (default)` : key.slice(dot + 1);
1505
+ laneEntries[lane].push({
1506
+ activity,
1507
+ capability: cap,
1508
+ summary: one(cap, 'invocation.use-when') ?? one(cap, 'meaning.says') ?? '',
1509
+ });
1510
+ assignedCaps.add(cap.name);
1511
+ }
1512
+ for (const cap of uniqueCapabilities) {
1513
+ if (assignedCaps.has(cap.name))
1514
+ continue;
1515
+ const inferred = inferSeatedLane(cap);
1516
+ if (inferred === null)
1517
+ continue;
1518
+ laneEntries[inferred.lane].push({
1519
+ activity: inferred.activity,
1520
+ capability: cap,
1521
+ summary: one(cap, 'invocation.use-when') ?? one(cap, 'meaning.says') ?? '',
1522
+ });
1523
+ assignedCaps.add(cap.name);
1524
+ }
1525
+ for (const lane of LANES) {
1526
+ const entries = laneEntries[lane];
1527
+ if (entries.length === 0)
1528
+ continue;
1529
+ add(`skills/${lane}/SKILL.md`, renderRouterSkill(lane, LANE_DESCRIPTIONS[lane], host, entries));
1530
+ const seen = new Set();
1531
+ for (const entry of entries) {
1532
+ if (seen.has(entry.capability.name))
1533
+ continue;
1534
+ seen.add(entry.capability.name);
1535
+ const slug = toPortableSlug(entry.capability.name, 'capability');
1536
+ add(`skills/${lane}/references/${slug}.md`, renderCapabilityReference(reader, within, host, entry.capability, records, nodesByIdentity, inlineBodyOf(entry.capability.identity)));
1537
+ }
1538
+ }
1539
+ const unbound = uniqueCapabilities.filter((cap) => !assignedCaps.has(cap.name));
1540
+ if (unbound.length > 0) {
1541
+ const extraRouter = toPortableSlug(`${pluginName}-capabilities`, 'workspace-capabilities');
1542
+ const entries = unbound.map((cap) => ({
1543
+ activity: cap.name,
1544
+ capability: cap,
1545
+ summary: one(cap, 'invocation.use-when') ?? one(cap, 'meaning.says') ?? '',
1546
+ }));
1547
+ add(`skills/${extraRouter}/SKILL.md`, renderRouterSkill(extraRouter, `Additional capabilities compiled from ${displayName}. Use when invoking specialized workspace or kit methods not covered by a primary lane.`, host, entries));
1548
+ for (const cap of unbound) {
1549
+ const slug = toPortableSlug(cap.name, 'capability');
1550
+ add(`skills/${extraRouter}/references/${slug}.md`, renderCapabilityReference(reader, within, host, cap, records, nodesByIdentity, inlineBodyOf(cap.identity)));
1551
+ }
1552
+ }
1553
+ }
1554
+ else {
1555
+ // Single-kit workspace without .ia/bindings.json: emit ONE <kit-name> router skill + references/*.md.
1556
+ const kitRouter = toPortableSlug(pluginName.replace(/-kit$/, ''), 'kit');
1557
+ const recommendedByCap = new Map();
1558
+ for (const [key, row] of Object.entries(options.recommendedBindings ?? {})) {
1559
+ if (!recommendedByCap.has(row.capability))
1560
+ recommendedByCap.set(row.capability, key);
1561
+ }
1562
+ const entries = uniqueCapabilities.map((cap) => ({
1563
+ activity: recommendedByCap.get(cap.name) ?? cap.name,
1564
+ capability: cap,
1565
+ summary: one(cap, 'invocation.use-when') ?? one(cap, 'meaning.says') ?? '',
1566
+ }));
1567
+ add(`skills/${kitRouter}/SKILL.md`, renderRouterSkill(kitRouter, `${displayName} method router (${uniqueCapabilities.length} compiled capabilities). ${description}`, host, entries));
1568
+ for (const cap of uniqueCapabilities) {
1569
+ const slug = toPortableSlug(cap.name, 'capability');
1570
+ add(`skills/${kitRouter}/references/${slug}.md`, renderCapabilityReference(reader, within, host, cap, records, nodesByIdentity, inlineBodyOf(cap.identity)));
1571
+ }
1572
+ }
1573
+ }
1574
+ // 3. Governance context files when rules/laws/conventions/principles exist.
1575
+ const rules = [...active('law'), ...active('principle'), ...active('convention')];
1576
+ if (rules.length > 0) {
1577
+ if (host === 'gemini')
1578
+ add('GEMINI.md', renderRulesMarkdown(displayName, rules));
1579
+ else if (host === 'antigravity')
1580
+ add('rules/AGENTS.md', renderRulesMarkdown(displayName, rules));
1581
+ }
1582
+ // 4. Host-native agents from @agent-profile records.
1583
+ const profiles = authored('agent-profile').length > 0 ? authored('agent-profile') : active('agent-profile');
1584
+ for (const profile of profiles) {
1585
+ const mode = one(profile, 'invocation.mode');
1586
+ if (mode === 'none' || mode === 'delegated')
1587
+ continue;
1588
+ const rendered = renderAgentMarkdown(reader, within, host, profile, nodesByIdentity, inlineBodyOf(profile.identity));
1589
+ if (rendered !== null)
1590
+ add(`agents/${toPortableSlug(profile.name, 'agent')}.md`, rendered);
1591
+ }
1592
+ // 5. Compiled standalone @hook guards + native host hook manifest.
1593
+ const hookRules = active('hook')
1594
+ .map(standaloneHookOf)
1595
+ .filter((rule) => rule !== null)
1596
+ .slice(0, HOOK_LIMIT);
1597
+ if (hookRules.length > 0) {
1598
+ const hookManifest = renderHookManifest(host);
1599
+ if (hookManifest !== null) {
1600
+ const guardModel = compileMandateGuardModel(reader, within);
1601
+ add('scripts/guard.mjs', renderStandaloneGuardScript(host, hookRules, guardModel));
1602
+ add(hookManifest.path, hookManifest.bytes);
1603
+ }
1604
+ }
1605
+ // 6. Codex bridge doc & assets (skipping colliding paths).
1606
+ for (const asset of assets) {
1607
+ const clean = portablePath(asset.output);
1608
+ if (!out.some((file) => file.path === clean))
1609
+ add(clean, asset.bytes);
1610
+ }
1611
+ if (host === 'codex' && !out.some((file) => file.path === 'CODEX.md')) {
1612
+ add('CODEX.md', utf8Bytes(`# ${displayName}\n\nStandalone Codex plugin compiled from \`${pluginName}\`. Activate a router skill under \`skills/\` and read the matching \`references/<capability>.md\` file with \`Read\`.\n`));
1613
+ }
1614
+ return Object.freeze(out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0)));
1615
+ }
1616
+ //# sourceMappingURL=standalone-plugin.js.map