@knolo/cli 6.2.3 → 6.2.5

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.
package/README.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # @knolo/cli
2
2
 
3
+ `@knolo/cli` is how an agent publishes, pins, and installs shared knowledge.
4
+ Hub knowledge packs use `knolo publish` and `knolo add`. Skill packs use
5
+ `knolo skill pack`, `knolo skill publish`, and `knolo skill install`. The
6
+ pin is the digest. A receipt is an integrity check. It does not mean a
7
+ claim is proven.
8
+
3
9
  The CLI preserves the Knolo V4 pack workflow and adds explicit V5 Knowledge
4
10
  Image inspection and querying. Normal builds emit V4; the ICP legacy build path explicitly
5
11
  emits V3 until the canister gains a V4 profile. V5 Studio output is a verified
@@ -13,8 +19,11 @@ reader.
13
19
 
14
20
  `knolo compose`, `knolo attest`, and `knolo verify-attestation` cite local
15
21
  Knowledge Images and write an attestation sidecar. This tree's `@knolo/cli`
16
- package file is `6.2.3` and depends on `@knolo/core` `^6.2.0`. npm
17
- `latest` is `6.2.2` until `6.2.3` is published. They do not fetch Hub. Verification
22
+ package file is `6.2.4` and depends on `@knolo/core` `^6.2.0` and
23
+ `@knolo/exchange` `^0.1.0`. npm `latest` is `6.2.4`. `knolo exchange` hands
24
+ a verified V5 image to another agent. Shipped configs keep `adopt: deny`.
25
+ Discover reads a public advertisement and does not download a pack. They do
26
+ not fetch Hub for that handoff. Verification
18
27
  recomputes `compositionRoot` and checks bundled excerpt bytes. A keyring key
19
28
  must fall inside `notBefore`, `notAfter`, and `revokedAt`. `used` means a
20
29
  query or evaluation ran. It does not mean `SATISFIED`, and it does not mean a
@@ -26,8 +35,10 @@ model and does not take an API key. A verified trace matches the image. It
26
35
  does not mean the answer is true.
27
36
 
28
37
  `knolo flight ingest` packs a `flight-events-1` document into a V5 Knowledge
29
- Image and binds it to the SHA-256 of one log file. It does not decode the log.
30
- `log.format` is `ulog`, `dataflash`, or `rosbag2`. Optional producers live in
38
+ Image and binds it to the SHA-256 of one log file. `knolo flight verify-log`
39
+ hashes that file again and compares it with the image. It writes nothing.
40
+ Neither command decodes the log. `log.format` is `ulog`, `dataflash`, or
41
+ `rosbag2`. Optional producers live in
31
42
  `scripts/flight/` and are not part of `npm test`. `SATISFIED` on a later KAR
32
43
  check means the evidence requirements were met. It does not mean a flight was
33
44
  safe, legal, or compliant. See `docs/flight/README.md`.
@@ -37,6 +48,16 @@ a model. A receipt is an integrity check. It does not mean a claim is proven.
37
48
  `SATISFIED` means the evidence requirements were met. See
38
49
  [Skills](../../docs/skills/README.md).
39
50
 
51
+ `knolo research package` writes one V5 image from local files. `--agent` is
52
+ the host-supplied caller. An optional Cortex trace is verified against
53
+ `--cite` before the write. A cited pack stores a digest-bound composition
54
+ record and does not copy the cited image. Pass `--graph` when that trace
55
+ records KAR evaluations. The checked graph is stored in the image. The
56
+ command does not call a model and does not download an image.
57
+ `examples/skills/research-and-cite` and `examples/skills/share-findings`
58
+ install with `knolo skill install`. See
59
+ [Research packs](../../docs/guides/research-packs.md).
60
+
40
61
  The official CLI for building `.knolo` knowledge packs.
41
62
 
42
63
  It indexes structured content and produces a deterministic, local-first knowledge bundle for use with `@knolo/core`.
@@ -64,9 +85,13 @@ changing the local pack workflow:
64
85
 
65
86
  ```bash
66
87
  knolo search "refund policy"
88
+ knolo search "refund policy" --research
67
89
  knolo info acme/refund-policy
68
90
  ```
69
91
 
92
+ `--research` asks for packs whose image metadata role is `research-pack`.
93
+ `--agents` remains the agent-definition namespace.
94
+
70
95
  The production registry is `https://hub.knolo.dev`. Use `--registry` for a
71
96
  one-off override, or set `KNOLO_HUB_URL` for the current environment:
72
97
 
@@ -361,7 +386,7 @@ This ensures:
361
386
  ## 🗺 Roadmap
362
387
 
363
388
  The active roadmap is maintained in [`../../docs/ROADMAP.md`](../../docs/ROADMAP.md).
364
- The published npm release is `6.2.2`. This package file is `6.2.3` until that version is published. It preserves the V4 CLI, keeps V5 verification,
389
+ The published npm release is `6.2.4`. It preserves the V4 CLI, keeps V5 verification,
365
390
  migration, diagnostics, and read-only Studio management, and adds offline
366
391
  composition, attestation, and `knolo cortex`. Cortex verification does not
367
392
  mean an answer is true.
@@ -0,0 +1,206 @@
1
+ import {
2
+ adoptExchangeReceipt,
3
+ exportExchangeDirectory,
4
+ importExchangeDirectory,
5
+ inspectExchangeReceipt,
6
+ loadExchangeConfig,
7
+ publishExchangeOffer,
8
+ pullExchangeOffer,
9
+ startExchangeServer,
10
+ } from '@knolo/exchange';
11
+ import { registryApiUrl, resolveRegistryUrl } from './registry/config.mjs';
12
+
13
+ export async function runExchangeCli(argv) {
14
+ const { command, flags, positional } = parse(argv);
15
+ if (!flags.config && command !== 'inspect' && command !== 'discover')
16
+ throw new Error(
17
+ 'Usage: knolo exchange <serve|offer|pull|export|import|adopt|discover|inspect> --config <exchange.json>'
18
+ );
19
+ const config = flags.config ? loadExchangeConfig(flags.config) : undefined;
20
+ const now = flags.now === undefined ? Date.now() : Number(flags.now);
21
+ if (!Number.isSafeInteger(now))
22
+ throw new Error('V5 exchange --now must be an integer.');
23
+ if (command === 'serve') {
24
+ const truncateAfter = readTruncateHook();
25
+ const server = await startExchangeServer(config, {
26
+ ...(flags.home ? { homeDir: flags.home } : {}),
27
+ ...(flags.now === undefined ? {} : { now: () => now }),
28
+ ...(truncateAfter === undefined ? {} : { truncateAfter }),
29
+ });
30
+ console.log(server.url);
31
+ await new Promise((resolve) => {
32
+ process.once('SIGINT', resolve);
33
+ process.once('SIGTERM', resolve);
34
+ });
35
+ await server.close();
36
+ return;
37
+ }
38
+ if (command === 'offer') {
39
+ const imagePath = positional[0];
40
+ if (!imagePath || !flags.to)
41
+ throw new Error(
42
+ 'Usage: knolo exchange offer <image.knolo> --to <peer> --config <exchange.json>'
43
+ );
44
+ const published = await publishExchangeOffer(config, {
45
+ imagePath,
46
+ to: flags.to,
47
+ now,
48
+ ...(flags.ttl === undefined ? {} : { ttlMs: Number(flags.ttl) }),
49
+ });
50
+ console.log(published.offerId);
51
+ return;
52
+ }
53
+ if (command === 'pull') {
54
+ const offerId = positional[0];
55
+ if (!offerId || !flags.from)
56
+ throw new Error(
57
+ 'Usage: knolo exchange pull <offer-id> --from <peer> --config <exchange.json>'
58
+ );
59
+ const pulled = await pullExchangeOffer(config, {
60
+ offerId,
61
+ from: flags.from,
62
+ now,
63
+ ...(flags.home ? { homeDir: flags.home } : {}),
64
+ ...(flags.ttl === undefined ? {} : { ttlMs: Number(flags.ttl) }),
65
+ });
66
+ console.log(`cache: ${pulled.cachePath}`);
67
+ console.log(`sha256: ${pulled.sha256}`);
68
+ console.log(`stateRoot: ${pulled.stateRoot}`);
69
+ console.log(`receipt: ${pulled.receiptId}`);
70
+ return;
71
+ }
72
+ if (command === 'export') {
73
+ const imagePath = positional[0];
74
+ if (!imagePath || !flags.to || !flags.out)
75
+ throw new Error(
76
+ 'Usage: knolo exchange export <image.knolo> --to <peer> --out <dir> --config <exchange.json>'
77
+ );
78
+ const exported = await exportExchangeDirectory(config, {
79
+ imagePath,
80
+ to: flags.to,
81
+ outDir: flags.out,
82
+ now,
83
+ ...(flags.ttl === undefined ? {} : { ttlMs: Number(flags.ttl) }),
84
+ });
85
+ console.log(`directory: ${exported.directory}`);
86
+ console.log(`offer: ${exported.offerId}`);
87
+ console.log(`sha256: ${exported.sha256}`);
88
+ console.log(`stateRoot: ${exported.stateRoot}`);
89
+ return;
90
+ }
91
+ if (command === 'import') {
92
+ const directory = positional[0];
93
+ if (!directory)
94
+ throw new Error(
95
+ 'Usage: knolo exchange import <dir> --config <exchange.json>'
96
+ );
97
+ const imported = await importExchangeDirectory(config, {
98
+ directory,
99
+ now,
100
+ ...(flags.home ? { homeDir: flags.home } : {}),
101
+ });
102
+ console.log(`cache: ${imported.cachePath}`);
103
+ console.log(`sha256: ${imported.sha256}`);
104
+ console.log(`stateRoot: ${imported.stateRoot}`);
105
+ console.log(`receipt: ${imported.receiptId}`);
106
+ return;
107
+ }
108
+ if (command === 'adopt') {
109
+ const receiptId = positional[0];
110
+ if (!receiptId || !flags.store || !flags.home)
111
+ throw new Error(
112
+ 'Usage: knolo exchange adopt <receipt-id> --store <file> --home <dir> --config <exchange.json>'
113
+ );
114
+ const adopted = await adoptExchangeReceipt(config, {
115
+ receiptId,
116
+ storePath: flags.store,
117
+ homeDir: flags.home,
118
+ now,
119
+ });
120
+ console.log(`store: ${adopted.storePath}`);
121
+ console.log(`relation: ${adopted.relation}`);
122
+ console.log(`stateRoot: ${adopted.stateRoot}`);
123
+ return;
124
+ }
125
+ if (command === 'discover') {
126
+ const handle = positional[0];
127
+ if (!handle || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(handle))
128
+ throw new Error(
129
+ 'Usage: knolo exchange discover <handle> [--registry <url>]'
130
+ );
131
+ const registry = resolveRegistryUrl({ value: flags.registry });
132
+ const response = await fetch(
133
+ registryApiUrl(registry, ['publishers', handle])
134
+ );
135
+ if (!response.ok)
136
+ throw new Error(
137
+ `V5 exchange discover failed with status ${response.status}.`
138
+ );
139
+ const body = await response.json();
140
+ const exchange = body?.publisher?.exchange;
141
+ if (!Array.isArray(exchange) || exchange.length === 0)
142
+ throw new Error('V5 exchange advertisement is missing.');
143
+ for (const endpoint of exchange) {
144
+ console.log(`url: ${endpoint.url}`);
145
+ console.log(`keyId: ${endpoint.keyId}`);
146
+ console.log(`keyringRoot: ${endpoint.keyringRoot}`);
147
+ }
148
+ return;
149
+ }
150
+ if (command === 'inspect') {
151
+ const receiptId = positional[0];
152
+ if (!receiptId || !flags.home)
153
+ throw new Error(
154
+ 'Usage: knolo exchange inspect <receipt-id> --home <dir> [--config <exchange.json>]'
155
+ );
156
+ const receipt = await inspectExchangeReceipt(
157
+ flags.home,
158
+ receiptId,
159
+ config,
160
+ now
161
+ );
162
+ console.log(`role: ${receipt.role}`);
163
+ console.log(`offer: ${receipt.offerId}`);
164
+ console.log(`sha256: ${receipt.sha256}`);
165
+ console.log(`stateRoot: ${receipt.stateRoot}`);
166
+ console.log(`verification: ${receipt.verification}`);
167
+ console.log(`policy: ${receipt.policy}`);
168
+ return;
169
+ }
170
+ throw new Error(
171
+ 'Usage: knolo exchange <serve|offer|pull|export|import|adopt|discover|inspect>'
172
+ );
173
+ }
174
+
175
+ function readTruncateHook() {
176
+ const raw = process.env.KNOLO_EXCHANGE_TRUNCATE_AFTER;
177
+ if (raw === undefined || raw === '') return undefined;
178
+ const value = Number(raw);
179
+ if (!Number.isSafeInteger(value) || value < 1)
180
+ throw new Error('V5 exchange truncate hook is invalid.');
181
+ return value;
182
+ }
183
+
184
+ function parse(argv) {
185
+ const positional = [];
186
+ const flags = {};
187
+ for (let i = 0; i < argv.length; i += 1) {
188
+ const arg = argv[i];
189
+ if (
190
+ arg === '--config' ||
191
+ arg === '--to' ||
192
+ arg === '--from' ||
193
+ arg === '--home' ||
194
+ arg === '--ttl' ||
195
+ arg === '--now' ||
196
+ arg === '--out' ||
197
+ arg === '--store' ||
198
+ arg === '--registry'
199
+ ) {
200
+ flags[arg.slice(2)] = argv[++i];
201
+ } else if (arg.startsWith('--')) {
202
+ throw new Error(`Unknown flag for exchange: ${arg}`);
203
+ } else positional.push(arg);
204
+ }
205
+ return { command: positional[0], positional: positional.slice(1), flags };
206
+ }
package/bin/flight.mjs CHANGED
@@ -9,7 +9,7 @@ import { createHash } from 'node:crypto';
9
9
  import { createReadStream, existsSync, statSync, writeFileSync } from 'node:fs';
10
10
  import path from 'node:path';
11
11
  import { fileURLToPath, pathToFileURL } from 'node:url';
12
- import { readBounded } from './kar-limits.mjs';
12
+ import { KAR_CLI_MAX_IMAGE_BYTES, readBounded } from './kar-limits.mjs';
13
13
 
14
14
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
15
15
 
@@ -36,11 +36,16 @@ const KIND_FIELDS = {
36
36
  'scan-summary': ['phrase'],
37
37
  };
38
38
 
39
- const USAGE = `Usage: knolo flight ingest --events <events.json> --log <file> --out <image.knolo> [--json]
39
+ const USAGE = `Usage: knolo flight <ingest|verify-log> [options]
40
40
 
41
- Packs a flight-events-1 document into a V5 Knowledge Image.
42
- The command hashes --log and refuses the image when the hash or byte length differs.
43
- It does not decode a flight log. Parsing stays in an external producer.
41
+ knolo flight ingest --events <events.json> --log <file> --out <image.knolo> [--json]
42
+ knolo flight verify-log --image <image.knolo> --log <file> [--json]
43
+
44
+ ingest packs a flight-events-1 document into a V5 Knowledge Image.
45
+ It hashes --log and writes nothing when the hash or byte length differs.
46
+ verify-log hashes --log again and compares it with the flight-log object.
47
+ It writes nothing. A missing flight-log object fails closed.
48
+ Neither command decodes the log. Parsing stays in an external producer.
44
49
  A later KAR status of SATISFIED means evidence requirements were met.
45
50
  It does not mean a flight was safe, legal, or compliant.`;
46
51
 
@@ -51,6 +56,7 @@ export async function runFlightCli(argv) {
51
56
  console.log(USAGE);
52
57
  return;
53
58
  }
59
+ if (sub === 'verify-log') return verifyFlightLog(flags);
54
60
  if (sub !== 'ingest') throw new Error(`Unknown flight command "${sub}".\n${USAGE}`);
55
61
  const eventsPath = required(flags, 'events');
56
62
  const logPath = required(flags, 'log');
@@ -76,6 +82,57 @@ export async function runFlightCli(argv) {
76
82
  console.log(`FLIGHT IMAGE\nstate root ${image.stateRoot}\nevents ${document.events.length}\nwrote ${outPath}\n\nEvidence requirements are not a safety or compliance determination.`);
77
83
  }
78
84
 
85
+ async function verifyFlightLog(flags) {
86
+ const imagePath = required(flags, 'image');
87
+ const logPath = required(flags, 'log');
88
+ const stored = await readFlightLogBinding(imagePath);
89
+ const log = await inspectLog(logPath);
90
+ if (log.byteLength !== stored.byteLength || log.sha256 !== stored.sha256) {
91
+ throw new Error('FLIGHT_LOG_MISMATCH: log bytes do not match the flight-log object.');
92
+ }
93
+ if (flags.json) {
94
+ console.log(JSON.stringify({
95
+ ok: true,
96
+ stateRoot: stored.stateRoot,
97
+ logSha256: stored.sha256,
98
+ byteLength: stored.byteLength,
99
+ }, null, 2));
100
+ return;
101
+ }
102
+ console.log(`FLIGHT LOG VERIFIED\nstate root ${stored.stateRoot}\nlog ${stored.sha256}\nbytes ${stored.byteLength}\n\nEvidence requirements are not a safety or compliance determination.`);
103
+ }
104
+
105
+ async function readFlightLogBinding(imagePath) {
106
+ const bytes = readBounded(imagePath, KAR_CLI_MAX_IMAGE_BYTES);
107
+ const api = await loadImageApi();
108
+ if (!api.mountKnowledgeImageV5) throw new Error('Could not load @knolo/core. Build packages/core first.');
109
+ let image;
110
+ try {
111
+ image = api.mountKnowledgeImageV5(bytes);
112
+ } catch (error) {
113
+ const message = error instanceof Error ? error.message : String(error);
114
+ throw new Error(`FLIGHT_EVENTS_INVALID: ${message}`);
115
+ }
116
+ const logs = image.objects.filter((object) => object.meta && object.meta.role === 'flight-log');
117
+ if (logs.length !== 1) {
118
+ throw new Error('FLIGHT_EVENTS_INVALID: image must contain one flight-log object.');
119
+ }
120
+ const sha256 = logs[0].meta.logSha256;
121
+ const rawLength = logs[0].meta.byteLength;
122
+ const byteLength = typeof rawLength === 'number' ? rawLength : Number(rawLength);
123
+ const lengthText = typeof rawLength === 'string' ? rawLength : String(rawLength);
124
+ if (
125
+ typeof sha256 !== 'string' ||
126
+ !DIGEST.test(sha256) ||
127
+ !Number.isSafeInteger(byteLength) ||
128
+ byteLength < 0 ||
129
+ lengthText !== String(byteLength)
130
+ ) {
131
+ throw new Error('FLIGHT_EVENTS_INVALID: flight-log metadata is not a sha256 and byte length.');
132
+ }
133
+ return { sha256, byteLength, stateRoot: image.stateRoot };
134
+ }
135
+
79
136
  export function readEvents(file) {
80
137
  const resolved = path.resolve(process.cwd(), file);
81
138
  const stat = statSync(resolved);
package/bin/knolo.mjs CHANGED
@@ -80,6 +80,8 @@ const SUBCOMMANDS = new Set([
80
80
  'flight',
81
81
  'skill',
82
82
  'setup',
83
+ 'exchange',
84
+ 'research',
83
85
  ]);
84
86
  const ICP_SUBCOMMANDS = new Set([
85
87
  'init',
@@ -180,7 +182,9 @@ Commands:
180
182
  cortex Bounded evidence retrieval with a verifiable trace
181
183
  flight Pack a flight-events-1 document into a V5 Knowledge Image
182
184
  skill Create and share a Knolo skill pack
185
+ research Package local research files into a V5 Knowledge Image
183
186
  setup Prepare a local index and print the hub next steps
187
+ exchange Offer or pull a verified Knowledge Image from a peer
184
188
  icp Scaffold and operate an ICP-native knowledge canister
185
189
 
186
190
  Global options:
@@ -196,7 +200,7 @@ function printCommandHelp(command) {
196
200
  init: 'Usage: knolo init',
197
201
  add: 'Usage: knolo add <name> <path> | <publisher>/<slug>[@<version>] [--out <path>] [--force] [--json] [--registry <url>]',
198
202
  search:
199
- 'Usage: knolo search <query> [--format V4|V5] [--license <id>] [--official] [--agents] [--json] [--registry <url>]',
203
+ 'Usage: knolo search <query> [--format V4|V5] [--license <id>] [--official] [--agents] [--research] [--json] [--registry <url>]',
200
204
  info: 'Usage: knolo info <publisher>/<slug> [--json] [--registry <url>]',
201
205
  login:
202
206
  'Usage: knolo login [--token kno_…] [--stdin] [--registry <url>]\n\nStores the raw token locally. Hub write calls send Authorization: Bearer kno_….\nMint tokens at https://hub.knolo.dev/dashboard/tokens; login does not call POST /api/v1/tokens.',
@@ -220,7 +224,9 @@ function printCommandHelp(command) {
220
224
  compose: 'Usage: knolo compose <create|verify|excerpt|query> [options]\n\nOffline composition of Knowledge Images, packs, KAR sidecars, Domain Packs, and bounded excerpts.\n\n knolo compose create --members members.json --out composition/ [--host knowledge.knolo] [--availability material|digest] [--policy policy.json]\n knolo compose verify composition/ [--require-material] [--member alias=path]\n knolo compose excerpt --image knowledge.knolo --object <id> --out excerpt.json\n knolo compose query --composition composition/ --eql "FROM chunk SEARCH \\"valve\\"" [--question "..."] [--json]\n\ncompositionRoot does not change a V5 state root or a KAR root. statement used means a query or evaluation ran. It does not mean SATISFIED, and it does not mean a claim is true or false. Hub attested: true is a listing flag and is not an attestation root. The CLI does not fetch Hub.',
221
225
  attest: 'Usage: knolo attest <create|verify> [options]\n\n knolo attest create --composition composition/composition.json --subject composition --statement mount|used|cited --out attestation.json [--sign-key key.json --principal <id> --key-id <id> --issued-at <ms> --expires-at <ms>]\n knolo attest verify attestation.json [--composition composition.json] [--public-key key.json] [--now <ms>] [--content-only]\n\nstatement used means a query or KAR evaluation ran. It does not mean the claim is true or false. Hub attested: true is unrelated. Signing uses the supplied times. The CLI does not read the clock.',
222
226
  cortex: 'Usage: knolo cortex <find|ask|explain|verify> [options]\n\nBounded evidence retrieval. The CLI does not call a model.\n\n knolo cortex find <image> --question "..." [--top-k 100] --out candidates.json\n knolo cortex ask <image> --question "..." [--graph file] [--plan plan.json] [--mode find_relevant] --out answer.cortex.json\n knolo cortex explain answer.cortex.json\n knolo cortex verify --image <image> --answer answer.cortex.json [--graph file]\n\nVerification recomputes the trace roots. It does not mean the answer is true. A KAR status of SATISFIED means evidence requirements were met. It does not mean a claim is proven.',
223
- flight: 'Usage: knolo flight ingest --events <events.json> --log <file> --out <image.knolo> [--json]\n\nPacks a flight-events-1 document into a V5 Knowledge Image. The command hashes --log and writes nothing when the hash or byte length differs. It does not decode the log. log.format is ulog, dataflash, or rosbag2. A later KAR status of SATISFIED means evidence requirements were met. It does not mean a flight was safe, legal, or compliant.',
227
+ research:
228
+ 'Usage: knolo research package --question <text> --agent <id> --out <image.knolo> --source <file> [--source <file>] [--cite <image.knolo> --trace <answer.cortex.json> [--graph <file>]] [--json]\n\nPacks local files into one V5 Knowledge Image. --agent is the host-supplied caller. --cite and --trace are both required or both omitted. --graph is required when the trace contains KAR evaluations, and it is the same file knolo cortex verify would use. A trace is verified against --cite before any write. A failed check writes nothing. When --cite is set, the image stores a digest-bound composition record for that image and does not copy its bytes. When --graph is set, the checked graph is stored. The command does not call a model and does not download an image. A packed trace is an integrity check. It does not mean a claim is proven. SATISFIED means the trace evidence requirements were met.',
229
+ flight: 'Usage: knolo flight <ingest|verify-log> [options]\n\n knolo flight ingest --events <events.json> --log <file> --out <image.knolo> [--json]\n knolo flight verify-log --image <image.knolo> --log <file> [--json]\n\ningest packs a flight-events-1 document into a V5 Knowledge Image. It hashes --log and writes nothing when the hash or byte length differs. verify-log hashes --log again and compares it with the flight-log object. It writes nothing. A missing flight-log object fails closed. Neither command decodes the log. log.format is ulog, dataflash, or rosbag2. A later KAR status of SATISFIED means evidence requirements were met. It does not mean a flight was safe, legal, or compliant.',
224
230
  setup: `Usage: knolo setup [--registry <url>] [--root <dir>] [--agent <id>] [--auto-rebuild] [--reset] [--skills <path>] [--managed-skills <path>] [--memory <path>] [--transcripts <path>]
225
231
 
226
232
  Resolves the hub the same way as the other hub commands.
@@ -235,6 +241,23 @@ Pass --agent to set the caller name. Pass --auto-rebuild to rebuild on the next
235
241
  Does not prompt. Does not install a pack or call the hub.
236
242
  A missing knolo-box is printed, and setup still exits 0.
237
243
  When more than one skill folder matches, pass --skills or --managed-skills.`,
244
+ exchange: `Usage: knolo exchange <serve|offer|pull|export|import|adopt|discover|inspect> --config <exchange.json>
245
+
246
+ knolo exchange serve --config exchange.json
247
+ knolo exchange offer <image.knolo> --to <peer> --config exchange.json
248
+ knolo exchange pull <offer-id> --from <peer> --config exchange.json
249
+ knolo exchange export <image.knolo> --to <peer> --out <dir> --config exchange.json
250
+ knolo exchange import <dir> --config exchange.json
251
+ knolo exchange adopt <receipt-id> --store <file> --home <dir> --config exchange.json
252
+ knolo exchange discover <handle> [--registry <url>]
253
+ knolo exchange inspect <receipt-id> --home <dir> [--config exchange.json]
254
+
255
+ Pull, export, and import do not call Knolo Hub and do not write knolo.lock.json.
256
+ export writes offer.cbor and the image into a directory. import reads that
257
+ directory. Receiving an image verifies SHA-256 and the V5 state root. It does
258
+ not mount the image into a store or activate a skill. adopt opens a local
259
+ store only when policy.adopt is allow. discover reads a public publisher
260
+ advertisement and does not download pack bytes.`,
238
261
  skill: `Usage: knolo skill <init|check|pack|publish|install|search|info|list>
239
262
 
240
263
  knolo skill init <name> [--dir <parent>]
@@ -1919,10 +1942,18 @@ async function main() {
1919
1942
  const { runFlightCli } = await import('./flight.mjs');
1920
1943
  return await runFlightCli(commandArgs);
1921
1944
  }
1945
+ if (command === 'research') {
1946
+ const { runResearchCli } = await import('./research.mjs');
1947
+ return await runResearchCli(commandArgs);
1948
+ }
1922
1949
  if (command === 'skill') {
1923
1950
  const { runSkillCli } = await import('./skill.mjs');
1924
1951
  return await runSkillCli(commandArgs);
1925
1952
  }
1953
+ if (command === 'exchange') {
1954
+ const { runExchangeCli } = await import('./exchange.mjs');
1955
+ return await runExchangeCli(commandArgs);
1956
+ }
1926
1957
  if (command === 'setup') {
1927
1958
  const { runKnoloSetup } = await import('./setup.mjs');
1928
1959
  return await runKnoloSetup(commandArgs);
@@ -62,6 +62,7 @@ export async function runHubSearch(
62
62
  license: flags.license,
63
63
  official: flags.official ? 'true' : undefined,
64
64
  agents: flags.agents ? 'true' : undefined,
65
+ research: flags.research ? 'true' : undefined,
65
66
  });
66
67
  const body = await getJson(url, { fetchImpl });
67
68
  validatePacksResponse(body);
@@ -961,7 +962,7 @@ export function parseSearchArgs(args) {
961
962
  const flags = {};
962
963
  for (let i = 0; i < args.length; i++) {
963
964
  const arg = args[i];
964
- if (arg === '--json' || arg === '--official' || arg === '--agents') {
965
+ if (arg === '--json' || arg === '--official' || arg === '--agents' || arg === '--research') {
965
966
  flags[arg.slice(2)] = true;
966
967
  continue;
967
968
  }
@@ -980,7 +981,7 @@ export function parseSearchArgs(args) {
980
981
  const query = positional.join(' ').trim();
981
982
  if (!query)
982
983
  throw new Error(
983
- 'Usage: knolo search <query> [--format V4|V5] [--license <id>] [--official] [--agents] [--json] [--registry <url>]'
984
+ 'Usage: knolo search <query> [--format V4|V5] [--license <id>] [--official] [--agents] [--research] [--json] [--registry <url>]'
984
985
  );
985
986
  if (
986
987
  flags.format &&
@@ -0,0 +1,325 @@
1
+ /**
2
+ * knolo research package
3
+ *
4
+ * Packs local research files into one V5 Knowledge Image.
5
+ * It does not call a model, open a network connection, or download an image.
6
+ * A packed Cortex trace is an integrity check. It does not mean a claim is proven.
7
+ */
8
+ import { createHash } from 'node:crypto';
9
+ import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { fileURLToPath, pathToFileURL } from 'node:url';
12
+ import {
13
+ KAR_CLI_MAX_IMAGE_BYTES,
14
+ KAR_CLI_MAX_TEXT_BYTES,
15
+ readBounded,
16
+ } from './kar-limits.mjs';
17
+
18
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
19
+ const ACTOR = 'knolo-research';
20
+ const AGENT = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
21
+
22
+ const USAGE = `Usage: knolo research package --question <text> --agent <id> --out <image.knolo> --source <file> [--source <file>] [--cite <image.knolo> --trace <answer.cortex.json> [--graph <file>]] [--json]
23
+
24
+ Packs local files into one V5 Knowledge Image. --agent is the host-supplied caller.
25
+ --cite and --trace are both required or both omitted. --graph is required when the
26
+ trace contains KAR evaluations, and it is the same file knolo cortex verify would use.
27
+ A trace is verified against --cite before any write. A failed check writes nothing.
28
+ When --cite is set, the image stores a digest-bound composition record for that
29
+ image and does not copy its bytes. When --graph is set, the checked graph is stored.
30
+ The command does not call a model and does not download an image.
31
+ A packed trace is an integrity check. It does not mean a claim is proven.
32
+ SATISFIED means the trace evidence requirements were met.`;
33
+
34
+ export async function runResearchCli(argv) {
35
+ if (
36
+ argv.length === 0 ||
37
+ argv[0] === 'help' ||
38
+ argv[0] === '--help' ||
39
+ argv[0] === '-h'
40
+ ) {
41
+ console.log(USAGE);
42
+ return;
43
+ }
44
+ if (argv[0] !== 'package') {
45
+ throw new Error(`Unknown research command "${argv[0]}".\n${USAGE}`);
46
+ }
47
+ const flags = parseFlags(argv.slice(1));
48
+ if (flags.help) {
49
+ console.log(USAGE);
50
+ return;
51
+ }
52
+ await packageResearch(flags);
53
+ }
54
+
55
+ async function packageResearch(flags) {
56
+ const question = required(flags.question, '--question');
57
+ const agent = required(flags.agent, '--agent');
58
+ const outPath = required(flags.out, '--out');
59
+ if (!AGENT.test(agent)) {
60
+ throw new Error('RESEARCH_PACK_INVALID: --agent must be a short token.');
61
+ }
62
+ const questionBytes = Buffer.from(question, 'utf8');
63
+ if (
64
+ questionBytes.length === 0 ||
65
+ questionBytes.length > KAR_CLI_MAX_TEXT_BYTES
66
+ ) {
67
+ throw new Error('RESEARCH_PACK_INVALID: --question is empty or too large.');
68
+ }
69
+ if (flags.sources.length === 0) {
70
+ throw new Error('RESEARCH_PACK_INVALID: pass at least one --source.');
71
+ }
72
+ const cite = flags.cite ?? '';
73
+ const tracePath = flags.trace ?? '';
74
+ if (Boolean(cite) !== Boolean(tracePath)) {
75
+ throw new Error('RESEARCH_PACK_INVALID: pass --cite and --trace together.');
76
+ }
77
+ if (flags.graph && !tracePath) {
78
+ throw new Error(
79
+ 'RESEARCH_PACK_INVALID: --graph requires --cite and --trace.'
80
+ );
81
+ }
82
+ const resolvedOut = path.resolve(process.cwd(), outPath);
83
+ if (existsSync(resolvedOut))
84
+ throw new Error(`Refusing to overwrite ${outPath}`);
85
+
86
+ const names = new Set();
87
+ const sources = [];
88
+ for (const file of flags.sources) {
89
+ const source = path.basename(file);
90
+ if (!source || source === '.' || source === '..' || names.has(source)) {
91
+ throw new Error(
92
+ `RESEARCH_PACK_INVALID: --source basename "${source}" is missing or repeated.`
93
+ );
94
+ }
95
+ names.add(source);
96
+ const bytes = readBounded(file, KAR_CLI_MAX_TEXT_BYTES);
97
+ sources.push({
98
+ source,
99
+ bytes,
100
+ sha256: digest(bytes),
101
+ });
102
+ }
103
+
104
+ const apis = await loadApis();
105
+ let trace = null;
106
+ if (tracePath) {
107
+ const citeBytes = readBounded(cite, KAR_CLI_MAX_IMAGE_BYTES);
108
+ const cited = apis.core.mountKnowledgeImageV5(citeBytes);
109
+ const traceBytes = readBounded(tracePath, KAR_CLI_MAX_TEXT_BYTES);
110
+ const parsed = JSON.parse(new TextDecoder().decode(traceBytes));
111
+ const graphBytes = flags.graph
112
+ ? readBounded(flags.graph, KAR_CLI_MAX_TEXT_BYTES)
113
+ : undefined;
114
+ const graph =
115
+ graphBytes === undefined
116
+ ? undefined
117
+ : JSON.parse(new TextDecoder().decode(graphBytes));
118
+ const verified = await apis.cortex.verifyCortexAnswer({
119
+ image: new Uint8Array(citeBytes),
120
+ question: typeof parsed.question === 'string' ? parsed.question : '',
121
+ result: parsed,
122
+ ...(graph === undefined ? {} : { graph }),
123
+ });
124
+ if (!verified.ok) throw new Error(`${verified.code}: ${verified.message}`);
125
+ const composition = compositionForCite(apis.composition, {
126
+ cited,
127
+ citeBytes,
128
+ traceRoot: verified.traceRoot,
129
+ });
130
+ trace = {
131
+ bytes: traceBytes,
132
+ traceRoot: verified.traceRoot,
133
+ citedStateRoot: cited.stateRoot,
134
+ composition,
135
+ graphBytes,
136
+ };
137
+ }
138
+
139
+ const objects = [
140
+ {
141
+ kind: 'metadata',
142
+ bytes: questionBytes,
143
+ meta: { role: 'research-pack', agent },
144
+ },
145
+ ...sources.map((source) => ({
146
+ kind: 'chunk',
147
+ bytes: source.bytes,
148
+ meta: { source: source.source, sha256: source.sha256 },
149
+ })),
150
+ ];
151
+ if (trace) {
152
+ objects.push({
153
+ kind: 'metadata',
154
+ bytes: trace.bytes,
155
+ meta: {
156
+ role: 'cortex-trace',
157
+ traceRoot: trace.traceRoot,
158
+ citedStateRoot: trace.citedStateRoot,
159
+ },
160
+ });
161
+ objects.push({
162
+ kind: 'metadata',
163
+ bytes: Buffer.from(trace.composition.text),
164
+ meta: {
165
+ role: 'composition',
166
+ compositionRoot: trace.composition.compositionRoot,
167
+ citedStateRoot: trace.citedStateRoot,
168
+ traceRoot: trace.traceRoot,
169
+ },
170
+ });
171
+ if (trace.graphBytes) {
172
+ objects.push({
173
+ kind: 'metadata',
174
+ bytes: trace.graphBytes,
175
+ meta: { role: 'kar-graph' },
176
+ });
177
+ }
178
+ }
179
+ const image = apis.core.createKnowledgeImageV5({
180
+ actor: ACTOR,
181
+ sequence: 1,
182
+ objects,
183
+ });
184
+ writeNewFile(resolvedOut, outPath, Buffer.from(image.bytes));
185
+ if (flags.json) {
186
+ console.log(
187
+ JSON.stringify(
188
+ {
189
+ ok: true,
190
+ stateRoot: image.stateRoot,
191
+ sources: sources.length,
192
+ traceRoot: trace ? trace.traceRoot : null,
193
+ },
194
+ null,
195
+ 2
196
+ )
197
+ );
198
+ return;
199
+ }
200
+ console.log(
201
+ `RESEARCH PACK\nstate root ${image.stateRoot}\nsources ${sources.length}\ntrace ${trace ? trace.traceRoot : 'none'}\nwrote ${outPath}\n\nA packed trace is an integrity check. It does not mean a claim is proven.\nSATISFIED means evidence requirements were met.`
202
+ );
203
+ }
204
+
205
+ function writeNewFile(resolved, display, bytes) {
206
+ try {
207
+ writeFileSync(resolved, bytes, { flag: 'wx' });
208
+ } catch (error) {
209
+ if (error && error.code === 'EEXIST') {
210
+ throw new Error(`Refusing to overwrite ${display}`);
211
+ }
212
+ try {
213
+ unlinkSync(resolved);
214
+ } catch {
215
+ // The original write error is the one to surface.
216
+ }
217
+ throw error;
218
+ }
219
+ }
220
+
221
+ function compositionForCite(composition, input) {
222
+ let created;
223
+ try {
224
+ created = composition.createCompositionRecord({
225
+ host: { kind: 'none' },
226
+ availability: 'digest',
227
+ members: [
228
+ {
229
+ alias: 'cite',
230
+ kind: 'v5-image',
231
+ stateRoot: input.cited.stateRoot,
232
+ objectRoot: input.cited.commit.objectRoot,
233
+ commitDigest: input.cited.commitDigest,
234
+ sha256: digest(input.citeBytes),
235
+ },
236
+ ],
237
+ });
238
+ } catch (error) {
239
+ const code = error && error.code ? error.code : 'COMPOSITION_INVALID';
240
+ throw new Error(`${code}: ${error.message}`);
241
+ }
242
+ const verdict = composition.verifyCompositionRecord(created.record);
243
+ if (!verdict.ok) {
244
+ throw new Error(`${verdict.code}: composition check failed.`);
245
+ }
246
+ return {
247
+ compositionRoot: created.compositionRoot,
248
+ text: JSON.stringify(created.record),
249
+ };
250
+ }
251
+
252
+ function digest(bytes) {
253
+ return `sha256-${createHash('sha256').update(bytes).digest('hex')}`;
254
+ }
255
+
256
+ function required(value, flag) {
257
+ if (typeof value !== 'string' || value.length === 0) {
258
+ throw new Error(`RESEARCH_PACK_INVALID: ${flag} is required.`);
259
+ }
260
+ return value;
261
+ }
262
+
263
+ async function loadApis() {
264
+ const dist = path.resolve(__dirname, '../../core/dist');
265
+ const core = await importFirst(
266
+ [path.join(dist, 'index.js'), '@knolo/core'],
267
+ (loaded) => loaded.createKnowledgeImageV5 && loaded.mountKnowledgeImageV5
268
+ );
269
+ const cortex = await importFirst(
270
+ [path.join(dist, 'cortex/index.js'), '@knolo/core/cortex'],
271
+ (loaded) => loaded.verifyCortexAnswer
272
+ );
273
+ const composition = await importFirst(
274
+ [path.join(dist, 'composition/index.js'), '@knolo/core/composition'],
275
+ (loaded) => loaded.createCompositionRecord && loaded.verifyCompositionRecord
276
+ );
277
+ return { core, cortex, composition };
278
+ }
279
+
280
+ async function importFirst(candidates, check) {
281
+ for (const candidate of candidates) {
282
+ try {
283
+ const href = candidate.startsWith('@')
284
+ ? candidate
285
+ : pathToFileURL(candidate).href;
286
+ const loaded = await import(href);
287
+ if (check(loaded)) return loaded;
288
+ } catch {
289
+ // Try the next candidate.
290
+ }
291
+ }
292
+ throw new Error('Could not load @knolo/core. Build packages/core first.');
293
+ }
294
+
295
+ function parseFlags(argv) {
296
+ const flags = { sources: [], help: false, json: false };
297
+ for (let index = 0; index < argv.length; index += 1) {
298
+ const arg = argv[index];
299
+ if (arg === '--help' || arg === '-h') {
300
+ flags.help = true;
301
+ continue;
302
+ }
303
+ if (arg === '--json') {
304
+ flags.json = true;
305
+ continue;
306
+ }
307
+ if (!arg.startsWith('--'))
308
+ throw new Error(`Unexpected argument "${arg}".\n${USAGE}`);
309
+ const key = arg.slice(2);
310
+ const value = argv[index + 1];
311
+ if (value === undefined || value.startsWith('--')) {
312
+ throw new Error(`Missing value for --${key}`);
313
+ }
314
+ index += 1;
315
+ if (key === 'source') flags.sources.push(value);
316
+ else if (key === 'question') flags.question = value;
317
+ else if (key === 'agent') flags.agent = value;
318
+ else if (key === 'out') flags.out = value;
319
+ else if (key === 'cite') flags.cite = value;
320
+ else if (key === 'trace') flags.trace = value;
321
+ else if (key === 'graph') flags.graph = value;
322
+ else throw new Error(`Unknown option --${key}.\n${USAGE}`);
323
+ }
324
+ return flags;
325
+ }
package/bin/skill.mjs CHANGED
@@ -879,30 +879,48 @@ function sha256(bytes) {
879
879
  return createHash('sha256').update(bytes).digest('hex');
880
880
  }
881
881
 
882
+ function coreLoadDetail(error) {
883
+ if (!error) return 'module did not export the Knowledge Image API';
884
+ const code = error.code ? `${error.code}: ` : '';
885
+ const cause = error.cause ? `; ${coreLoadDetail(error.cause)}` : '';
886
+ return `${code}${error.message}${cause}`;
887
+ }
888
+
889
+ function coreModuleReady(loaded) {
890
+ return Boolean(
891
+ loaded?.createKnowledgeImageV5 &&
892
+ loaded.queryKnowledgeImageV5 &&
893
+ loaded.mountKnowledgeImageV5 &&
894
+ loaded.knowledgePolicyRootV5
895
+ );
896
+ }
897
+
882
898
  async function loadCore() {
883
- const candidates = [
884
- path.resolve(__dirname, '../../core/dist/index.js'),
885
- '@knolo/core',
886
- ];
887
- for (const candidate of candidates) {
888
- try {
889
- const href = candidate.startsWith('@')
890
- ? candidate
891
- : pathToFileURL(candidate).href;
892
- const loaded = await import(href);
893
- if (
894
- loaded.createKnowledgeImageV5 &&
895
- loaded.queryKnowledgeImageV5 &&
896
- loaded.mountKnowledgeImageV5 &&
897
- loaded.knowledgePolicyRootV5
898
- ) {
899
- return loaded;
899
+ const fileHref = pathToFileURL(
900
+ path.resolve(__dirname, '../../core/dist/index.js')
901
+ ).href;
902
+ let lastError = null;
903
+ // A failed ESM import stays cached for that exact URL. A later attempt uses
904
+ // a new file URL so a transient open does not stick for the process.
905
+ for (let attempt = 0; attempt < 3; attempt += 1) {
906
+ const fileUrl =
907
+ attempt === 0 ? fileHref : `${fileHref}?knolo-load=${attempt}`;
908
+ for (const specifier of [fileUrl, '@knolo/core']) {
909
+ try {
910
+ const loaded = await import(specifier);
911
+ if (coreModuleReady(loaded)) return loaded;
912
+ lastError = new Error('module did not export the Knowledge Image API');
913
+ } catch (error) {
914
+ lastError = error;
900
915
  }
901
- } catch {
902
- // Try the next candidate.
916
+ }
917
+ if (attempt < 2) {
918
+ await new Promise((resolve) => setTimeout(resolve, 25 * (attempt + 1)));
903
919
  }
904
920
  }
905
- throw new Error('Could not load @knolo/core. Build packages/core first.');
921
+ throw new Error(
922
+ `Could not load @knolo/core. Build packages/core first. (${coreLoadDetail(lastError)})`
923
+ );
906
924
  }
907
925
 
908
926
  const SKILL_ARCHIVE_FORMAT = 'knolo-skill-archive-v1';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@knolo/cli",
3
- "version": "6.2.3",
3
+ "version": "6.2.5",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "knolo": "bin/knolo.mjs"
@@ -9,7 +9,7 @@
9
9
  "bin/",
10
10
  "templates/"
11
11
  ],
12
- "description": "CLI for Knolo V4 packs, V5 Knowledge Images, KAR evidence-set retrieval, and offline composition.",
12
+ "description": "Publish, pin, and install shared Knolo knowledge, including Hub packs and skills.",
13
13
  "license": "Apache-2.0",
14
14
  "repository": {
15
15
  "type": "git",
@@ -28,11 +28,12 @@
28
28
  },
29
29
  "scripts": {
30
30
  "build": "node -e \"console.log('cli is executable via bin/knolo.mjs')\"",
31
- "test": "npm run build --prefix ../core && node --test test/cli.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/setup.test.mjs",
31
+ "test": "npm run build --prefix ../core && npm run build --prefix ../exchange && node --test test/cli.test.mjs test/kar.test.mjs test/kar-graph.test.mjs test/kar-produce.test.mjs test/hub.integration.test.mjs test/compose.test.mjs test/cortex.test.mjs test/flight.test.mjs test/skill.test.mjs test/setup.test.mjs test/exchange.test.mjs test/research.test.mjs",
32
32
  "test:hub": "node --test test/hub.integration.test.mjs"
33
33
  },
34
34
  "dependencies": {
35
- "@knolo/core": "^6.2.0"
35
+ "@knolo/core": "^6.2.0",
36
+ "@knolo/exchange": "^0.1.0"
36
37
  },
37
38
  "private": false
38
39
  }