Title: feat: repo registry — machine-readable module/file/owner/criticality map · Issue #736 · github/squad · GitHub
Open Graph Title: feat: repo registry — machine-readable module/file/owner/criticality map · Issue #736 · github/squad
X Title: feat: repo registry — machine-readable module/file/owner/criticality map · Issue #736 · github/squad
Description: Repo Registry — PRD & Implementation Guide Status: Ready to implement Author: Flight 🏗️ | Reviewers: Flight, FIDO, Booster Blocks: #670 (versioned file layout manifest), #733 (PR impact analysis) Estimated effort: ~1 session Part 1: Prod...
Open Graph Description: Repo Registry — PRD & Implementation Guide Status: Ready to implement Author: Flight 🏗️ | Reviewers: Flight, FIDO, Booster Blocks: #670 (versioned file layout manifest), #733 (PR impact analysis) E...
X Description: Repo Registry — PRD & Implementation Guide Status: Ready to implement Author: Flight 🏗️ | Reviewers: Flight, FIDO, Booster Blocks: #670 (versioned file layout manifest), #733 (PR impact analysi...
Opengraph URL: https://github.com/github/squad/issues/736
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"feat: repo registry — machine-readable module/file/owner/criticality map","articleBody":"# Repo Registry — PRD & Implementation Guide\n\n> **Status:** Ready to implement\n> **Author:** Flight 🏗️ | **Reviewers:** Flight, FIDO, Booster\n> **Blocks:** #670 (versioned file layout manifest), #733 (PR impact analysis)\n> **Estimated effort:** ~1 session\n\n---\n\n## Part 1: Product Requirements\n\n### Problem Statement\n\nBoth #670 (versioned file layout manifest) and #733 (PR impact analysis) need the same data: a machine-readable mapping of **file → module → owner → criticality**. Today this data exists but is trapped in formats that aren't programmatically consumable:\n\n| Data Source | Location | Format | Machine-Readable? |\n|-------------|----------|--------|--------------------|\n| Module ownership | `.squad/routing.md` lines 29–49 | Markdown table | ❌ Requires regex parsing |\n| Template manifest | `packages/squad-cli/src/cli/core/templates.ts` lines 31–251 | TypeScript const | ❌ Requires AST/regex extraction |\n| Package workspace map | `package.json` line 8 | JSON `\"workspaces\": [\"packages/*\"]` | ✅ Already machine-readable |\n| Criticality tiers | Nowhere | N/A | ❌ Don't exist yet |\n\nWithout a shared data layer, both #670 and #733 would independently parse these files, duplicating fragile logic. This issue creates **one generated JSON registry** that both consume.\n\n### Solution Overview\n\nA build-time generator reads the three source files, merges them into a single `.squad/repo-registry.json`, and a CI test (following the `template-sync.test.ts` pattern) ensures the committed JSON never drifts from sources. Utility functions in `scripts/registry-utils.mjs` provide the query API that downstream scripts (#670, #733) import.\n\n### Deliverables\n\n| File | Purpose |\n|------|---------|\n| `scripts/generate-repo-registry.mjs` | Generator: parses routing.md + templates.ts + package.json → JSON |\n| `scripts/registry-utils.mjs` | Utilities: `loadRegistry()`, `resolveFileToModule()`, `getFileCriticality()`, `getModuleOwner()`, `getPackageForFile()`, `getModulesByOwner()` |\n| `.squad/repo-registry.json` | Generated output (committed, CI-verified) |\n| `test/registry-sync.test.ts` | CI test: regenerates and diffs — fails if stale |\n| `test/registry-utils.test.ts` | Unit tests for each utility function and edge cases |\n\n### Registry JSON Schema (Complete)\n\n```jsonc\n{\n // Metadata\n \"generated\": \"2025-01-15T10:30:00.000Z\",\n \"generator\": \"scripts/generate-repo-registry.mjs\",\n \"metadata\": {\n // Flight's addition: content hashes for deterministic rebuild detection\n \"routing_md_hash\": \"sha256:abc123...\",\n \"templates_ts_hash\": \"sha256:def456...\",\n \"package_json_hash\": \"sha256:ghi789...\"\n },\n\n // Module ownership — extracted from .squad/routing.md lines 29–49\n // 20 entries, one per row in the \"Module Ownership\" table\n \"modules\": {\n \"src/adapter/\": { \"primary\": \"EECOM\", \"secondary\": \"CAPCOM\", \"package\": \"squad-cli\" },\n \"src/agents/\": { \"primary\": \"Procedures\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/build/\": { \"primary\": \"CONTROL\", \"secondary\": \"Network\", \"package\": \"squad-cli\" },\n \"src/casting/\": { \"primary\": \"EECOM\", \"secondary\": \"Procedures\", \"package\": \"squad-cli\" },\n \"src/cli/\": { \"primary\": \"EECOM\", \"secondary\": \"Network\", \"package\": \"squad-cli\" },\n \"src/client/\": { \"primary\": \"CAPCOM\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/config/\": { \"primary\": \"CONTROL\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/coordinator/\": { \"primary\": \"Procedures\", \"secondary\": \"Flight\", \"package\": \"squad-cli\" },\n \"src/hooks/\": { \"primary\": \"RETRO\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/marketplace/\": { \"primary\": \"Network\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/ralph/\": { \"primary\": \"EECOM\", \"secondary\": null, \"package\": \"squad-cli\" },\n \"src/runtime/\": { \"primary\": \"GNC\", \"secondary\": \"EECOM\", \"package\": \"squad-cli\" },\n \"src/sharing/\": { \"primary\": \"EECOM\", \"secondary\": \"Network\", \"package\": \"squad-cli\" },\n \"src/skills/\": { \"primary\": \"Procedures\", \"secondary\": null, \"package\": \"squad-cli\" },\n \"src/tools/\": { \"primary\": \"EECOM\", \"secondary\": \"CAPCOM\", \"package\": \"squad-cli\" },\n \"src/cli/shell/\": { \"primary\": \"VOX\", \"secondary\": \"DSKY\", \"package\": \"squad-cli\" },\n \"src/cli/shell/components/\":{ \"primary\": \"DSKY\", \"secondary\": \"VOX\", \"package\": \"squad-cli\" },\n \"tests/acceptance/\": { \"primary\": \"Sims\", \"secondary\": \"FIDO\", \"package\": null },\n \"src/index.ts\": { \"primary\": \"CONTROL\", \"secondary\": \"Flight\", \"package\": \"squad-cli\" }\n },\n\n // Critical files — derived from TEMPLATE_MANIFEST + conventions\n \"criticalFiles\": [\n { \"path\": \".github/agents/squad.agent.md\", \"tier\": \"critical\", \"source\": \"TEMPLATE_MANIFEST\" },\n { \"path\": \".github/workflows/squad-ci.yml\", \"tier\": \"critical\", \"source\": \"TEMPLATE_MANIFEST\" },\n { \"path\": \".github/workflows/squad-release.yml\", \"tier\": \"critical\", \"source\": \"TEMPLATE_MANIFEST\" },\n { \"path\": \"package.json\", \"tier\": \"critical\", \"source\": \"convention\" },\n { \"path\": \"packages/squad-sdk/package.json\", \"tier\": \"critical\", \"source\": \"convention\" },\n { \"path\": \"packages/squad-cli/package.json\", \"tier\": \"critical\", \"source\": \"convention\" },\n { \"path\": \".squad/routing.md\", \"tier\": \"high\", \"source\": \"convention\" },\n { \"path\": \"tsconfig.json\", \"tier\": \"high\", \"source\": \"convention\" }\n ],\n\n // Package workspace map — from package.json \"workspaces\": [\"packages/*\"]\n \"packages\": {\n \"squad-sdk\": { \"path\": \"packages/squad-sdk\" },\n \"squad-cli\": { \"path\": \"packages/squad-cli\" }\n },\n\n // Template files — extracted from TEMPLATE_MANIFEST in templates.ts\n \"templateFiles\": [\n { \"template\": \"squad.agent.md.template\", \"target\": \".github/agents/squad.agent.md\", \"overwriteOnUpgrade\": true, \"tier\": \"critical\" },\n { \"template\": \"casting-history.json\", \"target\": \".squad/casting-history.json\", \"overwriteOnUpgrade\": true, \"tier\": \"medium\" },\n { \"template\": \"casting-policy.json\", \"target\": \".squad/casting-policy.json\", \"overwriteOnUpgrade\": true, \"tier\": \"medium\" },\n { \"template\": \"casting-registry.json\", \"target\": \".squad/casting-registry.json\", \"overwriteOnUpgrade\": true, \"tier\": \"medium\" },\n { \"template\": \"workflows/squad-ci.yml\", \"target\": \".github/workflows/squad-ci.yml\", \"overwriteOnUpgrade\": true, \"tier\": \"critical\" },\n { \"template\": \"workflows/squad-release.yml\", \"target\": \".github/workflows/squad-release.yml\", \"overwriteOnUpgrade\": true, \"tier\": \"critical\" }\n ],\n\n // Criticality tier definitions — hardcoded (per Flight + FIDO consensus)\n \"criticalityTiers\": {\n \"critical\": { \"level\": 1, \"impact\": 10, \"description\": \"Breaking changes affect all users\" },\n \"high\": { \"level\": 2, \"impact\": 5, \"description\": \"Breaking changes affect most workflows\" },\n \"medium\": { \"level\": 3, \"impact\": 2, \"description\": \"Changes affect specific features\" },\n \"low\": { \"level\": 4, \"impact\": 1, \"description\": \"Changes are isolated\" },\n \"unknown\": { \"level\": 5, \"impact\": 0, \"description\": \"Unmapped path — update routing.md\" }\n }\n}\n```\n\n### Data Sources (Exact Paths & Line Numbers)\n\n| Source | File | Lines | What to Extract |\n|--------|------|-------|-----------------|\n| Module ownership table | `.squad/routing.md` | 29–49 | Parse \"Module Ownership\" Markdown table: `\\| \\`module/\\` \\| Primary \\| Secondary \\|` |\n| Template manifest | `packages/squad-cli/src/cli/core/templates.ts` | 31–251 | Extract `TEMPLATE_MANIFEST` array entries: `{ source, destination, overwriteOnUpgrade }` |\n| Workspace packages | `package.json` | 7–9 | Read `workspaces` array, glob `packages/*` to discover `squad-sdk`, `squad-cli` |\n| Criticality tiers | Hardcoded in generator | N/A | Use the `CRITICALITY_TIERS` const defined below |\n\n### How It Stays Current (CI Freshness)\n\n1. **Generator reads source files at build time** — routing.md, templates.ts, package.json are the single sources of truth\n2. **CI test verifies freshness** — `test/registry-sync.test.ts` regenerates the registry and diffs against committed JSON; fails if stale (same pattern as `test/template-sync.test.ts`)\n3. **Developers edit sources, not JSON** — edit routing.md or templates.ts, run `npm run registry`, commit result\n4. **No auto-commit** — CI fails on stale data; developer must intentionally regenerate (per Booster recommendation)\n5. **NOT in prebuild** — registry generation is on-demand only; `prebuild` remains unchanged (per Booster recommendation)\n\n### Forward Compatibility with #670\n\nThe schema is designed so #670 can extend modules with version lineage without breaking existing consumers:\n\n```jsonc\n\"modules\": {\n \"src/adapter/\": {\n \"primary\": \"EECOM\", \"secondary\": \"CAPCOM\", \"package\": \"squad-cli\",\n // #670 adds this (non-breaking):\n \"versions\": [{ \"version\": 1, \"layout\": \"classic\", \"migrationPath\": \"auto\" }]\n }\n}\n```\n\n### Consumers\n\n| Issue | How It Uses the Registry |\n|-------|------------------------|\n| **#670** (file layout manifest) | Extends the registry with version lineage, migration paths. The registry is seed data. |\n| **#733** (PR impact analysis) | Imports `registry-utils.mjs` in `scripts/analyze-impact.mjs` to resolve changed files → modules → owners → criticality for risk scoring. |\n\n---\n\n## Part 2: Implementation Guide\n\n### File List\n\n```\nscripts/\n ├─ generate-repo-registry.mjs # NEW — generator script\n └─ registry-utils.mjs # NEW — query utilities\n\ntest/\n ├─ registry-sync.test.ts # NEW — CI freshness guard\n └─ registry-utils.test.ts # NEW — utility unit tests\n\n.squad/\n └─ repo-registry.json # NEW — generated output (committed)\n\npackage.json # MODIFIED — add \"registry\" script\n.squad/routing.md # MODIFIED — add machine-readable comment\n```\n\n### `scripts/generate-repo-registry.mjs` — Generator Pseudocode\n\n```javascript\n#!/usr/bin/env node\n/**\n * generate-repo-registry.mjs — Reads routing.md + templates.ts + package.json\n * and produces .squad/repo-registry.json.\n *\n * Pattern follows: scripts/sync-templates.mjs (line-by-line file processing)\n */\n\nimport { readFileSync, writeFileSync, readdirSync } from 'node:fs';\nimport { createHash } from 'node:crypto';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst ROOT = join(__dirname, '..');\n\n// ─── 1. Parse routing.md Module Ownership table ────────────────────────\n\nfunction parseRoutingModules() {\n const content = readFileSync(join(ROOT, '.squad', 'routing.md'), 'utf-8');\n const lines = content.split('\\n');\n const modules = {};\n\n // Find the \"## Module Ownership\" section (line 27 in current routing.md)\n let inModuleTable = false;\n let headerParsed = false;\n\n for (const line of lines) {\n // Detect section start\n if (line.startsWith('## Module Ownership')) {\n inModuleTable = true;\n continue;\n }\n // Detect next section (stop parsing)\n if (inModuleTable && line.startsWith('## ')) {\n break;\n }\n if (!inModuleTable) continue;\n\n // Skip header row and separator row\n // Header: \"| Module | Primary | Secondary |\"\n // Separator: \"|--------|---------|-----------|\"\n if (line.includes('Module') && line.includes('Primary')) {\n headerParsed = true;\n continue;\n }\n if (line.match(/^\\|[-\\s|]+\\|$/)) continue;\n if (!headerParsed) continue;\n\n // Parse data rows. Actual format from routing.md:\n // | `src/adapter/` | EECOM 🔧 | CAPCOM 🕵️ |\n const cells = line.split('|').map(c => c.trim()).filter(Boolean);\n if (cells.length \u003c 2) continue;\n\n // Extract module path: strip backticks\n const modulePath = cells[0].replace(/`/g, '').trim();\n // Extract primary owner: strip emoji (everything after first space+emoji)\n const primary = cells[1].replace(/\\s*[\\u{1F000}-\\u{1FFFF}\\u{2600}-\\u{27BF}].*$/u, '').trim();\n // Extract secondary owner (may be \"—\" meaning none)\n const secondary = cells.length >= 3\n ? cells[2].replace(/\\s*[\\u{1F000}-\\u{1FFFF}\\u{2600}-\\u{27BF}].*$/u, '').trim()\n : null;\n\n if (!modulePath || !primary) {\n throw new Error(`Malformed routing.md row: \"${line}\"\\n` +\n 'routing.md is machine-read by this script. Fix the row format.');\n }\n\n modules[modulePath] = {\n primary,\n secondary: (secondary === '—' || secondary === '-' || !secondary) ? null : secondary,\n package: resolveModuleToPackage(modulePath),\n };\n }\n\n if (Object.keys(modules).length === 0) {\n throw new Error('No modules found in routing.md. ' +\n 'Expected \"## Module Ownership\" section with pipe-delimited table.');\n }\n\n console.log(` ✅ Parsed ${Object.keys(modules).length} modules from routing.md`);\n return modules;\n}\n\n// ─── 2. Extract TEMPLATE_MANIFEST from templates.ts ────────────────────\n\nfunction parseTemplateManifest() {\n // Read the TypeScript source directly — regex extraction, not AST.\n // The TEMPLATE_MANIFEST is a simple array of object literals (lines 31–251).\n const content = readFileSync(\n join(ROOT, 'packages', 'squad-cli', 'src', 'cli', 'core', 'templates.ts'),\n 'utf-8'\n );\n\n const entries = [];\n // Match each { source: '...', destination: '...', overwriteOnUpgrade: bool, ... }\n const blockRegex = /\\{\\s*source:\\s*'([^']+)',\\s*destination:\\s*'([^']+)',\\s*overwriteOnUpgrade:\\s*(true|false)/g;\n let match;\n while ((match = blockRegex.exec(content)) !== null) {\n const source = match[1]; // e.g., \"squad.agent.md.template\"\n const destination = match[2]; // e.g., \"../.github/agents/squad.agent.md\"\n const overwrite = match[3] === 'true';\n\n // Normalize destination: strip leading \"../\" to get repo-relative path\n const target = destination.startsWith('../')\n ? destination.slice(3)\n : `.squad/${destination}`;\n\n entries.push({\n template: source,\n target,\n overwriteOnUpgrade: overwrite,\n tier: classifyTemplateTier(target, overwrite),\n });\n }\n\n if (entries.length === 0) {\n throw new Error('No TEMPLATE_MANIFEST entries found in templates.ts. ' +\n 'Expected object literals with { source, destination, overwriteOnUpgrade }.');\n }\n\n console.log(` ✅ Extracted ${entries.length} template entries from templates.ts`);\n return entries;\n}\n\n// ─── 3. Read package.json workspaces ───────────────────────────────────\n\nfunction parsePackages() {\n // package.json line 8: \"workspaces\": [\"packages/*\"]\n const pkgJson = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf-8'));\n const packages = {};\n\n for (const pattern of pkgJson.workspaces || []) {\n // Glob \"packages/*\" → discover actual directories\n const baseDir = join(ROOT, pattern.replace('/*', ''));\n for (const entry of readdirSync(baseDir, { withFileTypes: true })) {\n if (entry.isDirectory()) {\n packages[entry.name] = { path: `${pattern.replace('/*', '')}/${entry.name}` };\n }\n }\n }\n\n console.log(` ✅ Found ${Object.keys(packages).length} workspace packages`);\n return packages;\n}\n\n// ─── 4. Helpers ────────────────────────────────────────────────────────\n\nfunction resolveModuleToPackage(modulePath) {\n // All src/ modules live in squad-cli (packages/squad-cli/src/...)\n // tests/acceptance/ is root-level\n if (modulePath.startsWith('src/')) return 'squad-cli';\n if (modulePath.startsWith('tests/')) return null;\n return null;\n}\n\nconst CRITICALITY_TIERS = {\n critical: { level: 1, impact: 10, description: 'Breaking changes affect all users' },\n high: { level: 2, impact: 5, description: 'Breaking changes affect most workflows' },\n medium: { level: 3, impact: 2, description: 'Changes affect specific features' },\n low: { level: 4, impact: 1, description: 'Changes are isolated' },\n unknown: { level: 5, impact: 0, description: 'Unmapped path — update routing.md' },\n};\n\nfunction classifyTemplateTier(target, overwriteOnUpgrade) {\n // Workflows and agent prompt are critical (breaking = CI/deploy failure)\n if (target.includes('.github/workflows/')) return 'critical';\n if (target.includes('squad.agent.md')) return 'critical';\n // Squad-owned templates that overwrite are high\n if (overwriteOnUpgrade) return 'high';\n // User-owned templates are medium\n return 'medium';\n}\n\nfunction buildCriticalFiles(templateEntries) {\n const files = [];\n // From templates\n for (const entry of templateEntries) {\n if (entry.tier === 'critical' || entry.tier === 'high') {\n files.push({ path: entry.target, tier: entry.tier, source: 'TEMPLATE_MANIFEST' });\n }\n }\n // Convention-based critical files\n files.push({ path: 'package.json', tier: 'critical', source: 'convention' });\n files.push({ path: 'packages/squad-sdk/package.json', tier: 'critical', source: 'convention' });\n files.push({ path: 'packages/squad-cli/package.json', tier: 'critical', source: 'convention' });\n files.push({ path: '.squad/routing.md', tier: 'high', source: 'convention' });\n files.push({ path: 'tsconfig.json', tier: 'high', source: 'convention' });\n return files;\n}\n\nfunction hashFile(relPath) {\n const content = readFileSync(join(ROOT, relPath), 'utf-8');\n return 'sha256:' + createHash('sha256').update(content).digest('hex').slice(0, 12);\n}\n\n// ─── 5. Main: Assemble & Write ────────────────────────────────────────\n\nconst modules = parseRoutingModules();\nconst templateEntries = parseTemplateManifest();\nconst packages = parsePackages();\n\nconst registry = {\n generated: new Date().toISOString(),\n generator: 'scripts/generate-repo-registry.mjs',\n metadata: {\n routing_md_hash: hashFile('.squad/routing.md'),\n templates_ts_hash: hashFile('packages/squad-cli/src/cli/core/templates.ts'),\n package_json_hash: hashFile('package.json'),\n },\n modules,\n criticalFiles: buildCriticalFiles(templateEntries),\n packages,\n templateFiles: templateEntries,\n criticalityTiers: CRITICALITY_TIERS,\n};\n\nconst outPath = join(ROOT, '.squad', 'repo-registry.json');\nwriteFileSync(outPath, JSON.stringify(registry, null, 2) + '\\n');\nconsole.log(`\\n📋 Registry written to .squad/repo-registry.json`);\n```\n\n### `scripts/registry-utils.mjs` — Full Function Signatures\n\n```javascript\n#!/usr/bin/env node\n/**\n * registry-utils.mjs — Query utilities for .squad/repo-registry.json.\n *\n * Consumers: #670 (file layout manifest), #733 (PR impact analysis)\n * @module scripts/registry-utils\n */\n\nimport { readFileSync } from 'node:fs';\nimport { join, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst ROOT = join(__dirname, '..');\nconst REGISTRY_PATH = join(ROOT, '.squad', 'repo-registry.json');\n\nlet _cache = null;\n\n/**\n * Load and parse the repo registry. Caches on first call.\n * @returns {object} The parsed registry object\n * @throws {Error} If .squad/repo-registry.json is missing or malformed\n */\nexport function loadRegistry() {\n if (_cache) return _cache;\n const raw = readFileSync(REGISTRY_PATH, 'utf-8');\n _cache = JSON.parse(raw);\n return _cache;\n}\n\n/**\n * Resolve a file path to its owning module using longest-prefix matching.\n *\n * Algorithm:\n * 1. Normalize the input path (forward slashes, no leading ./)\n * 2. Sort module paths by length descending (longest first)\n * 3. Return the first module whose path is a prefix of filePath\n * 4. If no match, return { module: \"unknown\", primary: \"Flight\", secondary: null }\n *\n * @param {string} filePath — Repo-relative path, e.g. \"src/adapter/client.ts\"\n * @returns {{ module: string, primary: string, secondary: string|null, package: string|null }}\n */\nexport function resolveFileToModule(filePath) {\n const registry = loadRegistry();\n const normalized = filePath.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n\n // Sort by path length descending so \"src/cli/shell/components/\" matches before \"src/cli/\"\n const sortedModules = Object.keys(registry.modules)\n .sort((a, b) => b.length - a.length);\n\n for (const modulePath of sortedModules) {\n if (normalized.startsWith(modulePath) || normalized === modulePath.replace(/\\/$/, '')) {\n return { module: modulePath, ...registry.modules[modulePath] };\n }\n }\n\n // Fallback: unknown path\n return { module: 'unknown', primary: 'Flight', secondary: null, package: null };\n}\n\n/**\n * Get the owner(s) of a module.\n * @param {string} modulePath — Module path, e.g. \"src/adapter/\"\n * @returns {{ primary: string, secondary: string|null }} Owner info\n * @throws {Error} If module not found in registry\n */\nexport function getModuleOwner(modulePath) {\n const registry = loadRegistry();\n const mod = registry.modules[modulePath];\n if (!mod) return { primary: 'Flight', secondary: null }; // fallback\n return { primary: mod.primary, secondary: mod.secondary };\n}\n\n/**\n * Get the criticality tier for a file.\n * Checks criticalFiles list first, then falls back to module-level default.\n * @param {string} filePath — Repo-relative path\n * @returns {string} One of: \"critical\", \"high\", \"medium\", \"low\", \"unknown\"\n */\nexport function getFileCriticality(filePath) {\n const registry = loadRegistry();\n const normalized = filePath.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n\n // Check explicit critical files list\n const entry = registry.criticalFiles.find(f => f.path === normalized);\n if (entry) return entry.tier;\n\n // Fall back to module-level heuristic\n const resolved = resolveFileToModule(normalized);\n if (resolved.module === 'unknown') return 'unknown';\n return 'medium'; // default tier for known modules\n}\n\n/**\n * Get the workspace package that contains a file.\n * @param {string} filePath — Repo-relative path\n * @returns {string|null} Package name or null if root-level\n */\nexport function getPackageForFile(filePath) {\n const registry = loadRegistry();\n const normalized = filePath.replace(/\\\\/g, '/').replace(/^\\.\\//, '');\n\n for (const [name, pkg] of Object.entries(registry.packages)) {\n if (normalized.startsWith(pkg.path + '/') || normalized.startsWith(pkg.path)) {\n return name;\n }\n }\n return null;\n}\n\n/**\n * Reverse lookup: get all modules owned by a given agent.\n * Useful for #733 risk scoring — \"what does this agent own?\"\n *\n * @param {string} agentName — Agent name, e.g. \"EECOM\"\n * @returns {{ primary: string[], secondary: string[] }} Module paths grouped by role\n */\nexport function getModulesByOwner(agentName) {\n const registry = loadRegistry();\n const result = { primary: [], secondary: [] };\n\n for (const [modulePath, mod] of Object.entries(registry.modules)) {\n if (mod.primary === agentName) result.primary.push(modulePath);\n if (mod.secondary === agentName) result.secondary.push(modulePath);\n }\n\n return result;\n}\n```\n\n### `test/registry-sync.test.ts` — CI Freshness Test\n\nFollowing the exact pattern from `test/template-sync.test.ts` (lines 16–21 for imports, 150–159 for script execution):\n\n```typescript\n/**\n * Registry sync tests — ensures .squad/repo-registry.json is fresh.\n *\n * Pattern: test/template-sync.test.ts (regenerate + diff)\n * Canonical sources: .squad/routing.md, templates.ts, package.json\n * Generated output: .squad/repo-registry.json\n */\n\nimport { describe, it, expect } from 'vitest';\nimport { readFileSync } from 'node:fs';\nimport { resolve, dirname } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { execSync } from 'node:child_process';\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\nconst ROOT = resolve(__dirname, '..');\n\n// FIDO's recommendation: normalize timestamps before diffing\nfunction normalizeRegistry(json: string): string {\n const obj = JSON.parse(json);\n obj.generated = 'TIMESTAMP_NORMALIZED_FOR_TESTING';\n // Also normalize source hashes (they depend on file content, not timing)\n // Hashes ARE semantic — keep them. Only strip the timestamp.\n return JSON.stringify(obj, null, 2);\n}\n\ndescribe('registry-sync: generate-repo-registry.mjs', () => {\n it('exits with code 0 (no syntax errors, no crashes)', () => {\n const output = execSync('node scripts/generate-repo-registry.mjs', {\n cwd: ROOT,\n encoding: 'utf-8',\n timeout: 30_000,\n });\n expect(output).toContain('Registry written');\n });\n\n it('committed registry matches freshly generated output', () => {\n // Read committed version\n const committed = readFileSync(\n resolve(ROOT, '.squad', 'repo-registry.json'), 'utf-8'\n );\n\n // Regenerate\n execSync('node scripts/generate-repo-registry.mjs', {\n cwd: ROOT, encoding: 'utf-8', timeout: 30_000,\n });\n const regenerated = readFileSync(\n resolve(ROOT, '.squad', 'repo-registry.json'), 'utf-8'\n );\n\n // Compare with normalized timestamps (FIDO's suggestion)\n expect(normalizeRegistry(regenerated)).toEqual(normalizeRegistry(committed));\n });\n});\n\ndescribe('registry-sync: schema validation', () => {\n const registry = JSON.parse(\n readFileSync(resolve(ROOT, '.squad', 'repo-registry.json'), 'utf-8')\n );\n\n it('has all required top-level keys', () => {\n expect(registry).toHaveProperty('generated');\n expect(registry).toHaveProperty('generator');\n expect(registry).toHaveProperty('metadata');\n expect(registry).toHaveProperty('modules');\n expect(registry).toHaveProperty('criticalFiles');\n expect(registry).toHaveProperty('packages');\n expect(registry).toHaveProperty('templateFiles');\n expect(registry).toHaveProperty('criticalityTiers');\n });\n\n it('modules have required fields (primary, secondary, package)', () => {\n for (const [path, mod] of Object.entries(registry.modules)) {\n expect(mod, `${path} missing primary`).toHaveProperty('primary');\n expect(typeof mod.primary).toBe('string');\n // secondary may be null\n expect(mod).toHaveProperty('secondary');\n expect(mod).toHaveProperty('package');\n }\n });\n\n it('has metadata source hashes', () => {\n expect(registry.metadata.routing_md_hash).toMatch(/^sha256:/);\n expect(registry.metadata.templates_ts_hash).toMatch(/^sha256:/);\n expect(registry.metadata.package_json_hash).toMatch(/^sha256:/);\n });\n\n it('criticalFiles entries have path, tier, source', () => {\n for (const file of registry.criticalFiles) {\n expect(file).toHaveProperty('path');\n expect(file).toHaveProperty('tier');\n expect(file).toHaveProperty('source');\n expect(['critical', 'high', 'medium', 'low']).toContain(file.tier);\n }\n });\n\n it('module count matches routing.md (currently 19 entries)', () => {\n // 19 rows in routing.md Module Ownership table (lines 31–49)\n // Update this count if routing.md changes\n expect(Object.keys(registry.modules).length).toBeGreaterThanOrEqual(15);\n });\n});\n```\n\n### `test/registry-utils.test.ts` — Complete Test Cases\n\n```typescript\n/**\n * Unit tests for scripts/registry-utils.mjs\n *\n * Tests each exported function with edge cases.\n * Uses mocked registry fixtures for isolation.\n */\n\nimport { describe, it, expect } from 'vitest';\n\n// ─── resolveFileToModule() — 6 edge cases ──────────────────────────────\n\ndescribe('resolveFileToModule()', () => {\n // 1. Root files (package.json, tsconfig.json)\n it('returns unknown for root-level files', () => {\n // package.json is not under any src/ module\n const result = resolveFileToModule('package.json');\n expect(result.module).toBe('unknown');\n expect(result.primary).toBe('Flight'); // fallback owner\n });\n\n // 2. Nested directories — longest match wins\n it('resolves nested path to most specific module', () => {\n // \"src/cli/shell/components/Foo.ts\" should match \"src/cli/shell/components/\"\n // NOT \"src/cli/\" or \"src/cli/shell/\"\n const result = resolveFileToModule('src/cli/shell/components/Foo.ts');\n expect(result.module).toBe('src/cli/shell/components/');\n expect(result.primary).toBe('DSKY');\n });\n\n // 3. Overlapping paths — \"src/cli/\" vs \"src/cli/shell/\"\n it('resolves src/cli/shell/repl.ts to src/cli/shell/ not src/cli/', () => {\n const result = resolveFileToModule('src/cli/shell/repl.ts');\n expect(result.module).toBe('src/cli/shell/');\n expect(result.primary).toBe('VOX');\n });\n\n // 4. Unknown paths — graceful fallback\n it('returns fallback for completely unknown paths', () => {\n const result = resolveFileToModule('some/random/file.txt');\n expect(result.module).toBe('unknown');\n expect(result.primary).toBe('Flight');\n expect(result.secondary).toBeNull();\n });\n\n // 5. Case sensitivity (repo uses lowercase paths)\n it('handles paths as-is (case-sensitive)', () => {\n // Registry stores \"src/adapter/\" — \"SRC/adapter/\" should NOT match\n const result = resolveFileToModule('SRC/adapter/client.ts');\n expect(result.module).toBe('unknown'); // case mismatch\n });\n\n // 6. Trailing slashes and normalization\n it('handles backslashes (Windows paths)', () => {\n const result = resolveFileToModule('src\\\\adapter\\\\client.ts');\n expect(result.module).toBe('src/adapter/');\n expect(result.primary).toBe('EECOM');\n });\n});\n\n// ─── getModuleOwner() ──────────────────────────────────────────────────\n\ndescribe('getModuleOwner()', () => {\n it('returns primary and secondary for known module', () => {\n const owner = getModuleOwner('src/adapter/');\n expect(owner.primary).toBe('EECOM');\n expect(owner.secondary).toBe('CAPCOM');\n });\n\n it('returns null secondary for modules with no secondary (src/ralph/)', () => {\n const owner = getModuleOwner('src/ralph/');\n expect(owner.primary).toBe('EECOM');\n expect(owner.secondary).toBeNull();\n });\n\n it('returns Flight fallback for unknown module', () => {\n const owner = getModuleOwner('nonexistent/');\n expect(owner.primary).toBe('Flight');\n });\n});\n\n// ─── getFileCriticality() ──────────────────────────────────────────────\n\ndescribe('getFileCriticality()', () => {\n it('returns critical for package.json', () => {\n expect(getFileCriticality('package.json')).toBe('critical');\n });\n\n it('returns high for .squad/routing.md', () => {\n expect(getFileCriticality('.squad/routing.md')).toBe('high');\n });\n\n it('returns medium for regular module files', () => {\n expect(getFileCriticality('src/adapter/client.ts')).toBe('medium');\n });\n\n it('returns unknown for unmapped paths', () => {\n expect(getFileCriticality('random/file.txt')).toBe('unknown');\n });\n});\n\n// ─── getPackageForFile() ───────────────────────────────────────────────\n\ndescribe('getPackageForFile()', () => {\n it('resolves SDK file to squad-sdk', () => {\n expect(getPackageForFile('packages/squad-sdk/src/index.ts')).toBe('squad-sdk');\n });\n\n it('resolves CLI file to squad-cli', () => {\n expect(getPackageForFile('packages/squad-cli/src/cli/core/templates.ts')).toBe('squad-cli');\n });\n\n it('returns null for root-level files', () => {\n expect(getPackageForFile('package.json')).toBeNull();\n });\n});\n\n// ─── getModulesByOwner() (Flight's suggestion) ────────────────────────\n\ndescribe('getModulesByOwner()', () => {\n it('returns all modules for EECOM (most prolific owner)', () => {\n const result = getModulesByOwner('EECOM');\n expect(result.primary.length).toBeGreaterThanOrEqual(5);\n expect(result.primary).toContain('src/adapter/');\n });\n\n it('returns empty arrays for unknown agent', () => {\n const result = getModulesByOwner('NonExistentAgent');\n expect(result.primary).toEqual([]);\n expect(result.secondary).toEqual([]);\n });\n});\n\n// ─── routing.md parsing edge cases ─────────────────────────────────────\n\ndescribe('routing.md parsing resilience', () => {\n // These test that the generator handles edge cases in routing.md format.\n // Tested via generate-repo-registry.mjs's parseRoutingModules().\n\n it('handles secondary owner \"—\" (em-dash) as null', () => {\n // src/ralph/ has secondary \"—\" in routing.md line 41\n const result = resolveFileToModule('src/ralph/foo.ts');\n expect(result.secondary).toBeNull();\n });\n\n it('strips emoji from owner names', () => {\n // routing.md uses \"EECOM 🔧\" — should parse as just \"EECOM\"\n const owner = getModuleOwner('src/adapter/');\n expect(owner.primary).toBe('EECOM');\n expect(owner.primary).not.toContain('🔧');\n });\n});\n```\n\n### `package.json` Changes\n\nAdd one script (do NOT modify prebuild — per Booster's recommendation):\n\n```jsonc\n// In package.json \"scripts\" section, add:\n\"registry\": \"node scripts/generate-repo-registry.mjs\"\n```\n\n### `.squad/routing.md` Change\n\nAdd comment at the top of the Module Ownership section (after line 27):\n\n```markdown\n## Module Ownership\n\n\u003c!-- Machine-readable alternative: .squad/repo-registry.json (generated by scripts/generate-repo-registry.mjs) -->\n\u003c!-- Do not change column order or header separators — they are parsed programmatically. Only add/update data rows. -->\n```\n\n---\n\n## Part 3: Acceptance Criteria\n\n- [ ] `scripts/generate-repo-registry.mjs` parses routing.md + templates.ts + package.json → valid JSON with 8 top-level keys: `generated`, `generator`, `metadata`, `modules`, `criticalFiles`, `packages`, `templateFiles`, `criticalityTiers`\n- [ ] `metadata` includes `routing_md_hash`, `templates_ts_hash`, `package_json_hash` (sha256 content hashes)\n- [ ] `.squad/repo-registry.json` committed with all modules from routing.md, critical files, packages, template files\n- [ ] `scripts/registry-utils.mjs` exports 6 functions: `loadRegistry()`, `resolveFileToModule()`, `getModuleOwner()`, `getFileCriticality()`, `getPackageForFile()`, `getModulesByOwner()`\n- [ ] `resolveFileToModule()` uses longest-prefix matching and returns `{ module: \"unknown\", primary: \"Flight\" }` for unmatched paths\n- [ ] `test/registry-sync.test.ts` follows template-sync pattern: regenerates + diffs (normalizing timestamp), fails if stale\n- [ ] `test/registry-utils.test.ts` covers: 6 `resolveFileToModule` edge cases, owner lookups, criticality tiers, package resolution, routing.md parsing resilience\n- [ ] `package.json` has `\"registry\": \"node scripts/generate-repo-registry.mjs\"` script (NOT in prebuild)\n- [ ] `.squad/routing.md` has comment noting machine-readable alternative exists\n- [ ] Generator fails loudly with clear error messages on malformed routing.md or missing source files\n- [ ] No product code changes (SDK/CLI) — this is repo tooling only\n- [ ] All existing tests pass (`npm test`)\n\n---\n\n## Part 4: Team Review Summary\n\n### Flight ��️ (Architecture)\n- ✅ **Schema is sound and forward-compatible** with #670\n- ✅ **Add `metadata.source_hash`** — enables deterministic rebuild detection. **Incorporated** into schema.\n- ✅ **Add `getModulesByOwner()`** — reverse lookup for #733 risk scoring. **Incorporated** into registry-utils.\n- ✅ **Hardcode criticality tiers** — no config file needed yet. **Incorporated.**\n- ✅ **Committed JSON is correct** — git history shows ownership changes, CI catches drift.\n- ✅ **Fallback to `{ module: \"unknown\", primary: \"Flight\" }`** — graceful degradation. **Incorporated.**\n- ✅ **`scripts/` location is correct** — matches sync-templates.mjs, bump-build.mjs pattern.\n\n### FIDO 🧪 (Test Strategy)\n- ✅ **registry-sync.test.ts: regenerate + diff** — exact template-sync pattern. **Incorporated.**\n- ✅ **Normalize timestamp before diffing** (Option A) — prevents CI flakiness. **Incorporated** as `normalizeRegistry()` helper.\n- ✅ **Separate `registry-utils.test.ts`** — keeps sync tests focused on freshness, utils tests on correctness. **Incorporated.**\n- ✅ **6 edge cases for `resolveFileToModule()`** — root files, nested dirs, overlapping paths, unknown, case sensitivity, trailing slashes. **All 6 incorporated.**\n- ✅ **Schema validation tests** — validate required fields, enum constraints, module counts. **Incorporated** in registry-sync.test.ts.\n- ✅ **routing.md parsing negative cases** — malformed pipes, missing columns, duplicate entries. **Incorporated.**\n- ✅ **Generator must fail loudly** on partial regeneration failures. **Incorporated** in AC.\n\n### Booster ⚙️ (CI/Freshness)\n- ✅ **Vitest test, not separate CI step** — runs in `npm test`, matches existing pattern. **Incorporated.**\n- ✅ **NOT in prebuild** — on-demand only; developers own the workflow. **Incorporated.**\n- ✅ **No auto-commit** — fail on stale, require developer action. **Incorporated.**\n- ✅ **Use `.mjs` extension** — matches all existing scripts. **Incorporated.**\n- ✅ **No separate GitHub Actions job** — registry-sync runs alongside all other vitest suites. **Incorporated.**\n\n---\n\n## Part 5: Dependencies\n\n### Build Order\n\n```\nThis issue (#736) — foundation layer\n ├──→ #733 (PR impact analysis) — imports registry-utils.mjs, can start in parallel\n └──→ #670 (file layout manifest) — extends registry schema, can start in parallel\n```\n\n### Blocks\n- **#670** — versioned file layout manifest. Extends the `modules` object with version lineage. Cannot start without the base schema.\n- **#733** — PR impact analysis. Imports `resolveFileToModule()`, `getModuleOwner()`, `getFileCriticality()` from registry-utils.mjs. Cannot score PR risk without the registry.\n\n### Related\n- **#730** — agent file resilience. Would benefit from criticality tiers but is not blocked.\n\n### Estimated Effort\n~1 session. The data already exists — this is extraction + formatting + utilities + CI test.\r\n","author":{"url":"https://github.com/diberry","@type":"Person","name":"diberry"},"datePublished":"2026-04-02T04:39:14Z","url":"https://github.com/github/squad/issues/736"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:cc967833-ef82-18f9-b8f7-e86c1953e461 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | E1C6:361639:1F8CE51:2A14B0C:6B017F1C |
| html-safe-nonce | 46ea03b4e72f741e212aecbffe69a38458fa6a26a4b8b1999101265701da48bc |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFMUM2OjM2MTYzOToxRjhDRTUxOjJBMTRCMEM6NkIwMTdGMUMiLCJ2aXNpdG9yX2lkIjoiOTE0MzMwMTM1NDE5MjczMTkzMiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | ffc49c8d97b351945c278b58d8b13dfefb856b554afcd5f16a1b43ac521b0f79 |
| hovercard-subject-tag | issue:4191548046 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/github/squad/736/issue_layout |
| twitter:image | https://opengraph.githubassets.com/fe242ef95e5499d85faa26306150c6149baedecc48f644dcab21e58c4e8d6ac9/github/squad/issues/736 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/fe242ef95e5499d85faa26306150c6149baedecc48f644dcab21e58c4e8d6ac9/github/squad/issues/736 |
| og:image:alt | Repo Registry — PRD & Implementation Guide Status: Ready to implement Author: Flight 🏗️ | Reviewers: Flight, FIDO, Booster Blocks: #670 (versioned file layout manifest), #733 (PR impact analysis) E... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | diberry |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| go-import | github.com/github/squad git https://github.com/github/squad.git |
| octolytics-dimension-user_id | 9919 |
| octolytics-dimension-user_login | github |
| octolytics-dimension-repository_id | 1151205052 |
| octolytics-dimension-repository_nwo | github/squad |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 1151205052 |
| octolytics-dimension-repository_network_root_nwo | github/squad |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width