@krisada-m/ksd-intelligence 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/.antigravity-plugin/plugin.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/agy-skills/erosiano-review/SKILL.md +17 -0
  5. package/dist/adapters/agy/skills.js +252 -0
  6. package/dist/adapters/cli/check-changed.js +3 -0
  7. package/dist/adapters/cli/main.js +1013 -0
  8. package/dist/adapters/cli/policy-bin.js +10 -0
  9. package/dist/adapters/cli/review-verdict.js +3 -0
  10. package/dist/adapters/omp/extension.js +884 -0
  11. package/dist/adapters/omp/skills.js +130 -0
  12. package/dist/adapters/ui/hud.js +389 -0
  13. package/dist/adapters/ui/tree.js +471 -0
  14. package/dist/core/audit/index.js +2 -0
  15. package/dist/core/audit/log.js +505 -0
  16. package/dist/core/audit/summary.js +188 -0
  17. package/dist/core/changes/changes.js +591 -0
  18. package/dist/core/changes/git.js +266 -0
  19. package/dist/core/changes/plan.js +109 -0
  20. package/dist/core/changes/render.js +356 -0
  21. package/dist/core/engine/build.js +178 -0
  22. package/dist/core/engine/child.js +389 -0
  23. package/dist/core/engine/host.js +206 -0
  24. package/dist/core/engine/lock.js +133 -0
  25. package/dist/core/engine/protocol.js +43 -0
  26. package/dist/core/engine/runtime.js +44 -0
  27. package/dist/core/engine/status.js +452 -0
  28. package/dist/core/engine/typescript.js +194 -0
  29. package/dist/core/engine/workspace.js +72 -0
  30. package/dist/core/graph/graph.js +127 -0
  31. package/dist/core/graph/limits.js +16 -0
  32. package/dist/core/impact/query.js +1292 -0
  33. package/dist/core/impact/render.js +590 -0
  34. package/dist/core/impact/session.js +694 -0
  35. package/dist/core/indexing/declarations.js +455 -0
  36. package/dist/core/indexing/differential.js +345 -0
  37. package/dist/core/indexing/doctor.js +120 -0
  38. package/dist/core/indexing/indexer.js +811 -0
  39. package/dist/core/indexing/keys.js +451 -0
  40. package/dist/core/indexing/lexical.js +212 -0
  41. package/dist/core/indexing/packages.js +57 -0
  42. package/dist/core/indexing/program.js +171 -0
  43. package/dist/core/indexing/resolve.js +1004 -0
  44. package/dist/core/indexing/stamp.js +52 -0
  45. package/dist/core/indexing/surface.js +335 -0
  46. package/dist/core/indexing/ui-progress.js +37 -0
  47. package/dist/core/indexing/verify.js +76 -0
  48. package/dist/core/kernel/config.js +383 -0
  49. package/dist/core/kernel/glob.js +105 -0
  50. package/dist/core/kernel/guards.js +4 -0
  51. package/dist/core/kernel/types.js +3 -0
  52. package/dist/core/kernel/verdict.js +142 -0
  53. package/dist/core/knowledge/anchors.js +139 -0
  54. package/dist/core/knowledge/knowledge.js +95 -0
  55. package/dist/core/knowledge/learning.js +102 -0
  56. package/dist/core/knowledge/render.js +76 -0
  57. package/dist/core/knowledge/store.js +109 -0
  58. package/dist/core/knowledge/yaml.js +87 -0
  59. package/dist/core/search/lexical.js +382 -0
  60. package/dist/core/search/render.js +98 -0
  61. package/dist/core/search/segments.js +118 -0
  62. package/dist/core/verify/parse.js +127 -0
  63. package/dist/core/verify/render.js +67 -0
  64. package/dist/core/verify/report.js +40 -0
  65. package/dist/core/verify/revision.js +79 -0
  66. package/dist/core/verify/run.js +117 -0
  67. package/dist/core/verify/store.js +66 -0
  68. package/dist/core/verify/verify.js +173 -0
  69. package/dist/core/workspace/init.js +267 -0
  70. package/dist/core/workspace/probe.js +56 -0
  71. package/dist/core/workspace/scan.js +420 -0
  72. package/dist/engineering/baseline.js +337 -0
  73. package/dist/engineering/change-scope.js +500 -0
  74. package/dist/engineering/check-changed.js +40 -0
  75. package/dist/engineering/config.js +129 -0
  76. package/dist/engineering/dist/policy.d.ts +17 -0
  77. package/dist/engineering/dist/policy.js +150 -0
  78. package/dist/engineering/dist/runtime.d.ts +40 -0
  79. package/dist/engineering/dist/runtime.js +77 -0
  80. package/dist/engineering/dist/sdlc.d.ts +7 -0
  81. package/dist/engineering/dist/sdlc.js +27 -0
  82. package/dist/engineering/eslint-rules/index.js +107 -0
  83. package/dist/engineering/index.d.ts +7 -0
  84. package/dist/engineering/index.js +319 -0
  85. package/dist/engineering/intelligence.js +44 -0
  86. package/dist/engineering/package.json +36 -0
  87. package/dist/engineering/policy.js +2 -0
  88. package/dist/engineering/practice-tool.js +72 -0
  89. package/dist/engineering/practices.js +283 -0
  90. package/dist/engineering/practices.json +2453 -0
  91. package/dist/engineering/review-verdict.js +262 -0
  92. package/dist/engineering/sdlc.js +2 -0
  93. package/dist/index.js +20 -0
  94. package/dist/storage/records.js +245 -0
  95. package/dist/storage/sqlite.js +314 -0
  96. package/dist/workflow/catalog.js +69 -0
  97. package/dist/workflow/classify.js +55 -0
  98. package/dist/workflow/loader.js +140 -0
  99. package/dist/workflow/packs.js +469 -0
  100. package/dist/workflow/registry.js +359 -0
  101. package/dist/workflow/render.js +61 -0
  102. package/dist/workflow/router.js +141 -0
  103. package/dist/workflow/sources.js +229 -0
  104. package/dist/workflow/types.js +44 -0
  105. package/dist/workflow/updates.js +532 -0
  106. package/engineering.lock.json +94 -0
  107. package/package.json +81 -4
  108. package/rules/engineering.md +20 -0
  109. package/scripts/agy-mcp.mjs +27 -0
  110. package/scripts/mcp/engineering.mjs +91 -0
  111. package/scripts/mcp/stdio.mjs +304 -0
  112. package/scripts/mcp/tools.mjs +491 -0
  113. package/skills/ksd-intelligence/SKILL.md +54 -0
  114. package/skills/matt-sdlc/SKILL.md +42 -0
  115. package/skills/osmani-quality/SKILL.md +38 -0
  116. package/skills/poteto-mode/SKILL.md +40 -0
  117. package/skills/pstack-analysis/SKILL.md +36 -0
  118. package/skills.lock.json +71 -0
  119. package/skills.registry.json +181 -0
@@ -0,0 +1,133 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { linkSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { isRecord } from '../kernel/guards.js';
5
+ export const LOCK_FILE = 'build.lock';
6
+ function readRaw(path) {
7
+ try {
8
+ return readFileSync(path, 'utf8');
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ }
14
+ function errorCode(error) {
15
+ return error instanceof Error && 'code' in error ? error.code : undefined;
16
+ }
17
+ // Linux: start time in clock ticks since boot (field 22 of /proc/<pid>/stat, counted after the
18
+ // parenthesised command name, which may contain spaces). Stable for the process's lifetime, unlike
19
+ // wall-clock renderings that shift when the clock is corrected (seen on WSL after resume).
20
+ // macOS: `ps -o lstart=`, rendered from the start time the kernel stored at fork.
21
+ function processIdentity(pid) {
22
+ try {
23
+ if (process.platform === 'linux') {
24
+ const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
25
+ const ticks = stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];
26
+ return ticks === undefined ? null : `ticks:${ticks}`;
27
+ }
28
+ const lstart = execFileSync('ps', ['-o', 'lstart=', '-p', String(pid)], {
29
+ encoding: 'utf8',
30
+ env: { ...process.env, LC_ALL: 'C' },
31
+ stdio: ['ignore', 'pipe', 'ignore'],
32
+ }).trim();
33
+ return lstart === '' ? null : `lstart:${lstart}`;
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ function parseHolder(raw) {
40
+ try {
41
+ const value = JSON.parse(raw);
42
+ if (!isRecord(value) || !Number.isInteger(value.pid) || typeof value.startedAt !== 'string') {
43
+ return null;
44
+ }
45
+ const identity = typeof value.identity === 'string' ? value.identity : null;
46
+ return { pid: Number(value.pid), startedAt: value.startedAt, identity };
47
+ }
48
+ catch {
49
+ return null; // corrupt lock file: stale
50
+ }
51
+ }
52
+ /** False when the holder process is gone or its pid now belongs to another process. */
53
+ export function isHolderAlive(holder) {
54
+ try {
55
+ process.kill(holder.pid, 0);
56
+ }
57
+ catch (error) {
58
+ if (errorCode(error) !== 'EPERM')
59
+ return false; // EPERM: alive, owned by another user
60
+ }
61
+ const now = processIdentity(holder.pid);
62
+ // Unknown on either side: keep the lock rather than risk two builders.
63
+ return holder.identity === null || now === null || now === holder.identity;
64
+ }
65
+ export function readLockHolder(cacheDir) {
66
+ const raw = readRaw(join(cacheDir, LOCK_FILE));
67
+ return raw === null ? null : parseHolder(raw);
68
+ }
69
+ /**
70
+ * Takes the per-repository build lock in the cache dir. Refused while a live process holds it; a
71
+ * lock whose holder is gone, or whose pid now belongs to another process, is stale and taken over.
72
+ * Released by release() or when this process exits normally.
73
+ */
74
+ export function acquireBuildLock(cacheDir) {
75
+ const path = join(cacheDir, LOCK_FILE);
76
+ const self = {
77
+ pid: process.pid,
78
+ startedAt: new Date(Date.now() - process.uptime() * 1000).toISOString(),
79
+ identity: processIdentity(process.pid),
80
+ };
81
+ const content = JSON.stringify(self);
82
+ for (let attempt = 0; attempt < 3; attempt++) {
83
+ // link() publishes a fully written file atomically and fails if a lock already exists.
84
+ const temp = `${path}.${process.pid}.tmp`;
85
+ writeFileSync(temp, content, { mode: 0o600 });
86
+ try {
87
+ linkSync(temp, path);
88
+ return { ok: true, release: holdUntilExit(path, content) };
89
+ }
90
+ catch (error) {
91
+ if (errorCode(error) !== 'EEXIST')
92
+ throw error;
93
+ }
94
+ finally {
95
+ rmSync(temp, { force: true });
96
+ }
97
+ const raw = readRaw(path);
98
+ if (raw === null)
99
+ continue; // released meanwhile
100
+ const holder = parseHolder(raw);
101
+ if (holder !== null && isHolderAlive(holder))
102
+ return { ok: false, holder };
103
+ // Stale: move it aside atomically, then confirm it is the file judged stale and not a fresh
104
+ // lock another session created after our read; a fresh one is put back.
105
+ const tomb = `${path}.stale-${process.pid}`;
106
+ try {
107
+ renameSync(path, tomb);
108
+ }
109
+ catch {
110
+ continue;
111
+ }
112
+ if (readRaw(tomb) !== raw) {
113
+ try {
114
+ linkSync(tomb, path);
115
+ }
116
+ catch {
117
+ // a third session took the slot; the next attempt reads its lock
118
+ }
119
+ }
120
+ rmSync(tomb, { force: true });
121
+ }
122
+ return { ok: false, holder: readLockHolder(cacheDir) };
123
+ }
124
+ function holdUntilExit(path, content) {
125
+ const release = () => {
126
+ process.off('exit', release);
127
+ // Only delete our own lock, never one taken over after this holder was judged stale.
128
+ if (readRaw(path) === content)
129
+ rmSync(path, { force: true });
130
+ };
131
+ process.on('exit', release);
132
+ return release;
133
+ }
@@ -0,0 +1,43 @@
1
+ import { StringDecoder } from 'node:string_decoder';
2
+ import { isRecord } from '../kernel/guards.js';
3
+ export function encode(message) {
4
+ return `${JSON.stringify(message)}\n`;
5
+ }
6
+ /** Parses one line; returns an error string for anything that is not a well-formed message. */
7
+ export function parseMessage(line) {
8
+ let raw;
9
+ try {
10
+ raw = JSON.parse(line);
11
+ }
12
+ catch {
13
+ return 'invalid JSON';
14
+ }
15
+ if (!isRecord(raw) || typeof raw.id !== 'string')
16
+ return 'message without a string id';
17
+ const { id } = raw;
18
+ if (raw.type === 'request' && typeof raw.op === 'string') {
19
+ return { type: 'request', id, op: raw.op, args: raw.args };
20
+ }
21
+ if (raw.type === 'progress' && typeof raw.message === 'string') {
22
+ return { type: 'progress', id, message: raw.message, data: raw.data };
23
+ }
24
+ if (raw.type === 'result') {
25
+ return { type: 'result', id, value: raw.value, retire: raw.retire === true };
26
+ }
27
+ if (raw.type === 'error' && typeof raw.code === 'string' && typeof raw.message === 'string') {
28
+ return { type: 'error', id, code: raw.code, message: raw.message, retire: raw.retire === true };
29
+ }
30
+ return `malformed ${String(raw.type)} message`;
31
+ }
32
+ /** Splits a byte stream into lines; chunks may cut a line or a multi-byte character in half. */
33
+ export function lineReader(onLine) {
34
+ const utf8 = new StringDecoder('utf8');
35
+ let pending = '';
36
+ return (chunk) => {
37
+ const lines = (pending + utf8.write(chunk)).split('\n');
38
+ pending = lines.pop() ?? '';
39
+ for (const line of lines)
40
+ if (line.trim() !== '')
41
+ onLine(line);
42
+ };
43
+ }
@@ -0,0 +1,44 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { totalmem } from 'node:os';
3
+ import { promisify } from 'node:util';
4
+ const run = promisify(execFile);
5
+ /**
6
+ * D45: `node` from PATH when it is >= 22.5 (built-in SQLite, faster checker); otherwise the
7
+ * runtime this process runs on, which inside OMP is its own Bun executable.
8
+ */
9
+ export async function chooseRuntime(env = process.env, execPath = process.execPath) {
10
+ try {
11
+ const { stdout } = await run('node', ['-p', 'process.execPath + "\\n" + process.versions.node'], {
12
+ env,
13
+ timeout: 10_000,
14
+ });
15
+ const [command, version = ''] = stdout.trim().split('\n');
16
+ const [major = 0, minor = 0] = version.split('.').map(Number);
17
+ if (command && (major > 22 || (major === 22 && minor >= 5))) {
18
+ return { kind: 'node', command, version };
19
+ }
20
+ }
21
+ catch {
22
+ // no usable node on PATH; fall through to this process's runtime
23
+ }
24
+ const bun = process.versions.bun;
25
+ return bun === undefined
26
+ ? { kind: 'node', command: execPath, version: process.versions.node }
27
+ : { kind: 'bun', command: execPath, version: bun };
28
+ }
29
+ /** Arguments placed before the child script. */
30
+ export function runtimeArgs(runtime, memoryLimitMb) {
31
+ if (runtime.kind === 'bun')
32
+ return [];
33
+ const args = [`--max-old-space-size=${memoryLimitMb}`];
34
+ // node:sqlite is unflagged from 22.13 / 23.4; earlier releases need the flag.
35
+ const [major = 0, minor = 0] = runtime.version.split('.').map(Number);
36
+ if ((major === 22 && minor < 13) || (major === 23 && minor < 4)) {
37
+ args.push('--experimental-sqlite');
38
+ }
39
+ return args;
40
+ }
41
+ /** `impact.maxMemoryMb`, or when null the smaller of 8,192 MB and half of physical RAM (D45). */
42
+ export function memoryLimitMb(configured, totalBytes = totalmem()) {
43
+ return configured ?? Math.min(8192, Math.floor(totalBytes / 2 / 2 ** 20));
44
+ }
@@ -0,0 +1,452 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { repositoryLimits } from '../graph/limits.js';
5
+ import { resolveRiskZones } from '../kernel/config.js';
6
+ import { isRecord } from '../kernel/guards.js';
7
+ import { impactConfigHash } from '../indexing/stamp.js';
8
+ import { matchGlob } from '../kernel/glob.js';
9
+ import { probe } from '../workspace/probe.js';
10
+ import { isCodeKind, kindOf, statVisible } from '../workspace/scan.js';
11
+ import { FAILURE_FILE, SCHEMA_VERSION, indexPath, openPublished, readFiles, readMeta, readSchemaVersion, } from '../../storage/sqlite.js';
12
+ import { consumeAuditWarning } from '../audit/log.js';
13
+ import { isHolderAlive, readLockHolder } from './lock.js';
14
+ import { chooseRuntime, memoryLimitMb } from './runtime.js';
15
+ import { pinnedTypescriptVersion, resolveTypescript } from './typescript.js';
16
+ import { loadWorkspace } from './workspace.js';
17
+ /** TOOLS.md §6 budget. */
18
+ export const STATUS_BUDGET = 3_000;
19
+ function stringList(raw) {
20
+ try {
21
+ const value = JSON.parse(raw ?? '[]');
22
+ return Array.isArray(value) ? value.filter((item) => typeof item === 'string') : [];
23
+ }
24
+ catch {
25
+ return [];
26
+ }
27
+ }
28
+ export function coverageOf(files) {
29
+ const coverage = {
30
+ scanned: files.length,
31
+ indexable: 0,
32
+ orphan: 0,
33
+ unindexed: 0,
34
+ reasons: {},
35
+ packages: new Set(files.map((file) => file.package).filter((pkg) => pkg !== null)).size,
36
+ };
37
+ for (const file of files) {
38
+ if (file.status === 'indexable')
39
+ coverage.indexable++;
40
+ if (file.status === 'orphan')
41
+ coverage.orphan++;
42
+ if (file.status === 'unindexed')
43
+ coverage.unindexed++;
44
+ if (file.reason !== null) {
45
+ coverage.reasons[file.reason] = (coverage.reasons[file.reason] ?? 0) + 1;
46
+ }
47
+ }
48
+ return coverage;
49
+ }
50
+ function grouped(db, sql) {
51
+ const result = {};
52
+ for (const row of db.prepare(sql).all())
53
+ result[String(row.k)] = Number(row.n);
54
+ return result;
55
+ }
56
+ function graphOf(db) {
57
+ const count = (sql) => Number(db.prepare(sql).get()?.n ?? 0);
58
+ const useRow = db
59
+ .prepare(`SELECT COALESCE(SUM(indexed_uses), 0) AS indexed,
60
+ COALESCE(SUM(local_uses), 0) AS local,
61
+ COALESCE(SUM(external), 0) AS external,
62
+ COALESCE(SUM(external_unresolved), 0) AS 'external-unresolved',
63
+ COALESCE(SUM(unresolved_other), 0) AS 'unresolved-other',
64
+ COALESCE(SUM(outside_scope), 0) AS 'outside-scope' FROM file_index`)
65
+ .get() ?? {};
66
+ return {
67
+ declarations: count("SELECT COUNT(*) AS n FROM declarations WHERE name != '<module>'"),
68
+ edges: count('SELECT COUNT(*) AS n FROM edges'),
69
+ uses: Object.fromEntries(Object.entries(useRow).map(([key, value]) => [key, Number(value)])),
70
+ extraction: grouped(db, 'SELECT extraction AS k, COUNT(*) AS n FROM file_index GROUP BY k'),
71
+ unresolved: grouped(db, 'SELECT reason AS k, COUNT(*) AS n FROM unresolved GROUP BY k'),
72
+ gapSites: grouped(db, 'SELECT code AS k, COUNT(*) AS n FROM gap_sites GROUP BY k'),
73
+ externalUnresolved: count('SELECT COALESCE(SUM(external_unresolved), 0) AS n FROM file_index'),
74
+ limits: repositoryLimits(db),
75
+ };
76
+ }
77
+ function presentationOf(db, files) {
78
+ let codeFiles = 0;
79
+ let outsideScope = 0;
80
+ for (const file of files) {
81
+ if (!isCodeKind(kindOf(file.path)))
82
+ continue;
83
+ codeFiles++;
84
+ if (file.reason === 'outside-index-scope')
85
+ outsideScope++;
86
+ }
87
+ return {
88
+ codeFiles,
89
+ outsideScope,
90
+ // Out-of-scope lexical rows serve the name cross-check, not index coverage.
91
+ extraction: grouped(db, `SELECT fi.extraction AS k, COUNT(*) AS n FROM file_index fi
92
+ JOIN files f ON f.path = fi.file
93
+ WHERE f.status IN ('indexable', 'orphan') GROUP BY k`),
94
+ };
95
+ }
96
+ /** Warn (strictly M > 2*N) when a positive `dir/*` include matches far fewer files than `dir/**`. */
97
+ function includeWarningsOf(include, paths) {
98
+ const warnings = [];
99
+ for (const pattern of include) {
100
+ if (pattern.startsWith('!') || !pattern.endsWith('/*'))
101
+ continue;
102
+ const wide = `${pattern}*`;
103
+ let narrow = 0;
104
+ let broad = 0;
105
+ for (const path of paths) {
106
+ if (matchGlob(pattern, path))
107
+ narrow++;
108
+ if (matchGlob(wide, path))
109
+ broad++;
110
+ }
111
+ if (broad > 2 * narrow) {
112
+ warnings.push(`include "${pattern}" matches ${narrow.toLocaleString('en-US')} files; "${wide}" would match ${broad.toLocaleString('en-US')}`);
113
+ }
114
+ }
115
+ return warnings;
116
+ }
117
+ /** Current visible paths: the stored census patched by drift, else one disk listing. */
118
+ async function visiblePaths(root, files, drift) {
119
+ if (files !== null && drift !== null) {
120
+ const gone = new Set(drift.deleted);
121
+ return [
122
+ ...files.filter((file) => !gone.has(file.path)).map((file) => file.path),
123
+ ...drift.added,
124
+ ];
125
+ }
126
+ return (await statVisible(root)).entries.map((entry) => entry.path);
127
+ }
128
+ /** The published index, read-only; null when none exists. Throws when it cannot be read. */
129
+ function readIndex(cacheDir, presentation) {
130
+ const db = openPublished(cacheDir);
131
+ if (db === null)
132
+ return null;
133
+ try {
134
+ const schemaVersion = readSchemaVersion(db);
135
+ const current = schemaVersion === SCHEMA_VERSION;
136
+ const meta = current ? readMeta(db) : {};
137
+ const files = current ? readFiles(db) : [];
138
+ return {
139
+ info: {
140
+ path: indexPath(cacheDir),
141
+ sizeBytes: statSync(indexPath(cacheDir)).size,
142
+ schemaVersion,
143
+ meta,
144
+ tsconfigs: stringList(meta.tsconfigs),
145
+ tsconfigBases: stringList(meta.tsconfig_bases),
146
+ tsconfigErrors: stringList(meta.tsconfig_errors),
147
+ coverage: coverageOf(files),
148
+ graph: current
149
+ ? graphOf(db)
150
+ : {
151
+ declarations: 0,
152
+ edges: 0,
153
+ uses: {},
154
+ extraction: {},
155
+ unresolved: {},
156
+ gapSites: {},
157
+ externalUnresolved: 0,
158
+ limits: { unboundedDynamicImports: 0, excludedFiles: 0, failedFiles: 0 },
159
+ },
160
+ },
161
+ files,
162
+ ...(current && presentation ? { presentation: presentationOf(db, files) } : {}),
163
+ };
164
+ }
165
+ finally {
166
+ db.close();
167
+ }
168
+ }
169
+ function readFailure(cacheDir, publishedAt) {
170
+ try {
171
+ const raw = JSON.parse(readFileSync(join(cacheDir, FAILURE_FILE), 'utf8'));
172
+ if (!isRecord(raw) || typeof raw.at !== 'string' || typeof raw.reason !== 'string')
173
+ return null;
174
+ // A later successful publish supersedes the failure.
175
+ if (publishedAt !== undefined && publishedAt > raw.at)
176
+ return null;
177
+ const problems = Array.isArray(raw.problems) ? raw.problems.map(String) : [];
178
+ return { at: raw.at, reason: raw.reason, problems };
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ }
184
+ function driftCount(drift) {
185
+ return drift.added.length + drift.deleted.length + drift.changed.length;
186
+ }
187
+ function degradation(status, configHash) {
188
+ const { typescript, index, indexError, drift, failure } = status;
189
+ if (!typescript.ok)
190
+ return [typescript.reason, typescript.fix];
191
+ if (indexError !== null)
192
+ return [`index unreadable: ${indexError}`, 'run: ei index'];
193
+ if (index === null)
194
+ return ['no index', 'run: ei index'];
195
+ if (index.schemaVersion !== SCHEMA_VERSION) {
196
+ return [
197
+ `index schema ${index.schemaVersion}, engine expects ${SCHEMA_VERSION}`,
198
+ 'run: ei index',
199
+ ];
200
+ }
201
+ if (failure !== null) {
202
+ return [`last build failed verification, older index kept`, 'run: ei doctor --deep'];
203
+ }
204
+ if (index.meta.config_hash !== configHash) {
205
+ return ['impact config changed since the last build', 'run: ei index'];
206
+ }
207
+ if (index.meta.typescript_version !== typescript.runtime.version) {
208
+ return [
209
+ `index built with typescript ${index.meta.typescript_version}, runtime is ${typescript.runtime.version}`,
210
+ 'run: ei index',
211
+ ];
212
+ }
213
+ if (drift !== null && driftCount(drift) > 0) {
214
+ return [`stale index: ${driftCount(drift)} files drifted`, 'run: ei index'];
215
+ }
216
+ return null;
217
+ }
218
+ /** Everything `ei_status` and `ei status` report; reads files only, never starts the engine. */
219
+ export async function workspaceStatus(start, options = {}) {
220
+ const workspace = await loadWorkspace(start, options.cacheHome);
221
+ const { impact } = workspace.config;
222
+ const [runtime, typescript] = await Promise.all([
223
+ chooseRuntime(options.env),
224
+ resolveTypescript({
225
+ version: pinnedTypescriptVersion(),
226
+ cacheHome: options.cacheHome,
227
+ repoRoot: workspace.root,
228
+ useWorkspaceTypescript: impact.useWorkspaceTypescript,
229
+ }),
230
+ ]);
231
+ let index = null;
232
+ let indexError = null;
233
+ let drift = null;
234
+ let census = null;
235
+ let presentation;
236
+ try {
237
+ const read = readIndex(workspace.cacheDir, options.presentation === 'index');
238
+ index = read?.info ?? null;
239
+ presentation = read?.presentation;
240
+ if (read && read.info.schemaVersion === SCHEMA_VERSION) {
241
+ census = read.files;
242
+ drift = await probe(workspace.root, impact, read.files);
243
+ }
244
+ }
245
+ catch (error) {
246
+ indexError = error instanceof Error ? error.message : String(error);
247
+ }
248
+ let includeWarnings = [];
249
+ // Reuses the census patched by drift; walks disk only when no probe result exists.
250
+ if (options.presentation !== undefined &&
251
+ impact.include.some((pattern) => !pattern.startsWith('!') && pattern.endsWith('/*'))) {
252
+ try {
253
+ includeWarnings = includeWarningsOf(impact.include, await visiblePaths(workspace.root, census, drift));
254
+ }
255
+ catch {
256
+ includeWarnings = []; // a failed scan must not break an otherwise valid status
257
+ }
258
+ }
259
+ const holder = readLockHolder(workspace.cacheDir);
260
+ const zones = resolveRiskZones(workspace.config.riskZones).map((zone) => zone.zone);
261
+ const partial = {
262
+ root: workspace.root,
263
+ repoId: workspace.repoId,
264
+ cacheDir: workspace.cacheDir,
265
+ config: { path: workspace.configPath, errors: workspace.configErrors, zones },
266
+ runtime,
267
+ memoryLimitMb: memoryLimitMb(impact.maxMemoryMb),
268
+ typescript,
269
+ index,
270
+ indexError,
271
+ failure: readFailure(workspace.cacheDir, index?.meta.built_at),
272
+ drift,
273
+ lock: holder && { pid: holder.pid, startedAt: holder.startedAt, alive: isHolderAlive(holder) },
274
+ };
275
+ const degraded = degradation(partial, impactConfigHash(impact));
276
+ const auditWarning = consumeAuditWarning(workspace.cacheDir);
277
+ return {
278
+ state: degraded === null ? 'ready' : 'degraded',
279
+ reason: degraded?.[0] ?? null,
280
+ fix: degraded?.[1] ?? null,
281
+ ...partial,
282
+ ...(auditWarning !== null ? { auditWarning } : {}),
283
+ ...(presentation !== undefined ? { presentation } : {}),
284
+ ...(includeWarnings.length > 0 ? { includeWarnings } : {}),
285
+ };
286
+ }
287
+ /** DESIGN §14: the engine's peak memory, as of the last build. */
288
+ function peakNote(raw) {
289
+ return raw === undefined
290
+ ? ''
291
+ : ` · engine peak ${Number(raw).toLocaleString('en-US')} MB (last build)`;
292
+ }
293
+ /** Why the index scope needed more than one program (DESIGN §6.2.1), from build metadata. */
294
+ function splitNote(raw) {
295
+ if (raw === undefined)
296
+ return '';
297
+ const parsed = JSON.parse(raw);
298
+ const keys = Array.isArray(parsed) ? parsed.map(String) : [];
299
+ return keys.length === 0 ? '' : ` (split by ${list(keys, 4)})`;
300
+ }
301
+ /** D49: the text shows home-relative paths; `details` keeps them absolute. */
302
+ export function homeRelative(path, home = homedir()) {
303
+ if (home === '' || home === '/')
304
+ return path;
305
+ if (path === home)
306
+ return '~';
307
+ return path.startsWith(`${home}/`) ? `~${path.slice(home.length)}` : path;
308
+ }
309
+ function list(items, max) {
310
+ const shown = items.slice(0, max).join(', ');
311
+ return items.length > max ? `${shown} (+${items.length - max} more)` : shown;
312
+ }
313
+ function seconds(ms) {
314
+ return ms === undefined ? '?' : `${(Number(ms) / 1000).toFixed(1)}`;
315
+ }
316
+ function kilobytes(bytes) {
317
+ return `${Math.max(1, Math.round(bytes / 1024)).toLocaleString('en-US')} KB`;
318
+ }
319
+ function counted(record) {
320
+ const entries = Object.entries(record)
321
+ .filter(([, n]) => n > 0)
322
+ .sort(([a], [b]) => (a < b ? -1 : 1));
323
+ return entries.length === 0 ? 'none' : entries.map(([k, n]) => `${k} ${n}`).join(' · ');
324
+ }
325
+ function phasesOf(meta) {
326
+ try {
327
+ const phases = JSON.parse(meta.phases ?? '{}');
328
+ if (!isRecord(phases))
329
+ return '';
330
+ const total = Object.values(phases).reduce((sum, ms) => sum + Number(ms), 0);
331
+ const parts = Object.entries(phases).map(([name, ms]) => `${name} ${seconds(Number(ms))}`);
332
+ return `${seconds(total)} s (${parts.join(' · ')})`;
333
+ }
334
+ catch {
335
+ return '';
336
+ }
337
+ }
338
+ function indexLine(status) {
339
+ const { index, drift } = status;
340
+ if (status.indexError !== null)
341
+ return `unreadable (${status.indexError}) · run: ei index`;
342
+ if (index === null)
343
+ return 'none · run: ei index';
344
+ const built = (index.meta.built_at ?? '?').slice(0, 16).replace('T', ' ');
345
+ let freshness = 'not probed';
346
+ if (drift !== null) {
347
+ // Live timings stay in `details.drift.ms`; the text is byte-identical for the same state.
348
+ const probeNote = `${drift.freshness} probe`;
349
+ freshness =
350
+ driftCount(drift) === 0
351
+ ? `fresh (${probeNote})`
352
+ : `stale: ${drift.changed.length} changed · ${drift.added.length} added · ${drift.deleted.length} deleted (${probeNote})`;
353
+ }
354
+ return `published ${built} UTC · ${freshness} · last ${index.meta.last_action ?? 'build'} ${phasesOf(index.meta)}`;
355
+ }
356
+ function coverageLine(coverage) {
357
+ const unindexedReasons = Object.entries(coverage.reasons)
358
+ .filter(([reason]) => reason !== 'no-tsconfig')
359
+ .sort(([a], [b]) => (a < b ? -1 : 1))
360
+ .map(([reason, count]) => `${reason} ${count}`);
361
+ const why = unindexedReasons.length > 0 ? ` (${unindexedReasons.join(' · ')})` : '';
362
+ return (`${coverage.scanned.toLocaleString('en-US')} scanned · ${coverage.indexable.toLocaleString('en-US')} indexable · ` +
363
+ `${coverage.orphan} orphan (no tsconfig) · ${coverage.unindexed.toLocaleString('en-US')} unindexed${why}`);
364
+ }
365
+ function problemsLine(index, failure) {
366
+ const { graph } = index;
367
+ const parts = [
368
+ `${graph.extraction['parse-error'] ?? 0} files failed to parse`,
369
+ `${graph.extraction['not-in-program'] ?? 0} not in a program`,
370
+ `${graph.unresolved['unresolved-import'] ?? 0} unresolved imports`,
371
+ `${graph.unresolved['unresolved-name-match'] ?? 0} unresolved name matches`,
372
+ graph.externalUnresolved === 0
373
+ ? 'dependencies installed: yes'
374
+ : `dependencies installed: no (${graph.externalUnresolved} bare imports unresolved)`,
375
+ ];
376
+ const reasons = failure === null
377
+ ? 'none'
378
+ : `${failure.reason}: ${list(failure.problems.map((p) => p.slice(0, 120)), 3)}`;
379
+ return `${parts.join(' · ')} · incompleteReasons: ${reasons}`;
380
+ }
381
+ function typescriptLine(ts) {
382
+ if (!ts.ok)
383
+ return `${ts.reason} · ${ts.fix}`;
384
+ const trust = ts.sha256 === null
385
+ ? 'workspace copy, not hash-pinned'
386
+ : `verified sha256 ${ts.sha256.slice(0, 12)}`;
387
+ return `${ts.runtime.version} (${ts.runtime.source}) · ${homeRelative(ts.runtime.path)} · ${trust}`;
388
+ }
389
+ /** The `ei_status` / `ei status` text (TOOLS.md §6). */
390
+ export function renderStatus(status) {
391
+ const lines = [
392
+ status.state === 'ready'
393
+ ? 'STATUS ready'
394
+ : `STATUS degraded (${status.reason}) · ${status.fix}`,
395
+ `Index ${indexLine(status)}`,
396
+ ];
397
+ const { index, drift } = status;
398
+ if (index !== null) {
399
+ lines.push(`Coverage ${coverageLine(index.coverage)}`);
400
+ const { graph, meta } = index;
401
+ lines.push(`Graph ${graph.declarations.toLocaleString('en-US')} declarations · ${graph.edges.toLocaleString('en-US')} edges · ` +
402
+ `programs ${meta.programs ?? '?'}${splitNote(meta.program_split)}`);
403
+ lines.push(`Problems ${problemsLine(index, status.failure)}`);
404
+ lines.push(`Gap sites ${counted(graph.gapSites)}`);
405
+ const { limits } = graph;
406
+ lines.push(`Limits ${limits.unboundedDynamicImports} unbounded dynamic imports · ${limits.excludedFiles} excluded files · ${limits.failedFiles} failed to index`);
407
+ const tsconfigProblems = index.tsconfigErrors.length === 0
408
+ ? 'none'
409
+ : `${index.tsconfigErrors.length}: ${list(index.tsconfigErrors.map((error) => error.slice(0, 160)), 3)}`;
410
+ lines.push(`Scope ${index.coverage.packages} packages · tsconfigs ${index.tsconfigs.length} (${list(index.tsconfigs, 6)}) · bases ${index.tsconfigBases.length} · tsconfig problems ${tsconfigProblems}`);
411
+ }
412
+ if (drift !== null && driftCount(drift) > 0) {
413
+ lines.push(`Drift ${list([...drift.changed, ...drift.added, ...drift.deleted], 5)}`);
414
+ }
415
+ const config = status.config;
416
+ const zonesText = config.zones.length === 0 ? 'none' : list(config.zones, 8);
417
+ if (config.path === null) {
418
+ lines.push(`Config no ei.config.json · detected defaults (run: ei init) · zones: ${zonesText}`);
419
+ }
420
+ else if (config.errors.length === 0) {
421
+ lines.push(`Config ei.config.json ok · zones: ${zonesText}`);
422
+ }
423
+ else {
424
+ lines.push(`Config ei.config.json: ${config.errors.length} problems, defaults used for those sections: ${list(config.errors, 3)} · zones: ${zonesText}`);
425
+ }
426
+ lines.push(`Runtime ${status.runtime.kind} ${status.runtime.version} (${homeRelative(status.runtime.command)}) · memory limit ${status.memoryLimitMb.toLocaleString('en-US')} MB${peakNote(status.index?.meta.peak_rss_mb)}`);
427
+ lines.push(`TypeScript ${typescriptLine(status.typescript)}`);
428
+ lines.push(index === null
429
+ ? `Store none yet · cache ${homeRelative(status.cacheDir)}`
430
+ : `Store ${homeRelative(index.path)} · ${kilobytes(index.sizeBytes)} · schema ${index.schemaVersion}`);
431
+ const lock = status.lock;
432
+ if (lock === null)
433
+ lines.push('Lock free');
434
+ else if (lock.alive)
435
+ lines.push(`Lock held by pid ${lock.pid} since ${lock.startedAt}`);
436
+ else
437
+ lines.push(`Lock stale (pid ${lock.pid} gone; the next build takes it over)`);
438
+ if (index !== null) {
439
+ const { indexed = 0, ...skippedUses } = index.graph.uses;
440
+ const useTotal = Object.values(index.graph.uses).reduce((sum, count) => sum + count, 0);
441
+ lines.push(`Uses approximate · indexed ${indexed.toLocaleString('en-US')} · skipped ${counted(skippedUses)} · ` +
442
+ `indexed share ${useTotal === 0 ? 'n/a' : `${((indexed / useTotal) * 100).toFixed(1)}%`}`);
443
+ }
444
+ if (status.auditWarning) {
445
+ lines.push(`Audit write failed (${status.auditWarning}); non-blocking`);
446
+ }
447
+ const text = lines.join('\n');
448
+ // Budget guard: lists above are already capped with "+N more"; this only fires on huge paths.
449
+ return text.length <= STATUS_BUDGET
450
+ ? text
451
+ : `${text.slice(0, STATUS_BUDGET - 40)}\n… (truncated at ${STATUS_BUDGET} characters)`;
452
+ }