heimdall-agent 1.2.0 → 1.4.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.
package/docs/SKILLS.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Heimdall Canonical Skills & Suites Directory
2
2
 
3
- This directory serves as the comprehensive reference manual for Heimdall's **25 Primary Toolkits & Suites (64 modular capabilities)**.
3
+ This directory serves as the reference manual for Heimdall's **30 Primary Toolkits & Suites (69 modular capabilities)**.
4
4
 
5
5
  > **Architecture & Execution**: Each skill module is an isolated directory containing a YAML-frontmattered `SKILL.md`. AI agent harnesses (Google Antigravity, Claude Code, OpenAI Codex CLI) parse frontmatter on startup and dynamically activate instructions via progressive disclosure.
6
6
 
@@ -46,6 +46,10 @@ heimdall update-skill all
46
46
  - [⚡ Herdr Coding Agent Multiplexer & Orchestrator](#herdr)
47
47
  - [⚡ Thermo Architectural & Maintainability Audit](#thermo)
48
48
  - [⚡ PStack Engineering Discipline](#pstack-discipline)
49
+ - [⚡ Google Chrome Modern Web Guidance](#modern-web-guidance)
50
+ - [⚡ MCP Orphan Process Cleanup](#mcp-cleanup)
51
+ - [⚡ MCP Template Resolver & Sync](#mcp-sync)
52
+ - [⚡ Upstream Skill Sync & Triage](#upstream-skill-sync)
49
53
 
50
54
  ---
51
55
 
@@ -68,7 +72,7 @@ heimdall update-skill all
68
72
  * **`systematic-debugging`**: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes ([Contract File](../skills/systematic-debugging/SKILL.md))
69
73
  * **`verification-before-completion`**: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always ([Contract File](../skills/verification-before-completion/SKILL.md))
70
74
  * **`finishing-a-development-branch`**: Use when implementation is complete, all tests pass, and you need to decide how to integrate the work ([Contract File](../skills/finishing-a-development-branch/SKILL.md))
71
- * **`using-git-worktrees`**: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback ([Contract File](../skills/using-git-worktrees/SKILL.md))
75
+ * **`using-git-worktrees`**: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - verifies or creates an isolated workspace via native tools or git worktree fallback ([Contract File](../skills/using-git-worktrees/SKILL.md))
72
76
  * **`requesting-code-review`**: Use when completing tasks, implementing major features, or before merging to verify work meets requirements ([Contract File](../skills/requesting-code-review/SKILL.md))
73
77
  * **`receiving-code-review`**: Use when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation ([Contract File](../skills/receiving-code-review/SKILL.md))
74
78
  * **`using-superpowers`**: Use when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions ([Contract File](../skills/using-superpowers/SKILL.md))
@@ -155,25 +159,25 @@ heimdall update-skill all
155
159
 
156
160
  ## Standalone Power Toolkits
157
161
 
158
- <a id="mattpocock-suite"></a>
159
- ### 📦 Matt Pocock Real Engineering Suite (8 modules)
160
-
161
- - **Upstream Source**: [https://github.com/mattpocock/skills](https://github.com/mattpocock/skills)
162
- - **Suite Type**: Multi-Skill Suite
163
-
164
- #### Included Modules:
165
-
166
- * **`codebase-design`**: Design deep modules (small interfaces hiding large implementations), apply the deletion test, and enforce legitimate seams based on John Ousterhout's *Philosophy of Software Design*. ([Contract File](../skills/codebase-design/SKILL.md))
167
- * **`domain-modeling`**: Extract ubiquitous language, domain models, and record Architecture Decision Records (ADRs) to eliminate terminology drift and document architectural choices. ([Contract File](../skills/domain-modeling/SKILL.md))
168
- * **`improve-codebase-architecture`**: Audit codebase structure, detect circular dependencies, evaluate module coupling, and generate dependency matrix reports. ([Contract File](../skills/improve-codebase-architecture/SKILL.md))
169
- * **`to-spec`**: Formalize requirements and interview outcomes into precise specifications with invariants, error matrices, and user journeys. ([Contract File](../skills/to-spec/SKILL.md))
170
- * **`to-tickets`**: Decompose formal specifications into atomic, dependency-ordered task tickets formatted for subagent task queues. ([Contract File](../skills/to-tickets/SKILL.md))
171
- * **`wayfinder`**: Map problem frontiers across large codebases, separating settled decisions from active frontier tickets and unexplored fog. ([Contract File](../skills/wayfinder/SKILL.md))
172
- * **`grill-me`**: Relentless interview protocol using the Design Tree Frontier, autonomous fact-finding, and Yes-to-Approve recommendation format before implementation begins. ([Contract File](../skills/grill-me/SKILL.md))
173
- * **`handoff`**: Compact session context into pointer-first handoff documents saved to $env:TEMP with mandatory Suggested Skills contracts to eliminate context drift and skill blindness. ([Contract File](../skills/handoff/SKILL.md))
174
-
175
- [↑ Back to top](#toc)
176
-
162
+ <a id="mattpocock-suite"></a>
163
+ ### 📦 Matt Pocock Real Engineering Suite (8 modules)
164
+
165
+ - **Upstream Source**: [https://github.com/mattpocock/skills](https://github.com/mattpocock/skills)
166
+ - **Suite Type**: Multi-Skill Suite
167
+
168
+ #### Included Modules:
169
+
170
+ * **`codebase-design`**: Design deep modules (small interfaces hiding large implementations), apply the deletion test, and enforce legitimate seams based on John Ousterhout's *Philosophy of Software Design*. ([Contract File](../skills/codebase-design/SKILL.md))
171
+ * **`domain-modeling`**: Extract ubiquitous language, domain models, and record Architecture Decision Records (ADRs) to eliminate terminology drift and document architectural choices. ([Contract File](../skills/domain-modeling/SKILL.md))
172
+ * **`improve-codebase-architecture`**: Audit codebase structure, detect circular dependencies, evaluate module coupling, and generate dependency matrix reports. ([Contract File](../skills/improve-codebase-architecture/SKILL.md))
173
+ * **`to-spec`**: Formalize requirements and interview outcomes into precise specifications with invariants, error matrices, and user journeys. ([Contract File](../skills/to-spec/SKILL.md))
174
+ * **`to-tickets`**: Decompose formal specifications into atomic, dependency-ordered task tickets formatted for subagent task queues. ([Contract File](../skills/to-tickets/SKILL.md))
175
+ * **`wayfinder`**: Map problem frontiers across large codebases, separating settled decisions from active frontier tickets and unexplored fog. ([Contract File](../skills/wayfinder/SKILL.md))
176
+ * **`grill-me`**: Relentless interview protocol using the Design Tree Frontier, autonomous fact-finding, and Yes-to-Approve recommendation format before implementation begins. ([Contract File](../skills/grill-me/SKILL.md))
177
+ * **`handoff`**: Compact session context into pointer-first handoff documents saved to $env:TEMP with mandatory Suggested Skills contracts to eliminate context drift and skill blindness. ([Contract File](../skills/handoff/SKILL.md))
178
+
179
+ [↑ Back to top](#toc)
180
+
177
181
  ---
178
182
 
179
183
  <a id="ponytail"></a>
@@ -398,3 +402,60 @@ heimdall update-skill all
398
402
  [↑ Back to top](#toc)
399
403
 
400
404
  ---
405
+
406
+ <a id="ruminate"></a>
407
+ ### ⚡ Ruminate Session Transcript Mining
408
+
409
+ - **Module Name**: `ruminate`
410
+ - **Description**: Mine historical Claude and Gemini session transcripts for correction patterns, repeated preferences, skill trigger failures, agent selection accuracy, doctrine violations, and cross-agent consistency drift. Writes findings as memory files or skill amendments. Use when bootstrapping a brain from existing conversation history or running periodic deep audits.
411
+ - **Upstream Inspiration**: [https://github.com/poteto/brainmaxxing](https://github.com/poteto/brainmaxxing)
412
+ - **Contract File**: [`skills/ruminate/SKILL.md`](../skills/ruminate/SKILL.md)
413
+
414
+ [↑ Back to top](#toc)
415
+
416
+ ---
417
+
418
+ <a id="modern-web-guidance"></a>
419
+ ### ⚡ Google Chrome Modern Web Guidance
420
+
421
+ - **Module Name**: `modern-web-guidance`
422
+ - **Description**: Search and retrieve Google Chrome Modern Web Guidance (Baseline-safe native HTML/CSS/JS APIs, Core Web Vitals, accessibility, and `legacy-scan` frontend modernization).
423
+ - **Upstream Source**: [https://github.com/GoogleChrome/modern-web-guidance](https://github.com/GoogleChrome/modern-web-guidance)
424
+ - **Contract File**: [`skills/modern-web-guidance/SKILL.md`](../skills/modern-web-guidance/SKILL.md)
425
+
426
+ [↑ Back to top](#toc)
427
+
428
+ ---
429
+
430
+ <a id="mcp-cleanup"></a>
431
+ ### ⚡ MCP Orphan Process Cleanup
432
+
433
+ - **Module Name**: `mcp-cleanup`
434
+ - **Description**: Kill orphaned MCP server processes left behind by crashed or closed agent sessions.
435
+ - **Contract File**: [`skills/mcp-cleanup/SKILL.md`](../skills/mcp-cleanup/SKILL.md)
436
+
437
+ [↑ Back to top](#toc)
438
+
439
+ ---
440
+
441
+ <a id="mcp-sync"></a>
442
+ ### ⚡ MCP Template Resolver & Sync
443
+
444
+ - **Module Name**: `mcp-sync`
445
+ - **Description**: Resolve Heimdall MCP template to local paths and sync to agent harness configs.
446
+ - **Contract File**: [`skills/mcp-sync/SKILL.md`](../skills/mcp-sync/SKILL.md)
447
+
448
+ [↑ Back to top](#toc)
449
+
450
+ ---
451
+
452
+ <a id="upstream-skill-sync"></a>
453
+ ### ⚡ Upstream Skill Sync & Triage
454
+
455
+ - **Module Name**: `upstream-skill-sync`
456
+ - **Description**: Audit upstream skill repositories in `config/skills.json` and classify updates via the 3-tier triage rubric (Safe 1:1, Defer/Selective Merge, Reject).
457
+ - **Contract File**: [`skills/upstream-skill-sync/SKILL.md`](../skills/upstream-skill-sync/SKILL.md)
458
+
459
+ [↑ Back to top](#toc)
460
+
461
+ ---
@@ -0,0 +1,60 @@
1
+ # Plan: Upstream Skill Provenance Links & `upstream-skill-sync` Triage Skill
2
+
3
+ ### Plan BLUF
4
+ - **Goal**: Add clickable upstream links to `readme.html` and `README*.md`, classify all 68+ skills by `integrationMode` in `config/skills.json`, and create `skills/upstream-skill-sync/SKILL.md` with a 3-tier update rubric.
5
+ - **Architectural Approach**: Approach A — enrich `config/skills.json` with `integrationMode` (`mirror` | `adapted` | `native`), bind a new `upstream-skill-sync` skill to `orchestrator` and `modernizer`, and surface `upstream` URLs across `readme.html`, `README.md`, and `README.pt-BR.md`.
6
+ - **Risk & Blast Radius**: Low — additive documentation, registry metadata, and one new skill (`68` → `69` modules, `29` → `30` toolkits); verified by `test/catalog-integrity.test.mjs` and `npm test`.
7
+ - **Human Approval Gate**: Required before modifying repository source/config files.
8
+
9
+ ---
10
+
11
+ ## Goal Description
12
+
13
+ Every skill in `config/skills.json` already records an `upstream` repository URL, and `heimdall update-skill <name|all>` prints those URLs. However:
14
+ 1. `readme.html` and `README.md` / `README.pt-BR.md` do not link individual skills or toolkits directly to their original upstream sources.
15
+ 2. Users have no standardized skill or decision rubric to instruct an AI harness to audit upstream repositories and classify changes into **Safe (1:1)**, **Defer / Selective Merge**, or **Not Recommended (Reject)** without overwriting Heimdall-specific customizations (such as `/ruminate` additions in `handoff` and `writing-plans`, BLUF/ASD-STE100 rules, or the Zero Dev-Server Policy).
16
+
17
+ This plan implements **Approach A** (Skill-Driven + Registry Metadata).
18
+
19
+ ---
20
+
21
+ ## Proposed Changes
22
+
23
+ ### 1. Registry Metadata & Triage Rubric (`config/skills.json`)
24
+
25
+ - Add `integrationMode` to every skill entry in `skills`:
26
+ - `"mirror"`: Clean 1:1 upstream skill (safe for direct diffing and 1:1 updates after security scan).
27
+ - `"adapted"`: Upstream skill with Heimdall-specific additions or overrides (e.g., `handoff`, `writing-plans`, `modern-web-guidance`, `ruminate`). Requires selective delta incorporation.
28
+ - `"native"`: Authored inside `heimdall-agent` (e.g., `communication-doctrine`, `mcp-sync`, `mcp-cleanup`, `claude-collaborator`, `gemini-collaborator`, `codex-collaborator`, `upstream-skill-sync`).
29
+ - Register the new `upstream-skill-sync` standalone suite & skill entry (`totalSuites`: `30`, `totalModules`: `69`).
30
+
31
+ ---
32
+
33
+ ### 2. Upstream Sync Skill & Agent Bindings
34
+
35
+ - Create `skills/upstream-skill-sync/SKILL.md` with frontmatter triggers (`"update skills"`, `"sync upstream skills"`, `"check skill updates"`, `"audit upstream"`).
36
+ - Define the 5-step execution workflow in ASD-STE100 syntax:
37
+ 1. **Read Registry**: Load `config/skills.json` and filter by target skill, suite, or `all`.
38
+ 2. **Check Upstream**: Run `git ls-remote <upstream>` or inspect upstream `SKILL.md` / release notes.
39
+ 3. **Security Gate**: Run `snyk-agent-scan` heuristics on fetched upstream diffs to block prompt injection or credential harvesting.
40
+ 4. **Classify via 3-Tier Triage Rubric**:
41
+ - **Tier 1 — Safe (1:1 Replace / Fast-Forward)**: Applies to `"mirror"` skills when upstream adds bugfixes, clearer examples, or new Baseline rules without violating Heimdall doctrine.
42
+ - **Tier 2 — Defer / Selective Merge**: Applies to `"adapted"` skills (or upstream skills overlapping existing Heimdall agents/doctrine). Extract only non-conflicting improvements; preserve `/ruminate` rules, BLUF/STE headers, and Goldfish isolation.
43
+ - **Tier 3 — Not Recommended (Reject / Skip)**: Reject upstream changes that introduce dev-server commands, chatbot closers, vague qualifiers (`ensure`, `properly`), bloated wrappers, or vendor lock-in.
44
+ 5. **Report & Verify**: Output a `Review Verdict` BLUF summary listing each skill's tier, source revision, and `npm test` status.
45
+ - Bind `upstream-skill-sync` in `agents/orchestrator.md` and `agents/modernizer.md`.
46
+
47
+ ---
48
+
49
+ ### 3. Upstream Provenance Links & Documentation Sync
50
+
51
+ - Update `readme.html`: add an `Upstream ↗` link and `mirror` / `adapted` / `native` badge to every skill card, add `upstream-skill-sync`, and update counters (`69` skills, `30` toolkits).
52
+ - Update `README.md` and `README.pt-BR.md`: add clickable upstream links to suite headings and standalone toolkit bullets, add `upstream-skill-sync` to the Standalone Toolkits list and `orchestrator` / `modernizer` rows.
53
+ - Update `docs/SKILLS.md` and run `syncCatalogCounts`.
54
+
55
+ ---
56
+
57
+ ## Verification Plan
58
+
59
+ 1. Run `npm test` (`node --test test/*.test.mjs`) to verify `Catalog and Documentation Count Integrity Sentinel` and `Communication Doctrine (BLUF & STE) Invariants` pass with `69` modules and `30` suites.
60
+ 2. Verify every skill card in `readme.html` has a valid `href="https://..."` upstream link and zero AI-slop buzzwords.
@@ -22,8 +22,8 @@ Universal directives for Google Antigravity, Claude Code, and OpenAI Codex CLI a
22
22
  1. Persona: Identity, core expertise, and voice traits.
23
23
  2. Chronological Rules: Ordered lifecycle steps from initialization to handoff.
24
24
  3. Unmistakable Guardrails: Explicit negative constraints and non-negotiable "If X, do Y" boundaries.
25
- - CANONICAL MODEL NAMES: Anthropic models are strictly 'claude-opus-5-5' (Opus 5.5) and 'claude-sonnet-5' (Sonnet 5). There is NO 'sonnet-5-5' or 'sonnet 5.5' (hallucination trap). Never emit, invoke, or allocate 'claude-sonnet-5-5'.
26
- - COMMUNICATION DISCIPLINE (BLUF & STE): Communication must prioritize zero-latency triage and testable clarity (skills/communication-doctrine). All status reports, review verdicts, and plan overviews must lead with Bottom Line Up Front (BLUF). All procedural execution steps must follow Simplified Technical English (STE): active imperative verbs, <= 20 words per step, zero banned vague qualifiers ('ensure', 'properly', 'appropriately', 'as needed').
25
+ - DYNAMIC MODEL REGISTRY: Resolve authorized model IDs, context limits, and specializations dynamically from `config/models.json` and `playbooks/06-model-registry-matrix.md` (refreshed via `heimdall sync` / `heimdall sync-models`). Never invent unlisted model IDs; route tasks by capability tier across any live registered model family (Anthropic, Google, OpenAI, Zhipu/GLM, Tencent/Hunyuan, Xiaomi/MiMo, etc.).
26
+ - COMMUNICATION DISCIPLINE (BLUF & STE): Apply `skills/communication-doctrine` on EVERY response, status report, review verdict, and plan. Lead with Bottom Line Up Front (BLUF) in the first 1-2 sentences. Write all procedural execution steps in ASD-STE100 Simplified Technical English (STE): active imperative verbs, <= 20 words per step, zero banned vague qualifiers ('ensure', 'properly', 'appropriately', 'gracefully', 'as needed', 'etc.').
27
27
  </core_discipline>
28
28
 
29
29
  <planning_protocol>
@@ -39,7 +39,7 @@ Universal directives for Google Antigravity, Claude Code, and OpenAI Codex CLI a
39
39
  - Generate an authoritative plan strictly following `05-canonical-plan-template.md` (resolved via `playbooks/`, `../playbooks/`, or `../heimdall-agent/playbooks/`).
40
40
  - PLAN STORAGE & LIFECYCLE: All plans MUST be created in `docs/designs/YYYY-MM-DD <plan name>.md`. Once implemented, verified, and confirmed working, the plan is moved to `docs/designs/old/YYYY-MM-DD <plan name>.md`.
41
41
  - The plan MUST specify:
42
- a) Multi-Agent Orchestration & Model Allocation Matrix (allocating tasks across Claude, Gemini, and Codex from `06-model-registry-matrix.md` in the same playbooks directory).
42
+ a) Multi-Agent Orchestration & Model Allocation Matrix (allocating tasks by capability tier across available model families in `06-model-registry-matrix.md` / `config/models.json` — including Claude, Gemini, Codex/GPT, GLM, Hunyuan, MiMo, and newly synced GhostCLI models).
43
43
  b) Symmetric Cross-Model Validation Loop (`herdr agent prompt`) and Non-Interactive Verification Harness.
44
44
  c) Orchestrator Heartbeat (cadence for monitoring task progress and liveness).
45
45
  d) Verification Harness (Non-interactive terminating test suites, static builds, and linters. Playwright E2E strictly against pre-existing human-managed servers or static build previews. NEVER include steps to start a dev server).
@@ -10,6 +10,7 @@ const { execSync } = require('child_process');
10
10
  const os = require('os');
11
11
  const fs = require('fs');
12
12
  const path = require('path');
13
+ const { lookupModelContextFromCatalog } = require('../lib/model-context.cjs');
13
14
 
14
15
  const MAX_STDIN = 1024 * 1024; // 1 MiB
15
16
 
@@ -47,6 +48,15 @@ function getActiveContextLimit() {
47
48
  const parsed = parseInt(process.env.HEIMDALL_ACTIVE_CONTEXT_LIMIT, 10);
48
49
  if (parsed > 0) return parsed;
49
50
  }
51
+ const activeModel =
52
+ process.env.HEIMDALL_ACTIVE_MODEL ||
53
+ process.env.ANTHROPIC_MODEL ||
54
+ process.env.OPENAI_MODEL ||
55
+ process.env.GEMINI_MODEL;
56
+ if (activeModel) {
57
+ const resolved = lookupModelContextFromCatalog(activeModel, path.join(__dirname, '..'));
58
+ if (resolved && resolved.tokens > 0) return resolved.tokens;
59
+ }
50
60
  return 1000000; // 1M default maximum
51
61
  }
52
62
 
@@ -211,9 +221,14 @@ async function main() {
211
221
  break;
212
222
  }
213
223
 
224
+ case 'user-prompt': {
225
+ process.stdout.write('[Heimdall Communication Doctrine] Lead with BLUF (conclusion in first 1-2 sentences). Use ASD-STE100 for procedural steps: active imperative verb first, <=20 words/step, zero banned words (ensure, properly, appropriately, gracefully, as needed, etc.).\n');
226
+ break;
227
+ }
228
+
214
229
  case 'pre-compact': {
215
230
  clearSessionState();
216
- process.stderr.write('[Heimdall Lifecycle Sentinel] Context compaction occurring. Ensure active tasks, rulings, and pending ledger items are preserved on disk.\n');
231
+ process.stderr.write('[Heimdall Lifecycle Sentinel] Context compaction occurring. Verify active tasks, rulings, and pending ledger items are preserved on disk.\n');
217
232
  break;
218
233
  }
219
234
 
package/hooks/hooks.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "description": "Heimdall Sentinel Lifecycle Hooks for Claude Code and AI Harnesses",
3
3
  "hooks": {
4
+ "UserPromptSubmit": [
5
+ {
6
+ "matcher": ".*",
7
+ "hooks": [
8
+ {
9
+ "type": "command",
10
+ "command": "node \"{{HOOKS_DIR}}/heimdall-hook.cjs\" user-prompt"
11
+ }
12
+ ]
13
+ }
14
+ ],
4
15
  "PreToolUse": [
5
16
  {
6
17
  "matcher": "Bash|PowerShell",
@@ -1,5 +1,8 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+
3
6
  /**
4
7
  * Authoritative Canonical Context Mappings (Max Capacity)
5
8
  * Derived from playbooks/06-model-registry-matrix.md
@@ -15,9 +18,19 @@ const CANONICAL_MODEL_CONTEXTS = {
15
18
  // GhostCLI / Custom Proxies (Max extended capacity)
16
19
  'claude-opus-5-5': 1000000,
17
20
  'claude-sonnet-5': 1000000,
21
+ 'claude-sonnet-5-5': 1000000,
18
22
  'claude-fable-5.1': 1000000,
23
+ 'claude-fable-5.2': 1000000,
19
24
  'z-ai/glm-5.3': 1000000,
20
25
  'glm-5.3': 1000000,
26
+ 'z-ai/glm-5.3-flash': 1000000,
27
+ 'glm-5.3-flash': 1000000,
28
+ 'tencent/Hy4-preview': 1000000,
29
+ 'tencent/hy4-preview': 1000000,
30
+ 'hy4-preview': 1000000,
31
+ 'XiaomiMiMo/MiMo-V2.6-Pro': 1000000,
32
+ 'xiaomimimo/mimo-v2.6-pro': 1000000,
33
+ 'mimo-v2.6-pro': 1000000,
21
34
  'gpt-6-astra': 1000000,
22
35
  'astra': 1000000
23
36
  };
@@ -115,9 +128,45 @@ function resolveCustomModelsEndpoint(endpoints = {}) {
115
128
  return null;
116
129
  }
117
130
 
131
+ /**
132
+ * Looks up a model's maximum context window from config/models.json first,
133
+ * falling back to CANONICAL_MODEL_CONTEXTS and the safe 128K default.
134
+ */
135
+ function lookupModelContextFromCatalog(modelId, rootDir) {
136
+ if (!modelId || typeof modelId !== 'string') {
137
+ return normalizeContextTokens(131072);
138
+ }
139
+ const cleanId = modelId.toLowerCase().trim().replace(/\[1m\]$/i, '');
140
+ const shortId = cleanId.split('/').pop();
141
+
142
+ if (rootDir) {
143
+ try {
144
+ const modelsPath = path.join(rootDir, 'config', 'models.json');
145
+ if (fs.existsSync(modelsPath)) {
146
+ const catalog = JSON.parse(fs.readFileSync(modelsPath, 'utf8'));
147
+ const all = [
148
+ ...(catalog.google || []),
149
+ ...(catalog.ghostcli || []),
150
+ ...(catalog.custom_proxies || [])
151
+ ];
152
+ const match = all.find(m => {
153
+ const mId = (m.id || '').toLowerCase().trim();
154
+ return mId === cleanId || mId.split('/').pop() === shortId;
155
+ });
156
+ if (match) {
157
+ return resolveModelMaxContext(match, { prioritizeMax: true });
158
+ }
159
+ }
160
+ } catch {}
161
+ }
162
+
163
+ return resolveModelMaxContext(cleanId, { prioritizeMax: true });
164
+ }
165
+
118
166
  module.exports = {
119
167
  CANONICAL_MODEL_CONTEXTS,
120
168
  normalizeContextTokens,
121
169
  resolveModelMaxContext,
122
- resolveCustomModelsEndpoint
170
+ resolveCustomModelsEndpoint,
171
+ lookupModelContextFromCatalog
123
172
  };
@@ -0,0 +1,294 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { resolveModelMaxContext } = require('./model-context.cjs');
6
+
7
+ /**
8
+ * Infers the model family/vendor from a model ID.
9
+ * Supports Anthropic, Google, OpenAI, Zhipu (GLM), Tencent (Hunyuan), Xiaomi (MiMo),
10
+ * and any future slash-prefixed or named provider.
11
+ */
12
+ function inferModelFamily(modelId) {
13
+ const id = (modelId || '').toLowerCase().trim();
14
+ if (!id) return 'unknown';
15
+ if (id.startsWith('claude-') || id.includes('anthropic')) return 'anthropic';
16
+ if (id.startsWith('gemini-') || id.includes('google')) return 'google';
17
+ if (id.startsWith('gpt-') || id.startsWith('o1') || id.startsWith('o3') || id.startsWith('o4') || id.includes('codex')) return 'openai';
18
+ if (id.startsWith('z-ai/') || id.includes('glm')) return 'z-ai';
19
+ if (id.startsWith('tencent/') || id.includes('hy4') || id.includes('hunyuan')) return 'tencent';
20
+ if (id.startsWith('xiaomimimo/') || id.includes('mimo')) return 'xiaomi';
21
+ if (id.includes('/')) return id.split('/')[0];
22
+ return id.split('-')[0] || 'unknown';
23
+ }
24
+
25
+ /**
26
+ * Classifies a model's capabilities, speed tier, and context capacity
27
+ * from its ID, displayName, description/specialization, and context window.
28
+ */
29
+ function classifyModelCapabilities(model, channel = 'ghostcli') {
30
+ const id = model?.id || model?.slug || '';
31
+ const displayName = model?.displayName || model?.display_name || id;
32
+ const text = `${id} ${displayName} ${model?.description || ''} ${model?.specialization || ''}`.toLowerCase();
33
+ const family = model?.family || inferModelFamily(id);
34
+ const resolvedCtx = resolveModelMaxContext(model, { prioritizeMax: true });
35
+
36
+ const isFast = /flash|fast|rápid|rapido|mini|lite|haiku|instant/.test(text);
37
+ const isUiCreative = /fable|design|ui|story|creative|visual|frontend/.test(text);
38
+ const isReasoning = /opus|pro|astra|reasoning|racioc[ií]nio|architect|frontier|gemini-4|hy4|mimo/.test(text);
39
+ const isAgentic = /agentic|ag[eê]ntic|c[oó]digo|code|sonnet|glm|astra|mimo|hy4/.test(text);
40
+ const isLongContext = resolvedCtx.tokens >= 950000;
41
+
42
+ const traits = new Set();
43
+ if (isFast) traits.add('fast');
44
+ if (isUiCreative) traits.add('ui_creative');
45
+ if (isReasoning) traits.add('deep_reasoning');
46
+ if (isAgentic) traits.add('agentic_coding');
47
+ if (isLongContext) traits.add('long_context');
48
+ if (traits.size === 0) traits.add('general');
49
+
50
+ return {
51
+ id,
52
+ displayName,
53
+ family,
54
+ channel,
55
+ contextLabel: resolvedCtx.label,
56
+ contextTokens: resolvedCtx.tokens,
57
+ description: model?.description || model?.specialization || '',
58
+ traits: [...traits],
59
+ isFast,
60
+ isUiCreative,
61
+ isReasoning,
62
+ isAgentic,
63
+ isLongContext
64
+ };
65
+ }
66
+
67
+ /**
68
+ * Flattens and deduplicates models from config/models.json into classified entries.
69
+ */
70
+ function collectCatalogModels(catalog = {}) {
71
+ const byId = new Map();
72
+ const sources = [
73
+ ['google', catalog.google || []],
74
+ ['ghostcli', catalog.ghostcli || []],
75
+ ['custom_proxies', catalog.custom_proxies || []]
76
+ ];
77
+
78
+ for (const [channel, list] of sources) {
79
+ for (const raw of list) {
80
+ if (!raw || !raw.id) continue;
81
+ if (!byId.has(raw.id)) {
82
+ byId.set(raw.id, classifyModelCapabilities(raw, channel));
83
+ }
84
+ }
85
+ }
86
+ return [...byId.values()];
87
+ }
88
+
89
+ const TIER_SCORING_RULES = {
90
+ deep_reasoning: (m) =>
91
+ (m.isReasoning ? 40 : 0) +
92
+ (m.isAgentic ? 15 : 0) +
93
+ (m.isLongContext ? 10 : 0) +
94
+ (/opus|gemini-4|astra/.test(m.id.toLowerCase()) ? 25 : 0) +
95
+ (m.isFast ? -15 : 0),
96
+ high_polish_vision: (m) =>
97
+ (m.isUiCreative ? 50 : 0) +
98
+ (m.isAgentic ? 20 : 0) +
99
+ (/sonnet|fable|flash|mimo/.test(m.id.toLowerCase()) ? 15 : 0),
100
+ responsive_flex_safety: (m) =>
101
+ (m.isUiCreative ? 35 : 0) +
102
+ (m.isFast ? 20 : 0) +
103
+ (m.isAgentic ? 20 : 0),
104
+ fast_verification: (m) =>
105
+ (m.isFast ? 45 : 0) +
106
+ (m.isAgentic ? 25 : 0) +
107
+ (/flash|sonnet|mimo|glm/.test(m.id.toLowerCase()) ? 15 : 0),
108
+ deep_assurance_audit: (m) =>
109
+ (m.isReasoning ? 45 : 0) +
110
+ (m.isLongContext ? 15 : 0) +
111
+ (/opus|gemini-4|astra|hy4/.test(m.id.toLowerCase()) ? 20 : 0) +
112
+ (m.isFast ? -15 : 0),
113
+ schema_migration_safety: (m) =>
114
+ (m.isReasoning ? 35 : 0) +
115
+ (m.contextTokens >= 1900000 ? 20 : (m.isLongContext ? 10 : 0)) +
116
+ (m.isAgentic ? 20 : 0),
117
+ surgical_restraint: (m) =>
118
+ (m.isFast ? 30 : 0) +
119
+ (m.isAgentic ? 30 : 0) +
120
+ (/sonnet|flash|glm|mimo/.test(m.id.toLowerCase()) ? 15 : 0),
121
+ adversarial_diff_eval: (m) =>
122
+ (m.isReasoning ? 45 : 0) +
123
+ (m.isAgentic ? 20 : 0) +
124
+ (/opus|gemini-4|astra|hy4|mimo/.test(m.id.toLowerCase()) ? 15 : 0),
125
+ legacy_migration_safety: (m) =>
126
+ (m.isLongContext ? 25 : 0) +
127
+ (m.isAgentic ? 25 : 0) +
128
+ (m.isReasoning ? 20 : 0)
129
+ };
130
+
131
+ /**
132
+ * Ranks all available models for a given agent capabilityTier and selects
133
+ * diverse cross-family models for adversarial review.
134
+ */
135
+ function rankModelsForCapabilityTier(capabilityTier, catalog) {
136
+ const models = Array.isArray(catalog) ? catalog : collectCatalogModels(catalog);
137
+ const scorer = TIER_SCORING_RULES[capabilityTier] || TIER_SCORING_RULES.surgical_restraint;
138
+
139
+ const scored = models
140
+ .map(m => ({ model: m, score: scorer(m) }))
141
+ .sort((a, b) => b.score - a.score || b.model.contextTokens - a.model.contextTokens || a.model.id.localeCompare(b.model.id));
142
+
143
+ // Pick top model per distinct family so non-Claude/Gemini/Codex models are surfaced
144
+ const topByFamily = new Map();
145
+ for (const { model } of scored) {
146
+ if (!topByFamily.has(model.family)) {
147
+ topByFamily.set(model.family, model);
148
+ }
149
+ }
150
+
151
+ const recommendedModels = [...topByFamily.values()].slice(0, 6).map(m => m.id);
152
+ const primary = scored[0]?.model;
153
+ const crossReviewers = [...topByFamily.values()]
154
+ .filter(m => !primary || m.family !== primary.family)
155
+ .slice(0, 4)
156
+ .map(m => m.id);
157
+
158
+ const pickFamily = (fam) => topByFamily.get(fam)?.id;
159
+ const vendorPreferences = {};
160
+ if (pickFamily('google')) vendorPreferences.gemini = pickFamily('google');
161
+ if (pickFamily('anthropic')) vendorPreferences.claude = pickFamily('anthropic');
162
+ if (pickFamily('openai')) vendorPreferences.codex = pickFamily('openai');
163
+
164
+ // Include non-legacy families dynamically (z-ai, tencent, xiaomi, etc.)
165
+ for (const [fam, model] of topByFamily.entries()) {
166
+ if (fam !== 'google' && fam !== 'anthropic' && fam !== 'openai') {
167
+ vendorPreferences[fam] = model.id;
168
+ }
169
+ }
170
+ vendorPreferences.default = 'inherit';
171
+
172
+ return { recommendedModels, crossReviewers, vendorPreferences };
173
+ }
174
+
175
+ /**
176
+ * Synchronizes config/agents.json with live models from config/models.json.
177
+ * Returns { modified: boolean, agentCount: number } or null if files are missing.
178
+ */
179
+ function syncAgentsWithModels(rootDir, dryRun = false) {
180
+ const modelsPath = path.join(rootDir, 'config', 'models.json');
181
+ const agentsPath = path.join(rootDir, 'config', 'agents.json');
182
+ if (!fs.existsSync(modelsPath) || !fs.existsSync(agentsPath)) return null;
183
+
184
+ try {
185
+ const catalog = JSON.parse(fs.readFileSync(modelsPath, 'utf8'));
186
+ const classified = collectCatalogModels(catalog);
187
+ if (classified.length === 0) return { modified: false, agentCount: 0 };
188
+
189
+ const rawAgents = fs.readFileSync(agentsPath, 'utf8');
190
+ const agentsConfig = JSON.parse(rawAgents);
191
+ const agentsMap = agentsConfig.agents || {};
192
+
193
+ let modified = false;
194
+ for (const agentDef of Object.values(agentsMap)) {
195
+ const { recommendedModels, crossReviewers, vendorPreferences } =
196
+ rankModelsForCapabilityTier(agentDef.capabilityTier, classified);
197
+
198
+ const nextVendor = JSON.stringify(vendorPreferences);
199
+ const prevVendor = JSON.stringify(agentDef.vendorPreferences || {});
200
+ const nextRec = JSON.stringify(recommendedModels);
201
+ const prevRec = JSON.stringify(agentDef.recommendedModels || []);
202
+ const nextCross = JSON.stringify(crossReviewers);
203
+ const prevCross = JSON.stringify(agentDef.crossReviewers || []);
204
+
205
+ if (nextVendor !== prevVendor || nextRec !== prevRec || nextCross !== prevCross) {
206
+ agentDef.vendorPreferences = vendorPreferences;
207
+ agentDef.recommendedModels = recommendedModels;
208
+ agentDef.crossReviewers = crossReviewers;
209
+ modified = true;
210
+ }
211
+ }
212
+
213
+ if (modified && !dryRun) {
214
+ fs.writeFileSync(agentsPath, JSON.stringify(agentsConfig, null, 2) + '\n', 'utf8');
215
+ }
216
+
217
+ return { modified, agentCount: Object.keys(agentsMap).length };
218
+ } catch {
219
+ return null;
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Builds the Markdown table for Section 2 (GhostCLI Models) from live catalog entries.
225
+ */
226
+ function buildGhostCliMarkdownSection(ghostcliModels) {
227
+ const rows = ghostcliModels.map(m => {
228
+ const c = classifyModelCapabilities(m, 'ghostcli');
229
+ const spec = c.description || c.traits.join(', ');
230
+ const effort = c.isFast ? '`low`, `medium`, `high`' : '`low`, `medium`, `high`, `xhigh`';
231
+ return `| **${c.displayName}** | \`${c.id}\` | ${c.family} | ${c.contextLabel} | ${effort} | ${spec} |`;
232
+ });
233
+
234
+ return [
235
+ '<!-- heimdall:ghostcli-models:start -->',
236
+ 'All GhostCLI models are discovered dynamically via `heimdall sync` / `heimdall sync-models` and stored in `config/models.json`:',
237
+ '',
238
+ '| Model Name | Canonical Flag | Family | Context Window | Allowed Effort Levels | Specialization / Description |',
239
+ '| :--- | :--- | :--- | :--- | :--- | :--- |',
240
+ ...rows,
241
+ '',
242
+ '> [!NOTE]',
243
+ '> **Dynamic Model Registry**: Always resolve live model IDs from `config/models.json` or this table after `heimdall sync` / `heimdall sync-models`. Route tasks by **capability tier** across all available families (Anthropic, Google, OpenAI, GLM, Hunyuan, MiMo, etc.), not only Claude/Gemini/Codex.',
244
+ '<!-- heimdall:ghostcli-models:end -->'
245
+ ].join('\n');
246
+ }
247
+
248
+ /**
249
+ * Synchronizes playbooks/06-model-registry-matrix.md Section 2 with config/models.json.
250
+ * Returns { modified: boolean } or null if files are missing.
251
+ */
252
+ function syncModelRegistryPlaybook(rootDir, dryRun = false) {
253
+ const modelsPath = path.join(rootDir, 'config', 'models.json');
254
+ const playbookPath = path.join(rootDir, 'playbooks', '06-model-registry-matrix.md');
255
+ if (!fs.existsSync(modelsPath) || !fs.existsSync(playbookPath)) return null;
256
+
257
+ try {
258
+ const catalog = JSON.parse(fs.readFileSync(modelsPath, 'utf8'));
259
+ const ghostcliModels = catalog.ghostcli || catalog.custom_proxies || [];
260
+ if (ghostcliModels.length === 0) return { modified: false };
261
+
262
+ const orig = fs.readFileSync(playbookPath, 'utf8');
263
+ const generatedBlock = buildGhostCliMarkdownSection(ghostcliModels);
264
+
265
+ let updated = orig;
266
+ const markerRegex = /<!-- heimdall:ghostcli-models:start -->[\s\S]*?<!-- heimdall:ghostcli-models:end -->/;
267
+ if (markerRegex.test(updated)) {
268
+ updated = updated.replace(markerRegex, generatedBlock);
269
+ } else {
270
+ const sectionRegex = /(## 2\. GhostCLI Models[^\n]*\n\n)[\s\S]*?(\n---\n)/;
271
+ if (sectionRegex.test(updated)) {
272
+ updated = updated.replace(sectionRegex, `$1${generatedBlock}\n$2`);
273
+ }
274
+ }
275
+
276
+ const modified = updated !== orig;
277
+ if (modified && !dryRun) {
278
+ fs.writeFileSync(playbookPath, updated, 'utf8');
279
+ }
280
+
281
+ return { modified };
282
+ } catch {
283
+ return null;
284
+ }
285
+ }
286
+
287
+ module.exports = {
288
+ inferModelFamily,
289
+ classifyModelCapabilities,
290
+ collectCatalogModels,
291
+ rankModelsForCapabilityTier,
292
+ syncAgentsWithModels,
293
+ syncModelRegistryPlaybook
294
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "heimdall-agent",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "Autonomous multi-agent engineering sentinel & bootstrapper. Synchronizes specialized agent personas, curated skills, and universal doctrine across Google Antigravity, Claude Code, OpenAI Codex CLI, Hermes Agent, OpenClaw, and Claude Desktop.",
5
5
  "type": "module",
6
6
  "bin": {