@pieai/pro-gov 0.4.6 → 0.4.8

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/dist/cli.js CHANGED
@@ -1801,14 +1801,7 @@ function applyStarterFiles(files, profile) {
1801
1801
  }
1802
1802
  function renderAgentsTemplate(template, projectName, profile) {
1803
1803
  const selectedRoute = `docs/governance/agents-routing/${profile}-v0.9.md`;
1804
- const profileWorkflowNote = profile === "doc-only" ? "- Engineering test workflows are not enabled by default for this doc-only project." : "";
1805
- return template.replace("# PROJECT_NAME AI Router", `# ${projectName} AI Router`).replace(
1806
- /\d+\. The selected agents routing file:\n - `docs\/governance\/agents-routing\/engineering-runtime-v0\.9\.md`, or\n - `docs\/governance\/agents-routing\/doc-only-v0\.9\.md`/,
1807
- `3. The selected agents routing file: \`${selectedRoute}\``
1808
- ).replace(
1809
- "- Name this project's adopted profile: `engineering-runtime` or `doc-only`.",
1810
- `- This project adopts the \`${profile}\` profile.`
1811
- ).replace("- PROFILE_WORKFLOW_NOTE", profileWorkflowNote).replace(/\n{3,}/g, "\n\n");
1804
+ return template.replace("# PROJECT_NAME AI Router", `# ${projectName} AI Router`).replace("`PROFILE_NAME`", `\`${profile}\``).replace("`PROFILE_ROUTE`", `\`${selectedRoute}\``).replace(/\n{3,}/g, "\n\n");
1812
1805
  }
1813
1806
  function readFlag(args, flag) {
1814
1807
  const index = args.indexOf(flag);
@@ -2792,8 +2785,8 @@ function printUsage3() {
2792
2785
  }
2793
2786
 
2794
2787
  // src/commands/portfolio.ts
2795
- import { existsSync as existsSync21 } from "node:fs";
2796
- import { join as join20 } from "node:path";
2788
+ import { existsSync as existsSync22 } from "node:fs";
2789
+ import { join as join21 } from "node:path";
2797
2790
 
2798
2791
  // src/portfolio/manifest.ts
2799
2792
  import { existsSync as existsSync18, readFileSync as readFileSync12 } from "node:fs";
@@ -3384,6 +3377,492 @@ function deduplicateIssues(issues) {
3384
3377
  });
3385
3378
  }
3386
3379
 
3380
+ // src/portfolio/ai-health.ts
3381
+ import { execFileSync } from "node:child_process";
3382
+ import {
3383
+ cpSync as cpSync2,
3384
+ existsSync as existsSync21,
3385
+ lstatSync as lstatSync6,
3386
+ mkdirSync as mkdirSync8,
3387
+ readFileSync as readFileSync15,
3388
+ readdirSync as readdirSync8,
3389
+ realpathSync as realpathSync2,
3390
+ statSync as statSync4,
3391
+ writeFileSync as writeFileSync7
3392
+ } from "node:fs";
3393
+ import { dirname as dirname12, join as join20, relative as relative8, resolve as resolve4 } from "node:path";
3394
+ import { fileURLToPath as fileURLToPath4 } from "node:url";
3395
+ function inspectPortfolioAiHealth(options) {
3396
+ const endpoints = collectEndpoints(options.manifest);
3397
+ const secretsRoot = options.secretsRoot ?? join20(dirname12(options.manifest.controlPlane?.path ?? endpoints[0]?.endpoint.path ?? process.cwd()), ".secrets");
3398
+ const homeDir = options.homeDir ?? process.env.HOME ?? "";
3399
+ const executionEngineRoot = options.manifest.executionEngine?.path;
3400
+ const skillRegistry = inspectSkillRegistry(executionEngineRoot);
3401
+ const expectedPackageVersion = packageVersion(join20(executionEngineRoot ?? "", "packages/pro-gov/package.json"));
3402
+ const repositories = endpoints.map(({ endpoint, role }) => inspectRepository(endpoint, role, secretsRoot, expectedPackageVersion));
3403
+ const summary = { healthy: 0, attention: 0, unhealthy: 0 };
3404
+ for (const repository of repositories) summary[repository.status] += 1;
3405
+ return {
3406
+ schemaVersion: 1,
3407
+ portfolioId: options.manifest.portfolioId,
3408
+ generatedAt: options.generatedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
3409
+ privacy: "Names, paths, counts, and configuration structure only. Secret values, environment values, MCP commands, arguments, and MCP environment maps are never collected.",
3410
+ secretsRoot: inspectSecretsRoot(secretsRoot),
3411
+ userMcp: inspectUserMcp(homeDir),
3412
+ skillRegistry,
3413
+ summary,
3414
+ repositories
3415
+ };
3416
+ }
3417
+ function writePortfolioAiHealthReport(report, outDir) {
3418
+ mkdirSync8(outDir, { recursive: true });
3419
+ const dashboardAssets = findDashboardAssets();
3420
+ for (const file of ["index.html", "app.js", "app.css"]) {
3421
+ const source = join20(dashboardAssets, file);
3422
+ if (!existsSync21(source)) throw new Error(`Portfolio dashboard asset is missing: ${source}`);
3423
+ cpSync2(source, join20(outDir, file));
3424
+ }
3425
+ const jsonPath = join20(outDir, "portfolio-ai-health.json");
3426
+ const htmlPath = join20(outDir, "index.html");
3427
+ writeFileSync7(jsonPath, `${JSON.stringify(report, null, 2)}
3428
+ `);
3429
+ writeFileSync7(join20(outDir, "data.js"), `window.__PORTFOLIO_AI_HEALTH__ = ${safeJavaScriptJson(report)};
3430
+ `);
3431
+ return { jsonPath, htmlPath };
3432
+ }
3433
+ function collectEndpoints(manifest) {
3434
+ const result = [];
3435
+ if (manifest.controlPlane) result.push({ endpoint: manifest.controlPlane, role: "control-plane" });
3436
+ if (manifest.executionEngine) result.push({ endpoint: manifest.executionEngine, role: "execution-engine" });
3437
+ for (const target of manifest.targets) result.push({ endpoint: target, role: "target" });
3438
+ const seen = /* @__PURE__ */ new Set();
3439
+ return result.filter(({ endpoint }) => {
3440
+ const key = resolve4(endpoint.path);
3441
+ if (seen.has(key)) return false;
3442
+ seen.add(key);
3443
+ return true;
3444
+ });
3445
+ }
3446
+ function inspectRepository(endpoint, role, secretsRoot, expectedPackageVersion) {
3447
+ const root = endpoint.path;
3448
+ const git = inspectGit2(root);
3449
+ const entries = inspectEntries(root);
3450
+ const skills = inspectSkills(root);
3451
+ const hooks = inspectHooks(root);
3452
+ const docs = inspectDocs(root, expectedPackageVersion);
3453
+ const mcp = {
3454
+ root: jsonObjectKeys(join20(root, ".mcp.json"), "mcpServers"),
3455
+ claudeCode: jsonObjectKeys(join20(root, ".claude/settings.json"), "mcpServers"),
3456
+ codex: tomlMcpNames(join20(root, ".codex/config.toml"))
3457
+ };
3458
+ const secrets = inspectRepositorySecrets(root, endpoint.id, secretsRoot, git.isRepository);
3459
+ const recommendations = [];
3460
+ if (!git.isRepository) recommendations.push("\u8BE5\u8DEF\u5F84\u4E0D\u662F Git \u4ED3\u5E93\uFF1B\u786E\u8BA4\u6E05\u5355\u8DEF\u5F84\u662F\u5426\u6B63\u786E\u3002");
3461
+ if (git.unmergedBranches.length > 0) recommendations.push(`\u6709 ${git.unmergedBranches.length} \u6761\u5206\u652F\u5C1A\u672A\u5408\u5165\u5F53\u524D HEAD\uFF1A${git.unmergedBranches.join(", ")}\u3002`);
3462
+ else if (git.branches.length > 1) recommendations.push(`\u6709 ${git.branches.length} \u6761\u672C\u5730\u5206\u652F\uFF0C\u5747\u5DF2\u5408\u5165\u5F53\u524D HEAD\uFF1B\u786E\u8BA4\u65E0\u5176\u4ED6\u5BBF\u4E3B\u5360\u7528\u540E\u53EF\u6E05\u7406\u989D\u5916\u5206\u652F\u3002`);
3463
+ if (git.worktrees.length > 1) recommendations.push(`\u6709 ${git.worktrees.length} \u4E2A worktree\uFF1B\u5B8C\u6210\u5E76\u5408\u5E76\u540E\u518D\u62C6\u9664\u4E34\u65F6 worktree\u3002`);
3464
+ if (git.dirtyPaths.length > 0) recommendations.push(`\u5DE5\u4F5C\u533A\u6709 ${git.dirtyPaths.length} \u4E2A\u53D8\u66F4\u8DEF\u5F84\uFF1B\u5148\u786E\u8BA4\u5F52\u5C5E\uFF0C\u4E0D\u8981\u7531\u5065\u5EB7\u626B\u63CF\u5668\u81EA\u52A8\u6E05\u7406\u3002`);
3465
+ if ((git.ahead ?? 0) > 0) recommendations.push(`\u5F53\u524D\u5206\u652F\u9886\u5148\u4E0A\u6E38 ${git.ahead} \u4E2A\u63D0\u4EA4\uFF1B\u786E\u8BA4\u5DE5\u4F5C\u5B8C\u6210\u540E\u518D\u63A8\u9001\u3002`);
3466
+ if (entries.agents === "missing") recommendations.push("\u7F3A\u5C11 AGENTS.md\uFF1B\u65E0\u6CD5\u53D1\u73B0\u9879\u76EE\u5165\u53E3\u89C4\u5219\u3002");
3467
+ if (entries.agents === "custom") recommendations.push("AGENTS.md \u672A\u8BC6\u522B\u5230 PGS Router \u6807\u8BB0\uFF1B\u68C0\u67E5\u662F\u5426\u5C1A\u672A\u540C\u6B65\u6216\u5DF2\u88AB\u9879\u76EE\u5185\u5BB9\u8986\u76D6\u3002");
3468
+ if (entries.claude === "missing") recommendations.push("\u7F3A\u5C11 CLAUDE.md\uFF1B\u5EFA\u8BAE\u94FE\u63A5\u5230 AGENTS.md\uFF0C\u907F\u514D\u4E24\u4EFD\u5165\u53E3\u6F02\u79FB\u3002");
3469
+ if (entries.claude === "thin-adapter") recommendations.push("CLAUDE.md \u662F\u517C\u5BB9\u9002\u914D\u5668\uFF1B\u53EF\u6539\u4E3A\u76F4\u63A5\u94FE\u63A5 AGENTS.md \u4EE5\u8FDB\u4E00\u6B65\u51CF\u5C11\u7EF4\u62A4\u9762\u3002");
3470
+ if (entries.claude === "custom") recommendations.push("CLAUDE.md \u662F\u72EC\u7ACB\u5165\u53E3\uFF1B\u5BB9\u6613\u4E0E AGENTS.md \u6F02\u79FB\uFF0C\u5EFA\u8BAE\u53EA\u4FDD\u7559\u9879\u76EE\u786E\u9700\u7684\u5BBF\u4E3B\u5DEE\u5F02\u3002");
3471
+ if (entries.claude === "dangling-symlink") recommendations.push("CLAUDE.md \u662F\u65AD\u5F00\u7684\u94FE\u63A5\uFF1B\u9700\u8981\u91CD\u65B0\u6307\u5411 AGENTS.md\u3002");
3472
+ if (entries.gemini === "custom") recommendations.push("GEMINI.md \u662F\u72EC\u7ACB\u5165\u53E3\uFF1B\u82E5\u6CA1\u6709 Gemini \u4E13\u5C5E\u5DEE\u5F02\uFF0C\u5EFA\u8BAE\u94FE\u63A5\u5230 AGENTS.md\u3002");
3473
+ if (entries.gemini === "dangling-symlink") recommendations.push("GEMINI.md \u662F\u65AD\u5F00\u7684\u94FE\u63A5\uFF1B\u9700\u8981\u91CD\u65B0\u6307\u5411 AGENTS.md\u3002");
3474
+ if (skills.canonical.some((skill) => skill.kind === "dangling-symlink")) recommendations.push("`.agents/skills` \u4E2D\u5B58\u5728\u65AD\u5F00\u7684\u6280\u80FD\u94FE\u63A5\u3002");
3475
+ if (skills.claudeCompatibility === "duplicate-directory") recommendations.push("`.claude/skills` \u662F\u72EC\u7ACB\u526F\u672C\uFF1B\u5EFA\u8BAE\u94FE\u63A5\u5230 `.agents/skills`\uFF0C\u907F\u514D\u53CC\u4EFD\u6280\u80FD\u6F02\u79FB\u3002");
3476
+ if (skills.claudeCompatibility === "dangling-symlink") recommendations.push("`.claude/skills` \u662F\u65AD\u5F00\u7684\u94FE\u63A5\u3002");
3477
+ if (hasWorkflowReminderHooks(hooks)) recommendations.push("\u53D1\u73B0 Stop/SubagentStop hook\uFF1B\u786E\u8BA4\u5B83\u662F\u5426\u4ECD\u6709\u9879\u76EE\u4E13\u5C5E\u7528\u9014\uFF0C\u5E76\u79FB\u9664\u9000\u4F11\u7684 PGS \u5DE5\u4F5C\u6D41\u63D0\u9192\u3002");
3478
+ const liveEnv = secrets.repositoryEnvFiles.filter((file) => !file.template);
3479
+ if (liveEnv.some((file) => file.tracked)) recommendations.push("\u53D1\u73B0\u88AB Git \u8DDF\u8E2A\u7684\u771F\u5B9E\u73AF\u5883\u6587\u4EF6\uFF1B\u5E94\u7ACB\u5373\u786E\u8BA4\u5176\u4E2D\u662F\u5426\u5305\u542B\u51ED\u636E\u5E76\u8FC1\u51FA\u4ED3\u5E93\u3002");
3480
+ else if (liveEnv.length > 0 && secrets.centralDirectory === "absent") recommendations.push("\u4ED3\u5E93\u6709\u672C\u5730\u73AF\u5883\u6587\u4EF6\uFF0C\u4F46\u4E2D\u592E `.secrets` \u4E2D\u6CA1\u6709\u5BF9\u5E94\u76EE\u5F55\uFF1B\u786E\u8BA4\u662F\u5426\u9700\u8981\u7EB3\u5165\u5206\u5C42\u7BA1\u7406\u3002");
3481
+ if (!docs.packages.aligned) recommendations.push(`PGS \u5305\u7248\u672C\u672A\u4E0E\u6267\u884C\u5F15\u64CE ${docs.packages.expected ?? "\u672A\u77E5\u7248\u672C"} \u5BF9\u9F50\uFF1B\u53D1\u5E03\u4E0A\u6E38\u540E\u518D\u540C\u6B65\u76EE\u6807\u4ED3\u5E93\u3002`);
3482
+ if (role === "target" && !docs.manifest) recommendations.push("\u7F3A\u5C11 docs/governance/MANIFEST.yml\uFF1B\u6587\u6863\u6E05\u5355\u65E0\u6CD5\u8BC1\u660E\u5DF2\u540C\u6B65\u3002");
3483
+ return {
3484
+ id: endpoint.id,
3485
+ role,
3486
+ path: root,
3487
+ profile: "profile" in endpoint ? endpoint.profile : void 0,
3488
+ status: deriveStatus(entries, git, hooks, skills, secrets),
3489
+ recommendations,
3490
+ git,
3491
+ entries,
3492
+ hooks,
3493
+ mcp,
3494
+ skills,
3495
+ secrets,
3496
+ docs
3497
+ };
3498
+ }
3499
+ function deriveStatus(entries, git, hooks, skills, secrets) {
3500
+ if (!git.isRepository || entries.agents === "missing" || entries.claude === "dangling-symlink" || entries.gemini === "dangling-symlink" || skills.canonical.some((item) => item.kind === "dangling-symlink") || secrets.repositoryEnvFiles.some((file) => file.tracked && !file.template)) return "unhealthy";
3501
+ if (entries.agents !== "pgs-router" || entries.claude !== "agents-symlink" || hasWorkflowReminderHooks(hooks) || skills.claudeCompatibility === "duplicate-directory" || skills.claudeCompatibility === "dangling-symlink" || git.branches.length > 1 || git.worktrees.length > 1 || git.dirtyPaths.length > 0 || (git.ahead ?? 0) > 0) return "attention";
3502
+ return "healthy";
3503
+ }
3504
+ function hasWorkflowReminderHooks(hooks) {
3505
+ return hooks.some((hook) => hook.events.some((event) => event.name === "Stop" || event.name === "SubagentStop"));
3506
+ }
3507
+ function inspectGit2(root) {
3508
+ const git = (...args) => {
3509
+ try {
3510
+ return execFileSync("git", args, { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trimEnd();
3511
+ } catch {
3512
+ return void 0;
3513
+ }
3514
+ };
3515
+ if (git("rev-parse", "--is-inside-work-tree") !== "true") return { isRepository: false, branches: [], mergedBranches: [], unmergedBranches: [], worktrees: [], dirtyPaths: [] };
3516
+ const status = git("status", "--porcelain=v1", "-uall") ?? "";
3517
+ const worktreeText = git("worktree", "list", "--porcelain") ?? "";
3518
+ const upstreamCounts = git("rev-list", "--left-right", "--count", "@{upstream}...HEAD")?.split(/\s+/).map(Number);
3519
+ return {
3520
+ isRepository: true,
3521
+ branch: git("branch", "--show-current") || "(detached)",
3522
+ branches: splitLines(git("for-each-ref", "--format=%(refname:short)", "refs/heads")),
3523
+ mergedBranches: splitLines(git("for-each-ref", "--merged=HEAD", "--format=%(refname:short)", "refs/heads")),
3524
+ unmergedBranches: splitLines(git("for-each-ref", "--no-merged=HEAD", "--format=%(refname:short)", "refs/heads")),
3525
+ worktrees: splitLines(worktreeText).filter((line) => line.startsWith("worktree ")).map((line) => line.slice(9)),
3526
+ dirtyPaths: splitLines(status).map((line) => line.slice(3)),
3527
+ behind: upstreamCounts?.[0],
3528
+ ahead: upstreamCounts?.[1]
3529
+ };
3530
+ }
3531
+ function inspectEntries(root) {
3532
+ const agentsPath = join20(root, "AGENTS.md");
3533
+ const agents = !existsSync21(agentsPath) ? "missing" : safeRead(agentsPath).includes("PGS-ROUTER:BEGIN") ? "pgs-router" : "custom";
3534
+ const claudePath = join20(root, "CLAUDE.md");
3535
+ let claude = "missing";
3536
+ if (pathLexists(claudePath)) {
3537
+ const info = lstatSync6(claudePath);
3538
+ if (info.isSymbolicLink()) {
3539
+ try {
3540
+ claude = realpathSync2(claudePath) === realpathSync2(agentsPath) ? "agents-symlink" : "custom";
3541
+ } catch {
3542
+ claude = "dangling-symlink";
3543
+ }
3544
+ } else {
3545
+ const content = safeRead(claudePath);
3546
+ claude = /AGENTS\.md/.test(content) && content.length < 2e3 ? "thin-adapter" : "custom";
3547
+ }
3548
+ }
3549
+ return { agents, claude, gemini: inspectOptionalEntry(root, "GEMINI.md", agentsPath) };
3550
+ }
3551
+ function inspectOptionalEntry(root, filename, agentsPath) {
3552
+ const path = join20(root, filename);
3553
+ if (!pathLexists(path)) return "missing";
3554
+ const info = lstatSync6(path);
3555
+ if (info.isSymbolicLink()) {
3556
+ try {
3557
+ return realpathSync2(path) === realpathSync2(agentsPath) ? "agents-symlink" : "custom";
3558
+ } catch {
3559
+ return "dangling-symlink";
3560
+ }
3561
+ }
3562
+ const content = safeRead(path);
3563
+ return /AGENTS\.md/.test(content) && content.length < 2e3 ? "thin-adapter" : "custom";
3564
+ }
3565
+ function inspectSkills(root) {
3566
+ const lock = readJson3(join20(root, ".pro-gov/assets.lock.json"));
3567
+ const managed = /* @__PURE__ */ new Set();
3568
+ const bundleIds = stringArray(isRecord3(lock) ? lock.bundleIds : void 0);
3569
+ if (isRecord3(lock) && Array.isArray(lock.assets)) {
3570
+ for (const asset of lock.assets) {
3571
+ if (!isRecord3(asset) || typeof asset.targetPath !== "string") continue;
3572
+ const match = asset.targetPath.match(/^\.agents\/skills\/([^/]+)$/);
3573
+ if (match) managed.add(match[1]);
3574
+ }
3575
+ }
3576
+ const skillRoot = join20(root, ".agents/skills");
3577
+ const canonical = pathLexists(skillRoot) && safeIsDirectory(skillRoot) ? safeReadDir(skillRoot).filter((name) => !name.startsWith(".")).map((name) => {
3578
+ const path = join20(skillRoot, name);
3579
+ const stat = lstatSync6(path);
3580
+ let kind = stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : "file";
3581
+ if (stat.isSymbolicLink()) {
3582
+ try {
3583
+ realpathSync2(path);
3584
+ } catch {
3585
+ kind = "dangling-symlink";
3586
+ }
3587
+ }
3588
+ return { name, kind, managed: managed.has(name) };
3589
+ }) : [];
3590
+ const locked = isRecord3(lock) && Array.isArray(lock.assets) ? lock.assets.length : 0;
3591
+ return {
3592
+ canonical,
3593
+ claudeCompatibility: inspectClaudeSkillRoot(root),
3594
+ bundleIds,
3595
+ lifecycle: {
3596
+ desired: bundleIds.length,
3597
+ locked,
3598
+ installed: canonical.filter((item) => item.managed && item.kind !== "dangling-symlink").length,
3599
+ discoverable: canonical.filter((item) => item.kind !== "dangling-symlink").length,
3600
+ runtime: "unobservable"
3601
+ }
3602
+ };
3603
+ }
3604
+ function inspectClaudeSkillRoot(root) {
3605
+ const path = join20(root, ".claude/skills");
3606
+ if (!pathLexists(path)) return "missing";
3607
+ const stat = lstatSync6(path);
3608
+ if (stat.isSymbolicLink()) {
3609
+ try {
3610
+ const target = realpathSync2(path);
3611
+ return target === realpathSync2(join20(root, ".agents/skills")) ? "shared-root" : "other";
3612
+ } catch {
3613
+ return "dangling-symlink";
3614
+ }
3615
+ }
3616
+ return stat.isDirectory() ? "duplicate-directory" : "other";
3617
+ }
3618
+ function inspectRepositorySecrets(root, id, secretsRoot, isRepository) {
3619
+ const centralPath = join20(secretsRoot, id);
3620
+ const envFiles = collectEnvironmentFiles(root).map((path) => ({
3621
+ path,
3622
+ tracked: isRepository ? gitTracks(root, path) : false,
3623
+ template: /(?:example|sample|template|defaults?)$/i.test(basenameOnly(path)),
3624
+ symlink: lstatSync6(join20(root, path)).isSymbolicLink()
3625
+ }));
3626
+ return {
3627
+ centralDirectory: existsSync21(centralPath) ? "present" : "absent",
3628
+ centralMode: existsSync21(centralPath) ? modeString(statSync4(centralPath).mode) : void 0,
3629
+ centralFiles: existsSync21(centralPath) ? collectCentralSecretFiles(centralPath) : [],
3630
+ repositoryEnvFiles: envFiles
3631
+ };
3632
+ }
3633
+ var SKIP_ENV_DIRECTORIES = /* @__PURE__ */ new Set([".git", ".next", ".nuxt", ".output", ".turbo", ".worktrees", "build", "coverage", "dist", "node_modules", "out", "target"]);
3634
+ function collectEnvironmentFiles(root, current = root, depth = 0) {
3635
+ if (depth > 5) return [];
3636
+ const found = [];
3637
+ try {
3638
+ for (const entry of readdirSync8(current, { withFileTypes: true })) {
3639
+ if (entry.isDirectory()) {
3640
+ if (!SKIP_ENV_DIRECTORIES.has(entry.name)) found.push(...collectEnvironmentFiles(root, join20(current, entry.name), depth + 1));
3641
+ } else if (entry.name === ".env" || entry.name.startsWith(".env.")) {
3642
+ found.push(relative8(root, join20(current, entry.name)));
3643
+ }
3644
+ }
3645
+ } catch {
3646
+ return found;
3647
+ }
3648
+ return found.sort();
3649
+ }
3650
+ function collectCentralSecretFiles(root, current = root, depth = 0) {
3651
+ if (depth > 3) return [];
3652
+ const found = [];
3653
+ try {
3654
+ for (const entry of readdirSync8(current, { withFileTypes: true })) {
3655
+ const path = join20(current, entry.name);
3656
+ if (entry.isDirectory()) found.push(...collectCentralSecretFiles(root, path, depth + 1));
3657
+ else found.push({ path: relative8(root, path), mode: modeString(lstatSync6(path).mode) });
3658
+ }
3659
+ } catch {
3660
+ return found;
3661
+ }
3662
+ return found.sort((left, right) => left.path.localeCompare(right.path));
3663
+ }
3664
+ function basenameOnly(path) {
3665
+ const parts = path.split(/[\\/]/);
3666
+ return parts[parts.length - 1] ?? path;
3667
+ }
3668
+ function inspectSecretsRoot(path) {
3669
+ return existsSync21(path) ? { path, exists: true, mode: modeString(statSync4(path).mode) } : { path, exists: false };
3670
+ }
3671
+ function inspectUserMcp(homeDir) {
3672
+ if (!homeDir) return { codex: [], claudeCode: [] };
3673
+ return {
3674
+ codex: tomlMcpNames(join20(homeDir, ".codex/config.toml")),
3675
+ claudeCode: jsonObjectKeys(join20(homeDir, ".claude/settings.json"), "mcpServers")
3676
+ };
3677
+ }
3678
+ var HOOK_EVENT_NAMES = /* @__PURE__ */ new Set([
3679
+ "PreToolUse",
3680
+ "PostToolUse",
3681
+ "PostToolUseFailure",
3682
+ "PermissionRequest",
3683
+ "UserPromptSubmit",
3684
+ "Notification",
3685
+ "SubagentStart",
3686
+ "SubagentStop",
3687
+ "Stop",
3688
+ "SessionStart",
3689
+ "SessionEnd",
3690
+ "PreCompact",
3691
+ "Setup",
3692
+ "TeammateIdle",
3693
+ "TaskCompleted",
3694
+ "ConfigChange",
3695
+ "WorktreeCreate",
3696
+ "WorktreeRemove"
3697
+ ]);
3698
+ function inspectHooks(root) {
3699
+ const configs = [
3700
+ { host: "agents", path: ".agents/hooks.json" },
3701
+ { host: "claude-code", path: ".claude/settings.json" },
3702
+ { host: "codex", path: ".codex/hooks.json" }
3703
+ ];
3704
+ return configs.map((config) => {
3705
+ const value = readJson3(join20(root, config.path));
3706
+ const counts = /* @__PURE__ */ new Map();
3707
+ collectHookEvents(value, counts);
3708
+ return {
3709
+ ...config,
3710
+ events: [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([name, count]) => ({ name, count }))
3711
+ };
3712
+ });
3713
+ }
3714
+ function collectHookEvents(value, counts) {
3715
+ if (Array.isArray(value)) {
3716
+ for (const item of value) collectHookEvents(item, counts);
3717
+ return;
3718
+ }
3719
+ if (!isRecord3(value)) return;
3720
+ for (const [key, child] of Object.entries(value)) {
3721
+ if (HOOK_EVENT_NAMES.has(key)) counts.set(key, Array.isArray(child) ? child.length : 1);
3722
+ collectHookEvents(child, counts);
3723
+ }
3724
+ }
3725
+ function inspectDocs(root, expected) {
3726
+ const packageJson = readJson3(join20(root, "package.json"));
3727
+ const dependencies = isRecord3(packageJson) ? { ...recordOrEmpty(packageJson.dependencies), ...recordOrEmpty(packageJson.devDependencies) } : {};
3728
+ const docGov = dependencyVersion(dependencies["@pieai/doc-gov"]);
3729
+ const proGov = dependencyVersion(dependencies["@pieai/pro-gov"]);
3730
+ const routerMatch = safeRead(join20(root, "AGENTS.md")).match(/PGS-ROUTER:BEGIN\s+v([0-9.]+)/);
3731
+ const declared = [docGov, proGov].filter((value) => Boolean(value));
3732
+ return {
3733
+ routerVersion: routerMatch?.[1],
3734
+ manifest: existsSync21(join20(root, "docs/governance/MANIFEST.yml")),
3735
+ currentWork: existsSync21(join20(root, "docs/reference/execution/current-work.md")),
3736
+ packages: {
3737
+ expected,
3738
+ docGov,
3739
+ proGov,
3740
+ aligned: expected ? declared.length > 0 && declared.every((version) => version === expected) : true
3741
+ }
3742
+ };
3743
+ }
3744
+ function dependencyVersion(value) {
3745
+ if (typeof value !== "string") return void 0;
3746
+ const match = value.match(/(\d+\.\d+\.\d+)/);
3747
+ return match?.[1];
3748
+ }
3749
+ function packageVersion(path) {
3750
+ const value = readJson3(path);
3751
+ return isRecord3(value) && typeof value.version === "string" ? value.version : void 0;
3752
+ }
3753
+ function recordOrEmpty(value) {
3754
+ return isRecord3(value) ? value : {};
3755
+ }
3756
+ function inspectSkillRegistry(executionEngineRoot) {
3757
+ if (!executionEngineRoot) return { source: 0, registered: 0, bundled: 0, bundles: 0 };
3758
+ const agentAssetsRoot = join20(executionEngineRoot, "agent-assets");
3759
+ const registry = readJson3(join20(agentAssetsRoot, "registry.json"));
3760
+ const assets = isRecord3(registry) && Array.isArray(registry.assets) ? registry.assets : [];
3761
+ const registeredSkills = assets.filter((asset) => isRecord3(asset) && asset.kind === "skill");
3762
+ const bundleRoot = join20(agentAssetsRoot, "bundles");
3763
+ const bundleFiles = safeReadDir(bundleRoot).filter((file) => file.endsWith(".json"));
3764
+ const bundledIds = /* @__PURE__ */ new Set();
3765
+ for (const file of bundleFiles) {
3766
+ const bundle = readJson3(join20(bundleRoot, file));
3767
+ if (!isRecord3(bundle) || !Array.isArray(bundle.assets)) continue;
3768
+ for (const id of bundle.assets) if (typeof id === "string") bundledIds.add(id);
3769
+ }
3770
+ const sourceRoots = [join20(agentAssetsRoot, "skills/pie-skills"), join20(agentAssetsRoot, "skills/npx-skills/.agents/skills")];
3771
+ const source = sourceRoots.reduce((count, root) => count + safeReadDir(root).filter((name) => existsSync21(join20(root, name, "SKILL.md"))).length, 0);
3772
+ return {
3773
+ source,
3774
+ registered: registeredSkills.length,
3775
+ bundled: registeredSkills.filter((asset) => isRecord3(asset) && typeof asset.id === "string" && bundledIds.has(asset.id)).length,
3776
+ bundles: bundleFiles.length
3777
+ };
3778
+ }
3779
+ function jsonObjectKeys(path, key) {
3780
+ const value = readJson3(path);
3781
+ if (!isRecord3(value) || !isRecord3(value[key])) return [];
3782
+ return Object.keys(value[key]).sort();
3783
+ }
3784
+ function tomlMcpNames(path) {
3785
+ if (!existsSync21(path)) return [];
3786
+ const names = /* @__PURE__ */ new Set();
3787
+ for (const line of safeRead(path).split(/\r?\n/)) {
3788
+ const match = line.match(/^\s*\[mcp_servers\.(?:"([^"]+)"|([^\.\]]+))\]\s*$/);
3789
+ const name = match?.[1] ?? match?.[2];
3790
+ if (name) names.add(name);
3791
+ }
3792
+ return [...names].sort();
3793
+ }
3794
+ function readJson3(path) {
3795
+ try {
3796
+ return JSON.parse(readFileSync15(path, "utf8"));
3797
+ } catch {
3798
+ return void 0;
3799
+ }
3800
+ }
3801
+ function safeRead(path) {
3802
+ try {
3803
+ return readFileSync15(path, "utf8");
3804
+ } catch {
3805
+ return "";
3806
+ }
3807
+ }
3808
+ function safeReadDir(path) {
3809
+ try {
3810
+ return readdirSync8(path).sort();
3811
+ } catch {
3812
+ return [];
3813
+ }
3814
+ }
3815
+ function safeIsDirectory(path) {
3816
+ try {
3817
+ return statSync4(path).isDirectory();
3818
+ } catch {
3819
+ return false;
3820
+ }
3821
+ }
3822
+ function pathLexists(path) {
3823
+ try {
3824
+ lstatSync6(path);
3825
+ return true;
3826
+ } catch {
3827
+ return false;
3828
+ }
3829
+ }
3830
+ function gitTracks(root, path) {
3831
+ try {
3832
+ execFileSync("git", ["ls-files", "--error-unmatch", "--", path], { cwd: root, stdio: "ignore" });
3833
+ return true;
3834
+ } catch {
3835
+ return false;
3836
+ }
3837
+ }
3838
+ function modeString(mode) {
3839
+ return (mode & 511).toString(8).padStart(3, "0");
3840
+ }
3841
+ function splitLines(value) {
3842
+ return value ? value.split(/\r?\n/).filter(Boolean) : [];
3843
+ }
3844
+ function stringArray(value) {
3845
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
3846
+ }
3847
+ function isRecord3(value) {
3848
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3849
+ }
3850
+ function findDashboardAssets() {
3851
+ const packageRoot2 = dirname12(dirname12(fileURLToPath4(import.meta.url)));
3852
+ const candidates = [
3853
+ process.env.PGS_DASHBOARD_ASSETS_DIR,
3854
+ join20(packageRoot2, "assets/portfolio-dashboard"),
3855
+ join20(process.cwd(), "assets/portfolio-dashboard"),
3856
+ join20(process.cwd(), "packages/pro-gov/assets/portfolio-dashboard")
3857
+ ].filter((value) => Boolean(value));
3858
+ const match = candidates.find((path) => existsSync21(join20(path, "index.html")));
3859
+ if (!match) throw new Error("Portfolio dashboard assets were not built. Run pnpm --filter @pieai/pro-gov build.");
3860
+ return match;
3861
+ }
3862
+ function safeJavaScriptJson(value) {
3863
+ return JSON.stringify(value).replace(/</g, "\\u003c").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
3864
+ }
3865
+
3387
3866
  // src/commands/portfolio.ts
3388
3867
  function runPortfolio(args) {
3389
3868
  const [subcommand2, ...rest] = args;
@@ -3391,9 +3870,41 @@ function runPortfolio(args) {
3391
3870
  if (subcommand2 === "plan") return runPortfolioPlan(rest);
3392
3871
  if (subcommand2 === "assets-check") return runPortfolioAssetsCheck(rest);
3393
3872
  if (subcommand2 === "doctor") return runPortfolioDoctor(rest);
3873
+ if (subcommand2 === "ai-health") return runPortfolioAiHealth(rest);
3394
3874
  printUsage4();
3395
3875
  return 1;
3396
3876
  }
3877
+ function runPortfolioAiHealth(args) {
3878
+ const options = parsePortfolioOptions(args);
3879
+ if (!options.ok) {
3880
+ console.error(options.error);
3881
+ printUsage4();
3882
+ return 1;
3883
+ }
3884
+ if (!options.value.outDir) {
3885
+ console.error("Expected --out <directory>");
3886
+ printUsage4();
3887
+ return 1;
3888
+ }
3889
+ const loaded = loadPortfolioManifest(options.value.configPath);
3890
+ if (loaded.issues.length > 0 || !loaded.manifest) {
3891
+ for (const issue of loaded.issues) console.error(`${issue.type}: ${issue.message}`);
3892
+ return 1;
3893
+ }
3894
+ const report = inspectPortfolioAiHealth({
3895
+ manifest: loaded.manifest,
3896
+ secretsRoot: options.value.secretsRoot
3897
+ });
3898
+ const written = writePortfolioAiHealthReport(report, options.value.outDir);
3899
+ if (options.value.json) {
3900
+ console.log(JSON.stringify({ ok: true, ...written, summary: report.summary }, null, 2));
3901
+ } else {
3902
+ console.log(`portfolio AI health report written (${report.repositories.length} repositories)`);
3903
+ console.log(`HTML: ${written.htmlPath}`);
3904
+ console.log(`JSON: ${written.jsonPath}`);
3905
+ }
3906
+ return 0;
3907
+ }
3397
3908
  function runPortfolioDoctor(args) {
3398
3909
  const options = parsePortfolioOptions(args);
3399
3910
  if (!options.ok) {
@@ -3675,6 +4186,16 @@ function parsePortfolioOptions(args) {
3675
4186
  index += 1;
3676
4187
  } else if (arg === "--json") {
3677
4188
  options.json = true;
4189
+ } else if (arg === "--out") {
4190
+ const outDir = args[index + 1];
4191
+ if (!outDir) return { ok: false, error: "Expected --out <directory>" };
4192
+ options.outDir = outDir;
4193
+ index += 1;
4194
+ } else if (arg === "--secrets-root") {
4195
+ const secretsRoot = args[index + 1];
4196
+ if (!secretsRoot) return { ok: false, error: "Expected --secrets-root <directory>" };
4197
+ options.secretsRoot = secretsRoot;
4198
+ index += 1;
3678
4199
  } else {
3679
4200
  return { ok: false, error: `Unknown portfolio option: ${arg}` };
3680
4201
  }
@@ -3686,8 +4207,8 @@ function isHost2(value) {
3686
4207
  return value === "codex" || value === "claude-code" || value === "gemini-cli" || value === "antigravity";
3687
4208
  }
3688
4209
  function findPortfolioAgentAssetsDir(manifest) {
3689
- const agentAssetsDir = manifest?.executionEngine?.path ? join20(manifest.executionEngine.path, "agent-assets") : void 0;
3690
- return agentAssetsDir && existsSync21(join20(agentAssetsDir, "registry.json")) ? agentAssetsDir : void 0;
4210
+ const agentAssetsDir = manifest?.executionEngine?.path ? join21(manifest.executionEngine.path, "agent-assets") : void 0;
4211
+ return agentAssetsDir && existsSync22(join21(agentAssetsDir, "registry.json")) ? agentAssetsDir : void 0;
3691
4212
  }
3692
4213
  function printUsage4() {
3693
4214
  console.error("Usage:");
@@ -3695,11 +4216,12 @@ function printUsage4() {
3695
4216
  console.error(" pro-gov portfolio plan --config <path> [--target <id|all>] [--host codex|claude-code|gemini-cli|antigravity] [--json]");
3696
4217
  console.error(" pro-gov portfolio assets-check --config <path> [--target <id|all>] [--json]");
3697
4218
  console.error(" pro-gov portfolio doctor --config <path> [--target <id|all>] [--json]");
4219
+ console.error(" pro-gov portfolio ai-health --config <path> --out <directory> [--secrets-root <directory>] [--json]");
3698
4220
  }
3699
4221
 
3700
4222
  // src/commands/sync.ts
3701
- import { existsSync as existsSync22, readFileSync as readFileSync15 } from "node:fs";
3702
- import { join as join21 } from "node:path";
4223
+ import { existsSync as existsSync23, readFileSync as readFileSync16 } from "node:fs";
4224
+ import { join as join22 } from "node:path";
3703
4225
  function runSync(args) {
3704
4226
  const check = args.includes("--check");
3705
4227
  if (!check) {
@@ -3727,8 +4249,8 @@ function runSync(args) {
3727
4249
  console.log("pro-gov sync check");
3728
4250
  console.log(`profile: ${profile}`);
3729
4251
  for (const file of planStarterFiles(profile)) {
3730
- const targetPath = join21(process.cwd(), file.targetPath);
3731
- if (!existsSync22(targetPath)) {
4252
+ const targetPath = join22(process.cwd(), file.targetPath);
4253
+ if (!existsSync23(targetPath)) {
3732
4254
  if (file.ownership === "optional-guardrail") continue;
3733
4255
  console.log(`missing: ${file.targetPath}`);
3734
4256
  differences += 1;
@@ -3736,8 +4258,8 @@ function runSync(args) {
3736
4258
  }
3737
4259
  if (file.ownership === "optional-guardrail") continue;
3738
4260
  if (file.ownership === "project-local-seed") continue;
3739
- const source = readFileSync15(file.absoluteSourcePath, "utf8");
3740
- const target = readFileSync15(targetPath, "utf8");
4261
+ const source = readFileSync16(file.absoluteSourcePath, "utf8");
4262
+ const target = readFileSync16(targetPath, "utf8");
3741
4263
  if (!matchesExpectedContent(file.targetPath, source, target)) {
3742
4264
  console.log(`different: ${file.targetPath}`);
3743
4265
  differences += 1;
@@ -3771,7 +4293,7 @@ function normalizeMarkdownTableCell(cell) {
3771
4293
  }
3772
4294
  function inferInstalledProfile(root) {
3773
4295
  const installed = ["engineering-runtime", "doc-only"].filter(
3774
- (profile) => existsSync22(join21(root, `docs/governance/agents-routing/${profile}-v0.9.md`))
4296
+ (profile) => existsSync23(join22(root, `docs/governance/agents-routing/${profile}-v0.9.md`))
3775
4297
  );
3776
4298
  return installed.length === 1 ? installed[0] : void 0;
3777
4299
  }
@@ -3795,6 +4317,7 @@ var COMMANDS = [
3795
4317
  "portfolio plan --config <path> [--target <id|all>] [--json]",
3796
4318
  "portfolio assets-check --config <path> [--target <id|all>] [--json]",
3797
4319
  "portfolio doctor --config <path> [--target <id|all>] [--json]",
4320
+ "portfolio ai-health --config <path> --out <directory> [--secrets-root <directory>] [--json]",
3798
4321
  "learn recall --query <text> [--target <path>] [--limit <n>] [--json]",
3799
4322
  "learn capture --title <text> --summary <text> [--category <slug>] [--target <path>] [--json]",
3800
4323
  "lens scan [--target <path>] [--json]",