release-skill 0.1.7 → 0.1.8

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 (63) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/plugin.json +2 -2
  4. package/.kimi-plugin/plugin.json +27 -0
  5. package/CHANGELOG.md +22 -0
  6. package/INSTALL.md +73 -2
  7. package/INSTALL.zh-CN.md +94 -99
  8. package/README.md +49 -35
  9. package/README.zh-CN.md +82 -321
  10. package/adapters/claude/.claude-plugin/marketplace.json +1 -1
  11. package/adapters/claude/.claude-plugin/plugin.json +1 -1
  12. package/adapters/claude/bin/release-skill.bundle.mjs +1061 -182
  13. package/adapters/claude/schemas/.render-manifest.json +4 -4
  14. package/adapters/claude/schemas/release-plan.schema.json +20 -2
  15. package/adapters/claude/schemas/release-project.schema.json +22 -4
  16. package/adapters/claude/schemas/release-run.schema.json +1 -0
  17. package/adapters/codex/.codex-plugin/plugin.json +2 -2
  18. package/adapters/codex/bin/release-skill.bundle.mjs +1061 -182
  19. package/adapters/codex/schemas/.render-manifest.json +4 -4
  20. package/adapters/codex/schemas/release-plan.schema.json +20 -2
  21. package/adapters/codex/schemas/release-project.schema.json +22 -4
  22. package/adapters/codex/schemas/release-run.schema.json +1 -0
  23. package/adapters/kimi/.kimi-plugin/plugin.json +27 -0
  24. package/adapters/kimi/bin/release-skill.bundle.mjs +84415 -0
  25. package/adapters/kimi/bin/release-skill.mjs +54 -0
  26. package/adapters/kimi/native/safe-write/binding.gyp +41 -0
  27. package/adapters/kimi/native/safe-write/prebuilds/darwin-arm64/safe_write.node +0 -0
  28. package/adapters/kimi/native/safe-write/prebuilds.json +24 -0
  29. package/adapters/kimi/native/safe-write/src/safe_write.cc +2032 -0
  30. package/adapters/kimi/schemas/.render-manifest.json +37 -0
  31. package/adapters/kimi/schemas/approval-record.schema.json +115 -0
  32. package/adapters/kimi/schemas/artifact-lock.schema.json +111 -0
  33. package/adapters/kimi/schemas/artifact-plan.schema.json +52 -0
  34. package/adapters/kimi/schemas/artifact-policy.schema.json +76 -0
  35. package/adapters/kimi/schemas/evidence-event.schema.json +89 -0
  36. package/adapters/kimi/schemas/release-plan.schema.json +878 -0
  37. package/adapters/kimi/schemas/release-project.schema.json +895 -0
  38. package/adapters/kimi/schemas/release-run.schema.json +343 -0
  39. package/adapters/kimi/skills/release-assess/SKILL.md +58 -0
  40. package/adapters/kimi/skills/release-help/SKILL.md +84 -0
  41. package/adapters/kimi/skills/release-prepare/SKILL.md +99 -0
  42. package/adapters/kimi/skills/release-publish/SKILL.md +64 -0
  43. package/adapters/kimi/skills/release-reconcile/SKILL.md +80 -0
  44. package/adapters/kimi/skills/release-setup/SKILL.md +102 -0
  45. package/adapters/kimi/skills/release-verify/SKILL.md +77 -0
  46. package/bin/release-skill-cli.mjs +16 -4
  47. package/bin/release-skill.bundle.mjs +1061 -182
  48. package/package.json +4 -2
  49. package/schemas/.render-manifest.json +4 -4
  50. package/schemas/release-plan.schema.json +20 -2
  51. package/schemas/release-project.schema.json +22 -4
  52. package/schemas/release-run.schema.json +1 -0
  53. package/src/adapters/contract.mjs +1 -0
  54. package/src/adapters/plugin-marketplace.mjs +990 -30
  55. package/src/commands/assess.mjs +50 -1
  56. package/src/commands/prepare.mjs +65 -0
  57. package/src/commands/publish.mjs +3 -0
  58. package/src/commands/reconcile.mjs +3 -0
  59. package/src/commands/setup.mjs +10 -5
  60. package/src/commands/verify.mjs +16 -6
  61. package/src/core/plan.mjs +118 -0
  62. package/src/core/verification-gates.mjs +1 -1
  63. package/src/producers/build-adapters.mjs +38 -8
@@ -28,6 +28,8 @@ import {
28
28
 
29
29
  import { createHash } from 'node:crypto';
30
30
  import { computeFrozenSnapshot, resolveFrozenPath } from '../snapshot/frozen.mjs';
31
+ import { computePlanDigest } from '../core/plan.mjs';
32
+ import { canonicalJson } from '../core/digest.mjs';
31
33
 
32
34
  const execFile = promisify(execFileCb);
33
35
 
@@ -57,7 +59,7 @@ async function verifyInstalledMarketplacePayload(action, context, installPath, c
57
59
  throw new Error('frozen marketplace snapshot digest no longer matches the plan');
58
60
  }
59
61
  const installedSnapshot = await computeFrozenSnapshot(installPath, {
60
- excludeRootEntries: consumer === 'codex' ? ['.git'] : [],
62
+ excludeRootEntries: consumer === 'codex' || consumer === 'kimi' ? ['.git'] : [],
61
63
  });
62
64
  if (
63
65
  JSON.stringify(transportPayload(sourceSnapshot.entries))
@@ -81,11 +83,592 @@ async function writeEvidenceAtomic(filePath, value) {
81
83
  }
82
84
  }
83
85
 
86
+ // ---------------------------------------------------------------------------
87
+ // Kimi Code protocol-gap modeling (BLOCKER-1 / MAJOR-1 / MAJOR-4 / MINOR-1).
88
+ //
89
+ // Kimi Code has NO scriptable plugin install/list CLI: plugin management is
90
+ // interactive-only (`/plugins install <path-or-url>` in the TUI). There is no
91
+ // `kimi plugins ...` subcommand and no `--json` output protocol. Therefore the
92
+ // kimi-marketplace-install action is modeled as a protocol capability gap:
93
+ //
94
+ // - execute NEVER execs a kimi CLI. It emits an actionable, version-pinned
95
+ // manual-install requirement bound to the frozen plan digest + identity.
96
+ // - observe consumes a structured human attestation (written after the
97
+ // operator runs the interactive install) plus read-only verification of
98
+ // the installed managed copy. Missing/expired/mismatched/escaping proof
99
+ // fails closed, so a kimi unit can never reach VERIFIED without it.
100
+ // ---------------------------------------------------------------------------
101
+
102
+ /** Structured manual-install requirement written by kimi execute. */
103
+ const KIMI_REQUIREMENT_FILE = 'release-skill-kimi-manual-install.json';
104
+ /** Structured human attestation consumed by kimi observe. */
105
+ const KIMI_ATTESTATION_FILE = 'release-skill-kimi-attestation.json';
106
+ /** Kimi Code managed install layout: $KIMI_CODE_HOME/plugins/managed/<id>/. */
107
+ const KIMI_MANAGED_SUBPATH = join('plugins', 'managed');
108
+ /** Maximum attestation validity window (mirrors the 24h approval expiry). */
109
+ const KIMI_MAX_ATTESTATION_VALIDITY_MS = 24 * 60 * 60 * 1000;
110
+
111
+ /** 64-char lowercase hex plan/payload digest pattern. */
112
+ const HEX_DIGEST_RE = /^[a-f0-9]{64}$/;
113
+
114
+ /**
115
+ * Normalize a plan back to its frozen form for digest comparison.
116
+ *
117
+ * Only lifecycle status fields are reset: the top-level `status` returns to
118
+ * "PREPARED" and every `externalActions[].status` returns to "PENDING". Every
119
+ * other field is preserved verbatim. publish/reconcile/verify mutate exactly
120
+ * these status fields in memory as the saga progresses, so normalizing them
121
+ * recovers the frozen digest while leaving all security-relevant fields
122
+ * (baseline, units, action parameters/expected, production config, …) intact.
123
+ *
124
+ * @param {object} plan
125
+ * @returns {object} the lifecycle-normalized plan
126
+ */
127
+ function normalizePlanForDigest(plan) {
128
+ const normalized = { ...plan, status: 'PREPARED' };
129
+ if (Array.isArray(plan.externalActions)) {
130
+ normalized.externalActions = plan.externalActions.map((action) => (
131
+ action && typeof action === 'object' && !Array.isArray(action)
132
+ ? { ...action, status: 'PENDING' }
133
+ : action
134
+ ));
135
+ }
136
+ return normalized;
137
+ }
138
+
139
+ /**
140
+ * Resolve and verify the genuine frozen plan digest from the adapter context.
141
+ *
142
+ * The kimi manual-install requirement and attestation bind to the REAL frozen
143
+ * plan digest (`context.plan.digest`) — never to `action.manifestDigest`, which
144
+ * is only the snapshot payload digest.
145
+ *
146
+ * Integrity model: the carried `context.plan.digest` is recomputed from the
147
+ * lifecycle-normalized plan and must match EXACTLY. Status transitions
148
+ * (top-level status, per-action checkpoint status) are normalized away, but any
149
+ * other field tamper changes the recomputed digest and fails closed. This
150
+ * proves the attestation is bound to the genuine frozen plan, not to a spoofed
151
+ * or mutated stand-in.
152
+ *
153
+ * @param {object} context - adapter context (must carry the frozen `plan`).
154
+ * @returns {string} the verified frozen plan digest.
155
+ * @throws {Error} when the plan is absent or the digest does not match.
156
+ */
157
+ function resolveBoundPlanDigest(context) {
158
+ const plan = context?.plan;
159
+ if (!plan || typeof plan !== 'object' || Array.isArray(plan)) {
160
+ throw new Error('context.plan is required to bind the kimi plan digest');
161
+ }
162
+ const carried = plan.digest;
163
+ if (typeof carried !== 'string' || !HEX_DIGEST_RE.test(carried)) {
164
+ throw new Error('context.plan.digest must be a 64-char lowercase hex frozen plan digest');
165
+ }
166
+ const normalized = normalizePlanForDigest(plan);
167
+ if (computePlanDigest(normalized) !== carried) {
168
+ throw new Error('context.plan.digest does not match the normalized frozen plan (a non-lifecycle field was tampered)');
169
+ }
170
+ return carried;
171
+ }
172
+
173
+ /**
174
+ * Authoritative, cross-run attestation directory for a kimi install.
175
+ *
176
+ * Lives at a stable root-fixed location keyed by the verified frozen plan
177
+ * digest and plugin id:
178
+ * <root>/.release-skill/kimi-attestations/<planDigest>/<plugin>/
179
+ *
180
+ * This survives the publish -> manual install -> reconcile -> verify chain,
181
+ * where each command otherwise uses a fresh runDir (an attestation written to a
182
+ * publish runDir would be invisible to reconcile/verify). Both the requirement
183
+ * and the human attestation live here. The segments are pre-validated (planDigest
184
+ * is 64-hex, plugin matches SAFE_ID_RE) and the resolved path is contained
185
+ * within the authority base, so no path escape is possible.
186
+ *
187
+ * @param {object} context - adapter context (needs `root`).
188
+ * @param {string} planDigest - verified frozen plan digest (64-hex).
189
+ * @param {string} plugin - plugin id (SAFE_ID_RE).
190
+ * @returns {string} absolute authority directory.
191
+ */
192
+ function kimiAuthorityDir(context, planDigest, plugin) {
193
+ if (!context?.root) {
194
+ throw new Error('context.root is required for the kimi attestation authority');
195
+ }
196
+ if (!HEX_DIGEST_RE.test(planDigest)) {
197
+ throw new Error('kimi attestation authority requires a 64-hex plan digest');
198
+ }
199
+ if (!SAFE_ID_RE.test(plugin)) {
200
+ throw new Error(`kimi attestation authority requires a safe plugin id: "${plugin}"`);
201
+ }
202
+ const base = resolve(context.root, '.release-skill', 'kimi-attestations');
203
+ const dir = resolve(base, planDigest, plugin);
204
+ const rel = relative(base, dir);
205
+ const sep = process.platform === 'win32' ? '\\' : '/';
206
+ if (
207
+ rel === '' || rel === '..' || isAbsolute(rel) || rel.startsWith(`..${sep}`)
208
+ || rel.split(sep).some((segment) => segment === '..' || segment === '')
209
+ ) {
210
+ throw new Error('kimi attestation authority path escapes its base');
211
+ }
212
+ return dir;
213
+ }
214
+
215
+ /**
216
+ * Build the official, version-pinned install URL for a frozen Git ref.
217
+ *
218
+ * Prefers the GitHub release-tag URL (`/releases/tag/<ref>`), which pins the
219
+ * exact published ref; `/tree/<ref>` is the documented equivalent. A bare
220
+ * repository URL is NOT acceptable because it installs the latest release (or
221
+ * default branch), which need not equal the frozen version.
222
+ *
223
+ * @param {string} repo - owner/repo
224
+ * @param {string} ref - frozen Git ref (tag)
225
+ * @returns {string}
226
+ */
227
+ function buildKimiInstallUrl(repo, ref) {
228
+ return `https://github.com/${repo}/releases/tag/${ref}`;
229
+ }
230
+
231
+ /**
232
+ * Human-facing, actionable manual-install closed-loop instructions for Kimi Code.
233
+ *
234
+ * @param {{installUrl:string, plugin:string, version:string, ref:string, isolatedHome:string, attestationDir:string}} p
235
+ * @returns {string[]}
236
+ */
237
+ function buildKimiManualInstructions({ installUrl, plugin, version, ref, isolatedHome, attestationDir }) {
238
+ return [
239
+ `Kimi Code has no scriptable plugin-install CLI; installation is a manual, interactive step.`,
240
+ `1) publish fails closed at this kimi checkpoint and leaves the run PARTIAL (the automated Git branch/tag, npm, and GitHub Release writes still complete first).`,
241
+ `2) Launch Kimi Code with the ISOLATED home from this requirement so the managed copy lands inside it: set HOME="${isolatedHome}" and KIMI_CODE_HOME="${isolatedHome}". The plugin installs to "${isolatedHome}/plugins/managed/${plugin}/".`,
242
+ `3) In that isolated Kimi Code session run: /plugins install ${installUrl} (pinned to frozen ref "${ref}", version ${version}; never install the bare repository URL). Confirm the trust prompt for plugin "${plugin}", then run /plugins reload (or /new).`,
243
+ `4) Write the attestation JSON to: ${attestationDir}/${KIMI_ATTESTATION_FILE}. planDigest MUST be the frozen plan digest; payloadDigest MUST be the frozen snapshot payload digest; installPath MUST be the isolated managed directory above. attestedAt must not be in the future and expiresAt must be within 24 hours of attestedAt.`,
244
+ ` Required fields: consumer="kimi", plugin, version, entrySkill, repo, ref, installPath, planDigest, payloadDigest, attestedBy, attestedAt, expiresAt.`,
245
+ `5) Re-run release-skill reconcile (promotes PARTIAL -> PUBLISHED) and then verify (-> VERIFIED). Both read the attestation from this same plan-digest-keyed authority directory, so a fresh run directory does not lose the proof.`,
246
+ `An install into the ordinary ~/.kimi-code is NOT acceptable proof: the attested installPath must resolve inside this requirement's isolated KIMI_CODE_HOME managed root, otherwise verification fails closed.`,
247
+ ];
248
+ }
249
+
250
+ /**
251
+ * Read the authoritative Kimi plugin manifest from a verified plugin root.
252
+ *
253
+ * `kimi.plugin.json` at the root takes priority over `.kimi-plugin/plugin.json`
254
+ * when both exist (official precedence). Returns the parsed manifest and the
255
+ * root-relative manifest path. Throws when no valid manifest is present.
256
+ *
257
+ * @param {string} pluginRootReal - realpath of the verified plugin root.
258
+ * @returns {Promise<{manifest:object, manifestRelative:string}>}
259
+ */
260
+ async function readKimiManifest(pluginRootReal) {
261
+ const candidates = [
262
+ 'kimi.plugin.json',
263
+ join('.kimi-plugin', 'plugin.json'),
264
+ ];
265
+ for (const manifestRelative of candidates) {
266
+ const manifestPath = resolve(pluginRootReal, manifestRelative);
267
+ let content;
268
+ try {
269
+ content = await readFile(manifestPath, 'utf8');
270
+ } catch {
271
+ continue;
272
+ }
273
+ let manifest;
274
+ try {
275
+ manifest = JSON.parse(content);
276
+ } catch {
277
+ throw new Error(`kimi plugin manifest ${manifestRelative} is not valid JSON`);
278
+ }
279
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
280
+ throw new Error(`kimi plugin manifest ${manifestRelative} is not an object`);
281
+ }
282
+ return { manifest, manifestRelative };
283
+ }
284
+ throw new Error('no kimi plugin manifest found (expected kimi.plugin.json or .kimi-plugin/plugin.json)');
285
+ }
286
+
287
+ /**
288
+ * Validate that a manifest `skills` value is a safe plugin-root-relative path.
289
+ *
290
+ * Accepts "./" or "./some/dir/" forms. Rejects absolute paths, ".." traversal,
291
+ * backslashes, and URLs. Returns the normalized root-relative path (no leading
292
+ * "./"). Throws on unsafe values.
293
+ *
294
+ * @param {string} skillsRaw
295
+ * @returns {string} normalized relative path ('' for the plugin root itself)
296
+ */
297
+ function normalizeKimiSkillsRel(skillsRaw) {
298
+ if (typeof skillsRaw !== 'string' || skillsRaw.length === 0) {
299
+ throw new Error('kimi manifest skills must be a non-empty relative path when present');
300
+ }
301
+ if (
302
+ skillsRaw.startsWith('/') ||
303
+ skillsRaw.includes('..') ||
304
+ skillsRaw.includes('\\') ||
305
+ /^https?:\/\//i.test(skillsRaw)
306
+ ) {
307
+ throw new Error(`kimi manifest skills "${skillsRaw}" is not a safe relative path`);
308
+ }
309
+ let rel = skillsRaw.replace(/^\.\//, '');
310
+ rel = rel.replace(/\/+$/, '');
311
+ if (rel.split('/').some((segment) => segment === '' || segment === '.' || segment === '..')) {
312
+ throw new Error(`kimi manifest skills "${skillsRaw}" is not a safe relative path`);
313
+ }
314
+ return rel;
315
+ }
316
+
317
+ /**
318
+ * Resolve the entry SKILL.md for a Kimi plugin from its authoritative manifest.
319
+ *
320
+ * - When the manifest declares `skills`, the entry skill resolves under that
321
+ * skills root (validated + realpath-contained within the plugin root).
322
+ * - When `skills` is omitted, Kimi's official single-skill semantics apply: the
323
+ * plugin root's own SKILL.md is the single skill.
324
+ *
325
+ * The returned path is realpath-contained within pluginRootReal and is a
326
+ * regular, non-symlink file. Throws on missing/escaping/invalid layouts so the
327
+ * caller fails closed.
328
+ *
329
+ * @param {string} pluginRootReal - realpath of the verified plugin root.
330
+ * @param {object} manifest - parsed kimi plugin manifest.
331
+ * @param {string} entrySkill - expected entry skill id.
332
+ * @returns {Promise<string>} realpath of the entry SKILL.md
333
+ */
334
+ async function resolveKimiEntrySkillFile(pluginRootReal, manifest, entrySkill) {
335
+ if (!entrySkill || typeof entrySkill !== 'string' || !SAFE_ID_RE.test(entrySkill)) {
336
+ throw new Error(`unsafe entrySkill: "${entrySkill}"`);
337
+ }
338
+ let entryAbs;
339
+ if (manifest.skills === undefined || manifest.skills === null) {
340
+ // Official single-skill semantics: root SKILL.md is the sole skill.
341
+ entryAbs = resolve(pluginRootReal, 'SKILL.md');
342
+ } else {
343
+ const skillsRel = normalizeKimiSkillsRel(manifest.skills);
344
+ const skillsRootAbs = skillsRel === '' ? pluginRootReal : resolve(pluginRootReal, skillsRel);
345
+ const skillsRootReal = await realpath(skillsRootAbs).catch(() => null);
346
+ if (!skillsRootReal) {
347
+ throw new Error(`kimi manifest skills root does not exist: ${manifest.skills}`);
348
+ }
349
+ const skillsContainment = relative(pluginRootReal, skillsRootReal);
350
+ const sepK = process.platform === 'win32' ? '\\' : '/';
351
+ if (
352
+ skillsContainment !== '' &&
353
+ (isAbsolute(skillsContainment) || skillsContainment === '..' || skillsContainment.startsWith(`..${sepK}`))
354
+ ) {
355
+ throw new Error(`kimi manifest skills "${manifest.skills}" escapes the plugin root after symlink resolution`);
356
+ }
357
+ entryAbs = resolve(skillsRootReal, entrySkill, 'SKILL.md');
358
+ }
359
+
360
+ // lstat the LEXICAL entry BEFORE realpath. A symlinked SKILL.md must be
361
+ // rejected outright; lstat-ing the realpath target instead would observe the
362
+ // resolved regular file and silently miss the symlink.
363
+ let entryLexicalStat;
364
+ try {
365
+ entryLexicalStat = await lstat(entryAbs);
366
+ } catch {
367
+ throw new Error(`kimi entry skill not found: ${relative(pluginRootReal, entryAbs) || 'SKILL.md'}`);
368
+ }
369
+ if (entryLexicalStat.isSymbolicLink()) {
370
+ throw new Error('kimi entry skill must not be a symlink');
371
+ }
372
+ if (!entryLexicalStat.isFile()) {
373
+ throw new Error('kimi entry skill is not a regular file');
374
+ }
375
+
376
+ const entryReal = await realpath(entryAbs).catch(() => null);
377
+ if (!entryReal) {
378
+ throw new Error(`kimi entry skill not found: ${relative(pluginRootReal, entryAbs) || 'SKILL.md'}`);
379
+ }
380
+ const entryContainment = relative(pluginRootReal, entryReal);
381
+ const sepE = process.platform === 'win32' ? '\\' : '/';
382
+ if (
383
+ entryContainment !== '' &&
384
+ (isAbsolute(entryContainment) || entryContainment === '..' || entryContainment.startsWith(`..${sepE}`))
385
+ ) {
386
+ throw new Error('kimi entry skill escapes the plugin root after symlink resolution');
387
+ }
388
+ return entryReal;
389
+ }
390
+
391
+ /**
392
+ * Validate a structured kimi manual-install attestation against the frozen
393
+ * action and the verified frozen plan digest.
394
+ *
395
+ * Bindings (fail closed on any mismatch):
396
+ * - `planDigest` binds to the REAL frozen plan digest (`boundPlanDigest`, from
397
+ * `context.plan.digest`) — NOT to `action.manifestDigest`.
398
+ * - `payloadDigest` binds separately to `action.manifestDigest` (the sealed
399
+ * snapshot payload digest).
400
+ * - plugin identity, version, entry skill, repo, and frozen ref must match.
401
+ * - Time bounds: `attestedAt` must not be in the future, the validity window
402
+ * (`expiresAt - attestedAt`) must not exceed 24h, and the attestation must
403
+ * not be expired relative to `isoNow`.
404
+ *
405
+ * @param {object} attestation - parsed attestation JSON.
406
+ * @param {object} action - the expanded kimi action (top-level fields).
407
+ * @param {string} isoNow - current ISO timestamp.
408
+ * @param {string} boundPlanDigest - verified frozen plan digest.
409
+ * @returns {{valid:boolean, error:string|null}}
410
+ */
411
+ function validateKimiAttestation(attestation, action, isoNow, boundPlanDigest) {
412
+ if (!attestation || typeof attestation !== 'object' || Array.isArray(attestation)) {
413
+ return { valid: false, error: 'kimi attestation is not an object' };
414
+ }
415
+ const requiredStrings = ['plugin', 'version', 'entrySkill', 'repo', 'ref', 'installPath', 'payloadDigest', 'planDigest', 'attestedBy', 'attestedAt', 'expiresAt'];
416
+ for (const field of requiredStrings) {
417
+ if (typeof attestation[field] !== 'string' || attestation[field].length === 0) {
418
+ return { valid: false, error: `kimi attestation missing required field "${field}"` };
419
+ }
420
+ }
421
+ if (attestation.consumer !== 'kimi') {
422
+ return { valid: false, error: `kimi attestation consumer "${attestation.consumer}" must be "kimi"` };
423
+ }
424
+ if (!HEX_DIGEST_RE.test(attestation.planDigest)) {
425
+ return { valid: false, error: 'kimi attestation planDigest must be a 64-char lowercase hex digest' };
426
+ }
427
+ if (attestation.planDigest !== boundPlanDigest) {
428
+ return { valid: false, error: 'kimi attestation planDigest does not match the frozen plan digest' };
429
+ }
430
+ if (attestation.plugin !== action.plugin) {
431
+ return { valid: false, error: `kimi attestation plugin "${attestation.plugin}" does not match action plugin "${action.plugin}"` };
432
+ }
433
+ if (attestation.version !== action.version) {
434
+ return { valid: false, error: `kimi attestation version "${attestation.version}" does not match action version "${action.version}"` };
435
+ }
436
+ if (attestation.entrySkill !== action.entrySkill) {
437
+ return { valid: false, error: `kimi attestation entrySkill "${attestation.entrySkill}" does not match action entrySkill "${action.entrySkill}"` };
438
+ }
439
+ if (attestation.repo !== action.repo) {
440
+ return { valid: false, error: `kimi attestation repo "${attestation.repo}" does not match action repo "${action.repo}"` };
441
+ }
442
+ const expectedRef = action.ref ?? `v${action.version}`;
443
+ if (attestation.ref !== expectedRef) {
444
+ return { valid: false, error: `kimi attestation ref "${attestation.ref}" does not match frozen ref "${expectedRef}"` };
445
+ }
446
+ if (attestation.payloadDigest !== action.manifestDigest) {
447
+ return { valid: false, error: 'kimi attestation payloadDigest does not match the frozen payload digest' };
448
+ }
449
+ const attestedMs = Date.parse(attestation.attestedAt);
450
+ const expiresMs = Date.parse(attestation.expiresAt);
451
+ const nowMs = Date.parse(isoNow);
452
+ if (!Number.isFinite(attestedMs) || !Number.isFinite(expiresMs) || !Number.isFinite(nowMs)) {
453
+ return { valid: false, error: 'kimi attestation attestedAt/expiresAt must be valid ISO timestamps' };
454
+ }
455
+ if (attestedMs > nowMs) {
456
+ return { valid: false, error: 'kimi attestation attestedAt is in the future' };
457
+ }
458
+ if (expiresMs <= attestedMs) {
459
+ return { valid: false, error: 'kimi attestation expiresAt must be after attestedAt' };
460
+ }
461
+ if (expiresMs - attestedMs > KIMI_MAX_ATTESTATION_VALIDITY_MS) {
462
+ return { valid: false, error: 'kimi attestation validity must not exceed 24 hours' };
463
+ }
464
+ if (nowMs > expiresMs) {
465
+ return { valid: false, error: 'kimi attestation has expired' };
466
+ }
467
+ return { valid: true, error: null };
468
+ }
469
+
470
+ /**
471
+ * Kimi Code protocol capability gap (BLOCKER-1): there is NO scriptable
472
+ * `kimi plugins install/list` CLI and no `--json` protocol. execute NEVER execs
473
+ * a kimi command. Instead it emits an actionable, version-pinned manual-install
474
+ * requirement bound to the real frozen plan digest + identity, and leaves
475
+ * success to observe, which consumes only a trusted human attestation plus
476
+ * read-only verification. Without that proof the checkpoint fails closed and can
477
+ * never reach VERIFIED.
478
+ *
479
+ * Isolation model (B/C): the kimi home is a STABLE, plan-digest-keyed directory
480
+ * under the attestation authority (`<authorityDir>/kimi-home`), not the per-run
481
+ * runDir consumer dir. The operator launches Kimi Code with that KIMI_CODE_HOME
482
+ * so the managed copy lands at `<kimiHome>/plugins/managed/<plugin>/`, a
483
+ * location that is identical across publish/reconcile/verify run dirs. execute
484
+ * creates ONLY the managed parent (`plugins/managed`), never `managed/<plugin>`
485
+ * (the operator's interactive install creates that). The requirement write is
486
+ * idempotent: an identical existing requirement is left untouched, a divergent
487
+ * one fails closed.
488
+ *
489
+ * @param {object} action - expanded kimi action (validated params already).
490
+ * @param {object} context - adapter context (root, runDir, plan).
491
+ * @returns {Promise<import('./contract.mjs').AdapterResult>}
492
+ */
493
+ async function executeKimiManualRequirement(action, context) {
494
+ const actionType = ActionType.KIMI_MARKETPLACE_INSTALL;
495
+
496
+ // (A) Bind to the REAL frozen plan digest via strict normalized recompute.
497
+ let planDigest;
498
+ try {
499
+ planDigest = resolveBoundPlanDigest(context);
500
+ } catch (planErr) {
501
+ return createResult({
502
+ actionType,
503
+ status: ActionStatus.EXECUTE_FAILED,
504
+ error: `cannot bind kimi requirement to the frozen plan: ${planErr.message}`,
505
+ });
506
+ }
507
+
508
+ // Validate the frozen timeout. Kimi execs no CLI, but the frozen-timeout
509
+ // fail-closed invariant still holds for every marketplace action.
510
+ try {
511
+ resolveTimeoutMs(action);
512
+ } catch (timeoutErr) {
513
+ return createResult({
514
+ actionType,
515
+ status: ActionStatus.EXECUTE_FAILED,
516
+ error: timeoutErr.message,
517
+ });
518
+ }
519
+
520
+ const ref = action.ref ?? `v${action.version}`;
521
+ const installUrl = buildKimiInstallUrl(action.repo, ref);
522
+
523
+ // (B) Stable, plan-digest-keyed authority dir — the ONLY kimi home, shared
524
+ // across publish/reconcile/verify run dirs.
525
+ let attestationDir;
526
+ try {
527
+ attestationDir = kimiAuthorityDir(context, planDigest, action.plugin);
528
+ } catch (dirErr) {
529
+ return createResult({
530
+ actionType,
531
+ status: ActionStatus.EXECUTE_FAILED,
532
+ error: dirErr.message,
533
+ });
534
+ }
535
+ const kimiHome = resolve(attestationDir, 'kimi-home');
536
+ const managedParent = resolve(kimiHome, KIMI_MANAGED_SUBPATH); // plugins/managed
537
+ // plugins/managed/<plugin> — created by the operator's interactive install.
538
+ const managedInstallRoot = resolve(managedParent, action.plugin);
539
+
540
+ const instructions = buildKimiManualInstructions({
541
+ installUrl,
542
+ plugin: action.plugin,
543
+ version: action.version,
544
+ ref,
545
+ isolatedHome: kimiHome,
546
+ attestationDir,
547
+ });
548
+
549
+ const requirement = {
550
+ kind: 'kimi-manual-install-requirement',
551
+ consumer: 'kimi',
552
+ plugin: action.plugin,
553
+ version: action.version,
554
+ entrySkill: action.entrySkill,
555
+ repo: action.repo,
556
+ ref,
557
+ installUrl,
558
+ // (A) planDigest binds to the real frozen plan digest;
559
+ // expectedPayloadDigest binds separately to the snapshot payload digest.
560
+ planDigest,
561
+ expectedPayloadDigest: action.manifestDigest,
562
+ isolatedHome: kimiHome,
563
+ kimiCodeHome: kimiHome,
564
+ managedInstallRoot,
565
+ attestationDir,
566
+ attestationFile: KIMI_ATTESTATION_FILE,
567
+ attestationTemplate: {
568
+ consumer: 'kimi',
569
+ plugin: action.plugin,
570
+ version: action.version,
571
+ entrySkill: action.entrySkill,
572
+ repo: action.repo,
573
+ ref,
574
+ installPath: managedInstallRoot,
575
+ planDigest,
576
+ payloadDigest: action.manifestDigest,
577
+ attestedBy: '<person responsible for the manual install>',
578
+ attestedAt: '<ISO 8601 now; must not be in the future>',
579
+ expiresAt: '<ISO 8601; within 24h of attestedAt>',
580
+ },
581
+ instructions,
582
+ };
583
+
584
+ // Create ONLY the managed parent (plugins/managed); never pre-create
585
+ // managed/<plugin> — the operator's interactive install creates that.
586
+ try {
587
+ await mkdir(managedParent, { recursive: true, mode: 0o700 });
588
+ } catch (mkdirErr) {
589
+ return createResult({
590
+ actionType,
591
+ status: ActionStatus.EXECUTE_FAILED,
592
+ error: `cannot create kimi managed parent directory: ${mkdirErr.message}`,
593
+ });
594
+ }
595
+
596
+ // Idempotent requirement write: an identical existing requirement is left
597
+ // untouched; a divergent existing requirement fails closed (never silently
598
+ // overwritten). `createdAt` is volatile and excluded from the comparison.
599
+ const requirementPath = resolve(attestationDir, KIMI_REQUIREMENT_FILE);
600
+ let existing = null;
601
+ let requirementMissing = false;
602
+ try {
603
+ const existingRaw = await readFile(requirementPath, 'utf8');
604
+ try {
605
+ existing = JSON.parse(existingRaw);
606
+ } catch (parseErr) {
607
+ return createResult({
608
+ actionType,
609
+ status: ActionStatus.EXECUTE_FAILED,
610
+ error: `existing kimi manual-install requirement is invalid JSON; refusing to overwrite: ${parseErr.message}`,
611
+ });
612
+ }
613
+ } catch (readErr) {
614
+ if (readErr?.code === 'ENOENT') {
615
+ requirementMissing = true;
616
+ } else {
617
+ return createResult({
618
+ actionType,
619
+ status: ActionStatus.EXECUTE_FAILED,
620
+ error: `existing kimi manual-install requirement cannot be read; refusing to overwrite: ${readErr.message}`,
621
+ });
622
+ }
623
+ }
624
+ if (!requirementMissing) {
625
+ if (!existing || typeof existing !== 'object' || Array.isArray(existing)) {
626
+ return createResult({
627
+ actionType,
628
+ status: ActionStatus.EXECUTE_FAILED,
629
+ error: 'existing kimi manual-install requirement is not an object; refusing to overwrite',
630
+ });
631
+ }
632
+ const { createdAt: _existingCreatedAt, ...existingBody } = existing;
633
+ if (canonicalJson(existingBody) !== canonicalJson(requirement)) {
634
+ return createResult({
635
+ actionType,
636
+ status: ActionStatus.EXECUTE_FAILED,
637
+ error: 'existing kimi manual-install requirement conflicts with the current frozen action; refusing to overwrite',
638
+ });
639
+ }
640
+ } else {
641
+ await writeEvidenceAtomic(requirementPath, { ...requirement, createdAt: new Date().toISOString() });
642
+ }
643
+
644
+ return createResult({
645
+ actionType,
646
+ status: ActionStatus.EXECUTED,
647
+ observation: {
648
+ installed: false,
649
+ manualInstallRequired: true,
650
+ consumer: 'kimi',
651
+ plugin: action.plugin,
652
+ version: action.version,
653
+ entrySkill: action.entrySkill,
654
+ repo: action.repo,
655
+ ref,
656
+ installUrl,
657
+ planDigest,
658
+ attestationDir,
659
+ kimiCodeHome: kimiHome,
660
+ managedInstallRoot,
661
+ instructions,
662
+ },
663
+ });
664
+ }
665
+
84
666
  const SUPPORTED_TYPES = [
85
667
  ActionType.PLUGIN_MANIFEST_VALIDATE,
86
668
  ActionType.PLUGIN_INSTALL_CHECK,
87
669
  ActionType.CLAUDE_MARKETPLACE_INSTALL,
88
670
  ActionType.CODEX_MARKETPLACE_INSTALL,
671
+ ActionType.KIMI_MARKETPLACE_INSTALL,
89
672
  ];
90
673
 
91
674
  /** Safe identifier pattern: lowercase alphanumeric, hyphens, dots, underscores. */
@@ -163,13 +746,22 @@ function validateMarketplaceParams(params) {
163
746
  return { valid: false, error: 'parameters must be an object' };
164
747
  }
165
748
  const { consumer, plugin, marketplace, repo, version, entrySkill } = params;
166
- if (!['claude', 'codex'].includes(consumer)) {
749
+ if (!['claude', 'codex', 'kimi'].includes(consumer)) {
167
750
  return { valid: false, error: `invalid consumer: "${consumer}"` };
168
751
  }
169
752
  if (!plugin || !SAFE_ID_RE.test(plugin)) {
170
753
  return { valid: false, error: `unsafe plugin identifier: "${plugin}"` };
171
754
  }
172
- if (!marketplace || !SAFE_ID_RE.test(marketplace)) {
755
+ // marketplace is a required identity field for Claude/Codex, which have
756
+ // scriptable marketplace add/install interfaces. Kimi Code has an interactive
757
+ // marketplace but NO non-interactive install API, so `marketplace` carries no
758
+ // executable meaning for kimi and is optional (validated only if present); it
759
+ // must not become a required identity condition for kimi execution/observe.
760
+ if (consumer === 'kimi') {
761
+ if (marketplace !== undefined && marketplace !== null && !SAFE_ID_RE.test(marketplace)) {
762
+ return { valid: false, error: `unsafe marketplace identifier: "${marketplace}"` };
763
+ }
764
+ } else if (!marketplace || !SAFE_ID_RE.test(marketplace)) {
173
765
  return { valid: false, error: `unsafe marketplace identifier: "${marketplace}"` };
174
766
  }
175
767
  if (!repo || !SAFE_REPO_RE.test(repo)) {
@@ -373,7 +965,8 @@ export function createPluginMarketplaceAdapter(deps = {}) {
373
965
  // Marketplace install preflight: fail-closed validation
374
966
  if (
375
967
  actionType === ActionType.CLAUDE_MARKETPLACE_INSTALL ||
376
- actionType === ActionType.CODEX_MARKETPLACE_INSTALL
968
+ actionType === ActionType.CODEX_MARKETPLACE_INSTALL ||
969
+ actionType === ActionType.KIMI_MARKETPLACE_INSTALL
377
970
  ) {
378
971
  // 1. Validate all parameters for injection safety
379
972
  const validation = validateMarketplaceParams(action);
@@ -449,6 +1042,9 @@ export function createPluginMarketplaceAdapter(deps = {}) {
449
1042
  // 6. Verify frozen snapshot exists and contains required marketplace files
450
1043
  const consumer = action.consumer;
451
1044
  let snapshotDirReal;
1045
+ // Authoritative kimi manifest (from the frozen snapshot), used to
1046
+ // resolve the entry skill via the manifest-declared skills root.
1047
+ let kimiSnapshotManifest = null;
452
1048
  try {
453
1049
  snapshotDirReal = await resolveFrozenPath(context.root, snapshotPath, 'frozen snapshot path');
454
1050
  } catch (frozenErr) {
@@ -459,6 +1055,40 @@ export function createPluginMarketplaceAdapter(deps = {}) {
459
1055
  });
460
1056
  }
461
1057
 
1058
+ // Kimi has no non-interactive marketplace/install API: the whole repo
1059
+ // is installed as one plugin. The authoritative manifest is read from
1060
+ // the verified snapshot root with official precedence
1061
+ // (kimi.plugin.json over .kimi-plugin/plugin.json).
1062
+ if (consumer === 'kimi') {
1063
+ let kimiManifestResult;
1064
+ try {
1065
+ kimiManifestResult = await readKimiManifest(snapshotDirReal);
1066
+ } catch (manifestErr) {
1067
+ return createResult({
1068
+ actionType,
1069
+ status: ActionStatus.PREFLIGHT_FAILED,
1070
+ error: `frozen snapshot kimi manifest invalid: ${manifestErr.message}`,
1071
+ });
1072
+ }
1073
+ const kimiManifest = kimiManifestResult.manifest;
1074
+ if (typeof kimiManifest.name !== 'string' || kimiManifest.name !== action.plugin) {
1075
+ return createResult({
1076
+ actionType,
1077
+ status: ActionStatus.PREFLIGHT_FAILED,
1078
+ error: `plugin manifest name "${kimiManifest.name}" does not match action plugin "${action.plugin}"`,
1079
+ });
1080
+ }
1081
+ if (typeof kimiManifest.version !== 'string' || kimiManifest.version !== action.version) {
1082
+ return createResult({
1083
+ actionType,
1084
+ status: ActionStatus.PREFLIGHT_FAILED,
1085
+ error: `plugin manifest version "${kimiManifest.version}" does not match action version "${action.version}"`,
1086
+ });
1087
+ }
1088
+ kimiSnapshotManifest = kimiManifest;
1089
+ }
1090
+
1091
+ if (consumer !== 'kimi') {
462
1092
  // Verify marketplace files exist.
463
1093
  // marketplace.json is at the snapshot root; plugin manifest is
464
1094
  // resolved relative to the entry's declared source path.
@@ -605,17 +1235,35 @@ export function createPluginMarketplaceAdapter(deps = {}) {
605
1235
  error: `plugin manifest version "${pluginManifestResult.manifest.version}" does not match action version "${action.version}"`,
606
1236
  });
607
1237
  }
1238
+ }
608
1239
 
609
- // Verify entrySkill file exists in snapshot
610
- const entrySkillFile = resolve(snapshotDirReal, 'skills', action.entrySkill, 'SKILL.md');
611
- try {
612
- await stat(entrySkillFile);
613
- } catch {
614
- return createResult({
615
- actionType,
616
- status: ActionStatus.PREFLIGHT_FAILED,
617
- error: `entry skill not found in snapshot: skills/${action.entrySkill}/SKILL.md`,
618
- });
1240
+ // Verify the entry skill exists in the snapshot.
1241
+ // Claude/Codex manifests always declare ./skills/, so the fixed
1242
+ // skills/<entrySkill>/SKILL.md layout is authoritative for them.
1243
+ // Kimi resolves the entry skill via the manifest-declared skills root
1244
+ // (MAJOR-4): the root is validated + realpath-contained, and omitted
1245
+ // `skills` means the official single-skill root SKILL.md.
1246
+ if (consumer === 'kimi') {
1247
+ try {
1248
+ await resolveKimiEntrySkillFile(snapshotDirReal, kimiSnapshotManifest, action.entrySkill);
1249
+ } catch (entryErr) {
1250
+ return createResult({
1251
+ actionType,
1252
+ status: ActionStatus.PREFLIGHT_FAILED,
1253
+ error: `entry skill not resolvable in snapshot: ${entryErr.message}`,
1254
+ });
1255
+ }
1256
+ } else {
1257
+ const entrySkillFile = resolve(snapshotDirReal, 'skills', action.entrySkill, 'SKILL.md');
1258
+ try {
1259
+ await stat(entrySkillFile);
1260
+ } catch {
1261
+ return createResult({
1262
+ actionType,
1263
+ status: ActionStatus.PREFLIGHT_FAILED,
1264
+ error: `entry skill not found in snapshot: skills/${action.entrySkill}/SKILL.md`,
1265
+ });
1266
+ }
619
1267
  }
620
1268
 
621
1269
  // Verify manifestDigest matches actual snapshot content using frozen algorithm
@@ -763,7 +1411,8 @@ export function createPluginMarketplaceAdapter(deps = {}) {
763
1411
  // Marketplace install execute
764
1412
  if (
765
1413
  actionType === ActionType.CLAUDE_MARKETPLACE_INSTALL ||
766
- actionType === ActionType.CODEX_MARKETPLACE_INSTALL
1414
+ actionType === ActionType.CODEX_MARKETPLACE_INSTALL ||
1415
+ actionType === ActionType.KIMI_MARKETPLACE_INSTALL
767
1416
  ) {
768
1417
  try {
769
1418
  assertIsolatedConsumerWritesAuthorized(context, actionType);
@@ -793,6 +1442,15 @@ export function createPluginMarketplaceAdapter(deps = {}) {
793
1442
  });
794
1443
  }
795
1444
 
1445
+ // Kimi has NO scriptable install CLI. It is handled entirely by the
1446
+ // manual-requirement helper, which uses a stable plan-digest-keyed
1447
+ // home and deliberately SKIPS the per-run isolated consumer dir and
1448
+ // its runDir containment check (that model only fits claude/codex,
1449
+ // which exec a real CLI into a per-run HOME).
1450
+ if (action.consumer === 'kimi') {
1451
+ return executeKimiManualRequirement(action, context);
1452
+ }
1453
+
796
1454
  const consumer = action.consumer;
797
1455
  const runDir = context.runDir;
798
1456
  const isolatedHome = resolve(runDir, 'consumers', `${consumer}-${action.plugin}`);
@@ -826,7 +1484,8 @@ export function createPluginMarketplaceAdapter(deps = {}) {
826
1484
  ? { HOME: isolatedHome, CLAUDE_CONFIG_DIR: resolve(isolatedHome, '.claude') }
827
1485
  : { HOME: isolatedHome, CODEX_HOME: isolatedHome }),
828
1486
  };
829
- // Ensure real HOME/CODEX_HOME don't leak back (already overridden above)
1487
+ // Ensure real HOME/CODEX_HOME don't leak back (already overridden
1488
+ // above).
830
1489
 
831
1490
  // Resolve frozen timeoutMs from the expanded action (top-level,
832
1491
  // not action.parameters -- the publish/reconcile/verify call path
@@ -845,9 +1504,10 @@ export function createPluginMarketplaceAdapter(deps = {}) {
845
1504
  });
846
1505
  }
847
1506
 
848
- // Step 1: Add marketplace
1507
+ // Step 1: Add marketplace (claude/codex only; kimi returned above)
849
1508
  const ref = action.ref ?? `v${action.version}`;
850
- let addOutput;
1509
+ let addOutput = null;
1510
+ if (consumer !== 'kimi') {
851
1511
  const marketplaceArgs = consumer === 'claude'
852
1512
  ? ['plugin', 'marketplace', 'add', `${action.repo}@${ref}`]
853
1513
  : ['plugin', 'marketplace', 'add', action.repo, '--ref', ref, '--json'];
@@ -885,8 +1545,10 @@ export function createPluginMarketplaceAdapter(deps = {}) {
885
1545
  error: `marketplace add failed: ${addErr.message}`,
886
1546
  });
887
1547
  }
1548
+ }
888
1549
 
889
- // Step 2: Install plugin
1550
+ // Step 2: Install plugin (claude/codex only; kimi has no install CLI
1551
+ // and returned the manual-install requirement above).
890
1552
  let installOutput;
891
1553
  const installArgs = consumer === 'claude'
892
1554
  ? ['plugin', 'install', `${action.plugin}@${action.marketplace}`]
@@ -1038,6 +1700,10 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1038
1700
  * For Codex: uses pluginId === "plugin@marketplace" match in installed array,
1039
1701
  * reads installedPath from add/install output or list, verifies install dir
1040
1702
  * is inside isolated HOME, computes real manifestDigest.
1703
+ *
1704
+ * For Kimi: uses name === plugin match in installed array, reads
1705
+ * installedPath from validated install evidence, verifies install dir
1706
+ * is inside isolated HOME, computes real manifestDigest.
1041
1707
  */
1042
1708
  async observe(action, context) {
1043
1709
  const { actionType } = action;
@@ -1085,7 +1751,8 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1085
1751
  // Marketplace install observe
1086
1752
  if (
1087
1753
  actionType === ActionType.CLAUDE_MARKETPLACE_INSTALL ||
1088
- actionType === ActionType.CODEX_MARKETPLACE_INSTALL
1754
+ actionType === ActionType.CODEX_MARKETPLACE_INSTALL ||
1755
+ actionType === ActionType.KIMI_MARKETPLACE_INSTALL
1089
1756
  ) {
1090
1757
  const consumer = action.consumer;
1091
1758
  const runDir = context.runDir;
@@ -1097,13 +1764,15 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1097
1764
  });
1098
1765
  }
1099
1766
  const isolatedHome = resolve(runDir, 'consumers', `${consumer}-${action.plugin}`);
1100
- const cliCmd = consumer === 'claude' ? 'claude' : 'codex';
1767
+ const cliCmd = consumer === 'claude' ? 'claude' : consumer === 'codex' ? 'codex' : 'kimi';
1101
1768
  const baseEnv = { ...process.env, ...(context.env ?? {}) };
1102
1769
  const env = {
1103
1770
  ...baseEnv,
1104
1771
  ...(consumer === 'claude'
1105
1772
  ? { HOME: isolatedHome, CLAUDE_CONFIG_DIR: resolve(isolatedHome, '.claude') }
1106
- : { HOME: isolatedHome, CODEX_HOME: isolatedHome }),
1773
+ : consumer === 'codex'
1774
+ ? { HOME: isolatedHome, CODEX_HOME: isolatedHome }
1775
+ : { HOME: isolatedHome, KIMI_CODE_HOME: isolatedHome }),
1107
1776
  };
1108
1777
 
1109
1778
  // Resolve frozen timeoutMs from the expanded action (top-level).
@@ -1120,6 +1789,293 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1120
1789
  });
1121
1790
  }
1122
1791
 
1792
+ // Kimi Code protocol capability gap (BLOCKER-1): there is NO
1793
+ // `kimi plugins list --json` interface. observe never execs a kimi
1794
+ // command. Instead it consumes a structured human attestation (written
1795
+ // after the interactive install) bound to the frozen plan digest and
1796
+ // expected identity, then performs read-only verification of the
1797
+ // installed managed copy: payload digest vs the sealed authority,
1798
+ // entry skill resolved via the manifest skills root (MAJOR-4), and
1799
+ // manifest name/version. Missing/expired/mismatched/escaping proof
1800
+ // fails closed so a kimi unit can never reach VERIFIED without it.
1801
+ if (consumer === 'kimi') {
1802
+ const expectedRef = action.ref ?? `v${action.version}`;
1803
+
1804
+ // Bind to the REAL frozen plan digest (A). Fail closed if the
1805
+ // context does not carry an intact frozen plan.
1806
+ let boundPlanDigest;
1807
+ try {
1808
+ boundPlanDigest = resolveBoundPlanDigest(context);
1809
+ } catch (planErr) {
1810
+ return createResult({
1811
+ actionType,
1812
+ status: ActionStatus.OBSERVED,
1813
+ observation: {
1814
+ installed: false,
1815
+ error: `cannot bind kimi observation to the frozen plan: ${planErr.message}`,
1816
+ },
1817
+ });
1818
+ }
1819
+
1820
+ // Stable, cross-run attestation authority (B). The requirement and
1821
+ // attestation live here, keyed by the verified plan digest + plugin,
1822
+ // so they survive publish PARTIAL -> reconcile -> verify (each of
1823
+ // which uses a fresh runDir).
1824
+ let attestationDir;
1825
+ try {
1826
+ attestationDir = kimiAuthorityDir(context, boundPlanDigest, action.plugin);
1827
+ } catch (dirErr) {
1828
+ return createResult({
1829
+ actionType,
1830
+ status: ActionStatus.OBSERVED,
1831
+ observation: { installed: false, error: dirErr.message },
1832
+ });
1833
+ }
1834
+
1835
+ // The execute-emitted requirement must exist and bind to the action
1836
+ // and the frozen plan digest.
1837
+ let requirement = null;
1838
+ try {
1839
+ requirement = JSON.parse(await readFile(resolve(attestationDir, KIMI_REQUIREMENT_FILE), 'utf8'));
1840
+ } catch {
1841
+ return createResult({
1842
+ actionType,
1843
+ status: ActionStatus.OBSERVED,
1844
+ observation: {
1845
+ installed: false,
1846
+ manualInstallRequired: true,
1847
+ error: 'kimi manual-install requirement is missing; run execute first',
1848
+ },
1849
+ });
1850
+ }
1851
+ if (
1852
+ requirement.planDigest !== boundPlanDigest ||
1853
+ requirement.plugin !== action.plugin ||
1854
+ requirement.version !== action.version ||
1855
+ requirement.entrySkill !== action.entrySkill ||
1856
+ requirement.repo !== action.repo ||
1857
+ requirement.ref !== expectedRef
1858
+ ) {
1859
+ return createResult({
1860
+ actionType,
1861
+ status: ActionStatus.OBSERVED,
1862
+ observation: {
1863
+ installed: false,
1864
+ error: 'kimi manual-install requirement does not match the frozen plan/action',
1865
+ },
1866
+ });
1867
+ }
1868
+
1869
+ // The trusted human attestation is mandatory and is read from the
1870
+ // stable authority dir. Without it the interactive install has not
1871
+ // been proven: fail closed.
1872
+ let attestation = null;
1873
+ try {
1874
+ attestation = JSON.parse(await readFile(resolve(attestationDir, KIMI_ATTESTATION_FILE), 'utf8'));
1875
+ } catch {
1876
+ return createResult({
1877
+ actionType,
1878
+ status: ActionStatus.OBSERVED,
1879
+ observation: {
1880
+ installed: false,
1881
+ manualInstallRequired: true,
1882
+ installUrl: requirement.installUrl,
1883
+ attestationDir,
1884
+ error: `kimi attestation is missing; write ${resolve(attestationDir, KIMI_ATTESTATION_FILE)} after the interactive install (${requirement.installUrl})`,
1885
+ },
1886
+ });
1887
+ }
1888
+
1889
+ const attestationCheck = validateKimiAttestation(attestation, action, new Date().toISOString(), boundPlanDigest);
1890
+ if (!attestationCheck.valid) {
1891
+ return createResult({
1892
+ actionType,
1893
+ status: ActionStatus.OBSERVED,
1894
+ observation: { installed: false, error: attestationCheck.error },
1895
+ });
1896
+ }
1897
+
1898
+ // The attested install path must live in the documented managed
1899
+ // layout under the STABLE, plan-digest-keyed isolated home (B). The
1900
+ // managed root is derived from the authority dir (itself derived from
1901
+ // the verified plan digest + plugin), so it is identical across
1902
+ // publish/reconcile/verify run dirs. No lexical-containment fallback
1903
+ // (C): every path must realpath-resolve and stay contained; a missing
1904
+ // home/root, a symlink, or an escape fails closed.
1905
+ const kimiCodeHome = resolve(attestationDir, 'kimi-home');
1906
+ const kimiCodeHomeReal = await realpath(kimiCodeHome).catch(() => null);
1907
+ if (!kimiCodeHomeReal) {
1908
+ return createResult({
1909
+ actionType,
1910
+ status: ActionStatus.OBSERVED,
1911
+ observation: {
1912
+ installed: false,
1913
+ error: `KIMI_CODE_HOME does not exist or cannot be resolved: ${kimiCodeHome}`,
1914
+ },
1915
+ });
1916
+ }
1917
+ const managedRootReal = await realpath(resolve(kimiCodeHomeReal, KIMI_MANAGED_SUBPATH, action.plugin)).catch(() => null);
1918
+ if (!managedRootReal) {
1919
+ return createResult({
1920
+ actionType,
1921
+ status: ActionStatus.OBSERVED,
1922
+ observation: {
1923
+ installed: false,
1924
+ error: `kimi managed plugin root does not exist: ${resolve(kimiCodeHomeReal, KIMI_MANAGED_SUBPATH, action.plugin)}`,
1925
+ },
1926
+ });
1927
+ }
1928
+ // installPath must be a real directory (not a symlink) that resolves
1929
+ // inside the managed root.
1930
+ const installPath = resolve(attestation.installPath);
1931
+ let installPathStat;
1932
+ try {
1933
+ installPathStat = await lstat(installPath);
1934
+ } catch {
1935
+ return createResult({
1936
+ actionType,
1937
+ status: ActionStatus.OBSERVED,
1938
+ observation: { installed: false, error: `kimi install path does not exist: ${attestation.installPath}` },
1939
+ });
1940
+ }
1941
+ if (installPathStat.isSymbolicLink()) {
1942
+ return createResult({
1943
+ actionType,
1944
+ status: ActionStatus.OBSERVED,
1945
+ observation: { installed: false, error: `kimi install path must not be a symlink: ${attestation.installPath}` },
1946
+ });
1947
+ }
1948
+ if (!installPathStat.isDirectory()) {
1949
+ return createResult({
1950
+ actionType,
1951
+ status: ActionStatus.OBSERVED,
1952
+ observation: { installed: false, error: `kimi install path must be a directory: ${attestation.installPath}` },
1953
+ });
1954
+ }
1955
+ const installPathReal = await realpath(installPath).catch(() => null);
1956
+ if (!installPathReal) {
1957
+ return createResult({
1958
+ actionType,
1959
+ status: ActionStatus.OBSERVED,
1960
+ observation: { installed: false, error: `kimi install path cannot be resolved: ${attestation.installPath}` },
1961
+ });
1962
+ }
1963
+ const sepK = process.platform === 'win32' ? '\\' : '/';
1964
+ const relToManaged = relative(managedRootReal, installPathReal);
1965
+ if (
1966
+ relToManaged !== '' &&
1967
+ (isAbsolute(relToManaged) || relToManaged === '..' || relToManaged.startsWith(`..${sepK}`))
1968
+ ) {
1969
+ return createResult({
1970
+ actionType,
1971
+ status: ActionStatus.OBSERVED,
1972
+ observation: {
1973
+ installed: false,
1974
+ error: `kimi install path escapes the managed root (${managedRootReal}): ${attestation.installPath}`,
1975
+ },
1976
+ });
1977
+ }
1978
+
1979
+ // Read-only payload binding: the installed managed copy must match
1980
+ // the sealed frozen authority exactly (transport-normalized).
1981
+ let manifestDigest;
1982
+ try {
1983
+ manifestDigest = await verifyInstalledMarketplacePayload(action, context, installPathReal, consumer);
1984
+ } catch (digestErr) {
1985
+ return createResult({
1986
+ actionType,
1987
+ status: ActionStatus.OBSERVED,
1988
+ observation: {
1989
+ installed: true,
1990
+ installPath: installPathReal,
1991
+ error: `failed to bind installed kimi payload to frozen authority: ${digestErr.message}`,
1992
+ },
1993
+ });
1994
+ }
1995
+ if (manifestDigest !== action.manifestDigest) {
1996
+ return createResult({
1997
+ actionType,
1998
+ status: ActionStatus.OBSERVED,
1999
+ observation: {
2000
+ installed: true,
2001
+ installPath: installPathReal,
2002
+ error: 'installed kimi payload digest does not match the frozen plan digest',
2003
+ },
2004
+ });
2005
+ }
2006
+
2007
+ // Entry skill must resolve via the installed manifest's skills root
2008
+ // (MAJOR-4), with official manifest precedence.
2009
+ let installedManifest;
2010
+ let entrySkillFound = false;
2011
+ try {
2012
+ const readManifest = await readKimiManifest(installPathReal);
2013
+ installedManifest = readManifest.manifest;
2014
+ await resolveKimiEntrySkillFile(installPathReal, installedManifest, action.entrySkill);
2015
+ entrySkillFound = true;
2016
+ } catch (entryErr) {
2017
+ return createResult({
2018
+ actionType,
2019
+ status: ActionStatus.OBSERVED,
2020
+ observation: {
2021
+ installed: true,
2022
+ installPath: installPathReal,
2023
+ manifestDigest,
2024
+ entrySkillFound: false,
2025
+ error: `kimi entry skill not resolvable in installed copy: ${entryErr.message}`,
2026
+ },
2027
+ });
2028
+ }
2029
+
2030
+ // Installed manifest identity must match the frozen action.
2031
+ if (installedManifest.name !== action.plugin) {
2032
+ return createResult({
2033
+ actionType,
2034
+ status: ActionStatus.OBSERVED,
2035
+ observation: {
2036
+ installed: true,
2037
+ installPath: installPathReal,
2038
+ manifestDigest,
2039
+ entrySkillFound: true,
2040
+ error: `installed kimi manifest name "${installedManifest.name}" does not match action plugin "${action.plugin}"`,
2041
+ },
2042
+ });
2043
+ }
2044
+ if (installedManifest.version !== action.version) {
2045
+ return createResult({
2046
+ actionType,
2047
+ status: ActionStatus.OBSERVED,
2048
+ observation: {
2049
+ installed: true,
2050
+ installPath: installPathReal,
2051
+ manifestDigest,
2052
+ entrySkillFound: true,
2053
+ error: `installed kimi manifest version "${installedManifest.version}" does not match action version "${action.version}"`,
2054
+ },
2055
+ });
2056
+ }
2057
+
2058
+ // Build the observation from independently verified fields only.
2059
+ // marketplace is intentionally NOT a kimi identity field (MINOR-1).
2060
+ const observation = {
2061
+ installed: true,
2062
+ installPath: installPathReal,
2063
+ entrySkillFound: true,
2064
+ entrySkill: action.entrySkill,
2065
+ manifestDigest,
2066
+ consumer,
2067
+ plugin: installedManifest.name,
2068
+ version: installedManifest.version,
2069
+ repo: action.repo,
2070
+ ref: expectedRef,
2071
+ };
2072
+ return createResult({
2073
+ actionType,
2074
+ status: ActionStatus.OBSERVED,
2075
+ observation,
2076
+ });
2077
+ }
2078
+
1123
2079
  // Read execute evidence — mandatory for observe validation
1124
2080
  let evidence = null;
1125
2081
  try {
@@ -1155,10 +2111,9 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1155
2111
  });
1156
2112
  }
1157
2113
 
1158
- // Run list command to verify installation
1159
- const listArgs = consumer === 'claude'
1160
- ? ['plugin', 'list', '--json']
1161
- : ['plugin', 'list', '--json'];
2114
+ // Run list command to verify installation (claude/codex only; kimi
2115
+ // has no list CLI and returned via the attestation path above).
2116
+ const listArgs = ['plugin', 'list', '--json'];
1162
2117
 
1163
2118
  let listOutput;
1164
2119
  try {
@@ -1213,7 +2168,7 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1213
2168
  });
1214
2169
  }
1215
2170
  installPath = found.installPath;
1216
- } else {
2171
+ } else if (consumer === 'codex') {
1217
2172
  // Codex: installPath comes from validated evidence, not from list
1218
2173
  installPath = evidence.installOutput?.installedPath;
1219
2174
  if (!installPath) {
@@ -1335,7 +2290,7 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1335
2290
  // is returned and verify therefore fails closed.
1336
2291
  try {
1337
2292
  const installedSnapshot = await computeFrozenSnapshot(installPath, {
1338
- excludeRootEntries: consumer === 'codex' ? ['.git'] : [],
2293
+ excludeRootEntries: consumer === 'codex' || consumer === 'kimi' ? ['.git'] : [],
1339
2294
  });
1340
2295
  manifestDigest = installedSnapshot.digest;
1341
2296
  } catch {
@@ -1354,14 +2309,15 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1354
2309
  consumer,
1355
2310
  };
1356
2311
 
1357
- // Fields from CLI evidence only
2312
+ // Fields from CLI evidence only (claude/codex; kimi observe returns
2313
+ // via the attestation path above and never reaches this point).
1358
2314
  if (consumer === 'claude') {
1359
2315
  // Claude list may not have name; extract plugin/marketplace from id
1360
2316
  const idParts = found.id.split('@');
1361
2317
  observation.plugin = idParts[0];
1362
2318
  observation.marketplace = idParts.slice(1).join('@');
1363
2319
  if (found.version) observation.version = found.version;
1364
- } else {
2320
+ } else if (consumer === 'codex') {
1365
2321
  if (found.name) observation.plugin = found.name;
1366
2322
  if (found.marketplaceName) observation.marketplace = found.marketplaceName;
1367
2323
  if (found.version) observation.version = found.version;
@@ -1510,3 +2466,7 @@ export function createPluginMarketplaceAdapter(deps = {}) {
1510
2466
  },
1511
2467
  });
1512
2468
  }
2469
+
2470
+ // Test-support exports: white-box regression tests assert the Kimi entry-skill
2471
+ // resolution and manifest-reading contracts directly (FU-3 / MAJOR-4).
2472
+ export { resolveKimiEntrySkillFile, readKimiManifest };