ultra-builder-pro-cli 0.22.0 → 0.24.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 (93) hide show
  1. package/.ultra-template/docs/research/README.md +4 -4
  2. package/CHANGELOG.md +83 -0
  3. package/README.md +68 -35
  4. package/adapters/_shared/codex-assets.cjs +121 -60
  5. package/adapters/_shared/interaction-contract.cjs +20 -7
  6. package/adapters/_shared/provenance.cjs +7 -2
  7. package/adapters/_shared/runtime-assets.cjs +4 -3
  8. package/adapters/_shared/runtime-native.cjs +132 -0
  9. package/adapters/claude.js +61 -31
  10. package/adapters/codex.js +178 -81
  11. package/adapters/grok.js +372 -0
  12. package/adapters/kimi.js +8 -4
  13. package/adapters/opencode.js +211 -33
  14. package/agents/code-reviewer.md +4 -2
  15. package/agents/debugger.md +4 -1
  16. package/agents/review-code.md +7 -3
  17. package/agents/review-comments.md +7 -4
  18. package/agents/review-coordinator.md +11 -7
  19. package/agents/review-design.md +8 -4
  20. package/agents/review-errors.md +8 -4
  21. package/agents/review-spec.md +8 -5
  22. package/agents/review-tests.md +7 -4
  23. package/agents/tdd-runner.md +5 -2
  24. package/bin/install.js +9 -4
  25. package/bin/orchestrator.js +4 -13
  26. package/docs/AGENT-CONTEXT.md +141 -231
  27. package/docs/ARCHITECTURE.md +203 -498
  28. package/docs/ARTIFACT-AUTHORITY.md +38 -35
  29. package/docs/PLUGIN-ISOLATION-CONTRACT.md +12 -9
  30. package/docs/ROADMAP.md +85 -110
  31. package/docs/RUNTIME-COMPAT-MATRIX.md +139 -174
  32. package/docs/SKILL-AUTHORING.md +3 -3
  33. package/docs/STATE-DB-ACCESS-POLICY.md +25 -20
  34. package/docs/WORKFLOW-LIFECYCLE.md +174 -442
  35. package/hooks/README.md +11 -8
  36. package/hooks/active_task_context.py +16 -16
  37. package/hooks/adapters/grok.py +134 -0
  38. package/hooks/{context_spine.py → context_envelope.py} +26 -22
  39. package/hooks/health_check.py +19 -29
  40. package/hooks/pre_stop_check.py +22 -12
  41. package/hooks/subagent_tracker.py +1 -1
  42. package/hooks/workflow_checkpoint.py +14 -13
  43. package/hooks/workflow_context.py +11 -12
  44. package/hooks/workflow_resume.py +14 -13
  45. package/mcp-server/{breadcrumb.cjs → hook-context.cjs} +7 -9
  46. package/mcp-server/lib/artifact-registry.cjs +25 -1
  47. package/mcp-server/lib/baseline-workflow.cjs +36 -38
  48. package/mcp-server/lib/canonical-json.cjs +19 -0
  49. package/mcp-server/lib/change-workflow.cjs +637 -49
  50. package/mcp-server/lib/context-envelope.cjs +508 -0
  51. package/mcp-server/lib/decision-records.cjs +337 -0
  52. package/mcp-server/lib/doctor.cjs +91 -33
  53. package/mcp-server/lib/init-project.cjs +78 -39
  54. package/mcp-server/lib/managed-file-write.cjs +116 -0
  55. package/mcp-server/lib/plan-checkpoint.cjs +177 -0
  56. package/mcp-server/lib/project-context.cjs +178 -0
  57. package/mcp-server/lib/stage-checkpoints.cjs +309 -0
  58. package/mcp-server/lib/state-db.cjs +155 -24
  59. package/mcp-server/lib/task-ledger.cjs +522 -13
  60. package/mcp-server/lib/ultra-facade.cjs +834 -0
  61. package/mcp-server/lib/worker-packet.cjs +358 -0
  62. package/mcp-server/server.cjs +208 -1059
  63. package/orchestrator/daemon.cjs +27 -9
  64. package/orchestrator/parallel-orchestrator.cjs +111 -76
  65. package/orchestrator/session-runner.cjs +135 -34
  66. package/package.json +10 -3
  67. package/skills/ultra-change/SKILL.md +39 -98
  68. package/skills/ultra-deliver/SKILL.md +42 -65
  69. package/skills/ultra-dev/SKILL.md +52 -99
  70. package/skills/ultra-doctor/SKILL.md +35 -57
  71. package/skills/ultra-init/SKILL.md +48 -88
  72. package/skills/ultra-init/references/brownfield-adoption.md +11 -8
  73. package/skills/ultra-plan/SKILL.md +54 -132
  74. package/skills/ultra-research/SKILL.md +58 -112
  75. package/skills/ultra-review/SKILL.md +28 -46
  76. package/skills/ultra-review/references/unified-schema.md +2 -0
  77. package/skills/ultra-review/scripts/review_wait.py +8 -0
  78. package/skills/ultra-status/SKILL.md +22 -45
  79. package/skills/ultra-test/SKILL.md +27 -61
  80. package/skills/ultra-think/SKILL.md +29 -48
  81. package/skills/ultra-think/references/interaction-boundary.md +56 -0
  82. package/spec/cli-protocol.md +80 -187
  83. package/spec/mcp-tools.yaml +130 -2738
  84. package/spec/schemas/mcp-tools.schema.json +1 -1
  85. package/spec/schemas/state-db.sql +107 -4
  86. package/spec/schemas/{task-ledger.v1.schema.json → task-ledger.v2.schema.json} +70 -6
  87. package/ultra-tools/commands/status.cjs +369 -243
  88. package/mcp-server/lib/context-spine.cjs +0 -1208
  89. package/mcp-server/lib/decision-dialogue.cjs +0 -1128
  90. package/mcp-server/lib/project-breadcrumb.cjs +0 -173
  91. package/mcp-server/lib/spec-learning.cjs +0 -284
  92. package/mcp-server/lib/workflow-state.cjs +0 -2965
  93. package/skills/ultra-think/references/decision-dialogue.md +0 -153
package/adapters/codex.js CHANGED
@@ -30,6 +30,7 @@ const {
30
30
  const {
31
31
  PLUGIN_NAME,
32
32
  MANAGED_MARKER,
33
+ applyNativeDoctor,
33
34
  buildPlugin,
34
35
  installAgents,
35
36
  } = require('./_shared/codex-assets.cjs');
@@ -145,13 +146,18 @@ function marketplaceEntry() {
145
146
  }
146
147
 
147
148
  function upsertMarketplace(file) {
149
+ const payload = mergedMarketplace(file);
150
+ writeAtomic(file, JSON.stringify(payload, null, 2) + '\n');
151
+ return { file, name: payload.name, entry: marketplaceEntry() };
152
+ }
153
+
154
+ function mergedMarketplace(file) {
148
155
  const payload = loadMarketplace(file);
149
156
  const entry = marketplaceEntry();
150
157
  const index = payload.plugins.findIndex((plugin) => plugin && plugin.name === PLUGIN_NAME);
151
158
  if (index === -1) payload.plugins.push(entry);
152
159
  else payload.plugins[index] = entry;
153
- writeAtomic(file, JSON.stringify(payload, null, 2) + '\n');
154
- return { file, name: payload.name, entry };
160
+ return payload;
155
161
  }
156
162
 
157
163
  function removeMarketplaceEntry(file) {
@@ -300,6 +306,54 @@ function writeRuntimeManifest(configDir, data) {
300
306
  return file;
301
307
  }
302
308
 
309
+ function captureFiles(files) {
310
+ return [...new Set(files)].map((file) => {
311
+ try {
312
+ const stat = fs.statSync(file);
313
+ return { file, exists: true, contents: fs.readFileSync(file), mode: stat.mode & 0o7777 };
314
+ } catch (error) {
315
+ if (error.code === 'ENOENT') return { file, exists: false };
316
+ throw error;
317
+ }
318
+ });
319
+ }
320
+
321
+ function restoreFiles(snapshots) {
322
+ for (const snapshot of snapshots) {
323
+ if (!snapshot.exists) {
324
+ try {
325
+ fs.unlinkSync(snapshot.file);
326
+ } catch (error) {
327
+ if (error.code !== 'ENOENT') throw error;
328
+ }
329
+ continue;
330
+ }
331
+ writeAtomic(snapshot.file, snapshot.contents);
332
+ fs.chmodSync(snapshot.file, snapshot.mode);
333
+ }
334
+ }
335
+
336
+ function publishStagedAgents(staged, configDir) {
337
+ const targetRoot = path.join(configDir, 'agents');
338
+ ensureDir(targetRoot);
339
+ for (const file of staged.installed) {
340
+ const target = path.join(targetRoot, file);
341
+ if (fs.existsSync(target)) {
342
+ const existing = fs.readFileSync(target, 'utf8');
343
+ if (!existing.startsWith(`# ${MANAGED_MARKER}`)) {
344
+ throw new Error(`refusing to overwrite unmanaged Codex agent: ${target}`);
345
+ }
346
+ }
347
+ }
348
+ for (const file of staged.installed) {
349
+ writeAtomic(
350
+ path.join(targetRoot, file),
351
+ fs.readFileSync(path.join(staged.root, file)),
352
+ );
353
+ }
354
+ return { root: targetRoot, installed: staged.installed };
355
+ }
356
+
303
357
  function install(ctx = {}) {
304
358
  const configDir = resolveTarget(ctx);
305
359
  const repoRoot = resolveRepoRoot(ctx);
@@ -308,93 +362,137 @@ function install(ctx = {}) {
308
362
  ensureDir(configDir);
309
363
 
310
364
  const previousManifest = readRuntimeManifest(configDir);
311
- const legacy = cleanupLegacyConfig(configDir);
312
- const plugin = buildPlugin({ repoRoot, pluginRoot });
313
- const agents = installAgents({ repoRoot, configDir });
314
- const marketplace = upsertMarketplace(marketplaceFile);
315
- const previousVersions = listKnownHookCacheVersions(
316
- configDir,
317
- marketplace.name,
318
- previousManifest,
319
- );
320
-
365
+ if (fs.existsSync(pluginRoot) && !isManaged(pluginRoot)) {
366
+ throw new Error(`refusing to replace unmanaged plugin directory: ${pluginRoot}`);
367
+ }
368
+ ensureDir(path.dirname(pluginRoot));
369
+ const stagingRoot = fs.mkdtempSync(path.join(path.dirname(pluginRoot), `.${PLUGIN_NAME}-staging-`));
370
+ const backupRoot = `${stagingRoot}-previous`;
371
+ const agentStagingConfig = fs.mkdtempSync(path.join(configDir, `.${PLUGIN_NAME}-agents-`));
372
+ let plugin = null;
373
+ let stagedAgents = null;
374
+ let agents = null;
375
+ let marketplace = null;
376
+ let previousVersions = [];
377
+ let previousAdapters = [];
378
+ let snapshots = [];
379
+ let movedPrevious = false;
380
+ let published = false;
321
381
  let registration = null;
322
382
  let hookCompatibility = null;
323
- if (shouldRunPluginCli(ctx)) {
324
- const previousAdapters = hookAdaptersForVersions(
383
+ let legacy = { configUpdated: false, removed: [] };
384
+ try {
385
+ plugin = buildPlugin({ repoRoot, pluginRoot: stagingRoot, publishedRoot: pluginRoot });
386
+ stagedAgents = installAgents({ repoRoot, configDir: agentStagingConfig });
387
+ const marketplacePayload = mergedMarketplace(marketplaceFile);
388
+ marketplace = {
389
+ file: marketplaceFile,
390
+ name: marketplacePayload.name,
391
+ entry: marketplaceEntry(),
392
+ };
393
+ previousVersions = listKnownHookCacheVersions(
394
+ configDir,
395
+ marketplace.name,
396
+ previousManifest,
397
+ );
398
+ previousAdapters = hookAdaptersForVersions(
325
399
  configDir,
326
400
  marketplace.name,
327
401
  previousVersions,
328
402
  );
329
- try {
403
+ snapshots = captureFiles([
404
+ marketplaceFile,
405
+ runtimeManifestFile(configDir),
406
+ path.join(configDir, RUNTIME_MANIFEST_DIR, PROVENANCE_FILE),
407
+ ...stagedAgents.installed.map((file) => path.join(configDir, 'agents', file)),
408
+ ...previousAdapters,
409
+ ]);
410
+
411
+ if (fs.existsSync(pluginRoot)) {
412
+ fs.renameSync(pluginRoot, backupRoot);
413
+ movedPrevious = true;
414
+ }
415
+ fs.renameSync(stagingRoot, pluginRoot);
416
+ published = true;
417
+ agents = publishStagedAgents(stagedAgents, configDir);
418
+ writeAtomic(marketplaceFile, JSON.stringify(marketplacePayload, null, 2) + '\n');
419
+
420
+ if (shouldRunPluginCli(ctx)) {
330
421
  registration = runPluginCli('add', marketplace.name, ctx);
331
- } catch (registrationError) {
332
- try {
333
- hookCompatibility = restoreCachedHookAdapters(
334
- previousAdapters,
335
- currentHookAdapter(configDir, marketplace.name, plugin),
336
- );
337
- } catch (recoveryError) {
338
- throw new AggregateError(
339
- [registrationError, recoveryError],
340
- `codex plugin add and hook cache recovery both failed`,
341
- );
422
+ hookCompatibility = restoreCachedHookAdapters(
423
+ previousAdapters,
424
+ currentHookAdapter(configDir, marketplace.name, plugin),
425
+ );
426
+ }
427
+ const hookCacheVersions = normalizeHookCacheVersions([
428
+ ...previousVersions,
429
+ plugin.version,
430
+ ]);
431
+ const manifestFile = writeRuntimeManifest(configDir, {
432
+ plugin: { root: plugin.root, version: plugin.version },
433
+ marketplace: { file: marketplace.file, name: marketplace.name },
434
+ agents: agents.installed,
435
+ hookCacheVersions,
436
+ });
437
+ const source = provenance.packageSource(repoRoot);
438
+ const provenanceFile = path.join(configDir, RUNTIME_MANIFEST_DIR, PROVENANCE_FILE);
439
+ const provenanceManifest = provenance.writeProvenance({
440
+ file: provenanceFile,
441
+ adapter: 'codex',
442
+ ...source,
443
+ roots: { plugin: pluginRoot, config: configDir },
444
+ assets: [
445
+ ...provenance.assetRefsForTree('plugin', pluginRoot, {
446
+ exclude: ['.ubp-managed'],
447
+ }),
448
+ ...agents.installed.map((file) => ({ root: 'config', path: path.join('agents', file) })),
449
+ { root: 'config', path: path.join(RUNTIME_MANIFEST_DIR, RUNTIME_MANIFEST_FILE) },
450
+ ],
451
+ contracts: {
452
+ plugin_manifest: { root: 'plugin', path: '.codex-plugin/plugin.json' },
453
+ mcp_registration: { root: 'plugin', path: '.mcp.json' },
454
+ mcp_launcher: { root: 'plugin', path: 'runtime/launch.cjs' },
455
+ native_runtime: { root: 'plugin', path: 'runtime/native-runtime.json' },
456
+ context_envelope_helper: { root: 'plugin', path: 'runtime/hook-context.cjs' },
457
+ hook_event_helper: { root: 'plugin', path: 'runtime/hook-event.cjs' },
458
+ hooks_manifest: { root: 'plugin', path: 'hooks/hooks.json' },
459
+ hook_adapter: { root: 'plugin', path: HOOK_ADAPTER_RELATIVE },
460
+ runtime_manifest: { root: 'config', path: path.join(RUNTIME_MANIFEST_DIR, RUNTIME_MANIFEST_FILE) },
461
+ },
462
+ });
463
+ provenanceManifest.file = provenanceFile;
464
+ legacy = cleanupLegacyConfig(configDir);
465
+ if (movedPrevious) removeTree(backupRoot);
466
+ removeTree(agentStagingConfig);
467
+ return {
468
+ target: configDir,
469
+ plugin,
470
+ agents,
471
+ marketplace,
472
+ registration,
473
+ hookCompatibility,
474
+ legacy,
475
+ manifestFile,
476
+ provenance: provenanceManifest,
477
+ config: { updated: legacy.configUpdated },
478
+ };
479
+ } catch (error) {
480
+ if (published && fs.existsSync(pluginRoot)) removeTree(pluginRoot);
481
+ else if (fs.existsSync(stagingRoot)) removeTree(stagingRoot);
482
+ if (movedPrevious && fs.existsSync(backupRoot)) fs.renameSync(backupRoot, pluginRoot);
483
+ try {
484
+ restoreFiles(snapshots);
485
+ const currentCache = marketplace && plugin
486
+ ? path.join(pluginCacheRoot(configDir, marketplace.name), plugin.version)
487
+ : null;
488
+ if (currentCache && !previousVersions.includes(plugin.version) && fs.existsSync(currentCache)) {
489
+ removeTree(currentCache);
342
490
  }
343
- throw registrationError;
491
+ } finally {
492
+ if (fs.existsSync(agentStagingConfig)) removeTree(agentStagingConfig);
344
493
  }
345
- hookCompatibility = restoreCachedHookAdapters(
346
- previousAdapters,
347
- currentHookAdapter(configDir, marketplace.name, plugin),
348
- );
494
+ throw error;
349
495
  }
350
- const hookCacheVersions = normalizeHookCacheVersions([
351
- ...previousVersions,
352
- plugin.version,
353
- ]);
354
- const manifestFile = writeRuntimeManifest(configDir, {
355
- plugin: { root: plugin.root, version: plugin.version },
356
- marketplace: { file: marketplace.file, name: marketplace.name },
357
- agents: agents.installed,
358
- hookCacheVersions,
359
- });
360
- const source = provenance.packageSource(repoRoot);
361
- const provenanceFile = path.join(configDir, RUNTIME_MANIFEST_DIR, PROVENANCE_FILE);
362
- const provenanceManifest = provenance.writeProvenance({
363
- file: provenanceFile,
364
- adapter: 'codex',
365
- ...source,
366
- roots: { plugin: pluginRoot, config: configDir },
367
- assets: [
368
- ...provenance.assetRefsForTree('plugin', pluginRoot, {
369
- exclude: ['.ubp-managed'],
370
- }),
371
- ...agents.installed.map((file) => ({ root: 'config', path: path.join('agents', file) })),
372
- { root: 'config', path: path.join(RUNTIME_MANIFEST_DIR, RUNTIME_MANIFEST_FILE) },
373
- ],
374
- contracts: {
375
- plugin_manifest: { root: 'plugin', path: '.codex-plugin/plugin.json' },
376
- mcp_registration: { root: 'plugin', path: '.mcp.json' },
377
- mcp_launcher: { root: 'plugin', path: 'runtime/launch.cjs' },
378
- hook_event_helper: { root: 'plugin', path: 'runtime/hook-event.cjs' },
379
- hooks_manifest: { root: 'plugin', path: 'hooks/hooks.json' },
380
- hook_adapter: { root: 'plugin', path: HOOK_ADAPTER_RELATIVE },
381
- runtime_manifest: { root: 'config', path: path.join(RUNTIME_MANIFEST_DIR, RUNTIME_MANIFEST_FILE) },
382
- },
383
- });
384
- provenanceManifest.file = provenanceFile;
385
-
386
- return {
387
- target: configDir,
388
- plugin,
389
- agents,
390
- marketplace,
391
- registration,
392
- hookCompatibility,
393
- legacy,
394
- manifestFile,
395
- provenance: provenanceManifest,
396
- config: { updated: legacy.configUpdated },
397
- };
398
496
  }
399
497
 
400
498
  function doctor(ctx = {}) {
@@ -452,8 +550,7 @@ function doctor(ctx = {}) {
452
550
  }
453
551
  }
454
552
  report.checks.hook_targets = { status: hookTargetsOk ? 'pass' : 'fail' };
455
- if (report.status !== 'missing') report.status = report.issues.length === 0 ? 'healthy' : 'degraded';
456
- return report;
553
+ return applyNativeDoctor(report, path.join(pluginRoot, 'runtime'));
457
554
  }
458
555
 
459
556
  function removeManagedAgents(configDir, manifest) {
@@ -0,0 +1,372 @@
1
+ 'use strict';
2
+
3
+ /** Build a Grok Build native Ultra Builder Pro plugin. */
4
+
5
+ const fs = require('node:fs');
6
+ const os = require('node:os');
7
+ const path = require('node:path');
8
+ const { spawnSync } = require('node:child_process');
9
+
10
+ const {
11
+ applyNativeDoctor,
12
+ buildMcpRuntime,
13
+ mcpCommand,
14
+ } = require('./_shared/codex-assets.cjs');
15
+ const {
16
+ copyTree,
17
+ ensureDir,
18
+ isManaged,
19
+ markManaged,
20
+ removeTree,
21
+ writeAtomic,
22
+ } = 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
+
38
+ 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
+
43
+ function resolveTarget(ctx = {}) {
44
+ if (ctx.configDir) return path.resolve(ctx.configDir);
45
+ if (ctx.scope === 'global') {
46
+ return path.join(ctx.homeDir || os.homedir(), '.grok');
47
+ }
48
+ return path.join(ctx.cwd || process.cwd(), '.grok');
49
+ }
50
+
51
+ function resolvePluginRoot(ctx = {}) {
52
+ return path.join(resolveTarget(ctx), 'plugins', PLUGIN_NAME);
53
+ }
54
+
55
+ function resolveRepoRoot(ctx = {}) {
56
+ return ctx.repoRoot || path.resolve(__dirname, '..');
57
+ }
58
+
59
+ function copySkills(repoRoot, pluginRoot) {
60
+ const copied = [];
61
+ for (const name of skillsForRuntime('grok')) {
62
+ const source = path.join(repoRoot, 'skills', name);
63
+ if (!fs.existsSync(path.join(source, 'SKILL.md'))) {
64
+ throw new Error(`missing allowlisted Grok skill: ${name}`);
65
+ }
66
+ const files = copyTree(source, path.join(pluginRoot, 'skills', name), {
67
+ transform(buffer, relative) {
68
+ if (!relative.endsWith('.md')) return buffer;
69
+ let text = adaptInteractionGuidance(buffer.toString('utf8'), 'grok');
70
+ if (name === 'ultra-review') {
71
+ text = text.replace(
72
+ /(?:the current host's native|the host-native) bounded-worker\s+mechanism/g,
73
+ 'Grok Build subagents using the installed read-only agent definitions',
74
+ );
75
+ }
76
+ if (relative !== 'SKILL.md') return Buffer.from(text);
77
+ const { fm, body } = parseFrontmatter(text);
78
+ if (!fm) throw new Error(`missing frontmatter in Grok skill: ${name}`);
79
+ const policy = skillPolicy(name);
80
+ return Buffer.from(serializeFrontmatter({
81
+ name,
82
+ description: fm.description,
83
+ 'user-invocable': policy.userInvocable,
84
+ ...(policy.userInvocable ? { 'disable-model-invocation': true } : {}),
85
+ }, body));
86
+ },
87
+ });
88
+ copied.push(...files.map((relative) => path.join(name, relative)));
89
+ }
90
+ return copied;
91
+ }
92
+
93
+ function copyCommands(repoRoot, pluginRoot) {
94
+ const copied = [];
95
+ for (const name of COMMAND_NAMES) {
96
+ const source = path.join(repoRoot, 'commands', `${name}.md`);
97
+ if (!fs.existsSync(source)) throw new Error(`missing Grok command: ${name}.md`);
98
+ const target = path.join(pluginRoot, 'commands', `${name}.md`);
99
+ const text = adaptInteractionGuidance(fs.readFileSync(source, 'utf8'), 'grok');
100
+ writeAtomic(target, text);
101
+ copied.push(`${name}.md`);
102
+ }
103
+ return copied;
104
+ }
105
+
106
+ function copyAgents(repoRoot, pluginRoot) {
107
+ const copied = [];
108
+ const sourceRoot = path.join(repoRoot, 'agents');
109
+ for (const file of fs.readdirSync(sourceRoot).filter((name) => name.endsWith('.md')).sort()) {
110
+ const { fm, body } = parseFrontmatter(
111
+ fs.readFileSync(path.join(sourceRoot, file), 'utf8'),
112
+ );
113
+ if (!fm?.name || !fm?.description) {
114
+ throw new Error(`invalid Grok agent frontmatter: ${file}`);
115
+ }
116
+ const next = { ...fm };
117
+ delete next.model;
118
+ delete next.maxTurns;
119
+ delete next.permissionMode;
120
+ delete next.mcpServers;
121
+ delete next.hooks;
122
+ next.mcpInheritance = 'all';
123
+ const instructions = [
124
+ 'Use the immutable Worker Packet supplied by the parent. Echo its exact packet_digest.',
125
+ 'Do not call Ultra MCP write tools or mutate another worker artifact.',
126
+ '',
127
+ adaptInteractionGuidance(body, 'grok').trim(),
128
+ '',
129
+ ].join('\n');
130
+ writeAtomic(
131
+ path.join(pluginRoot, 'agents', file),
132
+ serializeFrontmatter(next, instructions),
133
+ );
134
+ copied.push(file);
135
+ }
136
+ return copied;
137
+ }
138
+
139
+ function hookCommand(feature, ...args) {
140
+ return {
141
+ type: 'command',
142
+ command: [
143
+ 'python3 "${GROK_PLUGIN_ROOT}/hooks/adapters/grok.py"',
144
+ JSON.stringify(feature),
145
+ ...args.map((arg) => JSON.stringify(arg)),
146
+ ].join(' '),
147
+ timeout: 10,
148
+ };
149
+ }
150
+
151
+ function buildHooksManifest() {
152
+ return {
153
+ description: [
154
+ 'Ultra hooks are observational except for exact managed-file protection.',
155
+ 'Grok ignores SessionStart/PostCompact stdout, so Skills read ultra.context explicitly.',
156
+ ].join(' '),
157
+ hooks: {
158
+ SessionStart: [{
159
+ matcher: 'startup|resume|clear|compact',
160
+ hooks: [hookCommand('health_check.py')],
161
+ }],
162
+ PreToolUse: [{
163
+ matcher: 'Edit|Write|MultiEdit|search_replace|apply_patch',
164
+ hooks: [hookCommand('active_task_context.py')],
165
+ }],
166
+ PreCompact: [{
167
+ matcher: 'manual|auto',
168
+ hooks: [hookCommand('workflow_checkpoint.py')],
169
+ }],
170
+ Stop: [{
171
+ hooks: [hookCommand('pre_stop_check.py')],
172
+ }],
173
+ SubagentStart: [{
174
+ hooks: [hookCommand('subagent_tracker.py', 'start')],
175
+ }],
176
+ SubagentStop: [{
177
+ hooks: [hookCommand('subagent_tracker.py', 'stop')],
178
+ }],
179
+ },
180
+ };
181
+ }
182
+
183
+ function copyHooks(repoRoot, pluginRoot) {
184
+ const copied = [];
185
+ ensureDir(path.join(pluginRoot, 'hooks', 'adapters'));
186
+ for (const name of WORKFLOW_HOOK_FILES) {
187
+ const source = path.join(repoRoot, 'hooks', name);
188
+ if (!fs.existsSync(source)) throw new Error(`missing allowlisted Grok hook: ${name}`);
189
+ fs.copyFileSync(source, path.join(pluginRoot, 'hooks', name));
190
+ copied.push(name);
191
+ }
192
+ fs.copyFileSync(
193
+ path.join(repoRoot, 'hooks', 'adapters', 'grok.py'),
194
+ path.join(pluginRoot, 'hooks', 'adapters', 'grok.py'),
195
+ );
196
+ copied.push(path.join('adapters', 'grok.py'));
197
+ writeAtomic(
198
+ path.join(pluginRoot, 'hooks', 'hooks.json'),
199
+ `${JSON.stringify(buildHooksManifest(), null, 2)}\n`,
200
+ );
201
+ return copied;
202
+ }
203
+
204
+ function writeManifests(repoRoot, pluginRoot, runtime) {
205
+ const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
206
+ const repository = typeof pkg.repository === 'string'
207
+ ? pkg.repository.replace(/^git\+/, '').replace(/\.git$/, '')
208
+ : String(pkg.repository?.url || '').replace(/^git\+/, '').replace(/\.git$/, '');
209
+ writeAtomic(path.join(pluginRoot, 'plugin.json'), `${JSON.stringify({
210
+ name: PLUGIN_NAME,
211
+ version: pkg.version,
212
+ description: 'Grok Build native Ultra workflows, Worker Packets, observational hooks, and a project-local MCP safety kernel.',
213
+ author: { name: typeof pkg.author === 'string' ? pkg.author : 'Ultra Builder Pro contributors' },
214
+ homepage: pkg.homepage,
215
+ repository,
216
+ license: pkg.license || 'MIT',
217
+ }, null, 2)}\n`);
218
+ const command = mcpCommand(runtime.launcher);
219
+ writeAtomic(path.join(pluginRoot, '.mcp.json'), `${JSON.stringify({
220
+ mcpServers: {
221
+ [MCP_SERVER_NAME]: {
222
+ type: 'stdio',
223
+ command: command.command,
224
+ args: command.args,
225
+ },
226
+ },
227
+ }, null, 2)}\n`);
228
+ }
229
+
230
+ function validatePlugin(pluginRoot, ctx = {}) {
231
+ const binary = ctx.grokBin || path.join(
232
+ ctx.homeDir || os.homedir(),
233
+ '.grok',
234
+ 'bin',
235
+ process.platform === 'win32' ? 'grok.exe' : 'grok',
236
+ );
237
+ if (!fs.existsSync(binary)) return { status: 'unavailable', binary };
238
+ const result = spawnSync(binary, ['plugin', 'validate', pluginRoot], {
239
+ encoding: 'utf8',
240
+ timeout: 30_000,
241
+ });
242
+ if (result.error) throw result.error;
243
+ if (result.status !== 0) {
244
+ throw new Error(
245
+ `grok plugin validate failed: ${(result.stderr || result.stdout || '').trim()}`,
246
+ );
247
+ }
248
+ return { status: 'pass', binary, output: (result.stdout || '').trim() };
249
+ }
250
+
251
+ function buildStaging(repoRoot, staging, ctx) {
252
+ const copied = {
253
+ commands: copyCommands(repoRoot, staging),
254
+ skills: copySkills(repoRoot, staging),
255
+ agents: copyAgents(repoRoot, staging),
256
+ hooks: copyHooks(repoRoot, staging),
257
+ };
258
+ const runtime = buildMcpRuntime(repoRoot, staging, { runtime: 'grok' });
259
+ writeManifests(repoRoot, staging, runtime);
260
+ if (fs.existsSync(path.join(repoRoot, 'LICENSE'))) {
261
+ fs.copyFileSync(path.join(repoRoot, 'LICENSE'), path.join(staging, 'LICENSE'));
262
+ }
263
+ markManaged(staging, { adapter: 'grok', plugin: PLUGIN_NAME });
264
+ const validation = validatePlugin(staging, ctx);
265
+ return { copied, validation };
266
+ }
267
+
268
+ function writeProvenance(repoRoot, pluginRoot) {
269
+ const source = provenance.packageSource(repoRoot);
270
+ const file = path.join(pluginRoot, PROVENANCE_FILE);
271
+ const manifest = provenance.writeProvenance({
272
+ file,
273
+ adapter: 'grok',
274
+ ...source,
275
+ roots: { plugin: pluginRoot },
276
+ assets: provenance.assetRefsForTree('plugin', pluginRoot, {
277
+ exclude: ['.ubp-managed', PROVENANCE_FILE],
278
+ }),
279
+ contracts: {
280
+ plugin_manifest: { root: 'plugin', path: 'plugin.json' },
281
+ mcp_registration: { root: 'plugin', path: '.mcp.json' },
282
+ mcp_launcher: { root: 'plugin', path: 'runtime/launch.cjs' },
283
+ native_runtime: { root: 'plugin', path: 'runtime/native-runtime.json' },
284
+ context_envelope_helper: { root: 'plugin', path: 'runtime/hook-context.cjs' },
285
+ hooks_manifest: { root: 'plugin', path: 'hooks/hooks.json' },
286
+ hook_adapter: { root: 'plugin', path: path.join('hooks', 'adapters', 'grok.py') },
287
+ },
288
+ });
289
+ return { file, manifest };
290
+ }
291
+
292
+ function install(ctx = {}) {
293
+ const target = resolvePluginRoot(ctx);
294
+ const repoRoot = resolveRepoRoot(ctx);
295
+ if (fs.existsSync(target) && !isManaged(target)) {
296
+ throw new Error(`refusing to replace unmanaged Grok plugin: ${target}`);
297
+ }
298
+ ensureDir(path.dirname(target));
299
+ const staging = fs.mkdtempSync(path.join(path.dirname(target), `${PLUGIN_NAME}-staging-`));
300
+ const backup = `${staging}-previous`;
301
+ let movedPrevious = false;
302
+ let published = false;
303
+ try {
304
+ const built = buildStaging(repoRoot, staging, ctx);
305
+ if (fs.existsSync(target)) {
306
+ fs.renameSync(target, backup);
307
+ movedPrevious = true;
308
+ }
309
+ fs.renameSync(staging, target);
310
+ published = true;
311
+ writeManifests(repoRoot, target, {
312
+ launcher: path.join(target, 'runtime', 'launch.cjs'),
313
+ });
314
+ const provenanceReport = writeProvenance(repoRoot, target);
315
+ if (movedPrevious) removeTree(backup);
316
+ return {
317
+ target,
318
+ ...built,
319
+ provenance: provenanceReport,
320
+ trusted: ctx.scope === 'global',
321
+ reload_required: true,
322
+ };
323
+ } catch (error) {
324
+ if (published && fs.existsSync(target)) removeTree(target);
325
+ else if (fs.existsSync(staging)) removeTree(staging);
326
+ if (movedPrevious && fs.existsSync(backup)) fs.renameSync(backup, target);
327
+ throw error;
328
+ }
329
+ }
330
+
331
+ function doctor(ctx = {}) {
332
+ const target = resolvePluginRoot(ctx);
333
+ const source = provenance.packageSource(resolveRepoRoot(ctx));
334
+ const report = provenance.inspectProvenance({
335
+ file: path.join(target, PROVENANCE_FILE),
336
+ expectedAdapter: 'grok',
337
+ expectedPackageVersion: source.packageInfo.version,
338
+ });
339
+ try {
340
+ const validation = validatePlugin(target, ctx);
341
+ report.checks.plugin_validation = validation;
342
+ } catch (error) {
343
+ report.checks.plugin_validation = { status: 'fail' };
344
+ report.issues.push({ code: 'PLUGIN_MANIFEST_INVALID', message: error.message });
345
+ }
346
+ return applyNativeDoctor(report, path.join(target, 'runtime'));
347
+ }
348
+
349
+ function uninstall(ctx = {}) {
350
+ const target = resolvePluginRoot(ctx);
351
+ const report = { target, removed: {} };
352
+ if (fs.existsSync(target)) {
353
+ if (!isManaged(target)) {
354
+ throw new Error(`refusing to remove unmanaged Grok plugin: ${target}`);
355
+ }
356
+ removeTree(target);
357
+ report.removed.plugin = true;
358
+ }
359
+ return report;
360
+ }
361
+
362
+ module.exports = {
363
+ name: 'grok',
364
+ PLUGIN_NAME,
365
+ MCP_SERVER_NAME,
366
+ buildHooksManifest,
367
+ resolveTarget,
368
+ resolvePluginRoot,
369
+ install,
370
+ doctor,
371
+ uninstall,
372
+ };