@krisada-m/ksd-intelligence 1.0.0 → 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 (40) hide show
  1. package/.antigravity-plugin/plugin.json +20 -0
  2. package/README.md +36 -8
  3. package/agy-skills/erosiano-review/SKILL.md +17 -0
  4. package/dist/adapters/cli/check-changed.js +1 -1
  5. package/dist/adapters/cli/main.js +29 -18
  6. package/dist/adapters/cli/review-verdict.js +1 -1
  7. package/dist/adapters/omp/extension.js +7 -16
  8. package/dist/adapters/ui/hud.js +99 -28
  9. package/dist/adapters/ui/tree.js +11 -0
  10. package/dist/core/engine/status.js +73 -2
  11. package/dist/core/indexing/indexer.js +24 -5
  12. package/dist/engineering/baseline.js +337 -0
  13. package/dist/{policy → engineering}/config.js +33 -10
  14. package/dist/{policy → engineering}/dist/policy.d.ts +3 -3
  15. package/dist/{policy → engineering}/dist/policy.js +25 -22
  16. package/dist/{policy → engineering}/dist/runtime.js +11 -9
  17. package/dist/engineering/index.d.ts +7 -0
  18. package/dist/engineering/index.js +319 -0
  19. package/dist/engineering/intelligence.js +44 -0
  20. package/dist/{policy → engineering}/package.json +7 -4
  21. package/dist/engineering/practice-tool.js +72 -0
  22. package/dist/engineering/practices.js +283 -0
  23. package/dist/engineering/practices.json +2453 -0
  24. package/engineering.lock.json +94 -0
  25. package/package.json +13 -6
  26. package/rules/engineering.md +20 -0
  27. package/scripts/mcp/engineering.mjs +91 -0
  28. package/scripts/mcp/tools.mjs +45 -5
  29. package/dist/policy/index.d.ts +0 -2
  30. package/dist/policy/index.js +0 -241
  31. package/dist/policy/policy.d.ts +0 -2
  32. /package/dist/{policy → engineering}/change-scope.js +0 -0
  33. /package/dist/{policy → engineering}/check-changed.js +0 -0
  34. /package/dist/{policy → engineering}/dist/runtime.d.ts +0 -0
  35. /package/dist/{policy → engineering}/dist/sdlc.d.ts +0 -0
  36. /package/dist/{policy → engineering}/dist/sdlc.js +0 -0
  37. /package/dist/{policy → engineering}/eslint-rules/index.js +0 -0
  38. /package/dist/{policy → engineering}/policy.js +0 -0
  39. /package/dist/{policy → engineering}/review-verdict.js +0 -0
  40. /package/dist/{policy → engineering}/sdlc.js +0 -0
@@ -40,6 +40,14 @@ function isConfigLevel(path) {
40
40
  name === 'ei.config.json' ||
41
41
  LOCKFILES.has(name));
42
42
  }
43
+ const CONFIG_CHANGED = 'config changed: ';
44
+ /** HUD wording only: a lockfile is a dependency change, not a config edit. */
45
+ function lockfileHudReason(reason) {
46
+ if (!reason.startsWith(CONFIG_CHANGED))
47
+ return reason;
48
+ const path = reason.slice(CONFIG_CHANGED.length);
49
+ return LOCKFILES.has(basename(path)) ? `lockfile changed: ${path}` : reason;
50
+ }
43
51
  function diffCensus(before, now) {
44
52
  const old = new Map(before.map((file) => [file.path, file]));
45
53
  const drift = {
@@ -222,7 +230,8 @@ export class Indexer {
222
230
  verify: 0,
223
231
  publish: 0,
224
232
  };
225
- const stamp = extractorStamp(this.ts.version, impactConfigHash(request.impact));
233
+ const configHash = impactConfigHash(request.impact);
234
+ const stamp = extractorStamp(this.ts.version, configHash);
226
235
  const started = performance.now();
227
236
  const published = this.readPublished();
228
237
  const fingerprint = request.freshness === 'stat' && published !== null
@@ -236,7 +245,16 @@ export class Indexer {
236
245
  const drift = published === null ? null : diffCensus(published.files, census.records);
237
246
  const coldReason = this.coldReason(request, stamp, published, drift);
238
247
  if (coldReason !== null || published === null || drift === null) {
239
- return this.cold(census, coldReason ?? 'no published index', stamp, request, phases, progress, hud, started);
248
+ // HUD-only wording: report.reason and build history keep the raw reason.
249
+ const stored = published?.meta.config_hash;
250
+ let shown;
251
+ if (coldReason === 'extractor stamp changed') {
252
+ shown =
253
+ stored !== undefined && stored !== configHash
254
+ ? 'config changed'
255
+ : 'engine updated (extractor stamp changed)';
256
+ }
257
+ return this.cold(census, coldReason ?? 'no published index', stamp, request, phases, progress, hud, started, shown);
240
258
  }
241
259
  const contentDrift = drift.added.size + drift.changed.size + drift.deleted.size;
242
260
  if (contentDrift === 0 && drift.touched === 0) {
@@ -420,10 +438,11 @@ export class Indexer {
420
438
  oldProgram: group.program,
421
439
  });
422
440
  }
423
- cold(census, reason, stamp, request, phases, progress, hud, runStarted) {
441
+ cold(census, reason, stamp, request, phases, progress, hud, runStarted, hudReason) {
442
+ const shown = hudReason ?? lockfileHudReason(reason);
424
443
  let started = performance.now();
425
444
  progress('program');
426
- hud({ phase: 'program', kind: 'cold', reason });
445
+ hud({ phase: 'program', kind: 'cold', reason: shown });
427
446
  const programs = this.createPrograms(census.records);
428
447
  phases.program += performance.now() - started;
429
448
  const indexable = census.records.filter((r) => r.status === 'indexable').map((r) => r.path);
@@ -438,7 +457,7 @@ export class Indexer {
438
457
  const sourceFile = (path) => ownerGroup.get(path)?.program.getSourceFile(join(this.root, path));
439
458
  // EXTRACT-LOCAL: declarations from each file's syntax tree; their names scope the resolve.
440
459
  progress('extract', { files: indexable.length });
441
- hud({ phase: 'extract', done: 0, total: indexable.length, kind: 'cold', reason });
460
+ hud({ phase: 'extract', done: 0, total: indexable.length, kind: 'cold', reason: shown });
442
461
  started = performance.now();
443
462
  const declarations = new Map();
444
463
  let extracted = 0;
@@ -0,0 +1,337 @@
1
+ #!/usr/bin/env node
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, opendirSync, readSync, realpathSync } from "node:fs";
3
+ import { createHash } from "node:crypto";
4
+ import { spawnSync } from "node:child_process";
5
+ import { devNull } from "node:os";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ const MAX_FILES = 64;
10
+ const MAX_ADDITIONAL_PATHS = 24;
11
+ const MAX_FILE_BYTES = 128 * 1024;
12
+ const MAX_DIRECTORY_ENTRIES = 256;
13
+ const KNOWN_FILES = [
14
+ "AGENTS.md", "README.md", "CONTRIBUTING.md", "package.json", "tsconfig.json", "jsconfig.json",
15
+ "eslint.config.js", "eslint.config.mjs", "eslint.config.cjs", ".eslintrc.json", "biome.json", "biome.jsonc",
16
+ ".prettierrc", ".prettierrc.json", "vitest.config.ts", "vitest.config.js", "jest.config.js", "jest.config.ts",
17
+ ".erosiano-dev.json", ".engineering-proxy.json", ".editorconfig", "turbo.json", "nx.json", "tsconfig.base.json",
18
+ "Makefile", "Dockerfile", "compose.yml", "compose.yaml", "docker-compose.yml", "docker-compose.yaml",
19
+ "pnpm-workspace.yaml", "package-lock.json", "pnpm-lock.yaml", "yarn.lock", "bun.lock",
20
+ "pyproject.toml", "requirements.txt", "go.mod", "Cargo.toml", "Gemfile", "composer.json", "pom.xml",
21
+ ];
22
+ const SKIP_DIRECTORIES = new Set([".git", "node_modules", ".venv", "vendor", "dist", "build", ".cache", ".omp", ".next"]);
23
+ const SOURCE_FILE = /\.(?:[cm]?[jt]sx?|py|go|rs|java|kt|cs|rb|php|sql|css|html|vue|svelte)$/i;
24
+ const SECRET_NAME = /(?:^\.env(?:\.|$)|(?:credential|secret|password|token|private.?key)|\.(?:pem|key|p12|pfx)$)/i;
25
+ const CONTROL = /[\u0000-\u001f\u007f]/;
26
+ const EXPLICIT_EVIDENCE = /\.(?:md|jsonc?|ya?ml|toml|ini|xml|sh)$/i;
27
+
28
+ function supportedEvidence(path) {
29
+ const name = basename(path);
30
+
31
+ return SOURCE_FILE.test(name) || KNOWN_FILES.includes(name) || EXPLICIT_EVIDENCE.test(name);
32
+ }
33
+
34
+ const sha256 = data => createHash("sha256").update(data).digest("hex");
35
+
36
+ function within(root, path) {
37
+ const rel = relative(root, path);
38
+
39
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(".." + sep));
40
+ }
41
+
42
+ function info(path) {
43
+ try {
44
+ return lstatSync(path);
45
+ } catch (error) {
46
+ if (error.code === "ENOENT" || error.code === "ENOTDIR") return null;
47
+ throw error;
48
+ }
49
+ }
50
+
51
+ function safePath(root, requested) {
52
+ if (typeof requested !== "string" || !requested || CONTROL.test(requested)) throw new Error("Invalid scope path");
53
+ const path = resolve(root, requested);
54
+ if (!within(root, path)) throw new Error("Scope is outside the project root");
55
+ const rel = relative(root, path);
56
+ let current = root;
57
+ for (const part of rel.split(sep).filter(Boolean)) {
58
+ if (SECRET_NAME.test(part) || SKIP_DIRECTORIES.has(part)) throw new Error("Excluded scope path");
59
+ current = join(current, part);
60
+ const metadata = info(current);
61
+ if (!metadata || metadata.isSymbolicLink()) throw new Error("Missing or symlinked scope path");
62
+ }
63
+
64
+ return path;
65
+ }
66
+
67
+ /** Read only bounded regular files at their canonical in-root paths. Never emit file contents. */
68
+ function boundedRead(root, path) {
69
+ const metadata = info(path);
70
+ if (!metadata) return { status: "absent" };
71
+ if (!metadata.isFile() || metadata.isSymbolicLink() || !within(root, path) || realpathSync(path) !== path) return { status: "excluded" };
72
+ if (metadata.size > MAX_FILE_BYTES) return { status: "oversize" };
73
+
74
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
75
+ try {
76
+ const before = fstatSync(fd);
77
+ if (!before.isFile() || before.size > MAX_FILE_BYTES || before.ino !== metadata.ino || before.dev !== metadata.dev) return { status: "changed" };
78
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
79
+ let length = 0;
80
+ while (length < buffer.length) {
81
+ const read = readSync(fd, buffer, length, buffer.length - length, null);
82
+ if (!read) break;
83
+ length += read;
84
+ }
85
+ const after = fstatSync(fd);
86
+ if (length > MAX_FILE_BYTES || before.size !== length || before.size !== after.size || before.mtimeMs !== after.mtimeMs || before.ctimeMs !== after.ctimeMs) return { status: "changed" };
87
+
88
+ return { status: "read", bytes: buffer.subarray(0, length) };
89
+ } finally {
90
+ closeSync(fd);
91
+ }
92
+ }
93
+
94
+ function revision(root) {
95
+ try {
96
+ const gitDir = info(join(root, ".git"));
97
+ if (!gitDir?.isDirectory() || gitDir.isSymbolicLink()) return { status: "unknown", reason: "No local Git metadata directory (linked worktrees require agent evidence)" };
98
+ const head = boundedRead(root, join(root, ".git", "HEAD"));
99
+ if (head.status !== "read") return { status: "unknown", reason: "HEAD unavailable" };
100
+ const value = head.bytes.toString("utf8").trim();
101
+ if (/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value)) return { status: "observed", head: value, branch: null };
102
+ const match = /^ref: (refs\/heads\/[A-Za-z0-9._/-]+)$/.exec(value);
103
+ if (!match || match[1].split("/").some(part => part === "." || part === ".." || part === "")) return { status: "unknown", reason: "Unsupported HEAD reference" };
104
+ const ref = boundedRead(root, join(root, ".git", match[1]));
105
+ let commit = ref.status === "read" ? ref.bytes.toString("utf8").trim() : undefined;
106
+ if (ref.status === "absent") {
107
+ const packed = boundedRead(root, join(root, ".git", "packed-refs"));
108
+ const line = packed.status === "read" ? packed.bytes.toString("utf8").split("\n").find(entry => entry.endsWith(" " + match[1])) : undefined;
109
+ commit = line?.split(" ")[0];
110
+ }
111
+ if (!commit || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(commit)) return { status: "unknown", reason: "Branch reference unavailable" };
112
+
113
+ return { status: "observed", head: commit, branch: match[1] };
114
+ } catch {
115
+ return { status: "unknown", reason: "Git metadata unreadable" };
116
+ }
117
+ }
118
+
119
+ // Opt-in only for the operator-invoked CLI. Never invoked during an ordinary agent turn.
120
+ // Git handles its own linked-worktree metadata. No shell, no repository hooks or inherited GIT_* overrides.
121
+ function nativeRevision(root) {
122
+ const env = {
123
+ PATH: process.env.PATH ?? "/usr/bin:/bin",
124
+ GIT_CONFIG_NOSYSTEM: "1",
125
+ GIT_CONFIG_GLOBAL: devNull,
126
+ GIT_OPTIONAL_LOCKS: "0",
127
+ GIT_TERMINAL_PROMPT: "0",
128
+ };
129
+ const run = args => spawnSync("git", ["-C", root, ...args], { env, encoding: "utf8", timeout: 2000, maxBuffer: 16384, shell: false });
130
+ try {
131
+ const result = run(["rev-parse", "--show-toplevel", "HEAD"]);
132
+ if (result.error || result.status !== 0) return { status: "unknown", reason: "Native Git revision unavailable" };
133
+ const [top, head, ...rest] = result.stdout.trimEnd().split("\n");
134
+ if (rest.length || !top || CONTROL.test(top) || realpathSync(top) !== root || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(head ?? "")) {
135
+ return { status: "unknown", reason: "Native Git root or revision did not match" };
136
+ }
137
+ const symbolic = run(["symbolic-ref", "--quiet", "HEAD"]);
138
+ if (symbolic.error) return { status: "unknown", reason: "Native Git branch unavailable" };
139
+ const branch = symbolic.status === 0 ? symbolic.stdout.trim() : null;
140
+ if (symbolic.status !== 0 && symbolic.status !== 1) return { status: "unknown", reason: "Native Git branch unavailable" };
141
+ if (branch !== null && !/^refs\/heads\/[A-Za-z0-9._/-]+$/.test(branch)) return { status: "unknown", reason: "Unsupported native Git reference" };
142
+
143
+ return { status: "observed", head, branch };
144
+ } catch {
145
+ return { status: "unknown", reason: "Native Git metadata unreadable" };
146
+ }
147
+ }
148
+
149
+ function directorySample(path) {
150
+ const dir = opendirSync(path);
151
+ const entries = [];
152
+ let scanned = 0;
153
+ let truncated = false;
154
+ try {
155
+ while (true) {
156
+ const entry = dir.readSync();
157
+ if (!entry) break;
158
+ scanned++;
159
+ if (scanned > MAX_DIRECTORY_ENTRIES) {
160
+ truncated = true;
161
+ break;
162
+ }
163
+ if (CONTROL.test(entry.name) || SECRET_NAME.test(entry.name) || SKIP_DIRECTORIES.has(entry.name)) continue;
164
+ const kind = entry.isFile() ? "file" : entry.isDirectory() ? "directory" : entry.isSymbolicLink() ? "symlink" : "other";
165
+ entries.push({ name: entry.name, kind });
166
+ }
167
+ } finally {
168
+ dir.closeSync();
169
+ }
170
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
171
+
172
+ return { entries, truncated };
173
+ }
174
+
175
+ function role(path) {
176
+ const name = basename(path);
177
+ if (["AGENTS.md", "README.md", "CONTRIBUTING.md"].includes(name)) return "instruction";
178
+ if (KNOWN_FILES.includes(name) || path.split(sep).includes("workflows")) return "tooling";
179
+ if (/(?:^|[.])(?:test|spec)\.[^.]+$/.test(name)) return "test";
180
+
181
+ return "source";
182
+ }
183
+
184
+ /** A bounded snapshot of sampled evidence, not an inferred or complete project convention baseline. */
185
+ export function collectBaselineEvidence({ root, scope = ".", additionalPaths = [], useGit = false }) {
186
+ if (typeof root !== "string" || !root || typeof scope !== "string" || !scope) throw new Error("Expected project root and scope");
187
+ if (!Array.isArray(additionalPaths) || additionalPaths.length > MAX_ADDITIONAL_PATHS) throw new Error("Too many explicit evidence paths");
188
+ if (typeof useGit !== "boolean") throw new Error("Invalid native Git option");
189
+
190
+ const requestedRoot = resolve(root);
191
+ const canonicalRoot = realpathSync(requestedRoot);
192
+ if (!info(canonicalRoot)?.isDirectory()) throw new Error("Project root must be a directory");
193
+ // Absolute cwd values can use a symlink alias of the operator-selected root (not a scope symlink).
194
+ const scoped = isAbsolute(scope) && within(requestedRoot, resolve(scope)) ? relative(requestedRoot, resolve(scope)) || "." : scope;
195
+ const target = safePath(canonicalRoot, scoped);
196
+ const targetInfo = info(target);
197
+ if (!targetInfo?.isFile() && !targetInfo?.isDirectory()) throw new Error("Scope must be a file or directory");
198
+ if (targetInfo.isFile() && !supportedEvidence(target)) throw new Error("Unsupported evidence file type");
199
+
200
+ const targetDirectory = targetInfo.isDirectory() ? target : dirname(target);
201
+ const evidence = [];
202
+ const unknowns = [];
203
+ const candidates = new Set();
204
+ const readRevision = useGit ? nativeRevision : revision;
205
+ const revisionBefore = readRevision(canonicalRoot);
206
+ if (targetInfo.isFile()) candidates.add(target);
207
+ // Callers, test files and CI/tooling beyond the direct sample must be explicit and bounded.
208
+ const explicit = new Set();
209
+ for (const requested of additionalPaths) {
210
+ if (typeof requested !== "string" || isAbsolute(requested)) throw new Error("Additional evidence paths must be relative to the project root");
211
+ const path = safePath(canonicalRoot, requested);
212
+ if (!info(path)?.isFile() || !supportedEvidence(path)) throw new Error("Unsupported additional evidence file");
213
+ explicit.add(relative(canonicalRoot, path));
214
+ candidates.add(path);
215
+ }
216
+ let current = targetDirectory;
217
+ while (true) {
218
+ for (const name of KNOWN_FILES) {
219
+ if (candidates.size >= MAX_FILES) {
220
+ unknowns.push("Evidence file cap reached");
221
+ break;
222
+ }
223
+ const path = join(current, name);
224
+ try {
225
+ if (info(path)) candidates.add(path);
226
+ } catch {
227
+ unknowns.push("Tooling evidence inaccessible");
228
+ }
229
+ }
230
+ if (current === canonicalRoot || candidates.size >= MAX_FILES) break;
231
+ current = dirname(current);
232
+ }
233
+ let directory;
234
+ try {
235
+ const sample = directorySample(targetDirectory);
236
+ directory = { path: relative(canonicalRoot, targetDirectory) || ".", fingerprint: sha256(JSON.stringify(sample.entries)), count: sample.entries.length, truncated: sample.truncated };
237
+ if (sample.truncated) unknowns.push("Directory inventory truncated");
238
+ for (const entry of sample.entries) {
239
+ if (!SOURCE_FILE.test(entry.name)) continue;
240
+ if (entry.kind !== "file") {
241
+ unknowns.push("Nonregular source evidence excluded");
242
+ continue;
243
+ }
244
+ if (candidates.size >= MAX_FILES) {
245
+ unknowns.push("Source sample cap reached");
246
+ break;
247
+ }
248
+ candidates.add(join(targetDirectory, entry.name));
249
+ }
250
+ } catch {
251
+ unknowns.push("Directory inventory unavailable");
252
+ }
253
+ for (const path of [...candidates].sort()) {
254
+ const rel = relative(canonicalRoot, path);
255
+ try {
256
+ const result = boundedRead(canonicalRoot, path);
257
+ if (result.status !== "read") {
258
+ unknowns.push("Evidence " + result.status + ": " + rel);
259
+ continue;
260
+ }
261
+ evidence.push({ path: rel, role: role(path), sha256: sha256(result.bytes), bytes: result.bytes.length });
262
+ } catch {
263
+ unknowns.push("Evidence unreadable: " + rel);
264
+ }
265
+ }
266
+ const revisionAfter = readRevision(canonicalRoot);
267
+ if (revisionBefore.status !== "observed" || revisionAfter.status !== "observed" || JSON.stringify(revisionBefore) !== JSON.stringify(revisionAfter)) unknowns.push("Git revision unavailable or changed during discovery");
268
+ const record = { schemaVersion: 1, root: canonicalRoot, scope: relative(canonicalRoot, target) || ".", revision: revisionAfter,
269
+ additionalPaths: [...explicit].sort(), revisionSource: useGit ? "native-git" : "local-metadata",
270
+ evidence, directory, unknowns: [...new Set(unknowns)], confidence: "LOW", coverage: "SAMPLED_EVIDENCE_ONLY" };
271
+ const fingerprint = sha256(JSON.stringify(record));
272
+
273
+ return { ...record, fingerprint, cacheable: record.unknowns.length === 0 };
274
+ }
275
+
276
+ export class ScopedBaselineCache {
277
+ #entries = new Map();
278
+
279
+ capture(input) {
280
+ const snapshot = collectBaselineEvidence(input);
281
+ const key = JSON.stringify([snapshot.root, snapshot.scope, snapshot.additionalPaths, snapshot.revisionSource]);
282
+ const previous = this.#entries.get(key);
283
+ const matched = snapshot.cacheable && previous?.cacheable && previous.fingerprint === snapshot.fingerprint;
284
+ this.#entries.delete(key);
285
+ if (snapshot.cacheable) this.#entries.set(key, snapshot);
286
+ if (this.#entries.size > 16) this.#entries.delete(this.#entries.keys().next().value);
287
+
288
+ return { ...snapshot, freshness: matched ? "MATCHED_SCOPED_EVIDENCE" : "NEW_OR_INCOMPLETE_EVIDENCE" };
289
+ }
290
+
291
+ clear() {
292
+ this.#entries.clear();
293
+ }
294
+ }
295
+
296
+ export function summarizeBaselineEvidence(record) {
297
+ const paths = record.evidence.slice(0, 12).map(item => item.path);
298
+
299
+ return JSON.stringify({ scope: record.scope, revision: record.revision, sampled: record.evidence.length, examplePaths: paths,
300
+ fingerprint: record.fingerprint, freshness: record.freshness, confidence: record.confidence, unknowns: record.unknowns.slice(0, 8),
301
+ limitation: "Only sampled bytes and direct directory inventory matched, not all dirty/untracked files, callers, or conventions. Discover remaining evidence through approved tools." });
302
+ }
303
+
304
+ function main(args) {
305
+ const usage = "Usage: erosiano-baseline --root project --scope relative-path [--include relative-file]... [--git]";
306
+ if (args.length < 4 || args[0] !== "--root" || args[2] !== "--scope") throw new Error(usage);
307
+ const additionalPaths = [];
308
+ let useGit = false;
309
+ for (let i = 4; i < args.length; i++) {
310
+ if (args[i] === "--git" && !useGit) {
311
+ useGit = true;
312
+ continue;
313
+ }
314
+ if (args[i] !== "--include" || i + 1 >= args.length || args[i + 1].startsWith("--")) throw new Error(usage);
315
+ additionalPaths.push(args[++i]);
316
+ }
317
+ console.log(JSON.stringify(collectBaselineEvidence({ root: args[1], scope: args[3], additionalPaths, useGit }), null, 2));
318
+ }
319
+
320
+ function isMainModule() {
321
+ try {
322
+ if (!process.argv[1]) return false;
323
+
324
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
325
+ } catch {
326
+ return false;
327
+ }
328
+ }
329
+
330
+ if (isMainModule()) {
331
+ try {
332
+ main(process.argv.slice(2));
333
+ } catch (error) {
334
+ console.error("Baseline evidence NOT_ASSESSED: " + error.message);
335
+ process.exitCode = 2;
336
+ }
337
+ }
@@ -1,7 +1,7 @@
1
1
  import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { homedir } from "node:os";
4
- import { dirname, join, resolve } from "node:path";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
5
 
6
6
  // Single source of truth for the supported modes; exported under the historical name.
7
7
  import { KSD_MODES } from "./sdlc.js";
@@ -9,7 +9,7 @@ export const SUPPORTED_MODES = KSD_MODES;
9
9
  const DEFAULT = Object.freeze({ enabled: true, enforcement: "balanced" });
10
10
 
11
11
  export function getGlobalConfigPath() {
12
- return join(homedir(), ".omp", "agent", "engineering-proxy.json");
12
+ return join(homedir(), ".omp", "agent", "erosiano-dev.json");
13
13
  }
14
14
 
15
15
  function realPath(path) {
@@ -41,8 +41,8 @@ function readScopedConfig(path, label) {
41
41
  let parsed;
42
42
  try {
43
43
  parsed = JSON.parse(readFileSync(path, "utf8"));
44
- } catch (error) {
45
- return { present: true, values: {}, error: `Cannot parse ${label}: ${error.message}` };
44
+ } catch {
45
+ return { present: true, values: {}, error: `Cannot parse ${label}` };
46
46
  }
47
47
 
48
48
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) ||
@@ -54,11 +54,29 @@ function readScopedConfig(path, label) {
54
54
  return { present: true, values: parsed };
55
55
  }
56
56
 
57
+ function selectConfig(path, legacyPath, label) {
58
+ const current = readScopedConfig(path, label);
59
+ const legacy = legacyPath ? readScopedConfig(legacyPath, `${label} (legacy)`) : { present: false, values: {} };
60
+ if (!current.present && legacy.present) return { ...legacy, source: legacyPath, legacy: true };
61
+ if (!legacy.present) return { ...current, source: path };
62
+
63
+ const conflict = current.error || legacy.error || JSON.stringify(current.values) !== JSON.stringify(legacy.values);
64
+ const warning = `${label}: new config is authoritative; legacy config ignored${conflict ? " (different or invalid values)" : ""}`;
65
+
66
+ return { ...current, source: path, warning };
67
+ }
68
+
69
+ function legacyGlobalPath(path) {
70
+ if (basename(path) === "erosiano-dev.json") return join(dirname(path), "engineering-proxy.json");
71
+
72
+ return undefined;
73
+ }
74
+
57
75
  export function loadConfig(cwd, { globalConfigPath = getGlobalConfigPath() } = {}) {
58
76
  const root = findProjectRoot(cwd);
59
- const projectConfigPath = join(root, ".engineering-proxy.json");
60
- const global = readScopedConfig(globalConfigPath, "global engineering-proxy.json");
61
- const project = readScopedConfig(projectConfigPath, ".engineering-proxy.json");
77
+ const projectConfigPath = join(root, ".erosiano-dev.json");
78
+ const global = selectConfig(globalConfigPath, legacyGlobalPath(globalConfigPath), "global erosiano-dev.json");
79
+ const project = selectConfig(projectConfigPath, join(root, ".engineering-proxy.json"), ".erosiano-dev.json");
62
80
  const configError = global.error ?? project.error;
63
81
  const enforcementSource = project.values.enforcement !== undefined ? "project"
64
82
  : global.values.enforcement !== undefined ? "global" : "default";
@@ -72,6 +90,9 @@ export function loadConfig(cwd, { globalConfigPath = getGlobalConfigPath() } = {
72
90
  globalConfigPresent: global.present,
73
91
  projectConfigPath,
74
92
  globalConfigPath,
93
+ projectConfigSource: project.source,
94
+ globalConfigSource: global.source,
95
+ configWarnings: [global.warning, project.warning].filter(Boolean),
75
96
  projectEnforcement: project.values.enforcement,
76
97
  globalEnforcement: global.values.enforcement,
77
98
  enforcementSource,
@@ -84,10 +105,12 @@ export function setScopedMode(cwd, scope, mode, { globalConfigPath = getGlobalCo
84
105
  if (scope !== "global" && scope !== "repo") throw new Error("Scope must be global or repo");
85
106
  if (mode !== null && !SUPPORTED_MODES.includes(mode)) throw new Error("Unsupported enforcement mode");
86
107
 
87
- const path = scope === "global" ? globalConfigPath : join(findProjectRoot(cwd), ".engineering-proxy.json");
88
- const existing = readScopedConfig(path, scope === "global" ? "global engineering-proxy.json" : ".engineering-proxy.json");
108
+ const root = findProjectRoot(cwd);
109
+ const path = scope === "global" ? globalConfigPath : join(root, ".erosiano-dev.json");
110
+ const legacyPath = scope === "global" ? legacyGlobalPath(path) : join(root, ".engineering-proxy.json");
111
+ const existing = selectConfig(path, legacyPath, scope === "global" ? "global erosiano-dev.json" : ".erosiano-dev.json");
89
112
  if (existing.error) throw new Error(existing.error);
90
- if (mode === null && existing.values.enforcement === undefined) return path;
113
+ if (mode === null && existing.values.enforcement === undefined && !existing.legacy) return path;
91
114
 
92
115
  const next = { ...existing.values };
93
116
  if (mode === null) delete next.enforcement;
@@ -1,7 +1,7 @@
1
1
  import { type KsdMode } from "./sdlc.js";
2
- export declare const SECTION_KEY = "engineering-proxy";
3
- export declare const POLICY_MARKER = "[Engineering Proxy Policy]";
4
- export declare const POLICY_END = "[End Engineering Proxy Policy]";
2
+ export declare const SECTION_KEY = "erosiano-dev";
3
+ export declare const POLICY_MARKER = "[erosiano-dev Policy]";
4
+ export declare const POLICY_END = "[End erosiano-dev Policy]";
5
5
  interface AgentStartEvent {
6
6
  systemPromptOptions?: {
7
7
  sections?: Record<string, string | undefined>;
@@ -1,12 +1,12 @@
1
1
  import { KSD_MODES } from "./sdlc.js";
2
2
  // Keep this policy orthogonal to Ponytail's simplicity and over-engineering guidance.
3
- export const SECTION_KEY = "engineering-proxy";
4
- export const POLICY_MARKER = "[Engineering Proxy Policy]";
5
- export const POLICY_END = "[End Engineering Proxy Policy]";
3
+ export const SECTION_KEY = "erosiano-dev";
4
+ export const POLICY_MARKER = "[erosiano-dev Policy]";
5
+ export const POLICY_END = "[End erosiano-dev Policy]";
6
6
  /** A complete line consisting only of a policy marker: the stable marker or a numbered legacy version. */
7
- const COMPLETE_MARKER_LINE = /^\[Engineering Proxy Policy(?: v\d+(?:\.\d+)*)?\]\r?$/;
7
+ const COMPLETE_MARKER_LINE = /^\[(?:Engineering Proxy|erosiano-dev) Policy(?: v\d+(?:\.\d+)*)?\]\r?$/;
8
8
  /** An array element is owned when it BEGINS with the stable or a numbered legacy marker (existing array contract). */
9
- const LEADING_MARKER = /^\[Engineering Proxy Policy(?: v\d+(?:\.\d+)*)?\]/;
9
+ const LEADING_MARKER = /^\[(?:Engineering Proxy|erosiano-dev) Policy(?: v\d+(?:\.\d+)*)?\]/;
10
10
  const changed = (next, base) => next !== base;
11
11
  /**
12
12
  * Locate complete owned blocks in a string prompt: each runs from a dedicated marker line to the next
@@ -33,15 +33,16 @@ function findStringBlocks(base) {
33
33
  index += 1;
34
34
  continue;
35
35
  }
36
+ const expectedEnd = line.text.startsWith("[Engineering Proxy Policy") ? "[End Engineering Proxy Policy]" : POLICY_END;
36
37
  let blockEnd = -1;
37
38
  for (let probe = index + 1; probe < lines.length; probe++) {
38
39
  const candidate = lines[probe];
39
- if (candidate.text.replace(/\r$/, "") === POLICY_END) {
40
- blockEnd = candidate.start + POLICY_END.length;
40
+ if (candidate.text.replace(/\r$/, "") === expectedEnd) {
41
+ blockEnd = candidate.start + expectedEnd.length;
41
42
  index = probe + 1;
42
43
  break;
43
44
  }
44
- if (COMPLETE_MARKER_LINE.test(candidate.text)) {
45
+ if (COMPLETE_MARKER_LINE.test(candidate.text) || candidate.text.replace(/\r$/, "") === POLICY_END || candidate.text.replace(/\r$/, "") === "[End Engineering Proxy Policy]") {
45
46
  unterminated = true;
46
47
  break;
47
48
  }
@@ -58,7 +59,7 @@ function findStringBlocks(base) {
58
59
  function reconcileString(base, policy, warn) {
59
60
  const { blocks, unterminated } = findStringBlocks(base);
60
61
  if (unterminated) {
61
- warn?.("KSD could not replace/remove an unterminated legacy policy; restart the session.");
62
+ warn?.("erosiano-dev could not replace/remove an unterminated legacy policy; restart the session.");
62
63
  return undefined;
63
64
  }
64
65
  if (blocks.length === 0) {
@@ -84,22 +85,23 @@ export function buildPolicy({ enforcement = "balanced" } = {}) {
84
85
  if (!KSD_MODES.includes(enforcement))
85
86
  throw new Error("Unsupported KSD enforcement mode");
86
87
  const cleanCode = enforcement === "adaptive"
87
- ? "Adaptive Clean Code: flat by default. Guard clauses and early returns; no else after return; no nested if when a guard clause or a combined condition works. Mark avoidable nesting in changed code as FIX REQUIRED in reviews; keep behavior-sensitive cases as WARN. Never weaken security, transactions or error handling to flatten code."
88
- : "Balanced Clean Code: prefer guard clauses and early returns where behavior is preserved; nesting findings stay advisory.";
88
+ ? "Adaptive Clean Code: flat by default. Guard clauses/early returns; no else after return or nesting avoidable by guards or combined conditions. Changed-code review: FIX REQUIRED for behavior-preserving fixes; WARN if behavior-sensitive. Never weaken security, transactions or error handling."
89
+ : "Balanced Clean Code: prefer behavior-preserving guards/early returns; nesting findings are advisory.";
89
90
  return `${POLICY_MARKER}
90
- KSD personal code style. Explicit user requirements and existing repo conventions win over it.
91
+ erosiano-dev personal style. Explicit user requirements and current repo conventions take precedence.
91
92
  ${cleanCode}
92
- - No nested ternaries: use if, a small named function, or a lookup map.
93
- - Blank line before a return only when two or more statements precede it in the same block; never before a first-statement return. One blank line between adjacent function implementations; leave TypeScript overload groups untouched.
94
- - Errors: domain logic returns a typed result (discriminated union); IO and infrastructure throw and are caught at the boundary (route handler, job runner, UI error boundary).
95
- - Types: no any, no \`as\` casts (\`as const\` is fine), no non-null \`!\`; narrow with type guards; exported functions declare return types.
96
- - Extract a helper only when it is reused or its name makes the caller clearer; length alone is not a reason.
97
- - Comments: one line explaining why; never restate the code.
98
- - Preserve existing architecture, contracts, validation and accessibility; no unrelated renames or refactors.
99
- - Ponytail owns YAGNI/simplification and /ponytail-review; do not duplicate or invoke it.
100
- - Risky behavior (auth/authorization, payments, DB schema/queries/RLS, destructive data operations, secrets, concurrency): prove normal-user denial (cross-tenant, another owner's record, unauthenticated), keep idempotency and replay protection, check constraints, locks, transaction boundaries and migration compatibility. Never run real payments or destructive shared-database checks.
93
+ - No nested ternaries; use if, named helper or lookup map.
94
+ - One blank before return after 2+ preceding statements in the same block; optional after one, none for first-statement return. One blank between adjacent implementations, not TS overloads.
95
+ - Prefer typed domain results (discriminated unions); throw IO/infrastructure errors, catch at boundary. Preserve project error contracts and causes.
96
+ - No any, \`as\` casts except \`as const\`, or non-null \`!\`; type guards, explicit exported return types.
97
+ - Extract helpers for reuse or clearer callers, not length. Comments: one line explaining why, not what.
98
+ - Before substantial changes, establish a scoped project baseline: instructions, native gates, maintained code/tests. Distinguish current, legacy and unknown; refresh stale evidence. Preserve architecture, contracts, validation, accessibility; no unrelated refactors. Never copy insecure legacy behavior.
99
+ - Select applicable practices after baseline via permitted resolver/catalog; never inject entire catalog.
100
+ - Ponytail owns YAGNI/simplification and /ponytail-review; don't duplicate or invoke it.
101
+ - Risky auth/authorization, payments, DB schema/queries/RLS, destructive data, secrets, concurrency: prove normal-user denial (cross-tenant/other owner/unauthenticated); preserve idempotency/replay protection, check constraints/locks/transactions/migration compatibility. Never run real payments or destructive shared-DB checks.
102
+ - Validate runtime boundaries, handle promise rejection/exhaustive states. Never weaken types, security or tests, invent APIs or fake production success.
101
103
  - Never claim a check passed without running it.
102
- Enforcement=${enforcement}: repo gates stay authoritative; these rules are deterministic only where the repo enables the KSD ESLint profile. The full SDLC checklist is delivered by /engineering-review.
104
+ Enforcement=${enforcement}: native gates authoritative; deterministic only if adopted. SDLC: /erosiano-dev review.
103
105
  ${POLICY_END}`;
104
106
  }
105
107
  /** Reconcile a string or array fallback prompt: remove owned guidance, or replace it with exactly one policy. */
@@ -135,6 +137,7 @@ export function augmentSystemPrompt(event, policy, warn) {
135
137
  failed = true;
136
138
  warn?.(message);
137
139
  });
140
+ delete sections["engineering-proxy"];
138
141
  if (policy === undefined || failed)
139
142
  delete sections[SECTION_KEY];
140
143
  else
@@ -46,26 +46,28 @@ export class KsdRuntime {
46
46
  catch {
47
47
  // Missing theme must never break headless/early-start UIs.
48
48
  }
49
- const paint = (tone, text) => {
49
+ let status;
50
+ if (enabled) {
51
+ const dot = isActive ? "●" : "○";
52
+ let colored = dot;
50
53
  try {
51
- return typeof theme?.fg === "function" ? theme.fg(tone, text) : text;
54
+ if (typeof theme?.fg === "function") {
55
+ colored = theme.fg(isActive ? "accent" : "dim", dot);
56
+ }
52
57
  }
53
58
  catch {
54
- return text;
59
+ // Theme rendering is optional.
55
60
  }
56
- };
57
- let status;
58
- if (enabled) {
59
- status = `${paint(isActive ? "accent" : "dim", isActive ? "●" : "○")} 🛡 ${paint("dim", "KSD:")} ${paint(isActive ? "accent" : "dim", mode.toUpperCase())}`;
61
+ status = `${colored} 🛡 EROSIANO: ${mode.toUpperCase()}`;
60
62
  if (notice)
61
63
  status += `; ${notice}`;
62
64
  }
63
65
  else if (notice)
64
- status = `${paint("accent", "⚠")} ${paint("dim", "KSD:")} ${notice}`;
66
+ status = `⚠ EROSIANO: ${notice}`;
65
67
  const before = this.statuses.get(ui);
66
68
  if (before && before.value === status && before.theme === theme)
67
69
  return;
68
- ui.setStatus("engineering-proxy", status);
70
+ ui.setStatus("erosiano-dev", status);
69
71
  this.statuses.set(ui, { value: status, theme, notice });
70
72
  }
71
73
  catch {
@@ -0,0 +1,7 @@
1
+ export interface EngineeringExtensionOptions {
2
+ globalConfigPath?: string;
3
+ defaultIntelligenceMode?: "off" | "native" | "mcp" | "cli";
4
+ label?: string;
5
+ }
6
+ export declare function createExtension(pi: unknown, options?: EngineeringExtensionOptions): void;
7
+ export default createExtension;