@krisada-m/ksd-intelligence 0.0.0-stage → 1.0.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 (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +167 -2
  3. package/dist/adapters/agy/skills.js +252 -0
  4. package/dist/adapters/cli/check-changed.js +3 -0
  5. package/dist/adapters/cli/main.js +1002 -0
  6. package/dist/adapters/cli/policy-bin.js +10 -0
  7. package/dist/adapters/cli/review-verdict.js +3 -0
  8. package/dist/adapters/omp/extension.js +893 -0
  9. package/dist/adapters/omp/skills.js +130 -0
  10. package/dist/adapters/ui/hud.js +318 -0
  11. package/dist/adapters/ui/tree.js +460 -0
  12. package/dist/core/audit/index.js +2 -0
  13. package/dist/core/audit/log.js +505 -0
  14. package/dist/core/audit/summary.js +188 -0
  15. package/dist/core/changes/changes.js +591 -0
  16. package/dist/core/changes/git.js +266 -0
  17. package/dist/core/changes/plan.js +109 -0
  18. package/dist/core/changes/render.js +356 -0
  19. package/dist/core/engine/build.js +178 -0
  20. package/dist/core/engine/child.js +389 -0
  21. package/dist/core/engine/host.js +206 -0
  22. package/dist/core/engine/lock.js +133 -0
  23. package/dist/core/engine/protocol.js +43 -0
  24. package/dist/core/engine/runtime.js +44 -0
  25. package/dist/core/engine/status.js +381 -0
  26. package/dist/core/engine/typescript.js +194 -0
  27. package/dist/core/engine/workspace.js +72 -0
  28. package/dist/core/graph/graph.js +127 -0
  29. package/dist/core/graph/limits.js +16 -0
  30. package/dist/core/impact/query.js +1292 -0
  31. package/dist/core/impact/render.js +590 -0
  32. package/dist/core/impact/session.js +694 -0
  33. package/dist/core/indexing/declarations.js +455 -0
  34. package/dist/core/indexing/differential.js +345 -0
  35. package/dist/core/indexing/doctor.js +120 -0
  36. package/dist/core/indexing/indexer.js +792 -0
  37. package/dist/core/indexing/keys.js +451 -0
  38. package/dist/core/indexing/lexical.js +212 -0
  39. package/dist/core/indexing/packages.js +57 -0
  40. package/dist/core/indexing/program.js +171 -0
  41. package/dist/core/indexing/resolve.js +1004 -0
  42. package/dist/core/indexing/stamp.js +52 -0
  43. package/dist/core/indexing/surface.js +335 -0
  44. package/dist/core/indexing/ui-progress.js +37 -0
  45. package/dist/core/indexing/verify.js +76 -0
  46. package/dist/core/kernel/config.js +383 -0
  47. package/dist/core/kernel/glob.js +105 -0
  48. package/dist/core/kernel/guards.js +4 -0
  49. package/dist/core/kernel/types.js +3 -0
  50. package/dist/core/kernel/verdict.js +142 -0
  51. package/dist/core/knowledge/anchors.js +139 -0
  52. package/dist/core/knowledge/knowledge.js +95 -0
  53. package/dist/core/knowledge/learning.js +102 -0
  54. package/dist/core/knowledge/render.js +76 -0
  55. package/dist/core/knowledge/store.js +109 -0
  56. package/dist/core/knowledge/yaml.js +87 -0
  57. package/dist/core/search/lexical.js +382 -0
  58. package/dist/core/search/render.js +98 -0
  59. package/dist/core/search/segments.js +118 -0
  60. package/dist/core/verify/parse.js +127 -0
  61. package/dist/core/verify/render.js +67 -0
  62. package/dist/core/verify/report.js +40 -0
  63. package/dist/core/verify/revision.js +79 -0
  64. package/dist/core/verify/run.js +117 -0
  65. package/dist/core/verify/store.js +66 -0
  66. package/dist/core/verify/verify.js +173 -0
  67. package/dist/core/workspace/init.js +267 -0
  68. package/dist/core/workspace/probe.js +56 -0
  69. package/dist/core/workspace/scan.js +420 -0
  70. package/dist/index.js +20 -0
  71. package/dist/policy/change-scope.js +500 -0
  72. package/dist/policy/check-changed.js +40 -0
  73. package/dist/policy/config.js +106 -0
  74. package/dist/policy/dist/policy.d.ts +17 -0
  75. package/dist/policy/dist/policy.js +147 -0
  76. package/dist/policy/dist/runtime.d.ts +40 -0
  77. package/dist/policy/dist/runtime.js +75 -0
  78. package/dist/policy/dist/sdlc.d.ts +7 -0
  79. package/dist/policy/dist/sdlc.js +27 -0
  80. package/dist/policy/eslint-rules/index.js +107 -0
  81. package/dist/policy/index.d.ts +2 -0
  82. package/dist/policy/index.js +241 -0
  83. package/dist/policy/package.json +33 -0
  84. package/dist/policy/policy.d.ts +2 -0
  85. package/dist/policy/policy.js +2 -0
  86. package/dist/policy/review-verdict.js +262 -0
  87. package/dist/policy/sdlc.js +2 -0
  88. package/dist/storage/records.js +245 -0
  89. package/dist/storage/sqlite.js +314 -0
  90. package/dist/workflow/catalog.js +69 -0
  91. package/dist/workflow/classify.js +55 -0
  92. package/dist/workflow/loader.js +140 -0
  93. package/dist/workflow/packs.js +469 -0
  94. package/dist/workflow/registry.js +359 -0
  95. package/dist/workflow/render.js +61 -0
  96. package/dist/workflow/router.js +141 -0
  97. package/dist/workflow/sources.js +229 -0
  98. package/dist/workflow/types.js +44 -0
  99. package/dist/workflow/updates.js +532 -0
  100. package/package.json +74 -4
  101. package/scripts/agy-mcp.mjs +27 -0
  102. package/scripts/mcp/stdio.mjs +304 -0
  103. package/scripts/mcp/tools.mjs +451 -0
  104. package/skills/ksd-intelligence/SKILL.md +54 -0
  105. package/skills/matt-sdlc/SKILL.md +42 -0
  106. package/skills/osmani-quality/SKILL.md +38 -0
  107. package/skills/poteto-mode/SKILL.md +40 -0
  108. package/skills/pstack-analysis/SKILL.md +36 -0
  109. package/skills.lock.json +71 -0
  110. package/skills.registry.json +181 -0
@@ -0,0 +1,532 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { randomBytes } from 'node:crypto';
3
+ import { mkdir, readdir, readFile, realpath, rename, stat, unlink, writeFile, } from 'node:fs/promises';
4
+ import { homedir } from 'node:os';
5
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
6
+ import { promisify } from 'node:util';
7
+ import { discoverAgySkills } from '../adapters/agy/skills.js';
8
+ import { discoverOmpSkills } from '../adapters/omp/skills.js';
9
+ import { PROVIDERS, catalog, skillIdsOf } from './catalog.js';
10
+ import { MAX_SKILL_BYTES, readSkill, sha256Hex } from './loader.js';
11
+ import { defaultSkillsDir, parseSkillFrontmatter } from './packs.js';
12
+ import { defaultRegistryPath, parseRegistry, readRegistry, validateRegistryConsistency, } from './registry.js';
13
+ import { defaultLockPath, parseLock, readLock, } from './sources.js';
14
+ import { PROVIDER_IDS, WorkflowError } from './types.js';
15
+ const execFileAsync = promisify(execFile);
16
+ const COMMIT = /^[0-9a-f]{40}$/;
17
+ const SCRIPT_EXT = /\.(?:sh|bash|zsh|ps1|bat|cmd|py|rb|pl|js|mjs|cjs|ts)$/i;
18
+ export function defaultUpdateStateDir(env = process.env) {
19
+ const base = env.XDG_CACHE_HOME ?? join(env.SNAP_REAL_HOME ?? env.HOME ?? homedir(), '.cache');
20
+ return resolve(base, 'ksd-intelligence', 'skill-updates');
21
+ }
22
+ async function gitHead(root) {
23
+ try {
24
+ const { stdout } = await execFileAsync('git', ['-C', root, 'rev-parse', 'HEAD']);
25
+ const head = stdout.trim();
26
+ return COMMIT.test(head) ? head : null;
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ }
32
+ async function atomicWriteFile(targetPath, content) {
33
+ await mkdir(dirname(targetPath), { recursive: true });
34
+ const tmp = `${targetPath}.${process.pid}.${randomBytes(6).toString('hex')}.tmp`;
35
+ await writeFile(tmp, content, 'utf8');
36
+ try {
37
+ await rename(tmp, targetPath);
38
+ }
39
+ catch (error) {
40
+ await unlink(tmp).catch(() => { });
41
+ throw error;
42
+ }
43
+ }
44
+ async function atomicActivatePair(lockPath, lock, registryPath, registry, previousLockText) {
45
+ const nextLockText = `${JSON.stringify(lock, null, 2)}\n`;
46
+ const nextRegistryText = `${JSON.stringify(registry, null, 2)}\n`;
47
+ await atomicWriteFile(lockPath, nextLockText);
48
+ try {
49
+ await atomicWriteFile(registryPath, nextRegistryText);
50
+ }
51
+ catch (error) {
52
+ // Roll back the first file if the second atomic rename fails.
53
+ await atomicWriteFile(lockPath, previousLockText).catch(() => { });
54
+ throw error;
55
+ }
56
+ }
57
+ function isContained(base, target) {
58
+ const rel = relative(base, target);
59
+ return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
60
+ }
61
+ // Inventories immediate `<subpath>/<name>/SKILL.md` files and detects any scripts/hooks inside them
62
+ // purely by reading directory metadata (never executes anything).
63
+ async function scanUpstreamSubpath(root, rootSubpath) {
64
+ const skills = new Map();
65
+ const scripts = [];
66
+ const base = await realpath(root);
67
+ const subpathDir = resolve(base, rootSubpath);
68
+ let realSubpath;
69
+ try {
70
+ realSubpath = await realpath(subpathDir);
71
+ if (!isContained(base, realSubpath))
72
+ return { skills, scripts };
73
+ if (!(await stat(realSubpath)).isDirectory())
74
+ return { skills, scripts };
75
+ }
76
+ catch {
77
+ return { skills, scripts };
78
+ }
79
+ const entries = (await readdir(realSubpath, { withFileTypes: true })).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
80
+ for (const entry of entries) {
81
+ if (!entry.isDirectory())
82
+ continue;
83
+ const skillDir = join(realSubpath, entry.name);
84
+ const skillFile = join(skillDir, 'SKILL.md');
85
+ try {
86
+ const realSkill = await realpath(skillFile);
87
+ if (isContained(base, realSkill)) {
88
+ const info = await stat(realSkill);
89
+ if (info.isFile() && info.size <= MAX_SKILL_BYTES) {
90
+ const bytes = await readFile(realSkill);
91
+ skills.set(`${entry.name}/SKILL.md`, sha256Hex(bytes));
92
+ }
93
+ }
94
+ }
95
+ catch {
96
+ // Not a skill directory.
97
+ }
98
+ // Detect executable/hook files without running them.
99
+ for (const subdir of ['scripts', 'hooks']) {
100
+ const nested = join(skillDir, subdir);
101
+ try {
102
+ const nestedEntries = await readdir(nested, { withFileTypes: true });
103
+ for (const item of nestedEntries) {
104
+ if (item.isFile())
105
+ scripts.push(`${entry.name}/${subdir}/${item.name}`);
106
+ }
107
+ }
108
+ catch {
109
+ // No scripts/hooks directory.
110
+ }
111
+ }
112
+ try {
113
+ const topEntries = await readdir(skillDir, { withFileTypes: true });
114
+ for (const item of topEntries) {
115
+ if (item.isFile() && SCRIPT_EXT.test(item.name)) {
116
+ scripts.push(`${entry.name}/${item.name}`);
117
+ }
118
+ }
119
+ }
120
+ catch {
121
+ // Ignore unreadable dir.
122
+ }
123
+ }
124
+ return { skills, scripts: [...new Set(scripts)].sort() };
125
+ }
126
+ function knownReferencePathsForProvider(registry, provider) {
127
+ const paths = new Set();
128
+ for (const id of skillIdsOf(provider)) {
129
+ const entry = catalog[id];
130
+ if (entry)
131
+ paths.add(entry.path);
132
+ }
133
+ for (const pack of Object.values(registry.packs)) {
134
+ if (pack.provider !== provider)
135
+ continue;
136
+ for (const sourcePath of pack.upstream.sourcePaths)
137
+ paths.add(sourcePath);
138
+ }
139
+ return paths;
140
+ }
141
+ // Step 1 & 2 of update lifecycle: Check upstream checkouts + diff added/removed/renamed/changed
142
+ // skills + detect breaking compatibility changes without mutating any live files.
143
+ export async function checkUpstreamUpdates(options) {
144
+ const lock = options.lock ?? (await readLock(options.lockPath ?? defaultLockPath()));
145
+ const registry = options.registry ?? (await readRegistry(options.registryPath ?? defaultRegistryPath()));
146
+ const nextLockProviders = {
147
+ matt: { ...lock.providers.matt, skills: { ...lock.providers.matt.skills } },
148
+ poteto: { ...lock.providers.poteto, skills: { ...lock.providers.poteto.skills } },
149
+ osmani: { ...lock.providers.osmani, skills: { ...lock.providers.osmani.skills } },
150
+ };
151
+ const nextRegistryProviders = {
152
+ matt: { ...registry.providers.matt },
153
+ poteto: { ...registry.providers.poteto },
154
+ osmani: { ...registry.providers.osmani },
155
+ };
156
+ const providers = [];
157
+ const allFindings = [];
158
+ let hasUpdates = false;
159
+ for (const provider of PROVIDER_IDS) {
160
+ const info = PROVIDERS[provider];
161
+ const root = options.roots[provider] ?? null;
162
+ const lockProv = lock.providers[provider];
163
+ const findings = [];
164
+ const changed = [];
165
+ const removed = [];
166
+ const added = [];
167
+ const renamed = [];
168
+ let unchangedCount = 0;
169
+ if (!root || !isAbsolute(root)) {
170
+ findings.push({
171
+ code: 'PROVIDER_UNAVAILABLE',
172
+ severity: 'blocking',
173
+ provider,
174
+ message: `${info.envVar} is unset or not an absolute path`,
175
+ });
176
+ providers.push({
177
+ provider,
178
+ root,
179
+ previousCommit: lockProv.commit,
180
+ nextCommit: null,
181
+ commitChanged: false,
182
+ added,
183
+ removed,
184
+ renamed,
185
+ changed,
186
+ unchangedCount,
187
+ upstreamScripts: [],
188
+ findings,
189
+ });
190
+ allFindings.push(...findings);
191
+ continue;
192
+ }
193
+ const head = await gitHead(root);
194
+ if (head === null) {
195
+ findings.push({
196
+ code: 'PROVIDER_UNAVAILABLE',
197
+ severity: 'blocking',
198
+ provider,
199
+ message: `${info.envVar}=${root} has no readable git HEAD`,
200
+ });
201
+ }
202
+ let inventory = { skills: new Map(), scripts: [] };
203
+ try {
204
+ inventory = await scanUpstreamSubpath(root, info.rootSubpath);
205
+ }
206
+ catch {
207
+ findings.push({
208
+ code: 'PROVIDER_UNAVAILABLE',
209
+ severity: 'blocking',
210
+ provider,
211
+ message: `${info.envVar}=${root} does not exist or cannot be scanned`,
212
+ });
213
+ }
214
+ const knownPaths = knownReferencePathsForProvider(registry, provider);
215
+ const removedWithPrevHash = [];
216
+ const nextSkills = { ...lockProv.skills };
217
+ for (const id of skillIdsOf(provider)) {
218
+ const entry = catalog[id];
219
+ const prevSha = lockProv.skills[id]?.sha256 ?? null;
220
+ try {
221
+ const loaded = await readSkill(id, options.roots);
222
+ if (prevSha !== loaded.sha256) {
223
+ changed.push({
224
+ id,
225
+ path: entry.path,
226
+ previousSha256: prevSha,
227
+ nextSha256: loaded.sha256,
228
+ });
229
+ nextSkills[id] = { sha256: loaded.sha256 };
230
+ hasUpdates = true;
231
+ }
232
+ else {
233
+ unchangedCount += 1;
234
+ }
235
+ }
236
+ catch (error) {
237
+ if (error instanceof WorkflowError && error.code === 'SKILL_NOT_FOUND') {
238
+ removed.push(entry.path);
239
+ removedWithPrevHash.push({ path: entry.path, prevSha });
240
+ findings.push({
241
+ code: 'BREAKING_DEPENDENCY_REMOVED',
242
+ severity: 'blocking',
243
+ provider,
244
+ skill: id,
245
+ message: `pinned allowlisted skill ${id} (${entry.path}) was removed upstream`,
246
+ });
247
+ }
248
+ else {
249
+ const detail = error instanceof Error ? error.message : String(error);
250
+ findings.push({
251
+ code: 'INVALID_UPSTREAM_SKILL',
252
+ severity: 'blocking',
253
+ provider,
254
+ skill: id,
255
+ message: `${id}: ${detail}`,
256
+ });
257
+ }
258
+ }
259
+ }
260
+ // Check non-pinned referenced upstream source paths (including poteto-mode).
261
+ for (const refPath of knownPaths) {
262
+ const isPinned = skillIdsOf(provider).some((id) => catalog[id].path === refPath);
263
+ if (isPinned)
264
+ continue;
265
+ if (!inventory.skills.has(refPath)) {
266
+ if (!removed.includes(refPath))
267
+ removed.push(refPath);
268
+ findings.push({
269
+ code: 'UPSTREAM_REFERENCE_REMOVED',
270
+ severity: 'warning',
271
+ provider,
272
+ skill: refPath,
273
+ message: `referenced upstream playbook ${provider}:${refPath} was not found`,
274
+ });
275
+ }
276
+ }
277
+ // Verify upstream poteto-mode still preserves opt-in guard if present.
278
+ if (provider === 'poteto' && inventory.skills.has('poteto-mode/SKILL.md')) {
279
+ try {
280
+ const potetoPath = resolve(root, info.rootSubpath, 'poteto-mode/SKILL.md');
281
+ const text = await readFile(potetoPath, 'utf8');
282
+ const fm = parseSkillFrontmatter(text);
283
+ if (!fm?.disableModelInvocation) {
284
+ findings.push({
285
+ code: 'AUTO_OPT_IN_VIOLATION',
286
+ severity: 'blocking',
287
+ provider,
288
+ skill: 'poteto-mode',
289
+ message: `upstream poteto-mode/SKILL.md dropped disable-model-invocation: true`,
290
+ });
291
+ }
292
+ }
293
+ catch {
294
+ // Already handled if missing.
295
+ }
296
+ }
297
+ // Detect newly added skills & hash-matched renames.
298
+ for (const [relPath, sha] of inventory.skills) {
299
+ if (knownPaths.has(relPath))
300
+ continue;
301
+ const renamedFrom = removedWithPrevHash.find((item) => item.prevSha === sha);
302
+ if (renamedFrom) {
303
+ renamed.push({ fromPath: renamedFrom.path, toPath: relPath, sha256: sha });
304
+ }
305
+ else {
306
+ added.push(relPath);
307
+ }
308
+ }
309
+ // Surface upstream scripts/hooks for manual review without executing them.
310
+ for (const scriptPath of inventory.scripts) {
311
+ const relevant = [...knownPaths].some((known) => scriptPath.startsWith(`${known.split('/')[0] ?? ''}/`));
312
+ if (relevant) {
313
+ findings.push({
314
+ code: 'UPSTREAM_SCRIPT_DETECTED',
315
+ severity: 'warning',
316
+ provider,
317
+ skill: scriptPath,
318
+ message: `upstream script/hook present (${scriptPath}); review manually, never auto-execute`,
319
+ });
320
+ }
321
+ }
322
+ const commitChanged = head !== null && head !== lockProv.commit;
323
+ if (commitChanged)
324
+ hasUpdates = true;
325
+ const providerBlocked = findings.some((f) => f.severity === 'blocking');
326
+ if (!providerBlocked && head !== null) {
327
+ nextLockProviders[provider] = { ...lockProv, commit: head, skills: nextSkills };
328
+ nextRegistryProviders[provider] = { ...registry.providers[provider], commit: head };
329
+ }
330
+ providers.push({
331
+ provider,
332
+ root,
333
+ previousCommit: lockProv.commit,
334
+ nextCommit: head,
335
+ commitChanged,
336
+ added: added.sort(),
337
+ removed: removed.sort(),
338
+ renamed,
339
+ changed,
340
+ unchangedCount,
341
+ upstreamScripts: inventory.scripts,
342
+ findings,
343
+ });
344
+ allFindings.push(...findings);
345
+ }
346
+ return {
347
+ checkedAt: new Date().toISOString(),
348
+ hasUpdates,
349
+ providers,
350
+ findings: allFindings,
351
+ blockingFindings: allFindings.filter((f) => f.severity === 'blocking'),
352
+ nextLock: { version: 1, providers: nextLockProviders },
353
+ nextRegistry: {
354
+ ...registry,
355
+ providers: nextRegistryProviders,
356
+ },
357
+ };
358
+ }
359
+ // Step 3 & 4: Validate dependencies + test AGY and OMP discovery + write a staged update bundle.
360
+ export async function stageSkillUpdate(options) {
361
+ const lockPath = options.lockPath ?? defaultLockPath();
362
+ const registryPath = options.registryPath ?? defaultRegistryPath();
363
+ const skillsDir = options.skillsDir ?? defaultSkillsDir();
364
+ const stateDir = options.stateDir ?? defaultUpdateStateDir();
365
+ const previousLock = await readLock(lockPath);
366
+ const previousRegistry = await readRegistry(registryPath);
367
+ const check = await checkUpstreamUpdates({
368
+ roots: options.roots,
369
+ lock: previousLock,
370
+ registry: previousRegistry,
371
+ });
372
+ const registryIssues = await validateRegistryConsistency(check.nextRegistry, check.nextLock, {
373
+ skillsDir,
374
+ });
375
+ for (const issue of registryIssues) {
376
+ check.findings.push({
377
+ code: 'REGISTRY_VALIDATION_FAILED',
378
+ severity: 'blocking',
379
+ skill: issue.subject,
380
+ message: `${issue.code}: ${issue.message}`,
381
+ });
382
+ }
383
+ const [agyResult, ompResult] = await Promise.all([
384
+ discoverAgySkills({ workspaceRoot: options.workspaceRoot, skillsDir, requireCatalog: true }),
385
+ discoverOmpSkills({ workspaceRoot: options.workspaceRoot, skillsDir, requireCatalog: true }),
386
+ ]);
387
+ const agySummary = {
388
+ platform: 'agy',
389
+ ok: agyResult.issues.length === 0,
390
+ discoveredCount: agyResult.skills.length,
391
+ autoCount: agyResult.autoVisible.length,
392
+ optInCount: agyResult.explicitOnly.length,
393
+ issues: agyResult.issues.map((i) => `${i.code}: ${i.message}`),
394
+ };
395
+ const ompSummary = {
396
+ platform: 'omp',
397
+ ok: ompResult.issues.length === 0,
398
+ discoveredCount: ompResult.skills.length,
399
+ autoCount: ompResult.autoVisible.length,
400
+ optInCount: ompResult.explicitOnly.length,
401
+ issues: ompResult.issues.map((i) => `${i.code}: ${i.message}`),
402
+ };
403
+ for (const rt of [agySummary, ompSummary]) {
404
+ if (!rt.ok) {
405
+ check.findings.push({
406
+ code: 'RUNTIME_DISCOVERY_FAILED',
407
+ severity: 'blocking',
408
+ message: `${rt.platform} discovery failed: ${rt.issues.join('; ')}`,
409
+ });
410
+ }
411
+ }
412
+ const blockingFindings = check.findings.filter((f) => f.severity === 'blocking');
413
+ const ok = blockingFindings.length === 0;
414
+ const stageId = `stage-${Date.now()}-${randomBytes(4).toString('hex')}`;
415
+ const staged = {
416
+ version: 1,
417
+ stageId,
418
+ createdAt: new Date().toISOString(),
419
+ status: ok ? 'staged' : 'blocked',
420
+ approved: false,
421
+ diff: {
422
+ checkedAt: check.checkedAt,
423
+ hasUpdates: check.hasUpdates,
424
+ providers: check.providers,
425
+ findings: check.findings,
426
+ blockingFindings,
427
+ },
428
+ validation: {
429
+ ok,
430
+ registryIssues,
431
+ runtimes: { agy: agySummary, omp: ompSummary },
432
+ },
433
+ previous: { lock: previousLock, registry: previousRegistry },
434
+ next: { lock: check.nextLock, registry: check.nextRegistry },
435
+ };
436
+ const stagePath = join(stateDir, 'staged', `${stageId}.json`);
437
+ await atomicWriteFile(stagePath, `${JSON.stringify(staged, null, 2)}\n`);
438
+ return { stagePath, staged };
439
+ }
440
+ // Step 5 & 6: Approve and atomically activate a staged update, recording a rollback snapshot first.
441
+ export async function publishStagedUpdate(options) {
442
+ if (!options.approve) {
443
+ throw new WorkflowError('INVALID_INPUT', 'publishing a staged skill update requires explicit approval (--approve)');
444
+ }
445
+ const stateDir = options.stateDir ?? defaultUpdateStateDir();
446
+ const lockPath = options.lockPath ?? defaultLockPath();
447
+ const registryPath = options.registryPath ?? defaultRegistryPath();
448
+ const skillsDir = options.skillsDir ?? defaultSkillsDir();
449
+ const stagePath = join(stateDir, 'staged', `${options.stageId}.json`);
450
+ let staged;
451
+ try {
452
+ staged = JSON.parse(await readFile(stagePath, 'utf8'));
453
+ }
454
+ catch (error) {
455
+ throw new WorkflowError('LOCK_INVALID', `cannot read staged update ${options.stageId}: ${error instanceof Error ? error.message : String(error)}`);
456
+ }
457
+ if (staged.status !== 'staged' || !staged.validation.ok) {
458
+ throw new WorkflowError('LOCK_INVALID', `staged update ${options.stageId} is blocked and cannot be published`);
459
+ }
460
+ // Re-parse and re-validate before activation so tampered stage files cannot slip through.
461
+ const nextLock = parseLock(JSON.stringify(staged.next.lock));
462
+ const nextRegistry = parseRegistry(JSON.stringify(staged.next.registry));
463
+ const regIssues = await validateRegistryConsistency(nextRegistry, nextLock, { skillsDir });
464
+ if (regIssues.length > 0) {
465
+ throw new WorkflowError('LOCK_INVALID', `staged update failed validation: ${regIssues.map((i) => i.message).join('; ')}`);
466
+ }
467
+ const currentLockText = await readFile(lockPath, 'utf8');
468
+ const currentLock = parseLock(currentLockText);
469
+ const currentRegistry = await readRegistry(registryPath);
470
+ if (!options.force &&
471
+ (JSON.stringify(currentLock) !== JSON.stringify(staged.previous.lock) ||
472
+ JSON.stringify(currentRegistry) !== JSON.stringify(staged.previous.registry))) {
473
+ throw new WorkflowError('LOCK_INVALID', 'live lockfile or registry changed since staging; re-stage before publishing');
474
+ }
475
+ const releaseId = `rel-${Date.now()}-${randomBytes(4).toString('hex')}`;
476
+ const snapshot = {
477
+ version: 1,
478
+ releaseId,
479
+ stageId: staged.stageId,
480
+ publishedAt: new Date().toISOString(),
481
+ lockPath,
482
+ registryPath,
483
+ previous: { lock: currentLock, registry: currentRegistry },
484
+ active: { lock: nextLock, registry: nextRegistry },
485
+ };
486
+ const snapshotPath = join(stateDir, 'history', `${releaseId}.json`);
487
+ await atomicWriteFile(snapshotPath, `${JSON.stringify(snapshot, null, 2)}\n`);
488
+ await atomicActivatePair(lockPath, nextLock, registryPath, nextRegistry, currentLockText);
489
+ return { snapshotPath, snapshot };
490
+ }
491
+ // Atomically restores the previous approved skills.lock.json and skills.registry.json from snapshot history.
492
+ export async function rollbackSkillUpdate(options) {
493
+ const stateDir = options.stateDir ?? defaultUpdateStateDir();
494
+ const lockPath = options.lockPath ?? defaultLockPath();
495
+ const registryPath = options.registryPath ?? defaultRegistryPath();
496
+ const skillsDir = options.skillsDir ?? defaultSkillsDir();
497
+ const historyDir = join(stateDir, 'history');
498
+ let releaseId = options.releaseId;
499
+ if (!releaseId) {
500
+ let files;
501
+ try {
502
+ files = (await readdir(historyDir))
503
+ .filter((name) => name.endsWith('.json'))
504
+ .sort()
505
+ .reverse();
506
+ }
507
+ catch {
508
+ throw new WorkflowError('LOCK_INVALID', `no release history found in ${historyDir}`);
509
+ }
510
+ const latest = files[0];
511
+ if (!latest)
512
+ throw new WorkflowError('LOCK_INVALID', `no release snapshots in ${historyDir}`);
513
+ releaseId = latest.replace(/\.json$/, '');
514
+ }
515
+ const snapshotPath = join(historyDir, `${releaseId}.json`);
516
+ let snapshot;
517
+ try {
518
+ snapshot = JSON.parse(await readFile(snapshotPath, 'utf8'));
519
+ }
520
+ catch (error) {
521
+ throw new WorkflowError('LOCK_INVALID', `cannot read release snapshot ${releaseId}: ${error instanceof Error ? error.message : String(error)}`);
522
+ }
523
+ const prevLock = parseLock(JSON.stringify(snapshot.previous.lock));
524
+ const prevRegistry = parseRegistry(JSON.stringify(snapshot.previous.registry));
525
+ const issues = await validateRegistryConsistency(prevRegistry, prevLock, { skillsDir });
526
+ if (issues.length > 0) {
527
+ throw new WorkflowError('LOCK_INVALID', `rollback snapshot ${releaseId} failed validation: ${issues.map((i) => i.message).join('; ')}`);
528
+ }
529
+ const currentLockText = await readFile(lockPath, 'utf8');
530
+ await atomicActivatePair(lockPath, prevLock, registryPath, prevRegistry, currentLockText);
531
+ return { restoredFrom: releaseId, lock: prevLock, registry: prevRegistry };
532
+ }
package/package.json CHANGED
@@ -1,6 +1,76 @@
1
1
  {
2
2
  "name": "@krisada-m/ksd-intelligence",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "KSD engineering policy plus ei_* code-intelligence tools for OMP",
6
+ "license": "MIT",
7
+ "author": "Krisada M. (https://github.com/Krisada-M)",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/Krisada-M/ksd-intelligence.git"
11
+ },
12
+ "homepage": "https://github.com/Krisada-M/ksd-intelligence#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/Krisada-M/ksd-intelligence/issues"
15
+ },
16
+ "publishConfig": {
17
+ "access": "public",
18
+ "provenance": true
19
+ },
20
+ "files": [
21
+ "dist/",
22
+ "scripts/agy-mcp.mjs",
23
+ "scripts/mcp/",
24
+ "skills/",
25
+ "skills.lock.json",
26
+ "skills.registry.json",
27
+ "LICENSE",
28
+ "README.md"
29
+ ],
30
+ "engines": {
31
+ "node": ">=22.5"
32
+ },
33
+ "scripts": {
34
+ "build": "tsc -p tsconfig.json && node scripts/copy-policy-to-dist.mjs",
35
+ "typecheck": "tsc -p tsconfig.json --noEmit && tsc -p tests/tsconfig.json --noEmit",
36
+ "test": "npm run build && tsc -p tests/tsconfig.json && node scripts/copy-policy-to-dist.mjs --test-tree && node --import ./tests/policy/helpers/isolated-home.js --test dist-test/tests/core/*.test.js dist-test/tests/workflow/*.test.js tests/policy/*.test.js tests/packaging/*.test.js",
37
+ "check:dist": "npm run build && git diff --exit-code dist/ && node scripts/check-dist-untracked.mjs",
38
+ "verify:skills": "node scripts/verify-unified-skills.mjs",
39
+ "lint": "eslint .",
40
+ "lint:fix": "eslint --fix .",
41
+ "format:check": "prettier --check .",
42
+ "format": "prettier --write .",
43
+ "prepare": "husky || true"
44
+ },
45
+ "bin": {
46
+ "ei": "dist/adapters/cli/main.js",
47
+ "ksd-check-changed": "dist/adapters/cli/check-changed.js",
48
+ "ksd-review-verdict": "dist/adapters/cli/review-verdict.js"
49
+ },
50
+ "exports": {
51
+ ".": "./dist/adapters/omp/extension.js",
52
+ "./eslint": "./dist/policy/eslint-rules/index.js"
53
+ },
54
+ "omp": {
55
+ "extensions": [
56
+ "./dist/adapters/omp/extension.js"
57
+ ]
58
+ },
59
+ "pi": {
60
+ "extensions": [
61
+ "./dist/adapters/omp/extension.js"
62
+ ]
63
+ },
64
+ "eiRuntime": {
65
+ "typescript": "5.9.3"
66
+ },
67
+ "devDependencies": {
68
+ "@types/node": "^22.20.5",
69
+ "eslint": "10.13.0",
70
+ "eslint-config-prettier": "^10.1.8",
71
+ "husky": "^9.1.7",
72
+ "prettier": "^3.10.0",
73
+ "typescript": "^5.9.0",
74
+ "typescript-eslint": "8.72.1"
75
+ }
76
+ }
@@ -0,0 +1,27 @@
1
+ #!/usr/bin/env node
2
+ import { createStdioServer, resolveMcpRoot } from './mcp/stdio.mjs';
3
+
4
+ const argv = process.argv.slice(2);
5
+ let supplied;
6
+ let workflow = false;
7
+ for (let i = 0; i < argv.length; i++) {
8
+ if (argv[i] === '--root' && i + 1 < argv.length && supplied === undefined) {
9
+ supplied = argv[++i];
10
+ } else if (argv[i] === '--workflow') {
11
+ workflow = true;
12
+ } else {
13
+ console.error(
14
+ 'usage: node scripts/agy-mcp.mjs --root /absolute/path/to/repository [--workflow]',
15
+ );
16
+ process.exit(2);
17
+ }
18
+ }
19
+ const resolved = await resolveMcpRoot(supplied, process.env);
20
+ if (!resolved.ok) {
21
+ console.error(resolved.message);
22
+ process.exit(2);
23
+ }
24
+ const env = workflow ? { ...process.env, KSD_MCP_WORKFLOW: '1' } : process.env;
25
+ // AGY may spawn MCP servers from its application directory rather than the workspace.
26
+ // Root is explicit and frozen for the entire process; tools cannot override it.
27
+ createStdioServer({ root: resolved.root, env });