ultra-builder-pro-cli 0.25.1 → 0.26.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 (241) hide show
  1. package/.ultra-template/contexts/TEMPLATE.md +87 -0
  2. package/.ultra-template/decisions/.gitkeep +1 -0
  3. package/.ultra-template/evidence/.gitkeep +1 -0
  4. package/.ultra-template/north-star.md +46 -0
  5. package/.ultra-template/research/.gitkeep +1 -0
  6. package/.ultra-template/specs/discovery.md +2 -2
  7. package/.ultra-template/tasks.json +3 -0
  8. package/.ultra-template/test-report.json +27 -0
  9. package/CHANGELOG.md +40 -0
  10. package/README.md +217 -579
  11. package/adapters/_shared/delegate-profiles/kimi-read-only.md +15 -0
  12. package/adapters/_shared/delegate-profiles/kimi-write.md +17 -0
  13. package/adapters/_shared/file-ops.cjs +76 -2
  14. package/adapters/_shared/host-profile.cjs +97 -0
  15. package/adapters/_shared/plugin-core.cjs +204 -0
  16. package/adapters/_shared/runtime-assets.cjs +31 -96
  17. package/adapters/claude.js +92 -291
  18. package/adapters/codex.js +309 -842
  19. package/adapters/grok.js +143 -1469
  20. package/adapters/kimi.js +124 -1053
  21. package/adapters/opencode.js +230 -742
  22. package/bin/delegate-worker.cjs +323 -0
  23. package/bin/delegate.cjs +456 -0
  24. package/bin/install.js +38 -11
  25. package/docs/ARCHITECTURE.md +122 -216
  26. package/docs/ARTIFACT-AUTHORITY.md +90 -268
  27. package/docs/DECISIONS.md +75 -87
  28. package/docs/PHILOSOPHY.md +177 -0
  29. package/docs/PLUGIN-ISOLATION-CONTRACT.md +62 -39
  30. package/docs/RUNTIME-COMPAT-MATRIX.md +99 -156
  31. package/docs/SKILL-AUTHORING.md +94 -73
  32. package/docs/WORKFLOW-LIFECYCLE.md +93 -189
  33. package/hooks/README.md +17 -37
  34. package/hooks/_common.py +113 -0
  35. package/hooks/adapters/codex.py +9 -16
  36. package/hooks/adapters/grok.py +5 -5
  37. package/hooks/adapters/kimi.py +8 -14
  38. package/hooks/block_dangerous_commands.py +95 -0
  39. package/hooks/compact_context.py +65 -0
  40. package/hooks/mid_workflow_recall.py +25 -0
  41. package/hooks/post_edit_guard.py +105 -0
  42. package/hooks/session_context.py +30 -0
  43. package/package.json +17 -52
  44. package/skills/ultra-change/SKILL.md +97 -50
  45. package/skills/ultra-change/references/change-contract.md +40 -1
  46. package/skills/ultra-delegate/SKILL.md +82 -0
  47. package/skills/ultra-delegate/references/delegation-contract.md +51 -0
  48. package/skills/ultra-delegate/scripts/delegate_wait.py +86 -0
  49. package/skills/ultra-deliver/SKILL.md +61 -42
  50. package/skills/ultra-deliver/references/baseline-reconciliation.md +39 -20
  51. package/skills/ultra-dev/SKILL.md +96 -62
  52. package/skills/ultra-dev/references/debugging.md +22 -0
  53. package/skills/ultra-domain-modeling/SKILL.md +79 -0
  54. package/skills/ultra-grilling/SKILL.md +79 -0
  55. package/skills/ultra-init/SKILL.md +94 -37
  56. package/skills/ultra-init/references/brownfield-adoption.md +33 -83
  57. package/skills/ultra-init/scripts/init_project.cjs +84 -0
  58. package/skills/ultra-plan/SKILL.md +88 -68
  59. package/skills/ultra-research/SKILL.md +62 -48
  60. package/skills/ultra-research/references/00-problem-validation.md +5 -5
  61. package/skills/ultra-research/references/01-opportunity-discovery.md +3 -3
  62. package/skills/ultra-research/references/02-market-assessment.md +5 -4
  63. package/skills/ultra-research/references/03-competitive-landscape.md +3 -3
  64. package/skills/ultra-research/references/04-product-strategy.md +3 -3
  65. package/skills/ultra-research/references/05-assumptions-validation.md +5 -5
  66. package/skills/ultra-research/references/10-user-personas.md +3 -2
  67. package/skills/ultra-research/references/11-user-scenarios.md +3 -3
  68. package/skills/ultra-research/references/20-user-stories.md +4 -3
  69. package/skills/ultra-research/references/21-features-scope.md +3 -2
  70. package/skills/ultra-research/references/22-success-metrics.md +3 -3
  71. package/skills/ultra-research/references/30-architecture-context.md +3 -3
  72. package/skills/ultra-research/references/31-solution-strategy.md +3 -3
  73. package/skills/ultra-research/references/32-building-blocks.md +3 -3
  74. package/skills/ultra-research/references/40-deployment.md +3 -3
  75. package/skills/ultra-research/references/41-quality-risks.md +3 -3
  76. package/skills/ultra-research/references/99-synthesis.md +7 -7
  77. package/skills/ultra-review/SKILL.md +59 -32
  78. package/skills/ultra-review/references/code.md +17 -0
  79. package/skills/ultra-review/references/comments.md +12 -0
  80. package/skills/ultra-review/references/design.md +12 -0
  81. package/skills/ultra-review/references/errors.md +13 -0
  82. package/skills/ultra-review/references/spec.md +13 -0
  83. package/skills/ultra-review/references/tests.md +12 -0
  84. package/skills/ultra-review/references/worker-packet.md +40 -0
  85. package/skills/ultra-review/scripts/review_wait.py +26 -15
  86. package/skills/ultra-status/SKILL.md +61 -36
  87. package/skills/ultra-tdd/SKILL.md +81 -0
  88. package/skills/ultra-tdd/references/templates/README.md +20 -0
  89. package/skills/ultra-tdd/references/templates/feature-flag-default-audit.sh +79 -0
  90. package/skills/ultra-tdd/references/templates/persistence-real.ts +78 -0
  91. package/skills/ultra-tdd/references/templates/testcontainer-postgres.py +78 -0
  92. package/skills/ultra-tdd/references/templates/testcontainer-postgres.ts +73 -0
  93. package/skills/ultra-tdd/references/templates/vertical-slice.ts +66 -0
  94. package/skills/ultra-tdd/references/test-execution.md +18 -0
  95. package/skills/ultra-test/SKILL.md +70 -30
  96. package/skills/ultra-test/references/export-syntax.md +18 -0
  97. package/skills/ultra-test/scripts/worktree_digest.cjs +54 -0
  98. package/skills/ultra-think/SKILL.md +49 -27
  99. package/skills/ultra-think/references/autonomy-boundary.md +48 -0
  100. package/skills/ultra-think/references/interaction-boundary.md +18 -33
  101. package/.ultra-template/docs/research/README.md +0 -55
  102. package/.ultra-template/reports/templates/delivery-report.json +0 -17
  103. package/.ultra-template/reports/templates/test-report.json +0 -18
  104. package/.ultra-template/tasks/tasks.json +0 -15
  105. package/.ultra-template/templates/task-context.md +0 -19
  106. package/adapters/_shared/codex-assets.cjs +0 -725
  107. package/adapters/_shared/codex-ultra-tools-entry.cjs +0 -11
  108. package/adapters/_shared/interaction-contract.cjs +0 -129
  109. package/adapters/_shared/path-rewrite.cjs +0 -79
  110. package/adapters/_shared/runtime-native.cjs +0 -132
  111. package/adapters/_shared/settings-merge.cjs +0 -76
  112. package/agents/code-reviewer.md +0 -42
  113. package/agents/debugger.md +0 -40
  114. package/agents/review-code.md +0 -49
  115. package/agents/review-comments.md +0 -38
  116. package/agents/review-coordinator.md +0 -56
  117. package/agents/review-design.md +0 -40
  118. package/agents/review-errors.md +0 -43
  119. package/agents/review-spec.md +0 -39
  120. package/agents/review-tests.md +0 -40
  121. package/agents/tdd-runner.md +0 -38
  122. package/bin/orchestrator.js +0 -383
  123. package/commands/ultra-change.md +0 -10
  124. package/commands/ultra-deliver.md +0 -10
  125. package/commands/ultra-dev.md +0 -10
  126. package/commands/ultra-doctor.md +0 -10
  127. package/commands/ultra-init.md +0 -10
  128. package/commands/ultra-plan.md +0 -10
  129. package/commands/ultra-research.md +0 -10
  130. package/commands/ultra-review.md +0 -10
  131. package/commands/ultra-status.md +0 -10
  132. package/commands/ultra-test.md +0 -10
  133. package/commands/ultra-think.md +0 -10
  134. package/docs/AGENT-CONTEXT.md +0 -191
  135. package/docs/COMMIT-HASH-BACKFILL.md +0 -51
  136. package/docs/LEGACY-CLI-CROSSWALK.md +0 -175
  137. package/docs/ROADMAP.md +0 -101
  138. package/docs/STATE-DB-ACCESS-POLICY.md +0 -161
  139. package/hooks/active_task_context.py +0 -152
  140. package/hooks/context_envelope.py +0 -100
  141. package/hooks/health_check.py +0 -196
  142. package/hooks/pre_stop_check.py +0 -66
  143. package/hooks/runtime_paths.py +0 -396
  144. package/hooks/subagent_tracker.py +0 -88
  145. package/hooks/workflow_checkpoint.py +0 -76
  146. package/hooks/workflow_context.py +0 -48
  147. package/hooks/workflow_resume.py +0 -84
  148. package/mcp-server/hook-context.cjs +0 -38
  149. package/mcp-server/hook-event.cjs +0 -34
  150. package/mcp-server/lib/archive-journal.cjs +0 -1119
  151. package/mcp-server/lib/archive-mutation-worker.py +0 -365
  152. package/mcp-server/lib/artifact-registry.cjs +0 -1232
  153. package/mcp-server/lib/baseline-workflow.cjs +0 -1193
  154. package/mcp-server/lib/canonical-json.cjs +0 -19
  155. package/mcp-server/lib/change-authority.cjs +0 -26
  156. package/mcp-server/lib/change-packet.cjs +0 -790
  157. package/mcp-server/lib/change-workflow.cjs +0 -65
  158. package/mcp-server/lib/context-envelope.cjs +0 -581
  159. package/mcp-server/lib/context-paths.cjs +0 -142
  160. package/mcp-server/lib/decision-records.cjs +0 -423
  161. package/mcp-server/lib/delivery-transaction.cjs +0 -471
  162. package/mcp-server/lib/doctor-backup-worker.cjs +0 -328
  163. package/mcp-server/lib/doctor.cjs +0 -627
  164. package/mcp-server/lib/git-bootstrap.cjs +0 -651
  165. package/mcp-server/lib/init-project.cjs +0 -1021
  166. package/mcp-server/lib/kernel-change-workflow.cjs +0 -2029
  167. package/mcp-server/lib/legacy-change-workflow.cjs +0 -3032
  168. package/mcp-server/lib/managed-file-write.cjs +0 -172
  169. package/mcp-server/lib/plan-checkpoint.cjs +0 -177
  170. package/mcp-server/lib/plan-publication-worker.cjs +0 -830
  171. package/mcp-server/lib/plan-store.cjs +0 -794
  172. package/mcp-server/lib/prd-parser.cjs +0 -83
  173. package/mcp-server/lib/pricing.cjs +0 -44
  174. package/mcp-server/lib/project-context.cjs +0 -178
  175. package/mcp-server/lib/projector.cjs +0 -386
  176. package/mcp-server/lib/provider-refs.cjs +0 -42
  177. package/mcp-server/lib/runtime-paths.cjs +0 -1714
  178. package/mcp-server/lib/runtime-state.cjs +0 -222
  179. package/mcp-server/lib/safe-project-file.cjs +0 -385
  180. package/mcp-server/lib/stage-checkpoints.cjs +0 -463
  181. package/mcp-server/lib/state-authority.cjs +0 -95
  182. package/mcp-server/lib/state-db.cjs +0 -1580
  183. package/mcp-server/lib/state-ops.cjs +0 -1428
  184. package/mcp-server/lib/task-contract.cjs +0 -404
  185. package/mcp-server/lib/task-expander.cjs +0 -105
  186. package/mcp-server/lib/task-ledger.cjs +0 -1964
  187. package/mcp-server/lib/telemetry.cjs +0 -85
  188. package/mcp-server/lib/topo.cjs +0 -131
  189. package/mcp-server/lib/ultra-facade.cjs +0 -2684
  190. package/mcp-server/lib/worker-packet.cjs +0 -358
  191. package/mcp-server/server.cjs +0 -437
  192. package/orchestrator/auto-merge.cjs +0 -128
  193. package/orchestrator/daemon.cjs +0 -264
  194. package/orchestrator/dispatch-rules.cjs +0 -78
  195. package/orchestrator/parallel-orchestrator.cjs +0 -903
  196. package/orchestrator/planner/plan-builder.cjs +0 -125
  197. package/orchestrator/recovery.cjs +0 -188
  198. package/orchestrator/session-close-journal-worker.cjs +0 -5
  199. package/orchestrator/session-close-journal.cjs +0 -1014
  200. package/orchestrator/session-runner.cjs +0 -1153
  201. package/orchestrator/worktree-manager.cjs +0 -282
  202. package/settings.json +0 -7
  203. package/skills/cc-collab/SKILL.md +0 -42
  204. package/skills/code-review-expert/SKILL.md +0 -43
  205. package/skills/code-review-expert/references/correctness-reliability.md +0 -30
  206. package/skills/code-review-expert/references/design-boundaries.md +0 -26
  207. package/skills/code-review-expert/references/removal-plan.md +0 -24
  208. package/skills/codex-collab/SKILL.md +0 -49
  209. package/skills/codex-collab/evals/evals.json +0 -35
  210. package/skills/integration-rules/SKILL.md +0 -32
  211. package/skills/security-rules/SKILL.md +0 -38
  212. package/skills/testing-rules/SKILL.md +0 -32
  213. package/skills/ultra-doctor/SKILL.md +0 -41
  214. package/skills/ultra-plan/references/semantic-preflight.md +0 -20
  215. package/skills/ultra-verify/SKILL.md +0 -46
  216. package/skills/ultra-verify/evals/evals.json +0 -46
  217. package/skills/ultra-verify/references/cross-verify-modes.md +0 -28
  218. package/skills/ultra-verify/references/evidence-status.md +0 -21
  219. package/skills/ultra-verify/scripts/verify_wait.py +0 -94
  220. package/spec/cli-protocol.md +0 -102
  221. package/spec/mcp-tools.yaml +0 -312
  222. package/spec/schemas/baseline-reconciliation.v1.schema.json +0 -73
  223. package/spec/schemas/change-delta.v1.schema.json +0 -153
  224. package/spec/schemas/command-manifest.schema.json +0 -29
  225. package/spec/schemas/context-file.v4.5.schema.json +0 -54
  226. package/spec/schemas/delivery-report.v1.schema.json +0 -66
  227. package/spec/schemas/documentation-reconciliation.v1.schema.json +0 -106
  228. package/spec/schemas/mcp-tools.schema.json +0 -136
  229. package/spec/schemas/skill-manifest.schema.json +0 -24
  230. package/spec/schemas/state-db.sql +0 -641
  231. package/spec/schemas/task-ledger.v2.schema.json +0 -296
  232. package/spec/schemas/tasks.v4.5.schema.json +0 -96
  233. package/spec/schemas/test-report.v1.schema.json +0 -225
  234. package/ultra-tools/cli.cjs +0 -129
  235. package/ultra-tools/commands/db.cjs +0 -226
  236. package/ultra-tools/commands/legacy-memory.cjs +0 -159
  237. package/ultra-tools/commands/migrate.cjs +0 -1386
  238. package/ultra-tools/commands/session.cjs +0 -213
  239. package/ultra-tools/commands/status.cjs +0 -559
  240. package/ultra-tools/commands/system.cjs +0 -498
  241. package/ultra-tools/commands/task.cjs +0 -105
package/adapters/grok.js CHANGED
@@ -1,1567 +1,241 @@
1
1
  'use strict';
2
2
 
3
- /** Build a Grok Build native Ultra Builder Pro plugin. */
4
-
5
3
  const fs = require('node:fs');
6
4
  const os = require('node:os');
7
5
  const path = require('node:path');
8
- const crypto = require('node:crypto');
9
6
  const { spawnSync } = require('node:child_process');
10
7
 
11
8
  const {
12
- applyNativeDoctor,
13
- buildMcpRuntime,
14
- } = require('./_shared/codex-assets.cjs');
9
+ copyHooks,
10
+ copySkills,
11
+ inspectPlugin,
12
+ markManaged,
13
+ publishManagedTrees,
14
+ removeManaged,
15
+ writePluginProvenance,
16
+ } = require('./_shared/plugin-core.cjs');
15
17
  const {
16
- copyTree,
18
+ captureAbsent,
17
19
  ensureDir,
18
20
  isManaged,
19
- markManaged,
21
+ managedMetadata,
22
+ pruneCreatedEmpty,
20
23
  removeTree,
21
24
  writeAtomic,
22
25
  } = require('./_shared/file-ops.cjs');
23
- const {
24
- parse: parseFrontmatter,
25
- serialize: serializeFrontmatter,
26
- } = require('./_shared/frontmatter.cjs');
27
- const {
28
- adaptInteractionGuidance,
29
- } = require('./_shared/interaction-contract.cjs');
30
- const provenance = require('./_shared/provenance.cjs');
31
- const {
32
- CORE_PUBLIC_SKILLS,
33
- WORKFLOW_HOOK_FILES,
34
- skillPolicy,
35
- skillsForRuntime,
36
- } = require('./_shared/runtime-assets.cjs');
37
26
 
38
27
  const PLUGIN_NAME = 'ultra-builder-pro';
39
- const MCP_SERVER_NAME = PLUGIN_NAME;
40
- const PROVENANCE_FILE = 'provenance.json';
41
- const COMMAND_NAMES = CORE_PUBLIC_SKILLS;
42
- const SOURCE_ROOT_PARTS = ['.ubp', 'plugin-sources', PLUGIN_NAME];
43
- const BACKUP_ROOT_PARTS = ['.ubp', 'backups'];
44
28
 
45
29
  function resolveTarget(ctx = {}) {
46
30
  if (ctx.configDir) return path.resolve(ctx.configDir);
47
- const configuredHome = [
48
- ctx.grokHome,
49
- ctx.grokEnv?.GROK_HOME,
50
- ctx.env?.GROK_HOME,
51
- process.env.GROK_HOME,
52
- ].find((candidate) => typeof candidate === 'string' && candidate.trim());
53
- if (configuredHome) return path.resolve(configuredHome);
54
- return path.join(ctx.homeDir || os.homedir(), '.grok');
55
- }
56
-
57
- function resolvePluginRoot(ctx = {}) {
58
- return path.join(resolveTarget(ctx), 'plugins', PLUGIN_NAME);
31
+ const configured = ctx.grokHome || ctx.grokEnv?.GROK_HOME || ctx.env?.GROK_HOME || process.env.GROK_HOME;
32
+ return configured ? path.resolve(configured) : path.join(ctx.homeDir || os.homedir(), '.grok');
59
33
  }
60
34
 
61
35
  function resolveSourceRoot(ctx = {}) {
62
- return path.join(resolveTarget(ctx), ...SOURCE_ROOT_PARTS);
36
+ return path.join(resolveTarget(ctx), '.ubp', 'plugin-sources', PLUGIN_NAME);
63
37
  }
64
38
 
65
- function resolveBackupRoot(ctx = {}) {
66
- return path.join(resolveTarget(ctx), ...BACKUP_ROOT_PARTS);
39
+ function resolvePluginRoot(ctx = {}) {
40
+ return path.join(resolveTarget(ctx), 'plugins', PLUGIN_NAME);
67
41
  }
68
42
 
69
43
  function resolveRepoRoot(ctx = {}) {
70
44
  return ctx.repoRoot || path.resolve(__dirname, '..');
71
45
  }
72
46
 
73
- function copySkills(repoRoot, pluginRoot) {
74
- const copied = [];
75
- for (const name of skillsForRuntime('grok')) {
76
- const source = path.join(repoRoot, 'skills', name);
77
- if (!fs.existsSync(path.join(source, 'SKILL.md'))) {
78
- throw new Error(`missing allowlisted Grok skill: ${name}`);
79
- }
80
- const files = copyTree(source, path.join(pluginRoot, 'skills', name), {
81
- transform(buffer, relative) {
82
- if (!relative.endsWith('.md')) return buffer;
83
- let text = adaptInteractionGuidance(buffer.toString('utf8'), 'grok');
84
- if (name === 'ultra-review') {
85
- text = text.replace(
86
- /(?:the current host's native|the host-native) bounded-worker\s+mechanism/g,
87
- 'Grok Build subagents using the installed read-only agent definitions',
88
- );
89
- }
90
- if (relative !== 'SKILL.md') return Buffer.from(text);
91
- const { fm, body } = parseFrontmatter(text);
92
- if (!fm) throw new Error(`missing frontmatter in Grok skill: ${name}`);
93
- const policy = skillPolicy(name);
94
- return Buffer.from(serializeFrontmatter({
95
- name,
96
- description: fm.description,
97
- 'user-invocable': policy.userInvocable,
98
- ...(policy.userInvocable ? { 'disable-model-invocation': true } : {}),
99
- }, body));
100
- },
101
- });
102
- copied.push(...files.map((relative) => path.join(name, relative)));
103
- }
104
- return copied;
105
- }
106
-
107
- function copyCommands(repoRoot, pluginRoot) {
108
- const copied = [];
109
- for (const name of COMMAND_NAMES) {
110
- const source = path.join(repoRoot, 'commands', `${name}.md`);
111
- if (!fs.existsSync(source)) throw new Error(`missing Grok command: ${name}.md`);
112
- const target = path.join(pluginRoot, 'commands', `${name}.md`);
113
- const text = adaptInteractionGuidance(fs.readFileSync(source, 'utf8'), 'grok');
114
- writeAtomic(target, text);
115
- copied.push(`${name}.md`);
47
+ function assertPluginScope(ctx = {}) {
48
+ if (ctx.scope === 'local' && !ctx.configDir) {
49
+ throw new Error('Grok plugins are user-scoped; use global scope or an isolated configDir');
116
50
  }
117
- return copied;
118
51
  }
119
52
 
120
- function copyAgents(repoRoot, pluginRoot) {
121
- const copied = [];
122
- const sourceRoot = path.join(repoRoot, 'agents');
123
- for (const file of fs.readdirSync(sourceRoot).filter((name) => name.endsWith('.md')).sort()) {
124
- const { fm, body } = parseFrontmatter(
125
- fs.readFileSync(path.join(sourceRoot, file), 'utf8'),
126
- );
127
- if (!fm?.name || !fm?.description) {
128
- throw new Error(`invalid Grok agent frontmatter: ${file}`);
129
- }
130
- const next = { ...fm };
131
- delete next.model;
132
- delete next.maxTurns;
133
- delete next.permissionMode;
134
- delete next.mcpServers;
135
- delete next.hooks;
136
- next.mcpInheritance = 'all';
137
- const instructions = [
138
- 'Use the immutable Worker Packet supplied by the parent. Echo its exact packet_digest.',
139
- 'Do not call Ultra MCP write tools or mutate another worker artifact.',
140
- '',
141
- adaptInteractionGuidance(body, 'grok').trim(),
142
- '',
143
- ].join('\n');
144
- writeAtomic(
145
- path.join(pluginRoot, 'agents', file),
146
- serializeFrontmatter(next, instructions),
147
- );
148
- copied.push(file);
149
- }
150
- return copied;
151
- }
152
-
153
- function hookCommand(feature, ...args) {
53
+ function hookCommand(name) {
154
54
  return {
155
55
  type: 'command',
156
- command: [
157
- 'python3 "${GROK_PLUGIN_ROOT}/hooks/adapters/grok.py"',
158
- JSON.stringify(feature),
159
- ...args.map((arg) => JSON.stringify(arg)),
160
- ].join(' '),
56
+ command: `python3 "\${GROK_PLUGIN_ROOT}/hooks/adapters/grok.py" ${JSON.stringify(name)}`,
161
57
  timeout: 10,
162
58
  };
163
59
  }
164
60
 
165
61
  function buildHooksManifest() {
166
62
  return {
167
- description: [
168
- 'Ultra hooks are observational except for exact managed-file protection.',
169
- 'Grok ignores SessionStart/PostCompact stdout, so Skills read ultra.context explicitly.',
170
- ].join(' '),
63
+ description: 'Ultra file-first context sensors and narrow effect protection.',
171
64
  hooks: {
172
- SessionStart: [{
173
- matcher: 'startup|resume|clear|compact',
174
- hooks: [hookCommand('health_check.py')],
175
- }],
176
- PreToolUse: [{
177
- matcher: 'Edit|Write|MultiEdit|search_replace|apply_patch',
178
- hooks: [hookCommand('active_task_context.py')],
179
- }],
180
- PreCompact: [{
181
- matcher: 'manual|auto',
182
- hooks: [hookCommand('workflow_checkpoint.py')],
183
- }],
184
- Stop: [{
185
- hooks: [hookCommand('pre_stop_check.py')],
186
- }],
187
- SubagentStart: [{
188
- hooks: [hookCommand('subagent_tracker.py', 'start')],
189
- }],
190
- SubagentStop: [{
191
- hooks: [hookCommand('subagent_tracker.py', 'stop')],
192
- }],
65
+ SessionStart: [
66
+ { matcher: 'startup|resume|clear', hooks: [hookCommand('session_context.py')] },
67
+ { matcher: 'compact', hooks: [hookCommand('compact_context.py')] },
68
+ ],
69
+ PreToolUse: [
70
+ { matcher: 'Write|Edit|Grep|apply_patch', hooks: [hookCommand('mid_workflow_recall.py')] },
71
+ { matcher: 'Bash', hooks: [hookCommand('block_dangerous_commands.py')] },
72
+ ],
73
+ PostToolUse: [
74
+ { matcher: 'Write|Edit|apply_patch', hooks: [hookCommand('post_edit_guard.py')] },
75
+ ],
76
+ PreCompact: [{ matcher: 'manual|auto', hooks: [hookCommand('compact_context.py')] }],
193
77
  },
194
78
  };
195
79
  }
196
80
 
197
- function copyHooks(repoRoot, pluginRoot) {
198
- const copied = [];
199
- ensureDir(path.join(pluginRoot, 'hooks', 'adapters'));
200
- for (const name of WORKFLOW_HOOK_FILES) {
201
- const source = path.join(repoRoot, 'hooks', name);
202
- if (!fs.existsSync(source)) throw new Error(`missing allowlisted Grok hook: ${name}`);
203
- fs.copyFileSync(source, path.join(pluginRoot, 'hooks', name));
204
- copied.push(name);
205
- }
206
- fs.copyFileSync(
207
- path.join(repoRoot, 'hooks', 'adapters', 'grok.py'),
208
- path.join(pluginRoot, 'hooks', 'adapters', 'grok.py'),
209
- );
210
- copied.push(path.join('adapters', 'grok.py'));
211
- writeAtomic(
212
- path.join(pluginRoot, 'hooks', 'hooks.json'),
213
- `${JSON.stringify(buildHooksManifest(), null, 2)}\n`,
214
- );
215
- return copied;
216
- }
217
-
218
- function writeManifests(repoRoot, pluginRoot) {
81
+ function buildStaging(repoRoot, staging, publishedRoot) {
82
+ const skills = copySkills({ runtime: 'grok', repoRoot, skillRoot: path.join(staging, 'skills') });
83
+ copyHooks({
84
+ runtime: 'grok', repoRoot, hookRoot: path.join(staging, 'hooks'),
85
+ hooksManifest: buildHooksManifest(),
86
+ });
219
87
  const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
220
- const repository = typeof pkg.repository === 'string'
221
- ? pkg.repository.replace(/^git\+/, '').replace(/\.git$/, '')
222
- : String(pkg.repository?.url || '').replace(/^git\+/, '').replace(/\.git$/, '');
223
- writeAtomic(path.join(pluginRoot, 'plugin.json'), `${JSON.stringify({
88
+ writeAtomic(path.join(staging, 'plugin.json'), `${JSON.stringify({
224
89
  name: PLUGIN_NAME,
225
90
  version: pkg.version,
226
- description: 'Grok Build native Ultra workflows, Worker Packets, observational hooks, and a project-local MCP safety kernel.',
227
- author: { name: typeof pkg.author === 'string' ? pkg.author : 'Ultra Builder Pro contributors' },
91
+ description: 'File-first Ultra Builder Pro workflows for Grok Build.',
92
+ author: { name: pkg.author },
228
93
  homepage: pkg.homepage,
229
- repository,
230
- license: pkg.license || 'MIT',
94
+ repository: pkg.repository?.url || pkg.repository,
95
+ license: pkg.license,
231
96
  }, null, 2)}\n`);
232
- const launcher = '${GROK_PLUGIN_ROOT}/runtime/launch.cjs';
233
- writeAtomic(path.join(pluginRoot, '.mcp.json'), `${JSON.stringify({
234
- mcpServers: {
235
- [MCP_SERVER_NAME]: {
236
- type: 'stdio',
237
- command: process.platform === 'win32' ? 'node.exe' : '/usr/bin/env',
238
- args: process.platform === 'win32' ? [launcher] : ['node', launcher],
239
- },
240
- },
241
- }, null, 2)}\n`);
242
- }
243
-
244
- function grokFailure(code, message, details = {}) {
245
- const error = new Error(message);
246
- error.code = code;
247
- error.details = details;
248
- return error;
249
- }
250
-
251
- function resolveGrokBinary(ctx = {}) {
252
- const executable = process.platform === 'win32' ? 'grok.exe' : 'grok';
253
- if (ctx.grokBin) {
254
- return fs.existsSync(ctx.grokBin) ? path.resolve(ctx.grokBin) : null;
255
- }
256
- const candidates = [
257
- ctx.grokEnv?.GROK_BIN,
258
- ctx.env?.GROK_BIN,
259
- process.env.GROK_BIN,
260
- path.join(resolveTarget(ctx), 'bin', executable),
261
- ].filter(Boolean);
262
- for (const candidate of candidates) {
263
- if (fs.existsSync(candidate)) return path.resolve(candidate);
264
- }
265
- const probe = spawnSync(executable, ['--version'], {
266
- encoding: 'utf8',
267
- timeout: 10_000,
268
- stdio: ['ignore', 'pipe', 'pipe'],
269
- });
270
- return probe.status === 0 ? executable : null;
271
- }
272
-
273
- function nativeEnvironment(ctx = {}) {
274
- return {
275
- ...process.env,
276
- ...(ctx.env || {}),
277
- ...(ctx.grokEnv || {}),
278
- GROK_HOME: resolveTarget(ctx),
279
- };
280
- }
281
-
282
- function runGrok(ctx, args, {
283
- timeout = 60_000,
284
- json = false,
285
- allowFailure = false,
286
- } = {}) {
287
- const binary = resolveGrokBinary(ctx);
288
- if (!binary) {
289
- throw grokFailure(
290
- 'GROK_CLI_UNAVAILABLE',
291
- 'Grok CLI is required for native plugin registration; install Grok Build or pass grokBin',
292
- );
293
- }
294
- const result = spawnSync(binary, args, {
295
- cwd: ctx.cwd || process.cwd(),
296
- env: nativeEnvironment(ctx),
297
- encoding: 'utf8',
298
- timeout,
299
- maxBuffer: 32 * 1024 * 1024,
300
- stdio: ['ignore', 'pipe', 'pipe'],
301
- });
302
- if (result.error) throw result.error;
303
- if (result.status !== 0 && !allowFailure) {
304
- const detail = (result.stderr || result.stdout || '').trim();
305
- throw grokFailure(
306
- 'GROK_CLI_COMMAND_FAILED',
307
- `grok ${args.join(' ')} failed${detail ? `: ${detail}` : ''}`,
308
- { args, status: result.status },
309
- );
310
- }
311
- let payload = null;
312
- if (json && result.status === 0) {
313
- try {
314
- payload = JSON.parse(result.stdout || 'null');
315
- } catch (error) {
316
- throw grokFailure(
317
- 'GROK_CLI_INVALID_JSON',
318
- `grok ${args.join(' ')} returned invalid JSON: ${error.message}`,
319
- );
320
- }
321
- }
322
- return {
323
- binary,
324
- status: result.status,
325
- stdout: result.stdout || '',
326
- stderr: result.stderr || '',
327
- payload,
328
- };
329
- }
330
-
331
- function probeNativeCapabilities(ctx = {}) {
332
- const binary = resolveGrokBinary(ctx);
333
- if (!binary) return { status: 'unavailable', binary: null, capabilities: {} };
334
- const commands = [
335
- { key: 'plugin_install', args: ['plugin', 'install', '--help'], required: ['--trust'] },
336
- { key: 'plugin_list', args: ['plugin', 'list', '--help'], required: ['--json'] },
337
- { key: 'plugin_details', args: ['plugin', 'details', '--help'], required: [] },
338
- { key: 'plugin_enable', args: ['plugin', 'enable', '--help'], required: [] },
339
- {
340
- key: 'plugin_uninstall',
341
- args: ['plugin', 'uninstall', '--help'],
342
- required: ['--confirm', '--keep-data'],
343
- },
344
- { key: 'inspect', args: ['inspect', '--help'], required: ['--json'] },
345
- { key: 'mcp_doctor', args: ['mcp', 'doctor', '--help'], required: ['--json'] },
346
- ];
347
- const capabilities = {};
348
- for (const command of commands) {
349
- const result = runGrok(ctx, command.args, { timeout: 15_000 });
350
- const output = `${result.stdout}\n${result.stderr}`;
351
- const missing = command.required.filter((flag) => !output.includes(flag));
352
- if (missing.length > 0) {
353
- throw grokFailure(
354
- 'GROK_CLI_CAPABILITY_MISSING',
355
- `installed Grok CLI does not expose ${command.key}: missing ${missing.join(', ')}`,
356
- { command: command.args, missing },
357
- );
358
- }
359
- capabilities[command.key] = true;
360
- }
361
- const version = runGrok(ctx, ['--version'], { timeout: 10_000 }).stdout.trim();
362
- return { status: 'pass', binary, version, capabilities };
363
- }
364
-
365
- function validatePlugin(pluginRoot, ctx = {}) {
366
- const capabilities = probeNativeCapabilities(ctx);
367
- if (capabilities.status === 'unavailable') {
368
- return { status: 'unavailable', binary: null };
369
- }
370
- const result = runGrok(ctx, ['plugin', 'validate', pluginRoot], { timeout: 30_000 });
371
- return {
372
- status: 'pass',
373
- binary: result.binary,
374
- output: result.stdout.trim(),
375
- version: capabilities.version,
376
- };
377
- }
378
-
379
- function pluginList(ctx = {}) {
380
- const result = runGrok(ctx, ['plugin', 'list', '--json'], { json: true });
381
- if (!Array.isArray(result.payload)) {
382
- throw grokFailure('GROK_PLUGIN_LIST_INVALID', 'grok plugin list --json must return an array');
383
- }
384
- return result.payload;
385
- }
386
-
387
- function installedPlugin(ctx = {}) {
388
- const matches = pluginList(ctx).filter((entry) => entry?.name === PLUGIN_NAME);
389
- if (matches.length > 1) {
390
- throw grokFailure(
391
- 'GROK_PLUGIN_REGISTRY_CONFLICT',
392
- `Grok registered ${matches.length} Ultra Builder Pro plugin entries`,
393
- );
394
- }
395
- const registered = matches[0] || null;
396
- if (
397
- registered
398
- && (
399
- registered.status !== 'installed'
400
- || typeof registered.path !== 'string'
401
- || !registered.path.trim()
402
- )
403
- ) {
404
- throw grokFailure(
405
- 'GROK_PLUGIN_REGISTRY_INVALID',
406
- 'Grok returned an invalid Ultra Builder Pro registry entry',
407
- );
408
- }
409
- return registered;
410
- }
411
-
412
- function parseActivationArray(section, key, file) {
413
- const declaration = new RegExp(`(?:^|\\n)\\s*${key}\\s*=`, 'g');
414
- const assignment = new RegExp(
415
- `(?:^|\\n)\\s*${key}\\s*=\\s*(\\[[\\s\\S]*?\\])\\s*(?:#.*)?(?=\\n|$)`,
416
- 'g',
417
- );
418
- const declarations = [...section.matchAll(declaration)];
419
- const assignments = [...section.matchAll(assignment)];
420
- if (declarations.length === 0) return null;
421
- if (declarations.length !== 1 || assignments.length !== 1) {
422
- throw grokFailure(
423
- 'GROK_PLUGIN_ACTIVATION_REGISTRY_INVALID',
424
- `Grok activation registry has an invalid plugins.${key} declaration: ${file}`,
425
- { file, key },
426
- );
427
- }
428
- let values;
429
- try {
430
- values = JSON.parse(assignments[0][1]);
431
- } catch (error) {
432
- throw grokFailure(
433
- 'GROK_PLUGIN_ACTIVATION_REGISTRY_INVALID',
434
- `Grok activation registry has an unreadable plugins.${key} array: ${file}`,
435
- { file, key, cause_code: error.code || null },
436
- );
437
- }
438
- if (!Array.isArray(values) || values.some((value) => typeof value !== 'string')) {
439
- throw grokFailure(
440
- 'GROK_PLUGIN_ACTIVATION_REGISTRY_INVALID',
441
- `Grok activation registry plugins.${key} must be a string array: ${file}`,
442
- { file, key },
443
- );
444
- }
445
- return values;
446
- }
447
-
448
- function registeredActivationState(ctx) {
449
- const file = path.join(resolveTarget(ctx), 'config.toml');
450
- if (!fs.existsSync(file)) return null;
451
- const text = fs.readFileSync(file, 'utf8');
452
- const lines = text.split(/\r?\n/);
453
- const sectionIndexes = lines
454
- .map((line, index) => (/^\s*\[plugins\]\s*(?:#.*)?$/.test(line) ? index : -1))
455
- .filter((index) => index >= 0);
456
- if (sectionIndexes.length === 0) return null;
457
- if (sectionIndexes.length !== 1) {
458
- throw grokFailure(
459
- 'GROK_PLUGIN_ACTIVATION_REGISTRY_INVALID',
460
- `Grok activation registry contains multiple [plugins] sections: ${file}`,
461
- { file },
462
- );
463
- }
464
- const start = sectionIndexes[0] + 1;
465
- let end = lines.length;
466
- for (let index = start; index < lines.length; index += 1) {
467
- if (/^\s*\[.+\]\s*(?:#.*)?$/.test(lines[index])) {
468
- end = index;
469
- break;
470
- }
471
- }
472
- const section = lines.slice(start, end).join('\n');
473
- const enabled = parseActivationArray(section, 'enabled', file);
474
- const disabled = parseActivationArray(section, 'disabled', file);
475
- const listedEnabled = enabled?.includes(PLUGIN_NAME) === true;
476
- const listedDisabled = disabled?.includes(PLUGIN_NAME) === true;
477
- if (listedEnabled && listedDisabled) {
478
- throw grokFailure(
479
- 'GROK_PLUGIN_ACTIVATION_REGISTRY_INVALID',
480
- `Grok activation registry lists ${PLUGIN_NAME} as both enabled and disabled`,
481
- { file },
482
- );
483
- }
484
- if (listedEnabled) return true;
485
- if (listedDisabled) return false;
486
- return null;
487
- }
488
-
489
- function resolveNativeInstallPath(plugin) {
490
- if (typeof plugin?.path !== 'string' || !plugin.path.trim()) {
491
- throw grokFailure(
492
- 'GROK_PLUGIN_PATH_MISSING',
493
- 'Grok registry did not return an installed path for Ultra Builder Pro',
494
- );
495
- }
496
- const target = path.resolve(plugin.path);
497
- if (!fs.existsSync(target)) {
498
- throw grokFailure('GROK_PLUGIN_PATH_MISSING', `Grok registered plugin path is missing: ${target}`);
499
- }
500
- const canonicalTarget = fs.realpathSync(target);
501
- if (!fs.statSync(canonicalTarget).isDirectory()) {
502
- throw grokFailure(
503
- 'GROK_PLUGIN_PATH_MISSING',
504
- `Grok registered plugin path is not a directory: ${canonicalTarget}`,
505
- );
506
- }
507
- return canonicalTarget;
508
- }
509
-
510
- function assertRegisteredSource(ctx, plugin, {
511
- expectedPackageName,
512
- expectedPackageVersion,
513
- sourceRoot = resolveSourceRoot(ctx),
514
- } = {}) {
515
- if (typeof plugin?.source !== 'string' || !plugin.source.trim()) {
516
- throw grokFailure(
517
- 'GROK_PLUGIN_SOURCE_MISSING',
518
- 'Grok registry did not return the source used to install Ultra Builder Pro',
519
- );
520
- }
521
- const expectedSource = path.resolve(sourceRoot);
522
- const registeredSource = path.resolve(plugin.source);
523
- if (!fs.existsSync(expectedSource) || !fs.existsSync(registeredSource)) {
524
- throw grokFailure(
525
- 'GROK_PLUGIN_SOURCE_MISSING',
526
- `Grok registered plugin source is missing: ${registeredSource}`,
527
- { expected: expectedSource, actual: registeredSource },
528
- );
529
- }
530
- const canonicalExpected = fs.realpathSync(expectedSource);
531
- const canonicalSource = fs.realpathSync(registeredSource);
532
- if (canonicalSource !== canonicalExpected) {
533
- throw grokFailure(
534
- 'GROK_PLUGIN_SOURCE_MISMATCH',
535
- `Grok registered ${canonicalSource}, expected managed source ${canonicalExpected}`,
536
- { expected: canonicalExpected, actual: canonicalSource },
537
- );
538
- }
539
- const report = assertManagedProvenance(canonicalSource, 'registered Grok source', {
540
- expectedPackageName,
541
- expectedPackageVersion,
542
- });
543
- return { path: canonicalSource, report };
544
- }
545
-
546
- function assertNativeInstallPath(ctx, plugin, {
547
- expectedPackageName = null,
548
- expectedPackageVersion = null,
549
- sourceRoot = resolveSourceRoot(ctx),
550
- } = {}) {
551
- const packageInfo = expectedPackageName
552
- ? null
553
- : provenance.packageSource(resolveRepoRoot(ctx)).packageInfo;
554
- const packageName = expectedPackageName || packageInfo.name;
555
- const packageVersion = expectedPackageVersion || plugin?.version;
556
- if (typeof packageVersion !== 'string' || !packageVersion.trim()) {
557
- throw grokFailure(
558
- 'GROK_PLUGIN_VERSION_MISSING',
559
- 'Grok registry did not return an Ultra Builder Pro package version',
560
- );
561
- }
562
- if (plugin.version !== packageVersion) {
563
- throw grokFailure(
564
- 'GROK_PLUGIN_VERSION_MISMATCH',
565
- `Grok registered Ultra Builder Pro ${plugin.version || '<missing>'}, expected ${packageVersion}`,
566
- { expected: packageVersion, actual: plugin.version || null },
567
- );
568
- }
569
- const target = resolveNativeInstallPath(plugin);
570
- if (!isManaged(target)) {
571
- throw grokFailure(
572
- 'GROK_PLUGIN_PATH_UNSAFE',
573
- `Grok registry returned an unmanaged plugin path: ${target}`,
574
- { path: target },
575
- );
576
- }
577
- assertManagedProvenance(target, 'registered Grok target', {
578
- expectedPackageName: packageName,
579
- expectedPackageVersion: packageVersion,
580
- });
581
- assertRegisteredSource(ctx, plugin, {
582
- expectedPackageName: packageName,
583
- expectedPackageVersion: packageVersion,
584
- sourceRoot,
585
- });
586
- return target;
587
- }
588
-
589
- function assertConsumerPath(expectedTarget, reportedPath, label, ctx = {}) {
590
- if (typeof reportedPath !== 'string' || !reportedPath.trim()) {
591
- throw grokFailure(
592
- 'GROK_PLUGIN_CONSUMER_PATH_MISSING',
593
- `Grok ${label} did not report the registered plugin path`,
594
- { expected: expectedTarget, actual: reportedPath || null, label },
595
- );
596
- }
597
- const absolute = path.resolve(ctx.cwd || process.cwd(), reportedPath);
598
- let canonical;
599
- try {
600
- canonical = fs.realpathSync(absolute);
601
- } catch (error) {
602
- throw grokFailure(
603
- 'GROK_PLUGIN_PATH_SHADOWED',
604
- `Grok ${label} resolved a missing path instead of the registered plugin: ${absolute}`,
605
- { expected: expectedTarget, actual: absolute, label, cause_code: error.code || null },
606
- );
607
- }
608
- if (canonical !== expectedTarget) {
609
- throw grokFailure(
610
- 'GROK_PLUGIN_PATH_SHADOWED',
611
- `Grok ${label} resolved ${canonical}, expected registered target ${expectedTarget}`,
612
- { expected: expectedTarget, actual: canonical, label },
613
- );
614
- }
615
- return canonical;
616
- }
617
-
618
- function nativeActivationState(ctx, target) {
619
- const registeredState = registeredActivationState(ctx);
620
- if (registeredState !== null) return registeredState;
621
- const inspect = runGrok(ctx, ['inspect', '--json'], { json: true }).payload;
622
- const matches = (Array.isArray(inspect?.plugins) ? inspect.plugins : [])
623
- .filter((entry) => entry?.name === PLUGIN_NAME);
624
- if (matches.length !== 1) {
625
- throw grokFailure(
626
- 'GROK_PLUGIN_ACTIVATION_STATE_INVALID',
627
- `Grok inspect returned ${matches.length} Ultra Builder Pro plugin entries`,
628
- { expected: 1, actual: matches.length },
629
- );
630
- }
631
- const plugin = matches[0];
632
- assertConsumerPath(target, plugin.path, 'inspect plugin activation', ctx);
633
- if (typeof plugin.enabled !== 'boolean') {
634
- throw grokFailure(
635
- 'GROK_PLUGIN_ACTIVATION_STATE_INVALID',
636
- 'Grok inspect did not report a boolean Ultra Builder Pro activation state',
637
- { actual: plugin.enabled ?? null },
638
- );
639
- }
640
- return plugin.enabled;
641
- }
642
-
643
- function restoreNativeActivation(ctx, target, enabled) {
644
- runGrok(ctx, ['plugin', enabled ? 'enable' : 'disable', PLUGIN_NAME]);
645
- const restored = nativeActivationState(ctx, target);
646
- if (restored !== enabled) {
647
- throw grokFailure(
648
- 'GROK_ROLLBACK_ACTIVATION_MISMATCH',
649
- `Grok restored Ultra Builder Pro with enabled=${restored}, expected enabled=${enabled}`,
650
- { expected: enabled, actual: restored },
651
- );
652
- }
653
- return restored;
654
- }
655
-
656
- function nativeConsumerState(ctx = {}, registered = null) {
657
- const registryEntry = registered || installedPlugin(ctx);
658
- const target = registryEntry ? assertNativeInstallPath(ctx, registryEntry) : null;
659
- const inspect = runGrok(ctx, ['inspect', '--json'], { json: true }).payload;
660
- const plugins = Array.isArray(inspect?.plugins) ? inspect.plugins : [];
661
- const servers = Array.isArray(inspect?.mcpServers) ? inspect.mcpServers : [];
662
- const matchingPlugins = plugins.filter((entry) => entry?.name === PLUGIN_NAME);
663
- const matchingServers = servers.filter((entry) => (
664
- entry?.name === MCP_SERVER_NAME
665
- && entry?.source?.type === 'plugin'
666
- && entry?.source?.plugin_name === PLUGIN_NAME
667
- ));
668
- if (target) {
669
- for (const pluginEntry of matchingPlugins) {
670
- assertConsumerPath(target, pluginEntry.path, 'inspect plugin', ctx);
671
- }
672
- for (const serverEntry of matchingServers) {
673
- assertConsumerPath(target, serverEntry.source.path, 'inspect plugin MCP source', ctx);
674
- }
675
- }
676
- const plugin = matchingPlugins[0] || null;
677
- const mcp = matchingServers[0] || null;
678
- const doctor = runGrok(
679
- ctx,
680
- ['mcp', 'doctor', MCP_SERVER_NAME, '--json'],
681
- { json: true, timeout: 60_000 },
682
- ).payload;
683
- const doctorServers = Array.isArray(doctor?.servers) ? doctor.servers : [];
684
- const doctorServer = doctorServers.find((entry) => {
685
- if (entry?.name !== MCP_SERVER_NAME) return false;
686
- if (typeof entry.source === 'string') return entry.source.includes(PLUGIN_NAME);
687
- return entry?.source?.plugin_name === PLUGIN_NAME;
688
- }) || null;
689
- return {
690
- inspect,
691
- doctor,
692
- plugin,
693
- mcp,
694
- doctorServer,
695
- target,
696
- healthy: Boolean(plugin && mcp && doctorServer?.healthy === true),
697
- };
698
- }
699
-
700
- function buildStaging(repoRoot, staging, ctx) {
701
- const copied = {
702
- commands: copyCommands(repoRoot, staging),
703
- skills: copySkills(repoRoot, staging),
704
- agents: copyAgents(repoRoot, staging),
705
- hooks: copyHooks(repoRoot, staging),
706
- };
707
- const runtime = buildMcpRuntime(repoRoot, staging, { runtime: 'grok' });
708
- writeManifests(repoRoot, staging);
709
- if (fs.existsSync(path.join(repoRoot, 'LICENSE'))) {
710
- fs.copyFileSync(path.join(repoRoot, 'LICENSE'), path.join(staging, 'LICENSE'));
711
- }
712
- markManaged(staging, { adapter: 'grok', plugin: PLUGIN_NAME });
713
- const validation = validatePlugin(staging, ctx);
714
- return { copied, validation };
715
- }
716
-
717
- function writeProvenance(repoRoot, pluginRoot) {
718
- const source = provenance.packageSource(repoRoot);
719
- const file = path.join(pluginRoot, PROVENANCE_FILE);
720
- const manifest = provenance.writeProvenance({
721
- file,
722
- adapter: 'grok',
723
- ...source,
724
- roots: { plugin: pluginRoot },
725
- assets: provenance.assetRefsForTree('plugin', pluginRoot, {
726
- exclude: ['.ubp-managed', PROVENANCE_FILE],
727
- }),
97
+ markManaged(staging, { adapter: 'grok', plugin: PLUGIN_NAME, version: pkg.version });
98
+ writePluginProvenance({
99
+ adapter: 'grok', repoRoot, stagingRoot: staging, publishedRoot,
728
100
  contracts: {
729
101
  plugin_manifest: { root: 'plugin', path: 'plugin.json' },
730
- mcp_registration: { root: 'plugin', path: '.mcp.json' },
731
- mcp_launcher: { root: 'plugin', path: 'runtime/launch.cjs' },
732
- native_runtime: { root: 'plugin', path: 'runtime/native-runtime.json' },
733
- context_envelope_helper: { root: 'plugin', path: 'runtime/hook-context.cjs' },
734
102
  hooks_manifest: { root: 'plugin', path: 'hooks/hooks.json' },
735
- hook_adapter: { root: 'plugin', path: path.join('hooks', 'adapters', 'grok.py') },
103
+ hook_adapter: { root: 'plugin', path: 'hooks/adapters/grok.py' },
736
104
  },
737
105
  });
738
- return { file, manifest };
106
+ return { skills };
739
107
  }
740
108
 
741
- function managedCopy(source, target) {
742
- ensureDir(path.dirname(target));
743
- fs.cpSync(source, target, { recursive: true, force: false, errorOnExist: true });
109
+ function shouldRunHostCli(ctx = {}) {
110
+ if (typeof ctx.runHostCli === 'boolean') return ctx.runHostCli;
111
+ return ctx.scope === 'global' && !ctx.configDir;
744
112
  }
745
113
 
746
- function rebaseProvenanceRoot(pluginRoot) {
747
- const file = path.join(pluginRoot, PROVENANCE_FILE);
748
- if (!fs.existsSync(file)) return null;
749
- const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
750
- if (!manifest.roots || typeof manifest.roots !== 'object') {
751
- throw grokFailure(
752
- 'GROK_ROLLBACK_SOURCE_INVALID',
753
- `rollback source has invalid provenance roots: ${file}`,
754
- );
755
- }
756
- manifest.roots.plugin = path.resolve(pluginRoot);
757
- writeAtomic(file, `${JSON.stringify(manifest, null, 2)}\n`);
758
- return manifest;
759
- }
760
-
761
- function sourceMatchesRegistration(source, registered) {
762
- try {
763
- const manifest = JSON.parse(fs.readFileSync(path.join(source, 'plugin.json'), 'utf8'));
764
- return (
765
- manifest.name === PLUGIN_NAME
766
- && (!registered.version || manifest.version === registered.version)
767
- );
768
- } catch {
769
- return false;
770
- }
771
- }
772
-
773
- function ensureRecoverySource(registered, sourceRoot, nativeBackup) {
774
- const declaredSource = typeof registered.source === 'string'
775
- ? path.resolve(registered.source)
776
- : null;
777
- if (
778
- declaredSource
779
- && fs.existsSync(declaredSource)
780
- && isManaged(declaredSource)
781
- && sourceMatchesRegistration(declaredSource, registered)
782
- ) {
783
- return declaredSource;
784
- }
785
- if (
786
- fs.existsSync(sourceRoot)
787
- && isManaged(sourceRoot)
788
- && sourceMatchesRegistration(sourceRoot, registered)
789
- ) {
790
- return sourceRoot;
791
- }
792
- if (fs.existsSync(sourceRoot)) {
793
- throw grokFailure(
794
- 'GROK_ROLLBACK_SOURCE_CONFLICT',
795
- `cannot reconstruct the prior Grok source over existing bytes: ${sourceRoot}`,
796
- );
797
- }
798
- if (!nativeBackup || !fs.existsSync(nativeBackup)) {
799
- throw grokFailure(
800
- 'GROK_ROLLBACK_SOURCE_MISSING',
801
- 'the previous Grok plugin source is unavailable and cannot be reconstructed safely',
802
- );
803
- }
804
- managedCopy(nativeBackup, sourceRoot);
805
- rebaseProvenanceRoot(sourceRoot);
806
- return sourceRoot;
807
- }
808
-
809
- function nativeUninstall(ctx, { allowMissing = false } = {}) {
810
- const entry = installedPlugin(ctx);
811
- if (!entry) {
812
- if (allowMissing) return null;
813
- throw grokFailure('GROK_PLUGIN_NOT_REGISTERED', 'Ultra Builder Pro is not registered by Grok');
814
- }
815
- runGrok(ctx, ['plugin', 'uninstall', PLUGIN_NAME, '--confirm', '--keep-data']);
816
- return entry;
817
- }
818
-
819
- function restoreNativeRegistration(ctx, source, {
820
- verifyConsumer = true,
821
- enabled = true,
822
- } = {}) {
823
- if (!source || !fs.existsSync(source)) {
824
- throw grokFailure(
825
- 'GROK_ROLLBACK_SOURCE_MISSING',
826
- `cannot restore Grok registration from missing source: ${source || '<none>'}`,
827
- );
828
- }
829
- const current = installedPlugin(ctx);
830
- if (current) nativeUninstall(ctx, { allowMissing: true });
831
- runGrok(ctx, ['plugin', 'install', source, '--trust']);
832
- const registered = installedPlugin(ctx);
833
- if (!registered) {
834
- throw grokFailure(
835
- 'GROK_ROLLBACK_NOT_REGISTERED',
836
- 'Grok did not register the restored Ultra Builder Pro source',
837
- );
838
- }
839
- const finalized = finalizeNativeRegistration(
840
- ctx,
841
- resolveRepoRoot(ctx),
842
- source,
843
- registered,
844
- { expectedPackageVersion: registered.version },
845
- );
846
- const target = finalized.target;
847
- if (
848
- typeof registered.source === 'string'
849
- && path.resolve(registered.source) !== path.resolve(source)
850
- ) {
851
- throw grokFailure(
852
- 'GROK_ROLLBACK_SOURCE_MISMATCH',
853
- `Grok restored Ultra from ${registered.source}, expected ${source}`,
854
- );
855
- }
856
- runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
857
- restoreNativeActivation(ctx, target, enabled);
858
- let consumer = null;
859
- if (verifyConsumer) {
860
- consumer = nativeConsumerState(ctx, registered);
861
- if (!consumer.healthy) {
862
- throw grokFailure(
863
- 'GROK_ROLLBACK_NOT_ACTIVE',
864
- 'restored Grok plugin did not pass native inspect and MCP Doctor',
865
- );
866
- }
867
- }
868
- return { registered, target, consumer };
869
- }
870
-
871
- function combinedRollbackFailure(originalError, rollbackError, recovery = {}) {
872
- const error = grokFailure(
873
- 'GROK_INSTALL_ROLLBACK_FAILED',
874
- [
875
- `Grok install failed: ${originalError.message}`,
876
- `rollback failed: ${rollbackError.message}`,
877
- ].join('; '),
878
- {
879
- original_code: originalError.code || null,
880
- rollback_code: rollbackError.code || null,
881
- ...recovery,
882
- },
883
- );
884
- error.cause = originalError;
885
- error.original_error = originalError.message;
886
- error.rollback_error = rollbackError.message;
887
- return error;
888
- }
889
-
890
- function combinedUninstallRollbackFailure(originalError, rollbackError, recovery = {}) {
891
- const error = grokFailure(
892
- 'GROK_UNINSTALL_ROLLBACK_FAILED',
893
- [
894
- `Grok uninstall failed: ${originalError.message}`,
895
- `rollback failed: ${rollbackError.message}`,
896
- ].join('; '),
897
- {
898
- original_code: originalError.code || null,
899
- rollback_code: rollbackError.code || null,
900
- ...recovery,
901
- },
902
- );
903
- error.cause = originalError;
904
- error.original_error = originalError.message;
905
- error.rollback_error = rollbackError.message;
906
- return error;
907
- }
908
-
909
- function assertOwnedForUninstall(target, label) {
910
- if (!fs.existsSync(target)) return;
911
- if (!isManaged(target)) {
912
- throw grokFailure(
913
- 'GROK_UNINSTALL_OWNERSHIP_CONFLICT',
914
- `refusing to uninstall because ${label} is not owned by Ultra: ${target}`,
915
- { label, path: target },
916
- );
917
- }
918
- }
919
-
920
- function assertManagedProvenance(target, label, {
921
- expectedPackageName,
922
- expectedPackageVersion = null,
923
- allowMarkerOnly = false,
924
- } = {}) {
925
- if (!fs.existsSync(target)) return null;
926
- const stat = fs.lstatSync(target);
927
- if (!stat.isDirectory()) {
928
- throw grokFailure(
929
- 'GROK_MANAGED_ROOT_INVALID',
930
- `${label} is not a managed directory: ${target}`,
931
- { label, path: target },
932
- );
933
- }
934
- if (!isManaged(target)) {
935
- throw grokFailure(
936
- 'GROK_MANAGED_ROOT_UNOWNED',
937
- `${label} is not owned by Ultra: ${target}`,
938
- { label, path: target },
939
- );
940
- }
941
- const file = path.join(target, PROVENANCE_FILE);
942
- if (allowMarkerOnly && !fs.existsSync(file)) {
943
- return { status: 'legacy', path: target };
944
- }
945
- const report = provenance.inspectProvenance({
946
- file,
947
- expectedAdapter: 'grok',
948
- expectedPackageVersion,
114
+ function runGrok(ctx, args) {
115
+ const result = spawnSync(ctx.grokBin || 'grok', args, {
116
+ encoding: 'utf8', timeout: ctx.hostCliTimeoutMs || 30000,
117
+ env: { ...process.env, GROK_HOME: resolveTarget(ctx) },
949
118
  });
950
- if (report.status !== 'healthy' || report.package?.name !== expectedPackageName) {
951
- throw grokFailure(
952
- 'GROK_MANAGED_ROOT_PROVENANCE_INVALID',
953
- `${label} failed Ultra provenance verification: ${target}`,
954
- { label, path: target, issues: report.issues },
955
- );
956
- }
957
- const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
958
- const declaredRoot = path.resolve(manifest.roots?.plugin || '');
959
- const canonicalDeclaredRoot = fs.existsSync(declaredRoot)
960
- ? fs.realpathSync(declaredRoot)
961
- : declaredRoot;
962
- const canonicalTarget = fs.realpathSync(target);
963
- if (canonicalDeclaredRoot !== canonicalTarget) {
964
- throw grokFailure(
965
- 'GROK_MANAGED_ROOT_PROVENANCE_INVALID',
966
- `${label} provenance is bound to a different root: ${target}`,
967
- {
968
- label,
969
- path: target,
970
- declared_root: manifest.roots?.plugin || null,
971
- },
972
- );
973
- }
974
- return report;
975
- }
976
-
977
- function finalizeNativeRegistration(ctx, repoRoot, sourceRoot, registered, {
978
- expectedPackageVersion = null,
979
- } = {}) {
980
- const packageInfo = provenance.packageSource(repoRoot).packageInfo;
981
- const packageVersion = expectedPackageVersion || packageInfo.version;
982
- if (registered.version !== packageVersion) {
983
- throw grokFailure(
984
- 'GROK_PLUGIN_VERSION_MISMATCH',
985
- `Grok installed Ultra Builder Pro ${registered.version || '<missing>'}, expected ${packageVersion}`,
986
- { expected: packageVersion, actual: registered.version || null },
987
- );
988
- }
989
- const target = resolveNativeInstallPath(registered);
990
- if (!isManaged(target)) {
991
- throw grokFailure(
992
- 'GROK_PLUGIN_PATH_UNSAFE',
993
- `Grok registry returned an unmanaged plugin path: ${target}`,
994
- { path: target },
995
- );
996
- }
997
- const source = assertRegisteredSource(ctx, registered, {
998
- expectedPackageName: packageInfo.name,
999
- expectedPackageVersion: packageVersion,
1000
- sourceRoot,
1001
- });
1002
- const file = path.join(target, PROVENANCE_FILE);
1003
- let copiedManifest;
1004
- try {
1005
- copiedManifest = JSON.parse(fs.readFileSync(file, 'utf8'));
1006
- } catch (error) {
1007
- throw grokFailure(
1008
- 'GROK_PLUGIN_TARGET_PROVENANCE_INVALID',
1009
- `Grok installed target has invalid copied provenance: ${target}`,
1010
- { path: target, cause_code: error.code || null },
1011
- );
1012
- }
1013
- const declaredRoot = path.resolve(copiedManifest.roots?.plugin || '');
1014
- const canonicalDeclaredRoot = fs.existsSync(declaredRoot)
1015
- ? fs.realpathSync(declaredRoot)
1016
- : declaredRoot;
1017
- if (
1018
- canonicalDeclaredRoot !== source.path
1019
- && canonicalDeclaredRoot !== target
1020
- ) {
1021
- throw grokFailure(
1022
- 'GROK_PLUGIN_TARGET_PROVENANCE_INVALID',
1023
- `Grok installed target provenance is not derived from its registered source: ${target}`,
1024
- { path: target, declared_root: copiedManifest.roots?.plugin || null },
1025
- );
1026
- }
1027
- if (
1028
- typeof copiedManifest.content?.digest !== 'string'
1029
- || copiedManifest.content.digest !== source.report.content_digest
1030
- ) {
1031
- throw grokFailure(
1032
- 'GROK_PLUGIN_TARGET_PROVENANCE_INVALID',
1033
- `Grok installed target does not match its registered source provenance: ${target}`,
1034
- {
1035
- path: target,
1036
- expected_digest: source.report.content_digest,
1037
- actual_digest: copiedManifest.content?.digest || null,
1038
- },
1039
- );
1040
- }
1041
- const manifest = rebaseProvenanceRoot(target);
1042
- const targetReport = assertManagedProvenance(target, 'registered Grok target', {
1043
- expectedPackageName: packageInfo.name,
1044
- expectedPackageVersion: packageVersion,
1045
- });
1046
- if (targetReport.content_digest !== source.report.content_digest) {
1047
- throw grokFailure(
1048
- 'GROK_PLUGIN_TARGET_PROVENANCE_INVALID',
1049
- `Grok installed target assets differ from its registered source: ${target}`,
1050
- {
1051
- path: target,
1052
- expected_digest: source.report.content_digest,
1053
- actual_digest: targetReport.content_digest,
1054
- },
1055
- );
1056
- }
1057
- assertNativeInstallPath(ctx, registered, {
1058
- expectedPackageName: packageInfo.name,
1059
- expectedPackageVersion: packageVersion,
1060
- sourceRoot,
1061
- });
1062
- return { target, provenance: { file, manifest } };
119
+ if (result.error) throw result.error;
120
+ if (result.status !== 0) throw new Error((result.stderr || result.stdout || '').trim() || `grok ${args.join(' ')} failed`);
121
+ return result.stdout;
1063
122
  }
1064
123
 
1065
- function installPreflight(ctx, repoRoot, sourceRoot, legacyRoot) {
1066
- try {
1067
- const packageInfo = provenance.packageSource(repoRoot).packageInfo;
1068
- const registered = installedPlugin(ctx);
1069
- let installedRoot = null;
1070
- if (registered) {
1071
- installedRoot = assertNativeInstallPath(ctx, registered, {
1072
- expectedPackageName: packageInfo.name,
1073
- expectedPackageVersion: registered.version,
1074
- sourceRoot,
1075
- });
1076
- const consumer = nativeConsumerState(ctx, registered);
1077
- if (!consumer.healthy) {
1078
- throw grokFailure(
1079
- 'GROK_PLUGIN_MCP_INACTIVE',
1080
- 'existing Grok registration did not pass native inspect and MCP Doctor',
1081
- );
1082
- }
1083
- } else {
1084
- assertManagedProvenance(sourceRoot, 'current Grok source', {
1085
- expectedPackageName: packageInfo.name,
1086
- expectedPackageVersion: null,
1087
- });
1088
- }
1089
- assertManagedProvenance(legacyRoot, 'legacy Grok plugin', {
1090
- expectedPackageName: packageInfo.name,
1091
- allowMarkerOnly: true,
1092
- });
1093
- return { registered, installedRoot };
1094
- } catch (error) {
1095
- const failure = grokFailure(
1096
- 'GROK_INSTALL_PREFLIGHT_FAILED',
1097
- `Grok install preflight failed: ${error.message}`,
1098
- { cause_code: error.code || null, ...(error.details || {}) },
1099
- );
1100
- failure.cause = error;
1101
- throw failure;
1102
- }
124
+ function installedPlugin(ctx) {
125
+ const value = JSON.parse(runGrok(ctx, ['plugin', 'list', '--json']));
126
+ if (!Array.isArray(value)) throw new Error('grok plugin list --json must return an array');
127
+ return value.find((entry) => entry?.name === PLUGIN_NAME) || null;
1103
128
  }
1104
129
 
1105
130
  function install(ctx = {}) {
131
+ assertPluginScope(ctx);
1106
132
  const sourceRoot = resolveSourceRoot(ctx);
1107
- const legacyRoot = resolvePluginRoot(ctx);
133
+ const configRoot = resolveTarget(ctx);
1108
134
  const repoRoot = resolveRepoRoot(ctx);
1109
- const capability = probeNativeCapabilities(ctx);
1110
- if (capability.status !== 'pass') {
1111
- throw grokFailure(
1112
- 'GROK_CLI_UNAVAILABLE',
1113
- 'Grok CLI is required for formal plugin installation; no files were changed',
1114
- );
1115
- }
1116
- const preflight = installPreflight(ctx, repoRoot, sourceRoot, legacyRoot);
1117
- const sourceParent = path.dirname(sourceRoot);
1118
- ensureDir(sourceParent);
1119
- const staging = fs.mkdtempSync(path.join(sourceParent, `${PLUGIN_NAME}-staging-`));
1120
- const sourceBackup = `${staging}-source-previous`;
1121
- const backupRoot = resolveBackupRoot(ctx);
1122
- const transactionId = crypto.randomUUID();
1123
- const legacyBackup = path.join(backupRoot, `legacy-plugin-${transactionId}`);
1124
- const nativeBackup = path.join(backupRoot, `native-plugin-${transactionId}`);
1125
- let sourceMoved = false;
1126
- let sourcePublished = false;
1127
- let legacyMoved = false;
1128
- let nativeSnapshot = false;
1129
- let registryMutationStarted = false;
1130
- const originalNative = preflight.registered;
1131
- let built;
1132
-
135
+ const cleanupAbsent = managedMetadata(sourceRoot)?.cleanup_absent
136
+ || captureAbsent(configRoot, ['.', '.ubp', path.join('.ubp', 'plugin-sources'), 'plugins']);
137
+ ensureDir(path.dirname(sourceRoot));
138
+ const staging = fs.mkdtempSync(path.join(path.dirname(sourceRoot), `.${PLUGIN_NAME}-staging-`));
139
+ const recovery = fs.existsSync(sourceRoot)
140
+ ? fs.mkdtempSync(path.join(path.dirname(sourceRoot), `.${PLUGIN_NAME}-recovery-`))
141
+ : null;
142
+ if (recovery) fs.cpSync(sourceRoot, recovery, { recursive: true });
143
+ let previousRegistration = null;
1133
144
  try {
1134
- built = buildStaging(repoRoot, staging, ctx);
1135
- if (fs.existsSync(sourceRoot)) {
1136
- if (!isManaged(sourceRoot)) {
1137
- throw grokFailure(
1138
- 'GROK_SOURCE_UNMANAGED',
1139
- `refusing to replace unmanaged Grok plugin source: ${sourceRoot}`,
1140
- );
1141
- }
1142
- fs.renameSync(sourceRoot, sourceBackup);
1143
- sourceMoved = true;
1144
- }
1145
- fs.renameSync(staging, sourceRoot);
1146
- sourcePublished = true;
1147
- writeProvenance(repoRoot, sourceRoot);
1148
-
1149
- if (originalNative) {
1150
- const installedRoot = preflight.installedRoot;
1151
- if (!isManaged(installedRoot)) {
1152
- throw grokFailure(
1153
- 'GROK_PLUGIN_OWNERSHIP_CONFLICT',
1154
- `refusing to replace an installed Grok plugin not owned by Ultra: ${installedRoot}`,
1155
- );
1156
- }
1157
- ensureDir(backupRoot);
1158
- managedCopy(installedRoot, nativeBackup);
1159
- nativeSnapshot = true;
1160
- }
1161
-
1162
- if (fs.existsSync(legacyRoot)) {
1163
- if (!isManaged(legacyRoot)) {
1164
- throw grokFailure(
1165
- 'GROK_LEGACY_PLUGIN_UNMANAGED',
1166
- `refusing to migrate unmanaged Grok plugin: ${legacyRoot}`,
1167
- );
1168
- }
1169
- ensureDir(backupRoot);
1170
- fs.renameSync(legacyRoot, legacyBackup);
1171
- legacyMoved = true;
1172
- }
1173
-
1174
- if (originalNative) {
1175
- registryMutationStarted = true;
1176
- nativeUninstall(ctx);
1177
- }
1178
- registryMutationStarted = true;
1179
- runGrok(ctx, ['plugin', 'install', sourceRoot, '--trust']);
1180
- runGrok(ctx, ['plugin', 'enable', PLUGIN_NAME]);
1181
- const registered = installedPlugin(ctx);
1182
- if (!registered) {
1183
- throw grokFailure(
1184
- 'GROK_PLUGIN_NOT_REGISTERED',
1185
- 'Grok accepted the plugin install command but did not register Ultra Builder Pro',
1186
- );
1187
- }
1188
- const finalized = finalizeNativeRegistration(ctx, repoRoot, sourceRoot, registered);
1189
- const target = finalized.target;
1190
- const provenanceReport = finalized.provenance;
1191
- const consumer = nativeConsumerState(ctx, registered);
1192
- if (!consumer.healthy) {
1193
- throw grokFailure(
1194
- 'GROK_PLUGIN_NOT_ACTIVE',
1195
- 'Grok registered Ultra Builder Pro but did not activate its plugin MCP consumer',
1196
- );
1197
- }
1198
-
1199
- if (sourceMoved && fs.existsSync(sourceBackup)) removeTree(sourceBackup);
1200
- if (nativeSnapshot && fs.existsSync(nativeBackup)) removeTree(nativeBackup);
145
+ const copied = buildStaging(repoRoot, staging, sourceRoot);
146
+ markManaged(staging, { cleanup_absent: cleanupAbsent });
147
+ publishManagedTrees([{ source: staging, target: sourceRoot, label: 'Grok plugin source' }]);
148
+ if (shouldRunHostCli(ctx)) {
149
+ runGrok(ctx, ['plugin', 'validate', sourceRoot]);
150
+ previousRegistration = installedPlugin(ctx);
151
+ if (previousRegistration) runGrok(ctx, ['plugin', 'uninstall', PLUGIN_NAME, '--confirm', '--keep-data']);
152
+ runGrok(ctx, ['plugin', 'install', sourceRoot, '--trust']);
153
+ runGrok(ctx, ['plugin', 'enable', PLUGIN_NAME]);
154
+ runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
155
+ }
156
+ if (recovery) removeTree(recovery);
1201
157
  return {
1202
- target,
1203
- source: sourceRoot,
1204
- ...built,
1205
- provenance: provenanceReport,
1206
- native_registry: {
1207
- status: 'pass',
1208
- repo_key: registered.repo_key || null,
1209
- path: target,
1210
- },
1211
- native_consumer: {
1212
- status: 'pass',
1213
- mcp: MCP_SERVER_NAME,
1214
- healthy: true,
1215
- },
1216
- migration: legacyMoved ? {
1217
- legacy_backup: legacyBackup,
1218
- legacy_source_removed: true,
1219
- } : null,
1220
- trusted: true,
1221
- reload_required: true,
158
+ target: sourceRoot,
159
+ pluginRoot: sourceRoot,
160
+ skillRoot: path.join(sourceRoot, 'skills'),
161
+ hookRoot: path.join(sourceRoot, 'hooks'),
162
+ copied,
1222
163
  };
1223
164
  } catch (error) {
1224
- let rollbackError = null;
1225
- let recoverySource = null;
165
+ const rollback = [];
1226
166
  try {
1227
- if (registryMutationStarted) nativeUninstall(ctx, { allowMissing: true });
1228
- if (sourcePublished && fs.existsSync(sourceRoot)) removeTree(sourceRoot);
1229
- else if (fs.existsSync(staging)) removeTree(staging);
1230
- if (sourceMoved && fs.existsSync(sourceBackup)) fs.renameSync(sourceBackup, sourceRoot);
1231
- if (legacyMoved && fs.existsSync(legacyBackup)) {
1232
- ensureDir(path.dirname(legacyRoot));
1233
- fs.renameSync(legacyBackup, legacyRoot);
1234
- }
1235
- if (originalNative && registryMutationStarted) {
1236
- recoverySource = ensureRecoverySource(originalNative, sourceRoot, nativeBackup);
1237
- restoreNativeRegistration(ctx, recoverySource);
167
+ if (fs.existsSync(sourceRoot)) removeTree(sourceRoot);
168
+ if (recovery) fs.renameSync(recovery, sourceRoot);
169
+ if (previousRegistration && shouldRunHostCli(ctx)) {
170
+ try { runGrok(ctx, ['plugin', 'uninstall', PLUGIN_NAME, '--confirm', '--keep-data']); } catch {}
171
+ runGrok(ctx, ['plugin', 'install', sourceRoot, '--trust']);
172
+ if (previousRegistration.enabled !== false) runGrok(ctx, ['plugin', 'enable', PLUGIN_NAME]);
1238
173
  }
1239
- if (nativeSnapshot && fs.existsSync(nativeBackup)) removeTree(nativeBackup);
1240
- } catch (caughtRollbackError) {
1241
- rollbackError = caughtRollbackError;
1242
- }
1243
- if (rollbackError) {
1244
- throw combinedRollbackFailure(error, rollbackError, {
1245
- recovery_source: recoverySource,
1246
- native_backup: nativeSnapshot && fs.existsSync(nativeBackup) ? nativeBackup : null,
1247
- });
174
+ } catch (rollbackError) {
175
+ rollback.push(rollbackError);
1248
176
  }
177
+ if (fs.existsSync(staging)) removeTree(staging);
178
+ pruneCreatedEmpty(configRoot, cleanupAbsent);
179
+ if (rollback.length) throw new AggregateError([error, ...rollback], 'Grok install and rollback failed');
1249
180
  throw error;
1250
181
  }
1251
182
  }
1252
183
 
1253
184
  function doctor(ctx = {}) {
1254
- const source = provenance.packageSource(resolveRepoRoot(ctx));
1255
- const capability = probeNativeCapabilities(ctx);
1256
- if (capability.status === 'unavailable') {
1257
- const sourceRoot = resolveSourceRoot(ctx);
1258
- const report = provenance.inspectProvenance({
1259
- file: path.join(sourceRoot, PROVENANCE_FILE),
1260
- expectedAdapter: 'grok',
1261
- expectedPackageVersion: source.packageInfo.version,
1262
- });
1263
- report.checks.native_registry = { status: 'unavailable' };
1264
- report.checks.native_consumer = { status: 'unavailable' };
1265
- report.issues.push({
1266
- code: 'GROK_CLI_UNAVAILABLE',
1267
- message: 'Grok CLI is unavailable, so native registry and MCP activation were not verified',
1268
- });
1269
- report.status = 'degraded';
1270
- return applyNativeDoctor(report, path.join(sourceRoot, 'runtime'));
1271
- }
1272
-
1273
- let registered;
1274
- try {
1275
- registered = installedPlugin(ctx);
1276
- } catch (error) {
1277
- return {
1278
- adapter: 'grok',
1279
- status: 'degraded',
1280
- manifest_path: null,
1281
- checks: { native_registry: { status: 'fail' } },
1282
- issues: [{ code: error.code || 'GROK_PLUGIN_LIST_FAILED', message: error.message }],
1283
- };
1284
- }
1285
- if (!registered) {
1286
- const legacyRoot = resolvePluginRoot(ctx);
1287
- return {
1288
- adapter: 'grok',
1289
- status: 'degraded',
1290
- manifest_path: fs.existsSync(path.join(legacyRoot, PROVENANCE_FILE))
1291
- ? path.join(legacyRoot, PROVENANCE_FILE)
1292
- : null,
1293
- checks: {
1294
- native_registry: { status: 'fail' },
1295
- raw_plugin: {
1296
- status: fs.existsSync(legacyRoot) ? 'found' : 'missing',
1297
- path: legacyRoot,
1298
- },
1299
- },
1300
- issues: [{
1301
- code: 'GROK_PLUGIN_NOT_REGISTERED',
1302
- message: fs.existsSync(legacyRoot)
1303
- ? 'a raw Grok plugin exists, but the native Grok plugin registry does not contain it'
1304
- : 'Ultra Builder Pro is not registered in the native Grok plugin registry',
1305
- }],
1306
- };
1307
- }
1308
-
1309
- let target;
1310
- try {
1311
- target = assertNativeInstallPath(ctx, registered, {
1312
- expectedPackageName: source.packageInfo.name,
1313
- expectedPackageVersion: source.packageInfo.version,
1314
- sourceRoot: resolveSourceRoot(ctx),
1315
- });
1316
- } catch (error) {
1317
- return {
1318
- adapter: 'grok',
1319
- status: 'degraded',
1320
- manifest_path: null,
1321
- checks: {
1322
- native_registry: {
1323
- status: 'fail',
1324
- repo_key: registered.repo_key || null,
1325
- path: registered.path,
1326
- },
1327
- native_consumer: { status: 'unknown' },
1328
- },
1329
- issues: [{
1330
- code: error.code || 'GROK_PLUGIN_PATH_INVALID',
1331
- message: error.message,
1332
- ...(error.details || {}),
1333
- }],
1334
- };
1335
- }
1336
- const report = provenance.inspectProvenance({
1337
- file: path.join(target, PROVENANCE_FILE),
1338
- expectedAdapter: 'grok',
1339
- expectedPackageVersion: source.packageInfo.version,
185
+ assertPluginScope(ctx);
186
+ const sourceRoot = resolveSourceRoot(ctx);
187
+ const report = inspectPlugin({
188
+ adapter: 'grok', repoRoot: resolveRepoRoot(ctx), pluginRoot: sourceRoot,
189
+ skillRoot: path.join(sourceRoot, 'skills'), hookRoot: path.join(sourceRoot, 'hooks'),
190
+ manifestFile: path.join(sourceRoot, 'plugin.json'),
1340
191
  });
1341
- report.checks.native_registry = {
1342
- status: 'pass',
1343
- repo_key: registered.repo_key || null,
1344
- path: target,
1345
- };
1346
- try {
1347
- const details = runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
1348
- report.checks.plugin_details = {
1349
- status: 'pass',
1350
- output: details.stdout.trim(),
1351
- };
1352
- } catch (error) {
1353
- report.checks.plugin_details = { status: 'fail' };
1354
- report.issues.push({
1355
- code: 'GROK_PLUGIN_DETAILS_FAILED',
1356
- message: error.message,
1357
- });
1358
- }
1359
- try {
1360
- const consumer = nativeConsumerState(ctx, registered);
1361
- report.checks.native_consumer = {
1362
- status: consumer.healthy ? 'pass' : 'fail',
1363
- plugin_discovered: Boolean(consumer.plugin),
1364
- plugin_mcp_active: Boolean(consumer.mcp),
1365
- mcp_healthy: consumer.doctorServer?.healthy === true,
1366
- };
1367
- if (!consumer.healthy) {
1368
- report.issues.push({
1369
- code: 'GROK_PLUGIN_MCP_INACTIVE',
1370
- message: 'Grok native inspection or MCP Doctor did not confirm the plugin MCP consumer',
1371
- });
1372
- }
1373
- } catch (error) {
1374
- report.checks.native_consumer = { status: 'fail' };
1375
- report.issues.push({
1376
- code: error.code || 'GROK_PLUGIN_MCP_CHECK_FAILED',
1377
- message: error.message,
1378
- });
1379
- }
1380
- try {
1381
- report.checks.plugin_validation = validatePlugin(target, ctx);
1382
- } catch (error) {
1383
- report.checks.plugin_validation = { status: 'fail' };
1384
- report.issues.push({ code: 'PLUGIN_MANIFEST_INVALID', message: error.message });
1385
- }
1386
- return applyNativeDoctor(report, path.join(target, 'runtime'));
192
+ if (shouldRunHostCli(ctx)) {
193
+ let discovered = false;
194
+ try {
195
+ const plugin = installedPlugin(ctx);
196
+ discovered = !!plugin && plugin.enabled !== false;
197
+ if (discovered) runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
198
+ } catch {}
199
+ report.checks.native_registry = { status: discovered ? 'pass' : 'fail' };
200
+ if (!discovered) report.issues.push({ code: 'GROK_PLUGIN_NOT_REGISTERED' });
201
+ }
202
+ report.status = report.issues.length === 0 ? 'healthy' : 'degraded';
203
+ return report;
1387
204
  }
1388
205
 
1389
206
  function uninstall(ctx = {}) {
207
+ assertPluginScope(ctx);
1390
208
  const sourceRoot = resolveSourceRoot(ctx);
1391
- const legacyRoot = resolvePluginRoot(ctx);
1392
- const capability = probeNativeCapabilities(ctx);
1393
- if (capability.status !== 'pass') {
1394
- throw grokFailure(
1395
- 'GROK_CLI_UNAVAILABLE',
1396
- 'Grok CLI is required for formal plugin uninstall; no files were changed',
1397
- );
1398
- }
1399
- const report = {
1400
- target: null,
1401
- source: sourceRoot,
1402
- removed: {},
1403
- native_registry: { status: capability.status },
209
+ const configRoot = resolveTarget(ctx);
210
+ const cleanupAbsent = managedMetadata(sourceRoot)?.cleanup_absent || [];
211
+ if (shouldRunHostCli(ctx)) {
212
+ const plugin = installedPlugin(ctx);
213
+ if (plugin) runGrok(ctx, ['plugin', 'uninstall', PLUGIN_NAME, '--confirm', '--keep-data']);
214
+ }
215
+ const legacy = resolvePluginRoot(ctx);
216
+ const removedLegacy = fs.existsSync(legacy) && isManaged(legacy)
217
+ ? removeManaged(legacy, 'legacy Grok plugin')
218
+ : false;
219
+ const removedSource = removeManaged(sourceRoot, 'Grok plugin source');
220
+ const cleaned = pruneCreatedEmpty(configRoot, cleanupAbsent);
221
+ return {
222
+ target: sourceRoot,
223
+ pluginRoot: sourceRoot,
224
+ removed: {
225
+ source: removedSource,
226
+ legacy: removedLegacy,
227
+ },
228
+ cleaned,
1404
229
  };
1405
- const registered = installedPlugin(ctx);
1406
- let installedRoot = null;
1407
- let registeredEnabled = null;
1408
- if (registered) {
1409
- installedRoot = resolveNativeInstallPath(registered);
1410
- report.target = installedRoot;
1411
- }
1412
- const declaredSource = registered && typeof registered.source === 'string'
1413
- ? path.resolve(registered.source)
1414
- : null;
1415
- const ownershipTargets = [
1416
- [installedRoot, 'managed target'],
1417
- [sourceRoot, 'persistent source'],
1418
- [legacyRoot, 'legacy raw plugin'],
1419
- [
1420
- declaredSource
1421
- && declaredSource !== path.resolve(sourceRoot)
1422
- && declaredSource !== installedRoot
1423
- ? declaredSource
1424
- : null,
1425
- 'registered source',
1426
- ],
1427
- ];
1428
- for (const [target, label] of ownershipTargets) {
1429
- if (target) assertOwnedForUninstall(target, label);
1430
- }
1431
- if (registered) {
1432
- installedRoot = assertNativeInstallPath(ctx, registered);
1433
- runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
1434
- registeredEnabled = nativeActivationState(ctx, installedRoot);
1435
- }
1436
-
1437
- const transactionId = crypto.randomUUID();
1438
- const sourceBackup = path.join(
1439
- path.dirname(sourceRoot),
1440
- `.${path.basename(sourceRoot)}-uninstall-${transactionId}`,
1441
- );
1442
- const legacyBackup = path.join(
1443
- path.dirname(legacyRoot),
1444
- `.${path.basename(legacyRoot)}-uninstall-${transactionId}`,
1445
- );
1446
- const backupRoot = resolveBackupRoot(ctx);
1447
- const nativeBackup = path.join(
1448
- backupRoot,
1449
- `uninstall-native-${transactionId}`,
1450
- );
1451
- let sourceStaged = false;
1452
- let legacyStaged = false;
1453
- let nativeSnapshot = false;
1454
- let registryMutationStarted = false;
1455
- try {
1456
- if (fs.existsSync(sourceRoot)) {
1457
- fs.renameSync(sourceRoot, sourceBackup);
1458
- sourceStaged = true;
1459
- }
1460
- if (fs.existsSync(legacyRoot)) {
1461
- fs.renameSync(legacyRoot, legacyBackup);
1462
- legacyStaged = true;
1463
- }
1464
- if (registered) {
1465
- ensureDir(backupRoot);
1466
- managedCopy(installedRoot, nativeBackup);
1467
- nativeSnapshot = true;
1468
- registryMutationStarted = true;
1469
- nativeUninstall(ctx);
1470
- report.removed.native_plugin = true;
1471
- }
1472
- const remaining = installedPlugin(ctx);
1473
- if (remaining) {
1474
- throw grokFailure(
1475
- 'GROK_UNINSTALL_NOT_REMOVED',
1476
- 'Grok reported uninstall success but the native registry still contains Ultra Builder Pro',
1477
- );
1478
- }
1479
- if (sourceStaged) report.removed.source = true;
1480
- if (legacyStaged) report.removed.legacy_plugin = true;
1481
- if (sourceStaged && fs.existsSync(sourceBackup)) removeTree(sourceBackup);
1482
- if (legacyStaged && fs.existsSync(legacyBackup)) removeTree(legacyBackup);
1483
- if (nativeSnapshot && fs.existsSync(nativeBackup)) removeTree(nativeBackup);
1484
- return report;
1485
- } catch (error) {
1486
- let rollbackError = null;
1487
- let recoverySource = null;
1488
- try {
1489
- if (sourceStaged && fs.existsSync(sourceBackup)) {
1490
- if (fs.existsSync(sourceRoot)) {
1491
- throw grokFailure(
1492
- 'GROK_UNINSTALL_ROLLBACK_SOURCE_CONFLICT',
1493
- `cannot restore Grok source over existing bytes: ${sourceRoot}`,
1494
- );
1495
- }
1496
- fs.renameSync(sourceBackup, sourceRoot);
1497
- }
1498
- if (legacyStaged && fs.existsSync(legacyBackup)) {
1499
- if (fs.existsSync(legacyRoot)) {
1500
- throw grokFailure(
1501
- 'GROK_UNINSTALL_ROLLBACK_LEGACY_CONFLICT',
1502
- `cannot restore legacy Grok plugin over existing bytes: ${legacyRoot}`,
1503
- );
1504
- }
1505
- fs.renameSync(legacyBackup, legacyRoot);
1506
- }
1507
- if (registered && registryMutationStarted) {
1508
- const current = installedPlugin(ctx);
1509
- if (current) {
1510
- const currentTarget = assertNativeInstallPath(ctx, current);
1511
- const originalSource = typeof registered.source === 'string'
1512
- ? path.resolve(registered.source)
1513
- : null;
1514
- const currentSource = typeof current.source === 'string'
1515
- ? path.resolve(current.source)
1516
- : null;
1517
- if (currentTarget !== installedRoot || currentSource !== originalSource) {
1518
- throw grokFailure(
1519
- 'GROK_UNINSTALL_ROLLBACK_REGISTRY_MISMATCH',
1520
- 'remaining Grok registration does not match the pre-uninstall registry entry',
1521
- {
1522
- expected_path: installedRoot,
1523
- actual_path: currentTarget,
1524
- expected_source: originalSource,
1525
- actual_source: currentSource,
1526
- },
1527
- );
1528
- }
1529
- runGrok(ctx, ['plugin', 'details', PLUGIN_NAME]);
1530
- restoreNativeActivation(ctx, currentTarget, registeredEnabled);
1531
- } else {
1532
- recoverySource = ensureRecoverySource(registered, sourceRoot, nativeBackup);
1533
- restoreNativeRegistration(ctx, recoverySource, {
1534
- verifyConsumer: false,
1535
- enabled: registeredEnabled,
1536
- });
1537
- }
1538
- }
1539
- if (nativeSnapshot && fs.existsSync(nativeBackup)) removeTree(nativeBackup);
1540
- } catch (caughtRollbackError) {
1541
- rollbackError = caughtRollbackError;
1542
- }
1543
- if (rollbackError) {
1544
- throw combinedUninstallRollbackFailure(error, rollbackError, {
1545
- recovery_source: recoverySource,
1546
- native_backup: nativeSnapshot && fs.existsSync(nativeBackup) ? nativeBackup : null,
1547
- source_backup: fs.existsSync(sourceBackup) ? sourceBackup : null,
1548
- legacy_backup: fs.existsSync(legacyBackup) ? legacyBackup : null,
1549
- });
1550
- }
1551
- throw error;
1552
- }
1553
230
  }
1554
231
 
1555
232
  module.exports = {
1556
233
  name: 'grok',
1557
234
  PLUGIN_NAME,
1558
- MCP_SERVER_NAME,
1559
235
  buildHooksManifest,
1560
236
  resolveTarget,
1561
237
  resolvePluginRoot,
1562
238
  resolveSourceRoot,
1563
- resolveGrokBinary,
1564
- probeNativeCapabilities,
1565
239
  install,
1566
240
  doctor,
1567
241
  uninstall,