@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
@@ -0,0 +1,94 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "repository": "https://github.com/Krisada-M/ksd-engineering",
4
+ "commit": "f8c85ce74dc9d94d73417e032f10b4a17232b754",
5
+ "sourceDirectory": "plugins/erosiano-dev",
6
+ "package": "omp-erosiano-dev",
7
+ "version": "0.7.0",
8
+ "files": {
9
+ "baseline.js": {
10
+ "gitBlob": "7acceae59049c075607bbcb2a1b0daa77320d7f0",
11
+ "mode": "100755"
12
+ },
13
+ "change-scope.js": {
14
+ "gitBlob": "b51d7a628cd7c2106a59b483f9f9664a6743fa4d",
15
+ "mode": "100644"
16
+ },
17
+ "check-changed.js": {
18
+ "gitBlob": "b6e14d643d452d9e0d449f9bcb40eff2dc4e5255",
19
+ "mode": "100755"
20
+ },
21
+ "config.js": {
22
+ "gitBlob": "d42fe9f7611fb45c37d3cc0ec904bc37c8c60351",
23
+ "mode": "100644"
24
+ },
25
+ "dist/policy.d.ts": {
26
+ "gitBlob": "ac4719a2ad45a60c2b086b86b4df0c6869d8b06c",
27
+ "mode": "100644"
28
+ },
29
+ "dist/policy.js": {
30
+ "gitBlob": "dddbf30c4369f3abcb26da968623c07aedfede00",
31
+ "mode": "100644"
32
+ },
33
+ "dist/runtime.d.ts": {
34
+ "gitBlob": "6f1cd36b727fcc3d7abc8d505740be58bc85c19a",
35
+ "mode": "100644"
36
+ },
37
+ "dist/runtime.js": {
38
+ "gitBlob": "9e148a4fb25ac60162b5c62df115a9f60f4997fb",
39
+ "mode": "100644"
40
+ },
41
+ "dist/sdlc.d.ts": {
42
+ "gitBlob": "deab3d24fbdc9d776bab296c8c5a1c604b4edb73",
43
+ "mode": "100644"
44
+ },
45
+ "dist/sdlc.js": {
46
+ "gitBlob": "b8a1a6f6d15042e14e8531e15f9bb514c1d6c622",
47
+ "mode": "100644"
48
+ },
49
+ "eslint-rules/index.js": {
50
+ "gitBlob": "1e05f3e2726b8203d192d710e3398083292da5e3",
51
+ "mode": "100644"
52
+ },
53
+ "index.d.ts": {
54
+ "gitBlob": "76520a3c098c99fc1abce5a15457d041c6d9b32b",
55
+ "mode": "100644"
56
+ },
57
+ "index.js": {
58
+ "gitBlob": "620f3909de24c626bf253f7403ecb922fa5d414d",
59
+ "mode": "100644"
60
+ },
61
+ "intelligence.js": {
62
+ "gitBlob": "67820bcd36661f3a962c3b2ac6446d328c346a34",
63
+ "mode": "100644"
64
+ },
65
+ "package.json": {
66
+ "gitBlob": "6652521461d677b4fe5e893f42456921543fd841",
67
+ "mode": "100644"
68
+ },
69
+ "policy.js": {
70
+ "gitBlob": "8dd150af2cfbe8e952fc48c4c343556c639845ab",
71
+ "mode": "100644"
72
+ },
73
+ "practice-tool.js": {
74
+ "gitBlob": "0938e6474f3a3a695abc4e6d962796c2ce225f7f",
75
+ "mode": "100644"
76
+ },
77
+ "practices.js": {
78
+ "gitBlob": "db56ad205a64a7bc0cc95b006ffa910bb59f8abb",
79
+ "mode": "100755"
80
+ },
81
+ "practices.json": {
82
+ "gitBlob": "d94e9aeba68dd9eb0ab2caf286688f22bf7622a3",
83
+ "mode": "100644"
84
+ },
85
+ "review-verdict.js": {
86
+ "gitBlob": "d7565fbf97dd74ea1c44dfbf9bb2b4cfaef7fc2c",
87
+ "mode": "100755"
88
+ },
89
+ "sdlc.js": {
90
+ "gitBlob": "47ea2562a7c1cd4460a09072795a6673b3d0c565",
91
+ "mode": "100644"
92
+ }
93
+ }
94
+ }
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@krisada-m/ksd-intelligence",
3
- "version": "1.0.0",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
- "description": "KSD engineering policy plus ei_* code-intelligence tools for OMP",
5
+ "description": "Local-first engineering and code intelligence for OMP and AGY",
6
6
  "license": "MIT",
7
7
  "author": "Krisada M. (https://github.com/Krisada-M)",
8
8
  "repository": {
@@ -25,7 +25,11 @@
25
25
  "skills.lock.json",
26
26
  "skills.registry.json",
27
27
  "LICENSE",
28
- "README.md"
28
+ "README.md",
29
+ "engineering.lock.json",
30
+ ".antigravity-plugin/",
31
+ "rules/",
32
+ "agy-skills/"
29
33
  ],
30
34
  "engines": {
31
35
  "node": ">=22.5"
@@ -40,16 +44,19 @@
40
44
  "lint:fix": "eslint --fix .",
41
45
  "format:check": "prettier --check .",
42
46
  "format": "prettier --write .",
43
- "prepare": "husky || true"
47
+ "prepare": "husky || true",
48
+ "verify:engineering": "node scripts/engineering-bundle.mjs"
44
49
  },
45
50
  "bin": {
46
51
  "ei": "dist/adapters/cli/main.js",
47
52
  "ksd-check-changed": "dist/adapters/cli/check-changed.js",
48
- "ksd-review-verdict": "dist/adapters/cli/review-verdict.js"
53
+ "ksd-review-verdict": "dist/adapters/cli/review-verdict.js",
54
+ "erosiano-baseline": "dist/engineering/baseline.js",
55
+ "erosiano-practices": "dist/engineering/practices.js"
49
56
  },
50
57
  "exports": {
51
58
  ".": "./dist/adapters/omp/extension.js",
52
- "./eslint": "./dist/policy/eslint-rules/index.js"
59
+ "./eslint": "./dist/engineering/eslint-rules/index.js"
53
60
  },
54
61
  "omp": {
55
62
  "extensions": [
@@ -0,0 +1,20 @@
1
+ ---
2
+ trigger: always_on
3
+ ---
4
+
5
+ <!-- Generated from the pinned erosiano-dev balanced policy. Do not edit. -->
6
+
7
+ erosiano-dev personal style. Explicit user requirements and current repo conventions take precedence.
8
+ Balanced Clean Code: prefer behavior-preserving guards/early returns; nesting findings are advisory.
9
+ - No nested ternaries; use if, named helper or lookup map.
10
+ - 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.
11
+ - Prefer typed domain results (discriminated unions); throw IO/infrastructure errors, catch at boundary. Preserve project error contracts and causes.
12
+ - No any, `as` casts except `as const`, or non-null `!`; type guards, explicit exported return types.
13
+ - Extract helpers for reuse or clearer callers, not length. Comments: one line explaining why, not what.
14
+ - 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.
15
+ - Select applicable practices after baseline via permitted resolver/catalog; never inject entire catalog.
16
+ - Ponytail owns YAGNI/simplification when present; do not duplicate it or invoke its review automatically.
17
+ - 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.
18
+ - Validate runtime boundaries, handle promise rejection/exhaustive states. Never weaken types, security or tests, invent APIs or fake production success.
19
+ - Never claim a check passed without running it.
20
+ Enforcement=balanced: native gates authoritative; deterministic only if adopted. For SDLC review, use the erosiano-review skill.
@@ -0,0 +1,91 @@
1
+ // AGY/stdio adapter to the pinned engineering runtime. No OMP lifecycle, subprocess or root override.
2
+ import { isAbsolute } from 'node:path';
3
+ import { collectBaselineEvidence } from '../../dist/engineering/baseline.js';
4
+ import { resolvePracticeTool } from '../../dist/engineering/practice-tool.js';
5
+
6
+ const schema = (properties, required) => ({
7
+ type: 'object',
8
+ properties,
9
+ required,
10
+ additionalProperties: false,
11
+ });
12
+ const annotations = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };
13
+
14
+ export const ENGINEERING_TOOLS = Object.freeze([
15
+ {
16
+ name: 'erosiano_baseline',
17
+ description:
18
+ 'Capture bounded sampled file hashes for a scope under the configured workspace. Supply relative scope and optional caller/test/config paths. Does not establish a complete semantic baseline or execute Git.',
19
+ inputSchema: schema(
20
+ {
21
+ scope: { type: 'string', minLength: 1, maxLength: 1024 },
22
+ additionalPaths: {
23
+ type: 'array',
24
+ maxItems: 24,
25
+ items: { type: 'string', minLength: 1, maxLength: 1024 },
26
+ },
27
+ },
28
+ ['scope'],
29
+ ),
30
+ annotations,
31
+ },
32
+ {
33
+ name: 'erosiano_resolve_practices',
34
+ description:
35
+ 'Resolve engineering practices from bounded supplied context. Fresh policy output requires a current baseline fingerprint and observed path provenance. Uses the fixed server root. Does not authenticate interpretations or run native checks.',
36
+ inputSchema: schema(
37
+ {
38
+ context: { type: 'string', maxLength: 65536 },
39
+ group: { type: 'string', maxLength: 64 },
40
+ format: { type: 'string', enum: ['decisions', 'policy'] },
41
+ },
42
+ ['context'],
43
+ ),
44
+ annotations,
45
+ },
46
+ ]);
47
+
48
+ function error(text) {
49
+ return { content: [{ type: 'text', text }], isError: true };
50
+ }
51
+
52
+ function validPath(path) {
53
+ return typeof path === 'string' && path.length > 0 && path.length <= 1024 && !isAbsolute(path);
54
+ }
55
+
56
+ export function callEngineering(root, name, args, signal) {
57
+ if (signal?.aborted) return error('Cancelled');
58
+ if (!args || typeof args !== 'object' || Array.isArray(args)) {
59
+ return error('INVALID_INPUT: expected an object');
60
+ }
61
+ try {
62
+ if (name === 'erosiano_baseline') {
63
+ if (
64
+ Object.keys(args).some((key) => !['scope', 'additionalPaths'].includes(key)) ||
65
+ !validPath(args.scope) ||
66
+ (args.additionalPaths !== undefined &&
67
+ (!Array.isArray(args.additionalPaths) ||
68
+ args.additionalPaths.length > 24 ||
69
+ !args.additionalPaths.every(validPath)))
70
+ ) {
71
+ return error('INVALID_INPUT: relative scoped paths only; fixed server root');
72
+ }
73
+ const record = collectBaselineEvidence({
74
+ root,
75
+ scope: args.scope,
76
+ additionalPaths: args.additionalPaths ?? [],
77
+ });
78
+ const text = JSON.stringify(record);
79
+ if (text.length > 65536) return error('NOT_ASSESSED: narrow the sampled evidence scope');
80
+ return { content: [{ type: 'text', text }] };
81
+ }
82
+ if (name !== 'erosiano_resolve_practices') return error('TOOL_UNAVAILABLE');
83
+ if (Object.keys(args).some((key) => !['context', 'group', 'format'].includes(key))) {
84
+ return error('INVALID_INPUT: unknown argument; fixed server root');
85
+ }
86
+ const result = resolvePracticeTool(args, { root });
87
+ return { content: result.content, ...(result.isError ? { isError: true } : {}) };
88
+ } catch {
89
+ return error('NOT_ASSESSED: invalid or inaccessible scoped engineering evidence');
90
+ }
91
+ }
@@ -20,6 +20,7 @@ import { renderWorkflow } from '../../dist/workflow/render.js';
20
20
  import { rootsFromEnv } from '../../dist/workflow/catalog.js';
21
21
  import { readLock, defaultLockPath } from '../../dist/workflow/sources.js';
22
22
  import { WorkflowError } from '../../dist/workflow/types.js';
23
+ import { ENGINEERING_TOOLS, callEngineering } from './engineering.mjs';
23
24
 
24
25
  const objectSchema = (properties, required = []) => ({
25
26
  type: 'object',
@@ -169,6 +170,17 @@ const result = (message, isError = false) => ({
169
170
  ...(isError ? { isError: true } : {}),
170
171
  });
171
172
 
173
+ // Keep the existing bounded guidance. Only fixed labels and typed summaries enter the table.
174
+ function presented(env, name, text, field, value, isError = false) {
175
+ if (env.KSD_MCP_MARKDOWN !== '1' || isError) return result(text, isError);
176
+ let fenceLength = 3;
177
+ for (const [run] of text.matchAll(/`{3,}/g)) fenceLength = Math.max(fenceLength, run.length + 1);
178
+ const fence = '`'.repeat(fenceLength);
179
+ return result(
180
+ `## ${name}\n\n| Field | Result |\n| --- | --- |\n| ${field} | ${value} |\n\nDetails:\n\n${fence}text\n${text}\n${fence}`,
181
+ );
182
+ }
183
+
172
184
  function validate(name, args) {
173
185
  if (!isObject(args)) return 'INVALID_INPUT: arguments must be an object';
174
186
  const allowed =
@@ -256,7 +268,14 @@ function validate(name, args) {
256
268
  export function createTools({ root, env = process.env }) {
257
269
  const enabled = env.EI_DISABLED !== '1';
258
270
  const workflowEnabled = enabled && env.KSD_MCP_WORKFLOW === '1';
259
- const definitions = enabled ? [...BASE_TOOLS, ...(workflowEnabled ? [WORKFLOW_TOOL] : [])] : [];
271
+ const engineeringEnabled = enabled && env.KSD_MCP_ENGINEERING === '1';
272
+ const definitions = enabled
273
+ ? [
274
+ ...BASE_TOOLS,
275
+ ...(workflowEnabled ? [WORKFLOW_TOOL] : []),
276
+ ...(engineeringEnabled ? ENGINEERING_TOOLS : []),
277
+ ]
278
+ : [];
260
279
  const cacheHome =
261
280
  env !== process.env && typeof env.HOME === 'string' && env.HOME !== '' ? env.HOME : undefined;
262
281
  let sessionPromise;
@@ -300,6 +319,9 @@ export function createTools({ root, env = process.env }) {
300
319
  async function call(name, args, signal, onProgress = () => {}) {
301
320
  if (!definitions.some((tool) => tool.name === name))
302
321
  return result('TOOL_UNAVAILABLE: tool is disabled or unknown', true);
322
+ if (engineeringEnabled && ENGINEERING_TOOLS.some((tool) => tool.name === name)) {
323
+ return callEngineering(root, name, args, signal);
324
+ }
303
325
  const started = performance.now();
304
326
  const invalid = validate(name, args);
305
327
  if (invalid) {
@@ -341,7 +363,7 @@ export function createTools({ root, env = process.env }) {
341
363
  );
342
364
  const extraWarning = consumeAuditWarning(status.cacheDir);
343
365
  if (extraWarning !== null) status.auditWarning = extraWarning;
344
- return result(renderStatus(status));
366
+ return presented(env, name, renderStatus(status), 'state', status.state);
345
367
  }
346
368
  if (name === 'ei_impact') {
347
369
  const session = await impactSession();
@@ -360,8 +382,12 @@ export function createTools({ root, env = process.env }) {
360
382
  },
361
383
  { root: ws.root, cacheDir: ws.cacheDir },
362
384
  );
363
- return result(
385
+ return presented(
386
+ env,
387
+ name,
364
388
  renderImpact(batch),
389
+ 'answers',
390
+ batch.answers.length,
365
391
  batch.answers.some((answer) => answer.kind === 'failure'),
366
392
  );
367
393
  }
@@ -385,7 +411,14 @@ export function createTools({ root, env = process.env }) {
385
411
  },
386
412
  { root: ws.root, cacheDir: ws.cacheDir },
387
413
  );
388
- return result(renderChangesOutcome(outcome), outcome.kind === 'failure');
414
+ return presented(
415
+ env,
416
+ name,
417
+ renderChangesOutcome(outcome),
418
+ 'outcome',
419
+ outcome.kind,
420
+ outcome.kind === 'failure',
421
+ );
389
422
  }
390
423
  if (name === 'ei_search') {
391
424
  const valid = validateSearchInput(args.query, args.limit);
@@ -409,7 +442,14 @@ export function createTools({ root, env = process.env }) {
409
442
  },
410
443
  { root: ws.root, cacheDir: ws.cacheDir },
411
444
  );
412
- return result(renderSearchOutcome(outcome), outcome.kind === 'failure');
445
+ return presented(
446
+ env,
447
+ name,
448
+ renderSearchOutcome(outcome),
449
+ outcome.kind === 'result' ? 'matches' : 'outcome',
450
+ outcome.kind === 'result' ? outcome.value.totalMatches : outcome.kind,
451
+ outcome.kind === 'failure',
452
+ );
413
453
  }
414
454
  const workflow = await prepareWorkflow({
415
455
  task: args.task,
@@ -1,2 +0,0 @@
1
- // Types for the migrated KSD policy module (plain JavaScript; see PROVENANCE.md).
2
- export declare function createExtension(pi: unknown, options?: { globalConfigPath?: string }): void;
@@ -1,241 +0,0 @@
1
- import { loadConfig, setScopedMode, SUPPORTED_MODES } from "./config.js";
2
- import { buildSdlcPolicy } from "./sdlc.js";
3
- import { augmentSystemPrompt, buildPolicy, SECTION_KEY } from "./policy.js";
4
- import { KsdRuntime } from "./dist/runtime.js";
5
-
6
- const MODE_ENTRY = "engineering-proxy-mode";
7
- const isDisabledByEnv = () => process.env.ENGINEERING_PROXY_DISABLED === "1";
8
-
9
- export function parseEngineeringCommand(input) {
10
- const words = String(input ?? "").trim().toLowerCase().split(/\s+/);
11
- if (words.length === 1) {
12
- if (words[0] === "" || words[0] === "status") return { type: "status" };
13
- if (SUPPORTED_MODES.includes(words[0])) return { type: "set-mode", mode: words[0] };
14
- if (words[0] === "reset") return { type: "reset-session" };
15
- }
16
- if (words.length === 2 && ["global", "repo"].includes(words[0])) {
17
- if (SUPPORTED_MODES.includes(words[1])) return { type: "set-scoped-mode", scope: words[0], mode: words[1] };
18
- if (words[1] === "reset") return { type: "reset-scoped-mode", scope: words[0] };
19
- }
20
-
21
- return { type: "invalid" };
22
- }
23
-
24
- function sessionOverride(entries) {
25
- if (!Array.isArray(entries)) return null;
26
-
27
- for (let i = entries.length - 1; i >= 0; i--) {
28
- const entry = entries[i];
29
- if (entry?.type !== "custom" || entry?.customType !== MODE_ENTRY) continue;
30
- if (entry.data?.reset === true) return null;
31
- if (SUPPORTED_MODES.includes(entry.data?.mode)) return entry.data.mode;
32
- }
33
-
34
- return null;
35
- }
36
-
37
- export function resolveSessionMode(entries, fallback = "balanced") {
38
- const defaultMode = SUPPORTED_MODES.includes(fallback) ? fallback : "balanced";
39
-
40
- return sessionOverride(entries) ?? defaultMode;
41
- }
42
-
43
- const REVIEW_INSTRUCTIONS = `Review the current requested change as Engineering Proxy. This delegation does not run any review code for you: perform the inspection yourself through your permitted tools, following OMP permissions and approvals.
44
-
45
- 1. Requirements: state the acceptance criteria and what the change must not break. Check requirements, relevant callers and contracts.
46
- 2. Scope: inspect the actual diff of tracked changes against the operator's stated base (or HEAD for worktree review), plus intended untracked files (NUL-safe discovery, \`git diff --no-index --no-ext-diff --no-textconv -U0 -- /dev/null <path>\`; exit 1 means differences), deletions and renames. Never stage user files to manufacture scope. A path keyword is a hint, not proof that other files are low risk.
47
- 3. Checks: discover the repository's existing check commands first and inspect their safety; declare the applicable required and critical gates, then select typecheck/lint/tests/runtime/CI checks and execute only through permitted tools. Record exact cwd, exit code, output and pass/fail/skip counts. Missing or denied commands and credentials are NOT_RUN or BLOCKED. Never run migrations, database resets or real payments in shared environments.
48
- 4. Evidence: a skipped test without required environment is NOT_RUN, not PASS. A CI YAML file is not proof its job exercised the change; inspect actual relevant job and step execution for the reviewed commit and distinguish dirty/untracked behavior it cannot cover. Source-only inspection cannot verify an executed gate. Optional installed ksd-check-changed and ksd-review-verdict validators may be invoked through approved OMP tools with supplied reports and required gates; they do not run checks or authenticate evidence. A tiny review needs no report file: report the observed evidence directly.
49
- 5. Risk: escalate Auth, Payments, Database/schema/query changes, RLS/authorization, destructive data operations, secrets and concurrency based on behavior, not filenames. For auth check normal-user denial (cross-tenant, another owner's record, unauthenticated; service-role success is not isolation proof). For payments preserve confirmation, idempotency and replay protection. For databases check constraints, locks, transaction boundaries and migration compatibility. For deletions check scope, cascades and recovery.
50
- 6. Style: independently verify the KSD style profile from the Engineering Proxy policy (guard clauses, no nested ternaries, result-vs-throw error split, strict types, why-only comments, blank-line rules), repo conventions and type safety. Review changed scope, not unrelated code.
51
- Report: acceptance criteria, affected contracts/risk, findings anchored to files with severity, exact observed check evidence (commands and results), and missing/denied/skipped/failed checks — then delivery and rollback implications. Never label release or merge readiness with unresolved required or security gates; no auto release/merge/push/deploy. Ponytail review must not be invoked here unless the user separately requested it; do not report a pass you did not observe.`;
52
-
53
- export function createExtension(pi, { globalConfigPath } = {}) {
54
- pi.setLabel?.("Engineering Proxy");
55
- // One runtime per extension instance: caches must not leak between hosts or tests.
56
- const runtime = new KsdRuntime(cwd => loadConfig(cwd, { globalConfigPath }), buildPolicy, isDisabledByEnv);
57
-
58
- let isActive = false;
59
- let selectedSessionMode = null;
60
- let lastWarning = null;
61
- const effectiveMode = config => selectedSessionMode ?? config.enforcement;
62
-
63
- const refreshConfig = ctx => runtime.getConfig(ctx?.cwd ?? process.cwd(), true);
64
-
65
- const updateStatus = (ctx, config, notice) => runtime.syncStatus(ctx, isActive, effectiveMode(config), notice);
66
-
67
- function notifyWarningOnce(ctx, message) {
68
- if (lastWarning === message) return;
69
- lastWarning = message;
70
- ctx?.ui?.notify?.(`${message} (${SECTION_KEY})`, "warning");
71
- }
72
-
73
- function clearWarning() {
74
- lastWarning = null;
75
- }
76
-
77
- /**
78
- * Reconcile the prompt in one call for both enabled and disabled paths.
79
- * `undefined` policy removes owned guidance; a failed legacy reconciliation is stored and notified
80
- * once per unchanged warning, never claimed as success.
81
- */
82
- function reconcilePrompt(event, ctx, policy) {
83
- let warned = false;
84
- const result = augmentSystemPrompt(event, policy, message => {
85
- warned = true;
86
- notifyWarningOnce(ctx, message);
87
- });
88
-
89
- if (warned) return { result, warned: true };
90
- clearWarning();
91
-
92
- return { result, warned: false };
93
- }
94
-
95
- function restoreSession(ctx) {
96
- isActive = false;
97
- const config = refreshConfig(ctx);
98
- runtime.invalidateStatus(ctx?.ui);
99
- const sessionManager = ctx?.sessionManager;
100
-
101
- // getBranch() is authoritative: nullish/malformed/throwing branch data means no session override,
102
- // never a fallback to all-branches entries.
103
- if (typeof sessionManager?.getBranch === "function") {
104
- try {
105
- selectedSessionMode = sessionOverride(sessionManager.getBranch());
106
- } catch {
107
- selectedSessionMode = null;
108
- }
109
- } else {
110
- try {
111
- selectedSessionMode = sessionOverride(sessionManager?.getEntries?.() ?? []);
112
- } catch {
113
- selectedSessionMode = null;
114
- }
115
- }
116
-
117
- updateStatus(ctx, config, lastWarning ?? undefined);
118
- }
119
-
120
- for (const eventName of ["session_start", "session_tree", "session_switch", "session_branch"]) {
121
- pi.on(eventName, (_event, ctx) => restoreSession(ctx));
122
- }
123
-
124
- pi.on("agent_start", (_event, ctx) => {
125
- isActive = true;
126
- updateStatus(ctx, runtime.getConfig(ctx?.cwd ?? process.cwd()), lastWarning ?? undefined);
127
- });
128
-
129
- pi.on("agent_end", (_event, ctx) => {
130
- isActive = false;
131
- updateStatus(ctx, runtime.getConfig(ctx?.cwd ?? process.cwd()), lastWarning ?? undefined);
132
- });
133
-
134
- pi.on("before_agent_start", (event, ctx) => {
135
- const config = refreshConfig(ctx);
136
- const policy = !config.enabled || isDisabledByEnv() ? undefined : runtime.getPolicy(effectiveMode(config));
137
- const { result } = reconcilePrompt(event, ctx, policy);
138
- updateStatus(ctx, config, lastWarning ?? undefined);
139
-
140
- return result;
141
- });
142
-
143
- pi.registerCommand("engineering-proxy", {
144
- description: "Engineering policy: status, session mode/reset, global mode/reset, repo mode/reset",
145
- handler: async (args, ctx) => {
146
- // Refresh and draw status BEFORE any validation or disabled early return, so a rejected
147
- // command cannot leave stale status behind.
148
- const config = refreshConfig(ctx);
149
- updateStatus(ctx, config, lastWarning ?? undefined);
150
- const parsed = parseEngineeringCommand(args);
151
- const enabled = config.enabled && !isDisabledByEnv();
152
-
153
- if (parsed.type === "invalid") {
154
- ctx.ui?.notify?.("Usage: /engineering-proxy [status|balanced|adaptive|reset|global <balanced|adaptive|reset>|repo <balanced|adaptive|reset>]", "warning");
155
-
156
- return;
157
- }
158
-
159
- if (parsed.type === "set-mode" || parsed.type === "reset-session") {
160
- if (!enabled && parsed.type === "set-mode") {
161
- ctx.ui?.notify?.("Engineering Proxy is disabled; mode unchanged.", "warning");
162
-
163
- return;
164
- }
165
-
166
- selectedSessionMode = parsed.type === "reset-session" ? null : parsed.mode;
167
- let persisted = false;
168
- try {
169
- if (typeof pi.appendEntry === "function") {
170
- pi.appendEntry(MODE_ENTRY, parsed.type === "reset-session" ? { reset: true } : { mode: selectedSessionMode });
171
- persisted = true;
172
- }
173
- } catch {
174
- // Runtime policy still updates, but session mode cannot be replayed.
175
- }
176
-
177
- updateStatus(ctx, config, lastWarning ?? undefined);
178
- const effective = effectiveMode(config);
179
- ctx.ui?.notify?.(`KSD mode: ${effective.toUpperCase()} (${persisted ? "saved in session" : "runtime only; session persistence unavailable"})`, persisted ? "info" : "warning");
180
-
181
- return;
182
- }
183
-
184
- if (parsed.type === "set-scoped-mode" || parsed.type === "reset-scoped-mode") {
185
- const mode = parsed.type === "reset-scoped-mode" ? null : parsed.mode;
186
- try {
187
- const path = setScopedMode(ctx.cwd, parsed.scope, mode, { globalConfigPath });
188
- const next = refreshConfig(ctx);
189
- updateStatus(ctx, next, lastWarning ?? undefined);
190
- ctx.ui?.notify?.(`KSD ${parsed.scope} ${mode ?? "reset"} saved to ${path}; effective: ${effectiveMode(next).toUpperCase()} (${selectedSessionMode ? "session" : next.enforcementSource})`, "info");
191
- } catch (error) {
192
- ctx.ui?.notify?.(`KSD ${parsed.scope} update failed: ${error.message}`, "warning");
193
- }
194
-
195
- return;
196
- }
197
-
198
- const names = pi.getCommands?.() ?? [];
199
- const ponytailFound = Array.isArray(names) && names.some(command => command?.name === "ponytail");
200
- const msg = `Engineering Proxy: ${enabled ? "ON" : "OFF"}; mode: ${effectiveMode(config).toUpperCase()} (${selectedSessionMode ? "session" : config.enforcementSource}); project default: ${(config.projectEnforcement ?? "unset").toUpperCase()}; global default: ${(config.globalEnforcement ?? "unset").toUpperCase()}; session: ${(selectedSessionMode ?? "inherit").toUpperCase()}; Ponytail command: ${ponytailFound ? "detected" : "not detected/unknown"}; Ponytail mode: not inspected`;
201
- const warnings = [config.configError, lastWarning].filter(Boolean);
202
- const plain = warnings.length ? `${msg}; WARNING: ${warnings.join("; ")}` : msg;
203
- let display = plain;
204
- try {
205
- const theme = ctx.ui?.theme;
206
- if (typeof theme?.fg === "function") {
207
- display = plain.replace(/(Engineering Proxy: |; mode: |; project default: |; global default: |; session: )(ON|OFF|BALANCED|ADAPTIVE|UNSET|INHERIT)/g,
208
- (_match, label, value) => `${label}${theme.fg("accent", value)}`)
209
- .replace(/Engineering Proxy:|; mode:|; project default:|; global default:|; session:|; Ponytail command:|; Ponytail mode:|; WARNING:/g,
210
- label => theme.fg(label === "; WARNING:" ? "accent" : "dim", label));
211
- }
212
- } catch {
213
- display = plain;
214
- }
215
- ctx.ui?.notify?.(display, warnings.length ? "warning" : "info");
216
- },
217
- });
218
-
219
- pi.registerCommand("engineering-review", {
220
- description: "Request a scoped, evidence-based engineering review (Ponytail optional)",
221
- handler: async (args, ctx) => {
222
- const config = refreshConfig(ctx);
223
- updateStatus(ctx, config, lastWarning ?? undefined);
224
- if (!config.enabled || isDisabledByEnv()) {
225
- ctx.ui?.notify?.("Engineering Proxy is disabled for this project", "warning");
226
-
227
- return;
228
- }
229
- const scope = typeof args === "string" && args.trim() ? `\nReview scope: ${args.trim()}` : "";
230
- const message = `${REVIEW_INSTRUCTIONS}\n\n${buildSdlcPolicy({ mode: effectiveMode(config) })}${scope}`;
231
- // Explicit operator command only: no automatic Ponytail invocation.
232
- if (ctx.isIdle?.() === false) {
233
- pi.sendUserMessage(message, { deliverAs: "followUp" });
234
- } else {
235
- pi.sendUserMessage(message);
236
- }
237
- },
238
- });
239
- }
240
-
241
- export default createExtension;
@@ -1,2 +0,0 @@
1
- // Types for the migrated KSD policy module's policy.js (plain JavaScript; see PROVENANCE.md).
2
- export declare const SECTION_KEY: string;
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes