@knolo/cli 6.2.4 → 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
@@ -35,8 +35,10 @@ model and does not take an API key. A verified trace matches the image. It
35
35
  does not mean the answer is true.
36
36
 
37
37
  `knolo flight ingest` packs a `flight-events-1` document into a V5 Knowledge
38
- Image and binds it to the SHA-256 of one log file. It does not decode the log.
39
- `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
40
42
  `scripts/flight/` and are not part of `npm test`. `SATISFIED` on a later KAR
41
43
  check means the evidence requirements were met. It does not mean a flight was
42
44
  safe, legal, or compliant. See `docs/flight/README.md`.
@@ -46,6 +48,16 @@ a model. A receipt is an integrity check. It does not mean a claim is proven.
46
48
  `SATISFIED` means the evidence requirements were met. See
47
49
  [Skills](../../docs/skills/README.md).
48
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
+
49
61
  The official CLI for building `.knolo` knowledge packs.
50
62
 
51
63
  It indexes structured content and produces a deterministic, local-first knowledge bundle for use with `@knolo/core`.
@@ -73,9 +85,13 @@ changing the local pack workflow:
73
85
 
74
86
  ```bash
75
87
  knolo search "refund policy"
88
+ knolo search "refund policy" --research
76
89
  knolo info acme/refund-policy
77
90
  ```
78
91
 
92
+ `--research` asks for packs whose image metadata role is `research-pack`.
93
+ `--agents` remains the agent-definition namespace.
94
+
79
95
  The production registry is `https://hub.knolo.dev`. Use `--registry` for a
80
96
  one-off override, or set `KNOLO_HUB_URL` for the current environment:
81
97
 
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
@@ -81,6 +81,7 @@ const SUBCOMMANDS = new Set([
81
81
  'skill',
82
82
  'setup',
83
83
  'exchange',
84
+ 'research',
84
85
  ]);
85
86
  const ICP_SUBCOMMANDS = new Set([
86
87
  'init',
@@ -181,6 +182,7 @@ Commands:
181
182
  cortex Bounded evidence retrieval with a verifiable trace
182
183
  flight Pack a flight-events-1 document into a V5 Knowledge Image
183
184
  skill Create and share a Knolo skill pack
185
+ research Package local research files into a V5 Knowledge Image
184
186
  setup Prepare a local index and print the hub next steps
185
187
  exchange Offer or pull a verified Knowledge Image from a peer
186
188
  icp Scaffold and operate an ICP-native knowledge canister
@@ -198,7 +200,7 @@ function printCommandHelp(command) {
198
200
  init: 'Usage: knolo init',
199
201
  add: 'Usage: knolo add <name> <path> | <publisher>/<slug>[@<version>] [--out <path>] [--force] [--json] [--registry <url>]',
200
202
  search:
201
- '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>]',
202
204
  info: 'Usage: knolo info <publisher>/<slug> [--json] [--registry <url>]',
203
205
  login:
204
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.',
@@ -222,7 +224,9 @@ function printCommandHelp(command) {
222
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.',
223
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.',
224
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.',
225
- 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.',
226
230
  setup: `Usage: knolo setup [--registry <url>] [--root <dir>] [--agent <id>] [--auto-rebuild] [--reset] [--skills <path>] [--managed-skills <path>] [--memory <path>] [--transcripts <path>]
227
231
 
228
232
  Resolves the hub the same way as the other hub commands.
@@ -1938,6 +1942,10 @@ async function main() {
1938
1942
  const { runFlightCli } = await import('./flight.mjs');
1939
1943
  return await runFlightCli(commandArgs);
1940
1944
  }
1945
+ if (command === 'research') {
1946
+ const { runResearchCli } = await import('./research.mjs');
1947
+ return await runResearchCli(commandArgs);
1948
+ }
1941
1949
  if (command === 'skill') {
1942
1950
  const { runSkillCli } = await import('./skill.mjs');
1943
1951
  return await runSkillCli(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.4",
3
+ "version": "6.2.5",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "knolo": "bin/knolo.mjs"
@@ -28,7 +28,7 @@
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 && 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",
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": {