@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,500 @@
1
+ import { realpathSync } from "node:fs";
2
+ import { basename, dirname, join, normalize, resolve } from "node:path";
3
+
4
+ /**
5
+ * Parse zero-context Git patches. Added lines only; deletion-only hunks are not enforceable.
6
+ * Only the standard two-parent `a/`/`b/` unified format produced with `-U0` is accepted;
7
+ * anything else (custom prefixes, combined diffs, context-bearing hunks) is rejected.
8
+ */
9
+ const POSIX = process.platform !== "win32";
10
+ const MAX_HUNK_LINES = 100_000;
11
+
12
+ const SIMPLE_ESCAPES = { a: 7, b: 8, f: 12, n: 10, r: 13, t: 9, v: 11, "\\": 0x5c, '"': 0x22 };
13
+ const decoder = new TextDecoder("utf-8", { fatal: true });
14
+
15
+ /** Decode one c-quoted Git path label (opening quote included) to a POSIX-ish string. */
16
+ function decodeQuotedLabel(label) {
17
+ const bytes = [];
18
+ let i = 1;
19
+ while (i < label.length) {
20
+ const ch = label.charAt(i);
21
+ if (ch === '"') {
22
+ return finishQuotedLabel(bytes);
23
+ }
24
+ if (ch !== "\\") {
25
+ const code = label.codePointAt(i);
26
+ if (code < 0x20 || (code >= 0xd800 && code <= 0xdfff)) throw new Error("Git path label is not properly quoted");
27
+ const character = String.fromCodePoint(code);
28
+ bytes.push(...Buffer.from(character, "utf8"));
29
+ i += character.length;
30
+ continue;
31
+ }
32
+ i += 1;
33
+ const esc = label.charAt(i);
34
+ if (esc === "") throw new Error("Git path label is not properly quoted");
35
+ if (esc >= "0" && esc <= "7") {
36
+ let value = 0;
37
+ for (let n = 0; n < 3; n++) {
38
+ const digit = label.charAt(i);
39
+ if (digit < "0" || digit > "7") break;
40
+ value = value * 8 + (digit.charCodeAt(0) - 0x30);
41
+ i += 1;
42
+ }
43
+ if (value > 0xff) throw new Error("Git path label is not properly quoted");
44
+ bytes.push(value);
45
+ continue;
46
+ }
47
+ const simple = SIMPLE_ESCAPES[esc];
48
+ if (simple === undefined) throw new Error("Git path label is not properly quoted");
49
+ bytes.push(simple);
50
+ i += 1;
51
+ }
52
+ throw new Error("Git path label is not properly quoted");
53
+ }
54
+
55
+ function finishQuotedLabel(bytes) {
56
+ // Decode the combined literal and escaped bytes strictly so invalid UTF-8 is rejected.
57
+ const text = decoder.decode(Uint8Array.from(bytes));
58
+
59
+ if (text.includes("\u0000")) throw new Error("Git path contains NUL bytes");
60
+
61
+ return text;
62
+ }
63
+
64
+ /** Slice the next space-delimited or quoted label token from the start of `text`. */
65
+ function nextLabel(text) {
66
+ if (text.startsWith('"')) {
67
+ let i = 1;
68
+ while (i < text.length) {
69
+ if (text[i] === "\\") { i += 2; continue; }
70
+ if (text[i] === '"') return { raw: text.slice(0, i + 1), rest: text.slice(i + 1) };
71
+ i += 1;
72
+ }
73
+ throw new Error("Git path label is not properly quoted");
74
+ }
75
+ const end = text.indexOf(" ");
76
+
77
+ if (end === -1) return { raw: text, rest: "" };
78
+
79
+ return { raw: text.slice(0, end), rest: text.slice(end) };
80
+ }
81
+
82
+ /** Validate the `diff --git a/… b/…` header; nonstandard prefixes/variants are rejected here. */
83
+ function requireDiffGitLabels(line) {
84
+ const body = line.slice("diff --git ".length);
85
+ const candidates = [];
86
+ const add = (oldLabel, rawNew) => {
87
+ let newLabel = rawNew;
88
+ if (rawNew.startsWith('"')) {
89
+ const token = nextLabel(rawNew);
90
+ if (token.rest !== "") throw new Error("Git diff --git header needs exactly two path labels");
91
+ newLabel = decodeQuotedLabel(token.raw);
92
+ }
93
+ if (oldLabel.startsWith("a/") && newLabel.startsWith("b/")) candidates.push({ oldLabel, newLabel });
94
+ };
95
+ if (body.startsWith('"')) {
96
+ const first = nextLabel(body);
97
+ if (!first.rest.startsWith(" ")) throw new Error("Git diff --git header needs two path labels");
98
+ add(decodeQuotedLabel(first.raw), first.rest.slice(1));
99
+ } else {
100
+ for (let boundary = body.indexOf(" "); boundary !== -1; boundary = body.indexOf(" ", boundary + 1)) {
101
+ const remainder = body.slice(boundary + 1);
102
+ if (remainder.startsWith("b/") || remainder.startsWith('"b/')) {
103
+ add(body.slice(0, boundary), remainder);
104
+ }
105
+ }
106
+ }
107
+ if (candidates.length === 0) {
108
+ throw new Error("Malformed or unsupported Git diff --git header; regenerate with -U0 and default a/ b/ prefixes");
109
+ }
110
+
111
+ return candidates;
112
+ }
113
+
114
+ /** Parse the label on a `---`/`+++` section line. The delimiter is the marker space itself. */
115
+ function sectionLabel(line) {
116
+ const body = line.slice(4);
117
+ if (body === "" ) throw new Error("Malformed Git diff path label");
118
+ if (body.startsWith('"')) {
119
+ const token = nextLabel(body);
120
+ if (token.rest !== "" && token.rest !== "\t") throw new Error("Malformed Git diff path label");
121
+
122
+ return decodeQuotedLabel(token.raw);
123
+ }
124
+ // Git closes an unquoted label that contains spaces/tabs with an appended TAB delimiter.
125
+ // The tab is the delimiter, not filename content, so exactly one is stripped.
126
+ const label = body.endsWith("\t") ? body.slice(0, -1) : body;
127
+
128
+ if (label === "" ) throw new Error("Malformed Git diff path label");
129
+
130
+ return label;
131
+ }
132
+
133
+ /** Validate a `+++` destination: must be a relative repository path (or /dev/null). */
134
+ function destinationPath(label) {
135
+ if (label === "/dev/null") return null; // deleted file; it can never gain added lines
136
+ if (!label.startsWith("b/")) throw new Error("Unsupported Git diff destination prefix; regenerate with -U0");
137
+
138
+ const rel = POSIX ? label.slice(2) : label.slice(2).replaceAll("\\", "/");
139
+ if (rel === "" ) throw new Error("Git diff destination path is empty");
140
+ if (rel === "/" || rel.startsWith("/") || (POSIX ? /^[A-Za-z]:[\\/]/ : /^[A-Za-z]:/).test(rel) || rel.startsWith("\\\\")) {
141
+ throw new Error("Git diff destination must be a relative repository path");
142
+ }
143
+ const normalized = POSIX ? normalize(rel) : normalize(rel).replaceAll("\\", "/");
144
+
145
+ if (normalized === ".." || normalized.startsWith("../")) throw new Error("Diff path escapes repository");
146
+
147
+ return normalized;
148
+ }
149
+
150
+ function setDestination(files, dest) {
151
+ if (dest !== null && !files.has(dest)) files.set(dest, new Set());
152
+ }
153
+
154
+ export function parseChangedLines(patch) {
155
+ if (typeof patch !== "string") throw new TypeError("Git diff must be text");
156
+ if (patch.includes("\u0000")) throw new Error("Git diff contains NUL bytes");
157
+
158
+ const files = new Map();
159
+ const lines = patch.split(/\r?\n/);
160
+ let dest = undefined; // selected destination: string key, null (/dev/null), or undefined (none yet)
161
+ let sawFileHeader = false;
162
+ let sawOldLabel = false;
163
+ let sawNewLabel = false;
164
+ let sawHunk = false;
165
+ let labels;
166
+ let metadata;
167
+ let oldLeft = 0;
168
+ let newLeft = 0;
169
+ let lineNumber = 0;
170
+ let oldEnd;
171
+ let newEnd;
172
+
173
+ function narrowLabels(predicate, message) {
174
+ labels = labels.filter(predicate);
175
+ if (labels.length === 0) throw new Error(message);
176
+ }
177
+
178
+ function finishSection() {
179
+ if (!labels) return;
180
+ if (labels.length > 1 && !metadata.renameTo && !metadata.copyTo) {
181
+ const samePath = labels.filter(({ oldLabel, newLabel }) => oldLabel.slice(2) === newLabel.slice(2));
182
+ if (samePath.length === 1) labels = samePath;
183
+ }
184
+ if (labels.length !== 1) throw new Error("Ambiguous Git diff path labels");
185
+ destinationPath(`b/${labels[0].oldLabel.slice(2)}`);
186
+ destinationPath(labels[0].newLabel);
187
+ if (sawOldLabel !== sawNewLabel) throw new Error("Incomplete Git diff file header");
188
+ if (metadata.renameFrom !== metadata.renameTo || metadata.copyFrom !== metadata.copyTo ||
189
+ metadata.oldMode !== metadata.newMode) {
190
+ throw new Error("Incomplete Git diff metadata");
191
+ }
192
+ if ((metadata.newFile && (metadata.deletedFile || metadata.renameTo || metadata.copyTo)) ||
193
+ (metadata.deletedFile && (metadata.renameTo || metadata.copyTo)) ||
194
+ (metadata.renameTo && metadata.copyTo)) {
195
+ throw new Error("Conflicting Git diff metadata");
196
+ }
197
+ if (sawNewLabel && !sawHunk) throw new Error("Git diff file headers require a hunk");
198
+ if (!sawHunk && !metadata.binary && !metadata.renameTo && !metadata.copyTo &&
199
+ !metadata.newMode && !metadata.newFile && !metadata.deletedFile) {
200
+ throw new Error("Incomplete Git diff section");
201
+ }
202
+ }
203
+
204
+ for (const [index, line] of lines.entries()) {
205
+ if (oldLeft > 0 || newLeft > 0) {
206
+ // Inside a declared hunk body: declared counts must be consumed before any header.
207
+ if (line === "\") continue;
208
+ if (line.startsWith("+")) {
209
+ if (newLeft <= 0) throw new Error("Malformed Git diff hunk: too many added lines");
210
+ if (dest === null) throw new Error("Deletion-only hunks cannot contain added lines");
211
+ if (!Number.isSafeInteger(lineNumber)) throw new Error("Git diff hunk line number exceeds safe integers");
212
+ files.get(dest).add(lineNumber);
213
+ lineNumber += 1;
214
+ newLeft -= 1;
215
+ continue;
216
+ }
217
+ if (line.startsWith("-")) {
218
+ if (oldLeft <= 0) throw new Error("Malformed Git diff hunk: too many removed lines");
219
+ oldLeft -= 1;
220
+ continue;
221
+ }
222
+ if (line.startsWith(" ")) {
223
+ throw new Error("Git diff hunks must not contain context lines; regenerate with -U0");
224
+ }
225
+ throw new Error("Git diff hunk is truncated or malformed");
226
+ }
227
+
228
+ if (line.startsWith("diff --git ")) {
229
+ finishSection();
230
+ labels = requireDiffGitLabels(line);
231
+ metadata = {};
232
+ sawFileHeader = true;
233
+ dest = undefined;
234
+ sawOldLabel = false;
235
+ sawNewLabel = false;
236
+ sawHunk = false;
237
+ oldEnd = undefined;
238
+ newEnd = undefined;
239
+ continue;
240
+ }
241
+ if (line.startsWith("diff --cc ") || line.startsWith("diff --combined ")) {
242
+ throw new Error("Combined Git diffs are not supported");
243
+ }
244
+ if (line.startsWith("diff ")) throw new Error("Unsupported Git diff header");
245
+ if (line.startsWith("--- ")) {
246
+ if (sawOldLabel || sawNewLabel || sawHunk) throw new Error("Malformed Git diff file header");
247
+ if (!labels) throw new Error("Git diff file header has no diff --git header");
248
+ const oldLabel = sectionLabel(line);
249
+ narrowLabels(({ oldLabel: oldPath, newLabel: newPath }) =>
250
+ oldLabel === oldPath || (oldLabel === "/dev/null" && oldPath.slice(2) === newPath.slice(2)),
251
+ "Git diff old path label does not match header");
252
+ if (metadata.newFile && oldLabel !== "/dev/null") throw new Error("Invalid Git diff new file header");
253
+ metadata.oldNull = oldLabel === "/dev/null";
254
+ sawOldLabel = true;
255
+ continue;
256
+ }
257
+ if (line.startsWith("+++ ")) {
258
+ if (!labels || !sawOldLabel || sawNewLabel || sawHunk) throw new Error("Malformed Git diff file header");
259
+ const newLabel = sectionLabel(line);
260
+ dest = destinationPath(newLabel);
261
+ narrowLabels(({ oldLabel: oldPath, newLabel: newPath }) =>
262
+ newLabel === newPath || (newLabel === "/dev/null" && !metadata.oldNull && oldPath.slice(2) === newPath.slice(2)),
263
+ "Git diff destination path label does not match header");
264
+ if (metadata.deletedFile && newLabel !== "/dev/null") throw new Error("Invalid Git diff deleted file header");
265
+ sawNewLabel = true;
266
+ setDestination(files, dest);
267
+ continue;
268
+ }
269
+ if (line.startsWith("@@ ")) {
270
+ if (!sawOldLabel || !sawNewLabel) throw new Error("Git diff hunk requires file headers");
271
+ sawHunk = true;
272
+ const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line);
273
+ if (!match) throw new Error("Malformed Git diff hunk header");
274
+ const newStart = Number(match[3]);
275
+ const newCount = match[4] === undefined ? 1 : Number(match[4]);
276
+ const oldStart = Number(match[1]);
277
+ const oldCount = match[2] === undefined ? 1 : Number(match[2]);
278
+ if (![oldStart, oldCount, newStart, newCount].every(Number.isSafeInteger)) {
279
+ throw new Error("Invalid Git diff hunk counts");
280
+ }
281
+ if (oldCount > MAX_HUNK_LINES || newCount > MAX_HUNK_LINES) {
282
+ throw new Error("Invalid or excessively large Git diff hunk");
283
+ }
284
+ if (!Number.isSafeInteger(oldStart + oldCount) || !Number.isSafeInteger(newStart + newCount)) {
285
+ throw new Error("Git diff hunk exclusive end exceeds safe integers");
286
+ }
287
+ if (dest === undefined) throw new Error("Git diff hunk appears before a destination path");
288
+ if (metadata.oldNull && oldCount > 0) throw new Error("New file hunks cannot contain removed lines");
289
+ if (oldCount === 0 && newCount === 0) throw new Error("Empty Git diff hunk");
290
+ if ((oldCount > 0 && oldStart === 0) || (newCount > 0 && newStart === 0)) {
291
+ throw new Error("Invalid Git diff hunk start");
292
+ }
293
+ const oldOffset = oldStart - (oldCount > 0 ? 1 : 0);
294
+ const newOffset = newStart - (newCount > 0 ? 1 : 0);
295
+ if (oldEnd !== undefined && (oldOffset < oldEnd || newOffset < newEnd)) {
296
+ throw new Error("Overlapping or out-of-order Git diff hunks");
297
+ }
298
+ if (oldOffset - (oldEnd ?? 0) !== newOffset - (newEnd ?? 0)) {
299
+ throw new Error("Inconsistent unchanged lines between Git diff hunks");
300
+ }
301
+ oldEnd = oldOffset + oldCount;
302
+ newEnd = newOffset + newCount;
303
+ if (dest === null && newCount > 0) throw new Error("Deletion-only hunks cannot contain added lines");
304
+ oldLeft = oldCount;
305
+ newLeft = newCount;
306
+ lineNumber = newStart;
307
+ continue;
308
+ }
309
+ if (line.startsWith("+") || line.startsWith("-")) throw new Error("Malformed Git diff hunk body");
310
+ if (line === "" && index === lines.length - 1) continue;
311
+ if (line === "\" && sawHunk) continue;
312
+ if (!labels) throw new Error("Not a recognizable Git patch");
313
+ if (sawOldLabel || sawNewLabel || sawHunk || metadata.binary) {
314
+ throw new Error("Malformed Git diff section");
315
+ }
316
+ let key;
317
+ let match;
318
+ if (/^index [0-9a-f]+\.\.[0-9a-f]+(?: [0-7]{6})?$/i.test(line)) key = "index";
319
+ else if (/^similarity index (?:100|[0-9]{1,2})%$/.test(line)) key = "similarity";
320
+ else if (/^dissimilarity index (?:100|[0-9]{1,2})%$/.test(line)) key = "dissimilarity";
321
+ else if ((match = /^(old mode|new mode|new file mode|deleted file mode) ([0-7]{6})$/.exec(line))) {
322
+ key = { "old mode": "oldMode", "new mode": "newMode", "new file mode": "newFile", "deleted file mode": "deletedFile" }[match[1]];
323
+ } else if ((match = /^(rename from|rename to|copy from|copy to) (.+)$/.exec(line))) {
324
+ key = { "rename from": "renameFrom", "rename to": "renameTo", "copy from": "copyFrom", "copy to": "copyTo" }[match[1]];
325
+ const path = sectionLabel(`--- ${match[2]}`);
326
+ narrowLabels(({ oldLabel, newLabel }) => path === (key.endsWith("From") ? oldLabel.slice(2) : newLabel.slice(2)),
327
+ "Git diff metadata path does not match header");
328
+ } else if (/^Binary files .+ and .+ differ$/.test(line)) key = "binary";
329
+ else throw new Error("Malformed or unsupported Git diff metadata");
330
+ if (metadata[key]) throw new Error("Duplicate Git diff metadata");
331
+ metadata[key] = true;
332
+ }
333
+
334
+ if (oldLeft > 0 || newLeft > 0) throw new Error("Git diff hunk is truncated or malformed");
335
+ finishSection();
336
+ if (files.size === 0 && !sawFileHeader && patch.trim() !== "") {
337
+ throw new Error("Not a recognizable Git patch");
338
+
339
+ }
340
+
341
+ return files;
342
+ }
343
+
344
+ /** Resolve symlinks via the nearest existing ancestor; ESLint may report paths that no longer exist. */
345
+ function canonical(path) {
346
+ const missing = [];
347
+ let current = resolve(path);
348
+ while (true) {
349
+ try {
350
+ return join(realpathSync(current), ...missing);
351
+ } catch {
352
+ // Not on disk (yet): resolve the parent instead.
353
+ }
354
+
355
+ const parent = dirname(current);
356
+ if (parent === current) return resolve(path);
357
+
358
+ missing.unshift(basename(current));
359
+ current = parent;
360
+ }
361
+ }
362
+
363
+ function reportPath(filename, realCwd) {
364
+ if (typeof filename !== "string" || filename.length === 0) return null;
365
+
366
+ return canonical(resolve(realCwd, filename));
367
+ }
368
+
369
+ function validateEslintReport(eslintReport) {
370
+ if (!Array.isArray(eslintReport)) throw new TypeError("Expected ESLint JSON array");
371
+ for (const entry of eslintReport) {
372
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
373
+ throw new TypeError("Each ESLint report entry must be an object");
374
+ }
375
+ if (typeof entry.filePath !== "string") {
376
+ throw new TypeError("Each ESLint report entry needs a filePath string");
377
+ }
378
+ if (!Array.isArray(entry.messages)) {
379
+ throw new TypeError("Each ESLint report entry needs a messages array");
380
+ }
381
+ let errors = 0;
382
+ let warnings = 0;
383
+ let fatals = 0;
384
+ for (const message of entry.messages) {
385
+ if (!message || typeof message !== "object" || Array.isArray(message)) {
386
+ throw new TypeError("Each ESLint diagnostic must be an object");
387
+ }
388
+ if (message.severity !== 1 && message.severity !== 2) {
389
+ throw new TypeError("ESLint diagnostic severity must be 1 or 2");
390
+ }
391
+ if (message.severity === 2) errors += 1;
392
+ else warnings += 1;
393
+ if (message.fatal !== undefined && typeof message.fatal !== "boolean") {
394
+ throw new TypeError("ESLint diagnostic fatal flag must be boolean");
395
+ }
396
+ if (message.fatal === true) fatals += 1;
397
+ if (message.line !== undefined && !(Number.isSafeInteger(message.line) && message.line > 0)) {
398
+ throw new TypeError("ESLint diagnostic line must be a positive integer or absent");
399
+ }
400
+ if (message.ruleId !== undefined && message.ruleId !== null && typeof message.ruleId !== "string") {
401
+ throw new TypeError("ESLint diagnostic ruleId must be a string or null");
402
+ }
403
+ }
404
+ // Only count keys actually present are validated, but a contradiction is caller error.
405
+ if (entry.errorCount !== undefined && entry.errorCount !== errors) {
406
+ throw new TypeError("ESLint report errorCount contradicts the supplied messages");
407
+ }
408
+ if (entry.warningCount !== undefined && entry.warningCount !== warnings) {
409
+ throw new TypeError("ESLint report warningCount contradicts the supplied messages");
410
+ }
411
+ if (entry.fatalErrorCount !== undefined && entry.fatalErrorCount !== fatals) {
412
+ throw new TypeError("ESLint report fatalErrorCount contradicts the supplied messages");
413
+ }
414
+ }
415
+ }
416
+
417
+ /**
418
+ * Restrict diagnostics from a real ESLint JSON report to changed source lines.
419
+ * The neighboring line is included for boundary spacing (new helper before old helper).
420
+ * A clean report does NOT prove that the required plugin rules were configured, and a
421
+ * locationless nonfatal warning (e.g. an ignored file) does NOT prove the file was linted.
422
+ */
423
+ export function inspectChangedScope(patch, eslintReport, { cwd = process.cwd() } = {}) {
424
+ // Input validation precedes scope decisions: a malformed report must never turn into NOT_APPLICABLE.
425
+ validateEslintReport(eslintReport);
426
+
427
+ const changes = parseChangedLines(patch);
428
+ const sourceFiles = [...changes.keys()].filter(name => /\.[cm]?[jt]sx?$/.test(name) && changes.get(name).size > 0);
429
+
430
+ const reports = new Map();
431
+ const realCwd = canonical(cwd);
432
+ for (const entry of eslintReport) {
433
+ const key = reportPath(entry.filePath, realCwd);
434
+ if (!key) continue;
435
+ if (reports.has(key)) throw new Error(`Duplicate ESLint report for ${key}`);
436
+ reports.set(key, entry.messages);
437
+ }
438
+ if (sourceFiles.length === 0) {
439
+ return { status: "NOT_APPLICABLE", checkedFiles: [], missingFiles: [], diagnostics: [] };
440
+ }
441
+
442
+ const missingFiles = [];
443
+ const diagnostics = [];
444
+
445
+ for (const file of sourceFiles) {
446
+ const changed = changes.get(file);
447
+ const messages = reports.get(reportPath(file, realCwd));
448
+ if (!messages) {
449
+ missingFiles.push(file);
450
+ continue;
451
+ }
452
+
453
+ let hasLocationlessWarning = false;
454
+
455
+ for (const issue of messages) {
456
+ const lineno = issue.line;
457
+ if (Number.isSafeInteger(lineno)) {
458
+ if (issue.fatal === true || changed.has(lineno) || changed.has(lineno - 1)) {
459
+ diagnostics.push(diagnostic(file, lineno, issue));
460
+ }
461
+ continue;
462
+ }
463
+ // Locationless: fatal errors and other errors are file-wide; warnings are not evidence.
464
+ if (issue.severity === 2 || issue.fatal === true) {
465
+ diagnostics.push({ ...diagnostic(file, null, issue), severity: "error" });
466
+ continue;
467
+ }
468
+ hasLocationlessWarning = true;
469
+ diagnostics.push({ ...diagnostic(file, null, issue), severity: "warning" });
470
+ }
471
+
472
+ if (hasLocationlessWarning) missingFiles.push(file);
473
+ }
474
+
475
+ const status = missingFiles.length > 0
476
+ ? "NOT_RUN"
477
+ : diagnostics.some(d => d.severity === "error")
478
+ ? "FIX_REQUIRED"
479
+ : diagnostics.length > 0
480
+ ? "WARN"
481
+ : "PASS";
482
+
483
+ return {
484
+ status,
485
+ checkedFiles: sourceFiles.filter(file => reports.has(reportPath(file, realCwd))),
486
+ missingFiles,
487
+ diagnostics,
488
+ limitation: "PASS only means no changed-line diagnostics in the supplied ESLint JSON; ESLint rule configuration and CI execution are not independently verified.",
489
+ };
490
+ }
491
+
492
+ function diagnostic(file, line, issue) {
493
+ return {
494
+ file,
495
+ line,
496
+ ruleId: issue.ruleId ?? null,
497
+ severity: issue.severity === 2 || issue.fatal ? "error" : "warning",
498
+ message: String(issue.message ?? "Unspecified diagnostic"),
499
+ };
500
+ }
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { inspectChangedScope } from "./change-scope.js";
6
+
7
+ function main(args) {
8
+ if (args.length !== 4 || args[0] !== "--diff" || args[2] !== "--eslint-report") {
9
+ throw new Error("Usage: node check-changed.js --diff git.patch --eslint-report eslint.json");
10
+ }
11
+
12
+ const patch = readFileSync(resolve(args[1]), "utf8");
13
+ const report = JSON.parse(readFileSync(resolve(args[3]), "utf8"));
14
+ const result = inspectChangedScope(patch, report);
15
+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");
16
+
17
+ if (result.status === "FIX_REQUIRED") process.exitCode = 1;
18
+ if (result.status === "NOT_RUN") process.exitCode = 2;
19
+ }
20
+
21
+ // Compare REAL paths so npm .bin symlinks still execute the CLI; unresolvable argv means NOT main.
22
+ function isMainModule() {
23
+ try {
24
+
25
+ if (!process.argv[1]) return false;
26
+
27
+ return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ if (isMainModule()) {
34
+ try {
35
+ main(process.argv.slice(2));
36
+ } catch (error) {
37
+ process.stderr.write("KSD style check NOT RUN: " + error.message + "\n");
38
+ process.exitCode = 2;
39
+ }
40
+ }
@@ -0,0 +1,129 @@
1
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join, resolve } from "node:path";
5
+
6
+ // Single source of truth for the supported modes; exported under the historical name.
7
+ import { KSD_MODES } from "./sdlc.js";
8
+ export const SUPPORTED_MODES = KSD_MODES;
9
+ const DEFAULT = Object.freeze({ enabled: true, enforcement: "balanced" });
10
+
11
+ export function getGlobalConfigPath() {
12
+ return join(homedir(), ".omp", "agent", "erosiano-dev.json");
13
+ }
14
+
15
+ function realPath(path) {
16
+ try {
17
+ return realpathSync(path);
18
+ } catch {
19
+ return path;
20
+ }
21
+ }
22
+
23
+ export function findProjectRoot(cwd) {
24
+ // Compare real paths: HOME or cwd may be reached through a symlink (process.cwd() is always real).
25
+ const home = realPath(resolve(homedir()));
26
+ let current = resolve(cwd);
27
+ while (true) {
28
+ if (existsSync(join(current, ".git"))) return current;
29
+ // ~/.omp holds global agent state; treating it as a project marker turns HOME into a second global scope.
30
+ // Test .omp existence first: realpath is only needed for ancestors that actually have the marker.
31
+ if (existsSync(join(current, ".omp")) && realPath(current) !== home) return current;
32
+ const parent = dirname(current);
33
+ if (parent === current) return resolve(cwd);
34
+ current = parent;
35
+ }
36
+ }
37
+
38
+ function readScopedConfig(path, label) {
39
+ if (!existsSync(path)) return { present: false, values: {} };
40
+
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(readFileSync(path, "utf8"));
44
+ } catch {
45
+ return { present: true, values: {}, error: `Cannot parse ${label}` };
46
+ }
47
+
48
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) ||
49
+ (parsed.enabled !== undefined && typeof parsed.enabled !== "boolean") ||
50
+ (parsed.enforcement !== undefined && !SUPPORTED_MODES.includes(parsed.enforcement))) {
51
+ return { present: true, values: {}, error: `Invalid ${label} (expected enabled:boolean and enforcement:'balanced|adaptive')` };
52
+ }
53
+
54
+ return { present: true, values: parsed };
55
+ }
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
+
75
+ export function loadConfig(cwd, { globalConfigPath = getGlobalConfigPath() } = {}) {
76
+ const root = findProjectRoot(cwd);
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");
80
+ const configError = global.error ?? project.error;
81
+ const enforcementSource = project.values.enforcement !== undefined ? "project"
82
+ : global.values.enforcement !== undefined ? "global" : "default";
83
+
84
+ return {
85
+ ...DEFAULT,
86
+ ...global.values,
87
+ ...project.values,
88
+ root,
89
+ configPresent: project.present,
90
+ globalConfigPresent: global.present,
91
+ projectConfigPath,
92
+ globalConfigPath,
93
+ projectConfigSource: project.source,
94
+ globalConfigSource: global.source,
95
+ configWarnings: [global.warning, project.warning].filter(Boolean),
96
+ projectEnforcement: project.values.enforcement,
97
+ globalEnforcement: global.values.enforcement,
98
+ enforcementSource,
99
+ ...(configError ? { enabled: false, configError } : {}),
100
+ };
101
+ }
102
+
103
+ /** Writes only the selected scope; preserves enabled and unrelated existing keys. */
104
+ export function setScopedMode(cwd, scope, mode, { globalConfigPath = getGlobalConfigPath() } = {}) {
105
+ if (scope !== "global" && scope !== "repo") throw new Error("Scope must be global or repo");
106
+ if (mode !== null && !SUPPORTED_MODES.includes(mode)) throw new Error("Unsupported enforcement mode");
107
+
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");
112
+ if (existing.error) throw new Error(existing.error);
113
+ if (mode === null && existing.values.enforcement === undefined && !existing.legacy) return path;
114
+
115
+ const next = { ...existing.values };
116
+ if (mode === null) delete next.enforcement;
117
+ else next.enforcement = mode;
118
+
119
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
120
+ const tempPath = `${path}.${randomUUID()}.tmp`;
121
+ try {
122
+ writeFileSync(tempPath, `${JSON.stringify(next, null, 2)}\n`, { flag: "wx", mode: 0o600 });
123
+ renameSync(tempPath, path);
124
+ } finally {
125
+ if (existsSync(tempPath)) unlinkSync(tempPath);
126
+ }
127
+
128
+ return path;
129
+ }
@@ -0,0 +1,17 @@
1
+ import { type KsdMode } from "./sdlc.js";
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
+ interface AgentStartEvent {
6
+ systemPromptOptions?: {
7
+ sections?: Record<string, string | undefined>;
8
+ };
9
+ systemPrompt?: string | string[];
10
+ }
11
+ export declare function buildPolicy({ enforcement }?: {
12
+ enforcement?: KsdMode;
13
+ }): string;
14
+ export declare function augmentSystemPrompt(event: AgentStartEvent | undefined, policy: string | undefined, warn?: (message: string) => void): {
15
+ systemPrompt: string | string[];
16
+ } | undefined;
17
+ export {};