@knolo/cli 6.2.10 → 6.2.11

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.
@@ -0,0 +1,453 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
3
+ import { homedir } from 'node:os';
4
+ import path from 'node:path';
5
+ import { cachePath } from './registry/lockfile.mjs';
6
+
7
+ const MAX_IMAGE_BYTES = 512 * 1024 * 1024;
8
+ const QUERY_VERSION = 'openclaw-knolo-query-v1';
9
+ const EVIDENCE_VERSION = 'knolo-mcp-evidence-receipt-v1';
10
+ const BUNDLE_VERSION = 'knolo-receipt-bundle-v1';
11
+ const ANSWER_VERSION = 'knolo-verified-answer-v1';
12
+ const QUERY_ID = /^qr_[a-f0-9]{24}$/;
13
+ const EVIDENCE_ID = /^er_[a-f0-9]{24}$/;
14
+ const PACK_REF = /^([a-z0-9-]+)\/([a-z0-9-]+)@([^@\s]+)$/;
15
+ const HEX_64 = /^[a-f0-9]{64}$/;
16
+
17
+ export async function runReceiptCli(args, options = {}) {
18
+ const action = args[0];
19
+ if (action === 'export') return exportReceipt(args.slice(1), options);
20
+ if (action === 'verify') return verifyBundle(args.slice(1), options);
21
+ if (action === 'cite') return citeBundle(args.slice(1), options);
22
+ throw new Error(usage());
23
+ }
24
+
25
+ function usage() {
26
+ return `Usage: knolo receipt export <receipt-id> [--audit-dir <dir> | --config <knolo-mcp.json>] [--policy <policy.json>] [--out <file>] [--pack-ref <publisher/slug@version>] [--principal <id>] [--redact]
27
+ knolo receipt verify <bundle.json> --pack <image | publisher/slug@version>
28
+ knolo receipt cite <bundle.json> --pack <image | publisher/slug@version> [--out <file>]
29
+
30
+ Exports a portable bundle for an openclaw-knolo-query-v1 or knolo-mcp-evidence-receipt-v1 record.
31
+ Verify checks that bundle against a local image file or a lockfile cache entry.
32
+ cite prints a knolo-verified-answer-v1 object after that check succeeds.
33
+ A publisher/slug@version pack is read from knolo.lock.json and the local cache.
34
+ Receipt verify does not contact a registry. The image is not rebuilt.
35
+ A receipt is an integrity check. It does not mean a claim is proven.
36
+ --redact omits the caller. It does not remove the query text.
37
+ Evidence verify checks the record digest and the image pins. It does not replay the tool.`;
38
+ }
39
+
40
+ async function exportReceipt(args, options) {
41
+ const { positional, flags } = parseFlags(args);
42
+ const receiptId = positional[0];
43
+ if (!receiptId || positional.length !== 1) throw new Error(usage());
44
+ if (!QUERY_ID.test(receiptId) && !EVIDENCE_ID.test(receiptId)) {
45
+ throw new Error('Receipt id is invalid. Nothing was written.');
46
+ }
47
+ const cwd = options.cwd ?? process.cwd();
48
+ const core = requiredCore(options.core);
49
+ const config = flags.config
50
+ ? await readJson(path.resolve(cwd, flags.config), 'knolo-mcp.json')
51
+ : null;
52
+ const auditDir = resolveAuditDir(flags, config, cwd);
53
+ const receiptPath = path.join(auditDir, `${receiptId}.json`);
54
+ const receipt = await readJson(receiptPath, 'Receipt');
55
+ if (!receipt || typeof receipt !== 'object' || Array.isArray(receipt)) {
56
+ throw new Error('Receipt must be a JSON object. Nothing was written.');
57
+ }
58
+ if (receipt.receiptId !== receiptId) {
59
+ throw new Error('Receipt id does not match the file. Nothing was written.');
60
+ }
61
+ const mount = findMount(config, receipt);
62
+ const policy = await loadPolicy(flags, mount, cwd);
63
+ const principal = resolvePrincipal(receipt, flags);
64
+ if (flags.packRef && !PACK_REF.test(flags.packRef)) {
65
+ throw new Error(
66
+ 'Pack reference must be publisher/slug@version. Nothing was written.'
67
+ );
68
+ }
69
+ const bundle = {
70
+ version: BUNDLE_VERSION,
71
+ type: receipt.version,
72
+ pack: {
73
+ byteSha256: receipt.byteSha256,
74
+ stateRoot: receipt.stateRoot,
75
+ ...(flags.packRef ? { reference: flags.packRef } : {}),
76
+ },
77
+ principal,
78
+ policy,
79
+ redacted: flags.redact ? { caller: true } : null,
80
+ receipt: flags.redact ? redactReceipt(receipt) : receipt,
81
+ };
82
+ if (bundle.type !== QUERY_VERSION && bundle.type !== EVIDENCE_VERSION) {
83
+ throw new Error('Unsupported receipt version. Nothing was written.');
84
+ }
85
+ if (mount?.path) {
86
+ const bytes = await readImage(mount.path);
87
+ if (digest(bytes) !== receipt.byteSha256) {
88
+ throw new Error(
89
+ 'Receipt byte digest does not match the mounted image. Nothing was written.'
90
+ );
91
+ }
92
+ try {
93
+ core.verifyKnoloReceiptBundleV1(bundle, bytes);
94
+ } catch (error) {
95
+ throw new Error(`${messageOf(error)} Nothing was written.`);
96
+ }
97
+ }
98
+ const serialized = `${JSON.stringify(bundle, null, 2)}\n`;
99
+ if (!flags.out) {
100
+ (options.print ?? console.log)(serialized.trimEnd());
101
+ return bundle;
102
+ }
103
+ const outPath = path.resolve(cwd, flags.out);
104
+ await writeNewFile(outPath, serialized);
105
+ (options.print ?? console.log)(
106
+ JSON.stringify({
107
+ ok: true,
108
+ action: 'export',
109
+ out: outPath,
110
+ redactedCaller: flags.redact,
111
+ })
112
+ );
113
+ return bundle;
114
+ }
115
+
116
+ async function verifyBundle(args, options) {
117
+ const { positional, flags } = parseFlags(args);
118
+ const bundlePath = positional[0];
119
+ if (!bundlePath || positional.length !== 1 || !flags.pack)
120
+ throw new Error(usage());
121
+ if (/^https?:\/\//i.test(flags.pack)) {
122
+ throw new Error('Receipt verify does not contact a registry.');
123
+ }
124
+ const cwd = options.cwd ?? process.cwd();
125
+ const homeDir = options.homeDir ?? homedir();
126
+ const core = requiredCore(options.core);
127
+ const bundle = await readJson(
128
+ path.resolve(cwd, bundlePath),
129
+ 'Receipt bundle'
130
+ );
131
+ const resolved = await resolvePack(flags.pack, cwd, homeDir);
132
+ if (
133
+ bundle?.pack?.reference &&
134
+ resolved.reference &&
135
+ bundle.pack.reference !== resolved.reference
136
+ ) {
137
+ throw new Error('Receipt bundle pack reference does not match --pack.');
138
+ }
139
+ const bytes = await readImage(resolved.filePath);
140
+ const sha256 = digest(bytes);
141
+ if (resolved.sha256 && resolved.sha256 !== sha256) {
142
+ throw new Error('Image bytes do not match the lockfile pin.');
143
+ }
144
+ if (resolved.stateRoot) {
145
+ let image;
146
+ try {
147
+ image = core.mountKnowledgeImageV5(bytes);
148
+ } catch (error) {
149
+ throw new Error(`Image failed V5 verification: ${messageOf(error)}`);
150
+ }
151
+ if (image.stateRoot !== resolved.stateRoot) {
152
+ throw new Error('Image stateRoot does not match the lockfile pin.');
153
+ }
154
+ }
155
+ const report = core.verifyKnoloReceiptBundleV1(bundle, bytes);
156
+ (options.print ?? console.log)(JSON.stringify(report, null, 2));
157
+ return report;
158
+ }
159
+
160
+ async function citeBundle(args, options) {
161
+ const { positional, flags } = parseFlags(args);
162
+ const bundlePath = positional[0];
163
+ if (!bundlePath || positional.length !== 1 || !flags.pack) {
164
+ throw new Error(usage());
165
+ }
166
+ if (/^https?:\/\//i.test(flags.pack)) {
167
+ throw new Error('Receipt cite does not contact a registry.');
168
+ }
169
+ const cwd = options.cwd ?? process.cwd();
170
+ const homeDir = options.homeDir ?? homedir();
171
+ const core = requiredCore(options.core);
172
+ const absolute = path.resolve(cwd, bundlePath);
173
+ const raw = await readFile(absolute);
174
+ let bundle;
175
+ try {
176
+ bundle = JSON.parse(raw.toString('utf8'));
177
+ } catch {
178
+ throw new Error(`Receipt bundle is invalid JSON: ${absolute}`);
179
+ }
180
+ const resolved = await resolvePack(flags.pack, cwd, homeDir);
181
+ if (
182
+ bundle?.pack?.reference &&
183
+ resolved.reference &&
184
+ bundle.pack.reference !== resolved.reference
185
+ ) {
186
+ throw new Error('Receipt bundle pack reference does not match --pack.');
187
+ }
188
+ const bytes = await readImage(resolved.filePath);
189
+ const sha256 = digest(bytes);
190
+ if (resolved.sha256 && resolved.sha256 !== sha256) {
191
+ throw new Error('Image bytes do not match the lockfile pin.');
192
+ }
193
+ if (resolved.stateRoot) {
194
+ let image;
195
+ try {
196
+ image = core.mountKnowledgeImageV5(bytes);
197
+ } catch (error) {
198
+ throw new Error(`Image failed V5 verification: ${messageOf(error)}`);
199
+ }
200
+ if (image.stateRoot !== resolved.stateRoot) {
201
+ throw new Error('Image stateRoot does not match the lockfile pin.');
202
+ }
203
+ }
204
+ try {
205
+ core.verifyKnoloReceiptBundleV1(bundle, bytes);
206
+ } catch (error) {
207
+ throw new Error(`${messageOf(error)} Nothing was written.`);
208
+ }
209
+ const reference = bundle?.pack?.reference;
210
+ const answer = {
211
+ version: ANSWER_VERSION,
212
+ bundleSha256: `sha256-${digest(raw)}`,
213
+ pack: {
214
+ byteSha256: bundle.pack.byteSha256,
215
+ stateRoot: bundle.pack.stateRoot,
216
+ ...(typeof reference === 'string' && reference.length > 0
217
+ ? { reference }
218
+ : {}),
219
+ },
220
+ };
221
+ const serialized = `${JSON.stringify(answer, null, 2)}\n`;
222
+ if (flags.out) await writeNewFile(path.resolve(cwd, flags.out), serialized);
223
+ (options.print ?? console.log)(serialized.trimEnd());
224
+ return answer;
225
+ }
226
+
227
+ async function resolvePack(spec, cwd, homeDir) {
228
+ const packMatch = PACK_REF.exec(spec);
229
+ if (!packMatch) {
230
+ return {
231
+ filePath: path.resolve(cwd, spec),
232
+ reference: null,
233
+ sha256: null,
234
+ stateRoot: null,
235
+ };
236
+ }
237
+ const reference = spec;
238
+ const name = `${packMatch[1]}/${packMatch[2]}`;
239
+ const version = packMatch[3];
240
+ const lock = await readLock(cwd);
241
+ const entry = lock.packs[name];
242
+ if (!entry?.sha256 || !HEX_64.test(entry.sha256)) {
243
+ throw new Error(
244
+ `Pack ${reference} is not in knolo.lock.json. Receipt verify does not contact a registry.`
245
+ );
246
+ }
247
+ if (String(entry.version) !== version) {
248
+ throw new Error(
249
+ `Lockfile pins ${name} at ${entry.version}. Receipt verify does not contact a registry.`
250
+ );
251
+ }
252
+ const filePath = cachePath(homeDir, entry.sha256);
253
+ try {
254
+ await readFile(filePath);
255
+ } catch (error) {
256
+ if (error?.code === 'ENOENT') {
257
+ throw new Error(
258
+ `Pack ${reference} is not in the local cache. Receipt verify does not contact a registry.`
259
+ );
260
+ }
261
+ throw error;
262
+ }
263
+ return {
264
+ filePath,
265
+ reference,
266
+ sha256: entry.sha256,
267
+ stateRoot: typeof entry.stateRoot === 'string' ? entry.stateRoot : null,
268
+ };
269
+ }
270
+
271
+ function resolveAuditDir(flags, config, cwd) {
272
+ if (flags.auditDir) return path.resolve(cwd, flags.auditDir);
273
+ if (typeof config?.auditDir === 'string' && config.auditDir) {
274
+ return path.resolve(cwd, config.auditDir);
275
+ }
276
+ throw new Error(
277
+ 'Pass --audit-dir or --config with auditDir. Nothing was written.'
278
+ );
279
+ }
280
+
281
+ function findMount(config, receipt) {
282
+ const mounts = Array.isArray(config?.mounts) ? config.mounts : [];
283
+ return (
284
+ mounts.find((mount) => mount && mount.id === receipt.imageId) ??
285
+ mounts.find((mount) => mount && mount.sha256 === receipt.byteSha256) ??
286
+ null
287
+ );
288
+ }
289
+
290
+ async function loadPolicy(flags, mount, cwd) {
291
+ const policyPath = flags.policy
292
+ ? path.resolve(cwd, flags.policy)
293
+ : typeof mount?.policyPath === 'string'
294
+ ? path.resolve(cwd, mount.policyPath)
295
+ : null;
296
+ if (!policyPath) {
297
+ throw new Error(
298
+ 'Pass --policy or a config mount with policyPath. Nothing was written.'
299
+ );
300
+ }
301
+ const policy = await readJson(policyPath, 'Policy');
302
+ if (!policy || typeof policy !== 'object' || Array.isArray(policy)) {
303
+ throw new Error('Policy must be a JSON object. Nothing was written.');
304
+ }
305
+ return policy;
306
+ }
307
+
308
+ function resolvePrincipal(receipt, flags) {
309
+ if (receipt.version === QUERY_VERSION) {
310
+ const principal = receipt.authorization?.principal;
311
+ if (typeof principal !== 'string' || !principal) {
312
+ throw new Error(
313
+ 'Query receipt has no authorization principal. Nothing was written.'
314
+ );
315
+ }
316
+ if (flags.principal && flags.principal !== principal) {
317
+ throw new Error(
318
+ 'Query receipt principal does not match --principal. Nothing was written.'
319
+ );
320
+ }
321
+ return principal;
322
+ }
323
+ if (receipt.version === EVIDENCE_VERSION) {
324
+ if (typeof flags.principal !== 'string' || !flags.principal) {
325
+ throw new Error(
326
+ 'Evidence export needs --principal. Nothing was written.'
327
+ );
328
+ }
329
+ return flags.principal;
330
+ }
331
+ throw new Error('Unsupported receipt version. Nothing was written.');
332
+ }
333
+
334
+ function redactReceipt(receipt) {
335
+ const copy = { ...receipt };
336
+ delete copy.caller;
337
+ delete copy.recordDigest;
338
+ return copy;
339
+ }
340
+
341
+ function requiredCore(core) {
342
+ if (
343
+ typeof core?.verifyKnoloReceiptBundleV1 !== 'function' ||
344
+ typeof core?.mountKnowledgeImageV5 !== 'function'
345
+ ) {
346
+ throw new Error('Could not load @knolo/core for the receipt check.');
347
+ }
348
+ return core;
349
+ }
350
+
351
+ async function readImage(filePath) {
352
+ const bytes = await readFile(filePath);
353
+ if (bytes.byteLength > MAX_IMAGE_BYTES) {
354
+ throw new Error(`Image is larger than ${MAX_IMAGE_BYTES} bytes.`);
355
+ }
356
+ return bytes;
357
+ }
358
+
359
+ async function readJson(filePath, label) {
360
+ let text;
361
+ try {
362
+ text = await readFile(filePath, 'utf8');
363
+ } catch (error) {
364
+ if (error?.code === 'ENOENT')
365
+ throw new Error(`${label} was not found: ${filePath}`);
366
+ throw error;
367
+ }
368
+ try {
369
+ return JSON.parse(text);
370
+ } catch {
371
+ throw new Error(`${label} is invalid JSON: ${filePath}`);
372
+ }
373
+ }
374
+
375
+ async function readLock(cwd) {
376
+ const filePath = path.resolve(cwd, 'knolo.lock.json');
377
+ let text;
378
+ try {
379
+ text = await readFile(filePath, 'utf8');
380
+ } catch (error) {
381
+ if (error?.code === 'ENOENT') return { packs: {} };
382
+ throw error;
383
+ }
384
+ let value;
385
+ try {
386
+ value = JSON.parse(text);
387
+ } catch {
388
+ throw new Error('knolo.lock.json is invalid JSON.');
389
+ }
390
+ const packs =
391
+ value?.packs &&
392
+ typeof value.packs === 'object' &&
393
+ !Array.isArray(value.packs)
394
+ ? value.packs
395
+ : {};
396
+ return { packs };
397
+ }
398
+
399
+ async function writeNewFile(filePath, text) {
400
+ await mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
401
+ const tempPath = path.join(
402
+ path.dirname(filePath),
403
+ `.${path.basename(filePath)}.${process.pid}.next`
404
+ );
405
+ try {
406
+ await writeFile(tempPath, text, { mode: 0o600 });
407
+ await rename(tempPath, filePath);
408
+ } catch (error) {
409
+ await unlink(tempPath).catch(() => {});
410
+ throw error;
411
+ }
412
+ }
413
+
414
+ function parseFlags(args) {
415
+ const positional = [];
416
+ const flags = { redact: false };
417
+ for (let index = 0; index < args.length; index += 1) {
418
+ const arg = args[index];
419
+ if (arg === '--redact') {
420
+ flags.redact = true;
421
+ continue;
422
+ }
423
+ if (
424
+ arg === '--audit-dir' ||
425
+ arg === '--config' ||
426
+ arg === '--policy' ||
427
+ arg === '--out' ||
428
+ arg === '--pack-ref' ||
429
+ arg === '--principal' ||
430
+ arg === '--pack'
431
+ ) {
432
+ const value = args[index + 1];
433
+ if (!value || value.startsWith('--'))
434
+ throw new Error(`${arg} requires a value.`);
435
+ index += 1;
436
+ if (arg === '--audit-dir') flags.auditDir = value;
437
+ else if (arg === '--pack-ref') flags.packRef = value;
438
+ else flags[arg.slice(2)] = value;
439
+ continue;
440
+ }
441
+ if (arg.startsWith('--')) throw new Error(`Unknown option ${arg}.`);
442
+ positional.push(arg);
443
+ }
444
+ return { positional, flags };
445
+ }
446
+
447
+ function digest(bytes) {
448
+ return createHash('sha256').update(bytes).digest('hex');
449
+ }
450
+
451
+ function messageOf(error) {
452
+ return error instanceof Error ? error.message : String(error);
453
+ }
@@ -11,6 +11,7 @@ import { createHash, randomUUID } from 'node:crypto';
11
11
  import { isIP } from 'node:net';
12
12
  import { homedir } from 'node:os';
13
13
  import path from 'node:path';
14
+ import { fileURLToPath, pathToFileURL } from 'node:url';
14
15
  import {
15
16
  normalizeRegistryUrl,
16
17
  registryApiUrl,
@@ -332,6 +333,17 @@ export async function runHubPublish(
332
333
  } = {}
333
334
  ) {
334
335
  const { packPath, flags } = parsePublishArgs(args);
336
+ const packFile = path.resolve(cwd, packPath);
337
+ const bytes = await readFile(packFile);
338
+ if (bytes.length > MAX_ARTIFACT_BYTES)
339
+ throw new Error('Artifact exceeds Hub’s 250 MB limit.');
340
+ if (looksLikeKnowledgeImageV5(bytes)) {
341
+ const report = await preflightKnowledgeImage(bytes, flags, print);
342
+ if (!report.ok) {
343
+ throw new Error('Publish preflight failed before any network request.');
344
+ }
345
+ }
346
+
335
347
  const credentials = await loadCredentials({ env, homeDir });
336
348
  const registry = resolveCredentialRegistry(
337
349
  flags.registry,
@@ -339,8 +351,8 @@ export async function runHubPublish(
339
351
  );
340
352
  const authHeaders = authorizationHeaders(credentials.token);
341
353
 
342
- // This request is deliberately first: it proves the stored dashboard token
343
- // is a Hub Bearer credential before any upload or publish mutation starts.
354
+ // The V5 preflight above is local. This request is the first network call:
355
+ // it proves the stored dashboard token before any upload or publish mutation.
344
356
  const account = await getJson(registryApiUrl(registry, ['account']), {
345
357
  fetchImpl,
346
358
  headers: authHeaders,
@@ -357,10 +369,6 @@ export async function runHubPublish(
357
369
  }
358
370
  const publisher = flags.publisher || accountPublisher;
359
371
 
360
- const packFile = path.resolve(cwd, packPath);
361
- const bytes = await readFile(packFile);
362
- if (bytes.length > MAX_ARTIFACT_BYTES)
363
- throw new Error('Artifact exceeds Hub’s 250 MB limit.');
364
372
  const sha256 = createSha256(bytes);
365
373
  const pathname = `sha256/${sha256}.knolo`;
366
374
 
@@ -373,17 +381,20 @@ export async function runHubPublish(
373
381
  },
374
382
  { fetchImpl, headers: authHeaders }
375
383
  );
376
- const upload = resolveUploadGrant(grant, sha256, { privatePack: Boolean(flags.private) });
384
+ const upload = resolveUploadGrant(grant, sha256, {
385
+ privatePack: Boolean(flags.private),
386
+ });
377
387
  let blobUrl;
378
388
  if (upload.reused && !upload.url && flags.private) {
379
389
  blobUrl = undefined;
380
390
  } else if (upload.reused) {
381
- blobUrl = (flags.private ? assertPrivatePackBlobUrl : assertPublicPackBlobUrl)(
382
- upload.url,
383
- 'reused artifact'
384
- ).toString();
391
+ blobUrl = (
392
+ flags.private ? assertPrivatePackBlobUrl : assertPublicPackBlobUrl
393
+ )(upload.url, 'reused artifact').toString();
385
394
  } else {
386
- assertGrantPutUrl(upload.putUrl, 'upload grant', { allowPrivate: Boolean(flags.private) });
395
+ assertGrantPutUrl(upload.putUrl, 'upload grant', {
396
+ allowPrivate: Boolean(flags.private),
397
+ });
387
398
  const uploaded = await putBytes(upload.putUrl, bytes, {
388
399
  fetchImpl,
389
400
  headers: {
@@ -397,10 +408,9 @@ export async function runHubPublish(
397
408
  `${flags.private ? 'Private' : 'Public'} Blob upload pathname is not locked to ${pathname}.`
398
409
  );
399
410
  }
400
- blobUrl = (flags.private ? assertPrivatePackBlobUrl : assertPublicPackBlobUrl)(
401
- uploaded.url,
402
- 'uploaded artifact'
403
- ).toString();
411
+ blobUrl = (
412
+ flags.private ? assertPrivatePackBlobUrl : assertPublicPackBlobUrl
413
+ )(uploaded.url, 'uploaded artifact').toString();
404
414
  }
405
415
 
406
416
  await postHubJson(
@@ -563,6 +573,14 @@ export function parsePublishArgs(args) {
563
573
  flags.private = true;
564
574
  continue;
565
575
  }
576
+ if (arg === '--allow-private') {
577
+ flags.allowPrivate = true;
578
+ continue;
579
+ }
580
+ if (arg === '--allow-findings') {
581
+ flags.allowFindings = true;
582
+ continue;
583
+ }
566
584
  if (arg === '--category') {
567
585
  const value = args[++i];
568
586
  if (value === undefined || value.startsWith('--')) {
@@ -590,7 +608,7 @@ export function parsePublishArgs(args) {
590
608
  !flags.license
591
609
  ) {
592
610
  throw new Error(
593
- 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--category <id>] [--private] [--json] [--registry <url>]'
611
+ 'Usage: knolo publish <pack.knolo> --slug <slug> --version <version> --license <SPDX> [--publisher <handle>] [--readme <text>] [--sources <text>] [--intended-use <text>] [--category <id>] [--private] [--allow-private] [--allow-findings] [--json] [--registry <url>]'
594
612
  );
595
613
  }
596
614
  if (!/^[a-z0-9-]+$/.test(flags.slug))
@@ -605,7 +623,10 @@ export function parsePublishArgs(args) {
605
623
  'Publish publisher must contain lowercase letters, numbers, and hyphens.'
606
624
  );
607
625
  if (flags.categories) {
608
- flags.categories = normalizeCategories(flags.categories, { min: 1, max: 3 });
626
+ flags.categories = normalizeCategories(flags.categories, {
627
+ min: 1,
628
+ max: 3,
629
+ });
609
630
  }
610
631
  return { packPath: positional[0], flags };
611
632
  }
@@ -685,6 +706,10 @@ async function optionalPublishHeaders(registry, { env, homeDir } = {}) {
685
706
  return credentials ? authorizationHeaders(credentials.token) : {};
686
707
  }
687
708
 
709
+ export async function optionalHubHeaders(registry, options) {
710
+ return optionalPublishHeaders(registry, options);
711
+ }
712
+
688
713
  async function readMatchingCredentials(registry, { env, homeDir } = {}) {
689
714
  try {
690
715
  const credentials = await loadCredentials({ env, homeDir });
@@ -744,6 +769,58 @@ function hubApiUrl(registry, segments) {
744
769
  return url;
745
770
  }
746
771
 
772
+ function looksLikeKnowledgeImageV5(bytes) {
773
+ return (
774
+ bytes.length >= 8 &&
775
+ bytes.subarray(0, 8).toString('latin1') === 'KNLOV5\0\0'
776
+ );
777
+ }
778
+
779
+ async function loadPublishCore() {
780
+ const dist = path.resolve(
781
+ path.dirname(fileURLToPath(import.meta.url)),
782
+ '../../../core/dist/index.js'
783
+ );
784
+ let last = 'missing';
785
+ for (const candidate of [dist, '@knolo/core']) {
786
+ try {
787
+ const loaded = await import(
788
+ candidate.startsWith('@') ? candidate : pathToFileURL(candidate).href
789
+ );
790
+ if (loaded.isKnowledgeImageV5 && loaded.checkKnowledgePublishV5)
791
+ return loaded;
792
+ } catch (error) {
793
+ last = error instanceof Error ? error.message : String(error);
794
+ }
795
+ }
796
+ throw new Error(
797
+ `Could not load @knolo/core. Build packages/core first. (${last})`
798
+ );
799
+ }
800
+
801
+ async function preflightKnowledgeImage(bytes, flags, print) {
802
+ const core = await loadPublishCore();
803
+ if (!core.isKnowledgeImageV5(bytes)) {
804
+ return { ok: true };
805
+ }
806
+ const report = core.checkKnowledgePublishV5(bytes, {
807
+ license: flags.license,
808
+ allowPrivate: Boolean(flags.allowPrivate),
809
+ allowFindings: Boolean(flags.allowFindings),
810
+ });
811
+ print(
812
+ `preflight ${report.ok ? 'ok' : 'failed'} chunks ${report.chunks} bytes ${report.bytes} sha256 ${report.sha256} stateRoot ${report.stateRoot}`
813
+ );
814
+ if (report.overrides.length > 0) {
815
+ print(`preflight override ${report.overrides.join(' ')}`);
816
+ }
817
+ for (const line of report.confirmations) print(line);
818
+ for (const finding of report.findings) {
819
+ print(`preflight finding ${finding.code} ${finding.detail}`);
820
+ }
821
+ return report;
822
+ }
823
+
747
824
  function createSha256(bytes) {
748
825
  return createHash('sha256').update(bytes).digest('hex');
749
826
  }
@@ -752,12 +829,13 @@ function resolveUploadGrant(body, sha256, { privatePack = false } = {}) {
752
829
  const pathname = body?.pathname || body?.upload?.pathname;
753
830
  const expectedPathname = `sha256/${sha256}.knolo`;
754
831
  if (typeof pathname !== 'string' || pathname !== expectedPathname) {
755
- throw new Error(`Hub upload pathname is not locked to ${expectedPathname}.`);
832
+ throw new Error(
833
+ `Hub upload pathname is not locked to ${expectedPathname}.`
834
+ );
756
835
  }
757
836
 
758
837
  const reusedUrl =
759
- (body?.reused && (body?.artifact?.url || body?.url)) ||
760
- body?.artifact?.url;
838
+ (body?.reused && (body?.artifact?.url || body?.url)) || body?.artifact?.url;
761
839
  if (typeof reusedUrl === 'string' && reusedUrl) {
762
840
  return { reused: true, pathname, url: reusedUrl };
763
841
  }
@@ -765,7 +843,8 @@ function resolveUploadGrant(body, sha256, { privatePack = false } = {}) {
765
843
  return { reused: true, pathname };
766
844
  }
767
845
 
768
- const upload = body?.upload && typeof body.upload === 'object' ? body.upload : body;
846
+ const upload =
847
+ body?.upload && typeof body.upload === 'object' ? body.upload : body;
769
848
  if (!upload || typeof upload.url !== 'string' || !upload.url) {
770
849
  if (body?.clientToken || upload?.clientToken) {
771
850
  throw new Error(
@@ -779,7 +858,9 @@ function resolveUploadGrant(body, sha256, { privatePack = false } = {}) {
779
858
  pathname,
780
859
  putUrl: upload.url,
781
860
  putHeaders:
782
- upload.headers && typeof upload.headers === 'object' ? upload.headers : {},
861
+ upload.headers && typeof upload.headers === 'object'
862
+ ? upload.headers
863
+ : {},
783
864
  };
784
865
  }
785
866
 
@@ -1168,7 +1249,12 @@ export function parseSearchArgs(args) {
1168
1249
  const flags = {};
1169
1250
  for (let i = 0; i < args.length; i++) {
1170
1251
  const arg = args[i];
1171
- if (arg === '--json' || arg === '--official' || arg === '--agents' || arg === '--research') {
1252
+ if (
1253
+ arg === '--json' ||
1254
+ arg === '--official' ||
1255
+ arg === '--agents' ||
1256
+ arg === '--research'
1257
+ ) {
1172
1258
  flags[arg.slice(2)] = true;
1173
1259
  continue;
1174
1260
  }