@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,359 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile, writeFile } from 'node:fs/promises';
3
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { PROVIDERS, lookupSkill } from './catalog.js';
6
+ import { SKILL_PACKS, defaultSkillsDir, parseSkillFrontmatter, } from './packs.js';
7
+ import { ORCHESTRATOR_SKILL_ID, PROVIDER_IDS, SKILL_PACK_IDS, WorkflowError, isOneOf, } from './types.js';
8
+ const COMMIT = /^[0-9a-f]{40}$/;
9
+ const RUNTIMES = ['agy', 'omp'];
10
+ const ACTIVATIONS = ['auto', 'opt-in'];
11
+ function isRecord(value) {
12
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
13
+ }
14
+ function registryError(message) {
15
+ return new WorkflowError('LOCK_INVALID', `registry: ${message}`);
16
+ }
17
+ export function defaultRegistryPath() {
18
+ const fallback = fileURLToPath(new URL('../../skills.registry.json', import.meta.url));
19
+ let dir = dirname(fileURLToPath(import.meta.url));
20
+ for (let depth = 0; depth < 5; depth += 1) {
21
+ const candidate = join(dir, 'skills.registry.json');
22
+ if (existsSync(join(dir, 'package.json')) && existsSync(candidate)) {
23
+ return candidate;
24
+ }
25
+ const parent = dirname(dir);
26
+ if (parent === dir)
27
+ break;
28
+ dir = parent;
29
+ }
30
+ return fallback;
31
+ }
32
+ function parseProvider(provider, raw) {
33
+ const where = `providers.${provider}`;
34
+ if (!isRecord(raw))
35
+ throw registryError(`${where} must be an object`);
36
+ const info = PROVIDERS[provider];
37
+ if (raw.repo !== info.repo) {
38
+ throw registryError(`${where}.repo is ${JSON.stringify(raw.repo)}, expected ${info.repo}`);
39
+ }
40
+ if (raw.rootSubpath !== info.rootSubpath) {
41
+ throw registryError(`${where}.rootSubpath is ${JSON.stringify(raw.rootSubpath)}, expected ${info.rootSubpath}`);
42
+ }
43
+ const commit = raw.commit;
44
+ if (commit !== null && !(typeof commit === 'string' && COMMIT.test(commit))) {
45
+ throw registryError(`${where}.commit must be null or a 40-char lowercase hex SHA`);
46
+ }
47
+ if (typeof raw.license !== 'string' || !raw.license.trim()) {
48
+ throw registryError(`${where}.license must be a non-empty string`);
49
+ }
50
+ if (typeof raw.attribution !== 'string' || !raw.attribution.trim()) {
51
+ throw registryError(`${where}.attribution must be a non-empty string`);
52
+ }
53
+ if (raw.adaptationBoundary !== 'upstream-read-only') {
54
+ throw registryError(`${where}.adaptationBoundary must be "upstream-read-only"`);
55
+ }
56
+ return {
57
+ repo: info.repo,
58
+ commit,
59
+ rootSubpath: info.rootSubpath,
60
+ license: raw.license,
61
+ attribution: raw.attribution,
62
+ adaptationBoundary: 'upstream-read-only',
63
+ };
64
+ }
65
+ function parseStringArray(where, raw) {
66
+ if (!Array.isArray(raw) || raw.some((item) => typeof item !== 'string' || !item.trim())) {
67
+ throw registryError(`${where} must be an array of non-empty strings`);
68
+ }
69
+ return [...raw];
70
+ }
71
+ function parsePack(packId, raw) {
72
+ const where = `packs.${packId}`;
73
+ if (!isRecord(raw))
74
+ throw registryError(`${where} must be an object`);
75
+ if (raw.id !== packId)
76
+ throw registryError(`${where}.id must equal ${packId}`);
77
+ const expected = SKILL_PACKS[packId];
78
+ if (raw.owner !== expected.owner) {
79
+ throw registryError(`${where}.owner must be ${expected.owner}`);
80
+ }
81
+ if (!isOneOf(PROVIDER_IDS, raw.provider) || raw.provider !== expected.provider) {
82
+ throw registryError(`${where}.provider must be ${expected.provider}`);
83
+ }
84
+ if (!isOneOf(ACTIVATIONS, raw.activation)) {
85
+ throw registryError(`${where}.activation must be "auto" or "opt-in"`);
86
+ }
87
+ if (typeof raw.disableModelInvocation !== 'boolean') {
88
+ throw registryError(`${where}.disableModelInvocation must be a boolean`);
89
+ }
90
+ const rawRuntimes = parseStringArray(`${where}.supportedRuntimes`, raw.supportedRuntimes);
91
+ const supportedRuntimes = [];
92
+ for (const rt of rawRuntimes) {
93
+ if (!isOneOf(RUNTIMES, rt))
94
+ throw registryError(`${where}.supportedRuntimes has invalid ${rt}`);
95
+ if (!supportedRuntimes.includes(rt))
96
+ supportedRuntimes.push(rt);
97
+ }
98
+ if (!isRecord(raw.dependencies))
99
+ throw registryError(`${where}.dependencies must be an object`);
100
+ const depProviders = parseStringArray(`${where}.dependencies.providers`, raw.dependencies.providers).map((value) => {
101
+ if (!isOneOf(PROVIDER_IDS, value)) {
102
+ throw registryError(`${where}.dependencies.providers has unknown provider ${value}`);
103
+ }
104
+ return value;
105
+ });
106
+ const depLeafSkills = parseStringArray(`${where}.dependencies.leafSkills`, raw.dependencies.leafSkills).map((value) => {
107
+ if (!lookupSkill(value)) {
108
+ throw registryError(`${where}.dependencies.leafSkills has non-allowlisted skill ${value}`);
109
+ }
110
+ return value;
111
+ });
112
+ const depPacks = parseStringArray(`${where}.dependencies.packs`, raw.dependencies.packs).map((value) => {
113
+ if (!isOneOf(SKILL_PACK_IDS, value)) {
114
+ throw registryError(`${where}.dependencies.packs has unknown pack ${value}`);
115
+ }
116
+ return value;
117
+ });
118
+ if (!isRecord(raw.upstream))
119
+ throw registryError(`${where}.upstream must be an object`);
120
+ const info = PROVIDERS[expected.provider];
121
+ if (raw.upstream.repo !== info.repo) {
122
+ throw registryError(`${where}.upstream.repo must equal ${info.repo}`);
123
+ }
124
+ if (raw.upstream.rootSubpath !== info.rootSubpath) {
125
+ throw registryError(`${where}.upstream.rootSubpath must equal ${info.rootSubpath}`);
126
+ }
127
+ const sourcePaths = parseStringArray(`${where}.upstream.sourcePaths`, raw.upstream.sourcePaths);
128
+ for (const sourcePath of sourcePaths) {
129
+ if (isAbsolute(sourcePath) || sourcePath.split(/[\\/]/).includes('..')) {
130
+ throw registryError(`${where}.upstream.sourcePaths has unsafe path ${sourcePath}`);
131
+ }
132
+ }
133
+ if (!isRecord(raw.ksdAdaptation))
134
+ throw registryError(`${where}.ksdAdaptation must be an object`);
135
+ if (typeof raw.ksdAdaptation.wrapperPath !== 'string' || !raw.ksdAdaptation.wrapperPath.trim()) {
136
+ throw registryError(`${where}.ksdAdaptation.wrapperPath must be a non-empty string`);
137
+ }
138
+ if (isAbsolute(raw.ksdAdaptation.wrapperPath) ||
139
+ raw.ksdAdaptation.wrapperPath.split(/[\\/]/).includes('..')) {
140
+ throw registryError(`${where}.ksdAdaptation.wrapperPath must be repo-relative`);
141
+ }
142
+ if (raw.ksdAdaptation.localPolicyOwner !== ORCHESTRATOR_SKILL_ID) {
143
+ throw registryError(`${where}.ksdAdaptation.localPolicyOwner must be ${ORCHESTRATOR_SKILL_ID}`);
144
+ }
145
+ if (!isRecord(raw.ksdAdaptation.runtimeNotes)) {
146
+ throw registryError(`${where}.ksdAdaptation.runtimeNotes must be an object`);
147
+ }
148
+ const agyNote = raw.ksdAdaptation.runtimeNotes.agy;
149
+ const ompNote = raw.ksdAdaptation.runtimeNotes.omp;
150
+ if (typeof agyNote !== 'string' ||
151
+ !agyNote.trim() ||
152
+ typeof ompNote !== 'string' ||
153
+ !ompNote.trim()) {
154
+ throw registryError(`${where}.ksdAdaptation.runtimeNotes must include agy and omp notes`);
155
+ }
156
+ return {
157
+ id: packId,
158
+ owner: expected.owner,
159
+ provider: expected.provider,
160
+ activation: raw.activation,
161
+ disableModelInvocation: raw.disableModelInvocation,
162
+ supportedRuntimes,
163
+ dependencies: {
164
+ providers: depProviders,
165
+ leafSkills: depLeafSkills,
166
+ packs: depPacks,
167
+ },
168
+ upstream: {
169
+ repo: info.repo,
170
+ rootSubpath: info.rootSubpath,
171
+ sourcePaths,
172
+ },
173
+ ksdAdaptation: {
174
+ wrapperPath: raw.ksdAdaptation.wrapperPath,
175
+ localPolicyOwner: ORCHESTRATOR_SKILL_ID,
176
+ runtimeNotes: { agy: agyNote, omp: ompNote },
177
+ },
178
+ };
179
+ }
180
+ export function parseRegistry(text) {
181
+ let raw;
182
+ try {
183
+ raw = JSON.parse(text);
184
+ }
185
+ catch (error) {
186
+ throw registryError(`not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
187
+ }
188
+ if (!isRecord(raw) || raw.version !== 1)
189
+ throw registryError('version must be 1');
190
+ if (raw.orchestrator !== ORCHESTRATOR_SKILL_ID) {
191
+ throw registryError(`orchestrator must be ${ORCHESTRATOR_SKILL_ID}`);
192
+ }
193
+ if (raw.lockfile !== 'skills.lock.json') {
194
+ throw registryError('lockfile must be "skills.lock.json"');
195
+ }
196
+ if (!isRecord(raw.providers))
197
+ throw registryError('providers must be an object');
198
+ if (!isRecord(raw.packs))
199
+ throw registryError('packs must be an object');
200
+ const extraPacks = Object.keys(raw.packs).filter((id) => !isOneOf(SKILL_PACK_IDS, id));
201
+ if (extraPacks.length > 0) {
202
+ throw registryError(`unknown packs: ${extraPacks.join(', ')}`);
203
+ }
204
+ return {
205
+ version: 1,
206
+ orchestrator: ORCHESTRATOR_SKILL_ID,
207
+ lockfile: 'skills.lock.json',
208
+ providers: {
209
+ matt: parseProvider('matt', raw.providers.matt),
210
+ poteto: parseProvider('poteto', raw.providers.poteto),
211
+ osmani: parseProvider('osmani', raw.providers.osmani),
212
+ },
213
+ packs: {
214
+ 'matt-sdlc': parsePack('matt-sdlc', raw.packs['matt-sdlc']),
215
+ 'pstack-analysis': parsePack('pstack-analysis', raw.packs['pstack-analysis']),
216
+ 'poteto-mode': parsePack('poteto-mode', raw.packs['poteto-mode']),
217
+ 'osmani-quality': parsePack('osmani-quality', raw.packs['osmani-quality']),
218
+ },
219
+ };
220
+ }
221
+ export async function readRegistry(path = defaultRegistryPath()) {
222
+ let text;
223
+ try {
224
+ text = await readFile(path, 'utf8');
225
+ }
226
+ catch (error) {
227
+ throw registryError(`cannot read registry ${path}: ${error instanceof Error ? error.message : String(error)}`);
228
+ }
229
+ return parseRegistry(text);
230
+ }
231
+ export async function writeRegistry(path, registry) {
232
+ await writeFile(path, `${JSON.stringify(registry, null, 2)}\n`);
233
+ }
234
+ function detectPackCycle(registry) {
235
+ const state = new Map();
236
+ const stack = [];
237
+ const visit = (id) => {
238
+ const current = state.get(id);
239
+ if (current === 'visiting') {
240
+ const start = stack.indexOf(id);
241
+ return [...stack.slice(start), id];
242
+ }
243
+ if (current === 'done')
244
+ return null;
245
+ state.set(id, 'visiting');
246
+ stack.push(id);
247
+ for (const dep of registry.packs[id].dependencies.packs) {
248
+ const cycle = visit(dep);
249
+ if (cycle)
250
+ return cycle;
251
+ }
252
+ stack.pop();
253
+ state.set(id, 'done');
254
+ return null;
255
+ };
256
+ for (const id of SKILL_PACK_IDS) {
257
+ const cycle = visit(id);
258
+ if (cycle)
259
+ return cycle;
260
+ }
261
+ return null;
262
+ }
263
+ export async function validateRegistryConsistency(registry, lock, options = {}) {
264
+ const issues = [];
265
+ const skillsDir = options.skillsDir ?? defaultSkillsDir();
266
+ const repoRoot = dirname(skillsDir);
267
+ for (const provider of PROVIDER_IDS) {
268
+ const regProv = registry.providers[provider];
269
+ const lockProv = lock.providers[provider];
270
+ if (regProv.commit !== lockProv.commit) {
271
+ issues.push({
272
+ code: 'REGISTRY_LOCK_DRIFT',
273
+ subject: `providers.${provider}`,
274
+ message: `registry pins commit ${String(regProv.commit)}, lockfile pins ${String(lockProv.commit)}`,
275
+ });
276
+ }
277
+ if (regProv.repo !== lockProv.repo || regProv.rootSubpath !== lockProv.rootSubpath) {
278
+ issues.push({
279
+ code: 'REGISTRY_LOCK_DRIFT',
280
+ subject: `providers.${provider}`,
281
+ message: `registry repo/rootSubpath disagrees with skills.lock.json`,
282
+ });
283
+ }
284
+ }
285
+ const cycle = detectPackCycle(registry);
286
+ if (cycle) {
287
+ issues.push({
288
+ code: 'CYCLIC_DEPENDENCY',
289
+ subject: cycle.join(' -> '),
290
+ message: `cyclic pack dependency detected: ${cycle.join(' -> ')}`,
291
+ });
292
+ }
293
+ for (const packId of SKILL_PACK_IDS) {
294
+ const pack = registry.packs[packId];
295
+ for (const runtime of RUNTIMES) {
296
+ if (!pack.supportedRuntimes.includes(runtime)) {
297
+ issues.push({
298
+ code: 'RUNTIME_UNSUPPORTED',
299
+ subject: packId,
300
+ message: `${packId} must support both AGY and OMP (missing ${runtime})`,
301
+ });
302
+ }
303
+ }
304
+ if (packId === 'poteto-mode' &&
305
+ (pack.activation !== 'opt-in' || !pack.disableModelInvocation)) {
306
+ issues.push({
307
+ code: 'OPT_IN_VIOLATION',
308
+ subject: packId,
309
+ message: `poteto-mode must remain activation="opt-in" and disableModelInvocation=true`,
310
+ });
311
+ }
312
+ // Upstream content must remain separated from local policy files under src/policy/.
313
+ if (pack.ksdAdaptation.wrapperPath.startsWith('src/policy/')) {
314
+ issues.push({
315
+ code: 'POLICY_BOUNDARY_VIOLATION',
316
+ subject: packId,
317
+ message: `${packId} wrapperPath cannot reside inside frozen src/policy/`,
318
+ });
319
+ }
320
+ for (const leafId of pack.dependencies.leafSkills) {
321
+ const entry = lookupSkill(leafId);
322
+ if (!entry || !(leafId in lock.providers[entry.provider].skills)) {
323
+ issues.push({
324
+ code: 'MISSING_DEPENDENCY',
325
+ subject: `${packId}:${leafId}`,
326
+ message: `${packId} depends on leaf skill ${leafId}, which is missing from lockfile`,
327
+ });
328
+ }
329
+ }
330
+ const wrapperAbs = resolve(repoRoot, pack.ksdAdaptation.wrapperPath);
331
+ const relToSkills = relative(skillsDir, wrapperAbs);
332
+ if (relToSkills === '..' || relToSkills.startsWith(`..${sep}`) || isAbsolute(relToSkills)) {
333
+ issues.push({
334
+ code: 'POLICY_BOUNDARY_VIOLATION',
335
+ subject: packId,
336
+ message: `${packId} wrapperPath ${pack.ksdAdaptation.wrapperPath} must live under skills/`,
337
+ });
338
+ }
339
+ else if (!existsSync(wrapperAbs)) {
340
+ issues.push({
341
+ code: 'MISSING_WRAPPER',
342
+ subject: packId,
343
+ message: `${packId} local KSD wrapper ${pack.ksdAdaptation.wrapperPath} does not exist`,
344
+ });
345
+ }
346
+ else if (pack.disableModelInvocation) {
347
+ const text = await readFile(wrapperAbs, 'utf8');
348
+ const fm = parseSkillFrontmatter(text);
349
+ if (!fm?.disableModelInvocation) {
350
+ issues.push({
351
+ code: 'OPT_IN_VIOLATION',
352
+ subject: packId,
353
+ message: `${packId} wrapper ${pack.ksdAdaptation.wrapperPath} must declare disable-model-invocation: true`,
354
+ });
355
+ }
356
+ }
357
+ }
358
+ return issues;
359
+ }
@@ -0,0 +1,61 @@
1
+ // Always the first thing in rendered output, before the task text or any skill content.
2
+ export const PRECEDENCE_HEADER = [
3
+ '# KSD Workflow',
4
+ 'KSD/project policy and explicit owner decisions take precedence over any skill text below.',
5
+ 'Never merge or deploy without explicit approval. Report verification evidence.',
6
+ ].join('\n');
7
+ function classifiedNote(workflow) {
8
+ if (workflow.classifiedBy === 'default') {
9
+ return 'default (no keyword matched; feature was assumed — pass `type` if that is wrong)';
10
+ }
11
+ return workflow.classifiedBy;
12
+ }
13
+ export function stageProtocolLine(stage) {
14
+ switch (stage) {
15
+ case 'investigate':
16
+ case 'implement':
17
+ return "Stage Protocol: Before changing a symbol, call `ei_impact` on it and follow the verdict's action.\n";
18
+ case 'verify':
19
+ return 'Stage Protocol: Run the tests listed by `ei_impact` / `ei_changes`; report real output.\n';
20
+ case 'review':
21
+ case 'ship':
22
+ return 'Stage Protocol: Call `ei_changes` and include its verdict and `unindexedChanges` in your report.\n';
23
+ case 'plan':
24
+ return '';
25
+ }
26
+ }
27
+ export function renderWorkflow(workflow) {
28
+ const secondaryLine = workflow.secondaryPacks.length > 0
29
+ ? `Secondary Packs: ${workflow.secondaryPacks
30
+ .map((pack) => {
31
+ const reason = workflow.secondaryReasons[pack];
32
+ return reason ? `${pack} (${reason})` : pack;
33
+ })
34
+ .join(', ')}\n`
35
+ : '';
36
+ const optInLine = workflow.optInPacks.length > 0 ? `Opt-In Modes: ${workflow.optInPacks.join(', ')}\n` : '';
37
+ const complianceLine = workflow.requirementCompliance.required
38
+ ? `Compliance Gate: ${workflow.requirementCompliance.dimensions.join(' × ')}\n`
39
+ : '';
40
+ let text = `${PRECEDENCE_HEADER}\n\n` +
41
+ `Orchestrator: ${workflow.orchestrator}\n` +
42
+ `Task: ${workflow.task}\n` +
43
+ `Type: ${workflow.type} (classifiedBy: ${classifiedNote(workflow)})\n` +
44
+ `Stage: ${workflow.stage}\n` +
45
+ stageProtocolLine(workflow.stage) +
46
+ `Risk: ${workflow.risk}\n` +
47
+ `Primary Pack: ${workflow.primaryPack}\n` +
48
+ secondaryLine +
49
+ optInLine +
50
+ complianceLine;
51
+ for (const entry of workflow.missing) {
52
+ text += `\nMISSING (not invoked): ${entry.id} — ${entry.reason}\n`;
53
+ }
54
+ for (const skill of workflow.loaded) {
55
+ text += `\n# Skill invoked: ${skill.id}\nSource: ${skill.file}\nsha256: ${skill.sha256} (${skill.hash === 'verified' ? 'matches lock' : 'NOT pinned in lock'})\nResolve linked resources relative to: ${skill.baseDir}\nDo not execute scripts without reviewing them.\n\n${skill.text}\n`;
56
+ }
57
+ for (const pack of workflow.packInstructions) {
58
+ text += `\n# Opt-in pack invoked: ${pack.id}\nSource: ${pack.file}\nsha256: ${pack.sha256} (bundled KSD catalog)\nResolve linked resources relative to: ${pack.baseDir}\nDo not execute scripts without reviewing them.\n\n${pack.text}\n`;
59
+ }
60
+ return text;
61
+ }
@@ -0,0 +1,141 @@
1
+ import { classifyTask } from './classify.js';
2
+ import { packForSkillId } from './packs.js';
3
+ import { COMPLIANCE_DIMENSIONS, ORCHESTRATOR_SKILL_ID, RISKS, STAGES, TASK_TYPES, WorkflowError, isOneOf, } from './types.js';
4
+ // One primary skill per stage, indexed by STAGES order:
5
+ // plan, investigate, implement, verify, review, ship.
6
+ const WORKFLOWS = {
7
+ bug: [
8
+ 'matt:diagnosing-bugs',
9
+ 'matt:diagnosing-bugs',
10
+ 'matt:tdd',
11
+ 'osmani:code-review-and-quality',
12
+ 'poteto:blast-radius',
13
+ 'osmani:shipping-and-launch',
14
+ ],
15
+ feature: [
16
+ 'osmani:spec-driven-development',
17
+ 'poteto:how',
18
+ 'matt:tdd',
19
+ 'osmani:code-review-and-quality',
20
+ 'matt:code-review',
21
+ 'osmani:shipping-and-launch',
22
+ ],
23
+ refactor: [
24
+ 'matt:codebase-design',
25
+ 'poteto:how',
26
+ 'osmani:incremental-implementation',
27
+ 'osmani:code-review-and-quality',
28
+ 'poteto:blast-radius',
29
+ 'osmani:shipping-and-launch',
30
+ ],
31
+ security: [
32
+ 'osmani:security-and-hardening',
33
+ 'matt:diagnosing-bugs',
34
+ 'matt:tdd',
35
+ 'osmani:security-and-hardening',
36
+ 'poteto:blast-radius',
37
+ 'osmani:shipping-and-launch',
38
+ ],
39
+ performance: [
40
+ 'osmani:performance-optimization',
41
+ 'poteto:why',
42
+ 'osmani:incremental-implementation',
43
+ 'osmani:performance-optimization',
44
+ 'poteto:blast-radius',
45
+ 'osmani:shipping-and-launch',
46
+ ],
47
+ ui: [
48
+ 'osmani:frontend-ui-engineering',
49
+ 'poteto:how',
50
+ 'osmani:frontend-ui-engineering',
51
+ 'osmani:browser-testing-with-devtools',
52
+ 'poteto:blast-radius',
53
+ 'osmani:shipping-and-launch',
54
+ ],
55
+ };
56
+ const REQ_COMPLIANCE_RE = /\b(?:req|reqs|requirement|requirements|acceptance criteria|req mismatch|spec mismatch|requirement compliance)\b/i;
57
+ export function hasRequirementComplianceSignal(task) {
58
+ return REQ_COMPLIANCE_RE.test(task);
59
+ }
60
+ function invalid(field, value, allowed) {
61
+ return new WorkflowError('INVALID_INPUT', `invalid ${field} ${JSON.stringify(value)}; expected one of: ${allowed.join(', ')}`);
62
+ }
63
+ function primarySkill(type, stage) {
64
+ const skill = WORKFLOWS[type][STAGES.indexOf(stage)];
65
+ if (skill === undefined)
66
+ throw new WorkflowError('INVALID_INPUT', `no workflow entry for ${type}/${stage}`);
67
+ return skill;
68
+ }
69
+ export function routeTask(input) {
70
+ const { task, stage = 'plan', risk = 'normal', type, potetoMode = false } = input;
71
+ if (typeof task !== 'string' || !task.trim())
72
+ throw new WorkflowError('INVALID_INPUT', 'non-empty task required');
73
+ if (!isOneOf(STAGES, stage))
74
+ throw invalid('stage', stage, STAGES);
75
+ if (!isOneOf(RISKS, risk))
76
+ throw invalid('risk', risk, RISKS);
77
+ if (type !== undefined && !isOneOf(TASK_TYPES, type))
78
+ throw invalid('type', type, TASK_TYPES);
79
+ if (typeof potetoMode !== 'boolean') {
80
+ throw new WorkflowError('INVALID_INPUT', 'potetoMode must be a boolean');
81
+ }
82
+ const cleanTask = task.trim();
83
+ const resolved = type === undefined ? classifyTask(cleanTask) : { type, classifiedBy: 'caller' };
84
+ const primary = primarySkill(resolved.type, stage);
85
+ const primaryPack = packForSkillId(primary);
86
+ const skillIds = [primary];
87
+ const secondaryPacks = [];
88
+ const secondaryReasons = {};
89
+ const addSecondary = (pack, reason) => {
90
+ if (pack === primaryPack || secondaryPacks.includes(pack))
91
+ return;
92
+ secondaryPacks.push(pack);
93
+ secondaryReasons[pack] = reason;
94
+ };
95
+ // High risk adds at most one extra reviewer/verifier, and only at review/verify.
96
+ if (risk === 'high' && stage === 'review') {
97
+ skillIds.push('poteto:blast-radius');
98
+ addSecondary('pstack-analysis', 'high-risk-review');
99
+ }
100
+ if (risk === 'high' && stage === 'verify') {
101
+ skillIds.push('osmani:security-and-hardening');
102
+ addSecondary('osmani-quality', 'high-risk-verify');
103
+ }
104
+ const reqSignal = hasRequirementComplianceSignal(cleanTask);
105
+ const stageRequiresCompliance = stage === 'verify' || stage === 'review' || stage === 'ship';
106
+ const requirementCompliance = {
107
+ required: reqSignal || stageRequiresCompliance,
108
+ dimensions: COMPLIANCE_DIMENSIONS,
109
+ trigger: reqSignal ? 'keyword' : stageRequiresCompliance ? 'stage' : 'none',
110
+ };
111
+ // Explicit REQ mismatch / compliance review justifies invoking Matt's code-review as secondary.
112
+ if (reqSignal && stage === 'review') {
113
+ skillIds.push('matt:code-review');
114
+ addSecondary('matt-sdlc', 'requirement-compliance');
115
+ }
116
+ else if (reqSignal && stage === 'verify') {
117
+ addSecondary('matt-sdlc', 'requirement-compliance');
118
+ }
119
+ // `poteto-mode` is strictly opt-in; KSD remains primary orchestrator and never auto-enables it.
120
+ const optInPacks = [];
121
+ if (potetoMode) {
122
+ optInPacks.push('poteto-mode');
123
+ addSecondary('poteto-mode', 'explicit-opt-in');
124
+ }
125
+ return {
126
+ task: cleanTask,
127
+ type: resolved.type,
128
+ classifiedBy: resolved.classifiedBy,
129
+ stage,
130
+ risk,
131
+ skillIds: [...new Set(skillIds)],
132
+ orchestrator: ORCHESTRATOR_SKILL_ID,
133
+ primaryPack,
134
+ secondaryPacks,
135
+ secondaryReasons,
136
+ optInPacks,
137
+ requirementCompliance,
138
+ mayMerge: false,
139
+ mayDeploy: false,
140
+ };
141
+ }