@knolo/cli 6.2.4 → 6.2.6

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,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.6",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "knolo": "bin/knolo.mjs"
@@ -28,11 +28,11 @@
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 test/kite.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.3",
36
36
  "@knolo/exchange": "^0.1.0"
37
37
  },
38
38
  "private": false
@@ -4,7 +4,7 @@
4
4
  mod closure;
5
5
  mod cover;
6
6
  mod evaluate;
7
- mod json;
7
+ pub(crate) mod json;
8
8
  mod model;
9
9
  mod session;
10
10