@astrokjs/okf 0.0.0-stage → 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE +9 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +9 -0
  4. package/README.md +57 -2
  5. package/dist/graph/compiler.d.ts +14 -0
  6. package/dist/graph/compiler.js +75 -0
  7. package/dist/graph/files.d.ts +7 -0
  8. package/dist/graph/files.js +102 -0
  9. package/dist/graph/index.d.ts +9 -0
  10. package/dist/graph/index.js +7 -0
  11. package/dist/graph/memory.d.ts +41 -0
  12. package/dist/graph/memory.js +144 -0
  13. package/dist/graph/metadata.d.ts +3 -0
  14. package/dist/graph/metadata.js +16 -0
  15. package/dist/graph/model.d.ts +88 -0
  16. package/dist/graph/model.js +18 -0
  17. package/dist/graph/project.d.ts +3 -0
  18. package/dist/graph/project.js +242 -0
  19. package/dist/graph/publish.d.ts +38 -0
  20. package/dist/graph/publish.js +56 -0
  21. package/dist/graph/query-core.d.ts +72 -0
  22. package/dist/graph/query-core.js +124 -0
  23. package/dist/graph/query-guide.d.ts +4 -0
  24. package/dist/graph/query-guide.js +35 -0
  25. package/dist/graph/query-reference.d.ts +4 -0
  26. package/dist/graph/query-reference.js +99 -0
  27. package/dist/graph/query.d.ts +59 -0
  28. package/dist/graph/query.js +191 -0
  29. package/dist/graph/schema.d.ts +5 -0
  30. package/dist/graph/schema.js +86 -0
  31. package/dist/graph/snapshot.d.ts +9 -0
  32. package/dist/graph/snapshot.js +115 -0
  33. package/dist/graph/sqlite-guide.d.ts +2 -0
  34. package/dist/graph/sqlite-guide.js +123 -0
  35. package/dist/graph/sqlite.d.ts +4 -0
  36. package/dist/graph/sqlite.js +4 -0
  37. package/dist/graph/version.d.ts +7 -0
  38. package/dist/graph/version.js +7 -0
  39. package/dist/graph/wasm.d.ts +23 -0
  40. package/dist/graph/wasm.js +60 -0
  41. package/dist/index.d.mts +9 -0
  42. package/dist/index.mjs +9 -0
  43. package/dist/okf/bundle.d.mts +2 -0
  44. package/dist/okf/bundle.mjs +58 -0
  45. package/dist/okf/document.d.mts +8 -0
  46. package/dist/okf/document.mjs +109 -0
  47. package/dist/okf/links.d.mts +11 -0
  48. package/dist/okf/links.mjs +91 -0
  49. package/dist/okf/markdown.d.mts +8 -0
  50. package/dist/okf/markdown.mjs +45 -0
  51. package/dist/okf/metadata.d.mts +18 -0
  52. package/dist/okf/metadata.mjs +127 -0
  53. package/dist/site/generate.d.mts +8 -0
  54. package/dist/site/generate.mjs +187 -0
  55. package/dist/site/ownership.d.ts +4 -0
  56. package/dist/site/ownership.js +78 -0
  57. package/dist/types.d.ts +78 -0
  58. package/dist/types.js +1 -0
  59. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,9 @@
1
+ Astrok is licensed under either of the following, at your option:
2
+
3
+ - MIT license (LICENSE-MIT)
4
+ - Apache License, Version 2.0 (LICENSE-APACHE)
5
+
6
+ SPDX-License-Identifier: MIT OR Apache-2.0
7
+
8
+ Third-party code retains its own license notices. The imported @astrokjs/runtime
9
+ package remains MIT-licensed; see its LICENSE.
package/LICENSE-APACHE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/LICENSE-MIT ADDED
@@ -0,0 +1,9 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @astrokjs/okf
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Read OKF 0.3 bundles, publish their Markdown sources and build an optional graph. Unknown types and
4
+ nested metadata are preserved. Markdown without a non-empty `type` is skipped with a warning; root
5
+ indexes and logs remain separate document kinds. Malformed YAML is an error.
6
+
7
+ The root exports `readBundle`, `parseSource` (`parseDocument` is an alias), `readMetadata`, URL
8
+ helpers and Markdown inspection. `parseSource` returns `{ document, errors, warnings }`; `document`
9
+ is null for skipped Markdown.
10
+
11
+ `readMetadata(metadata, { now })` accepts singleton list fields and derives `trustTier`,
12
+ `freshness`, `status` and `current` without changing the input. Only verification events at or after
13
+ `generated.at` count. Unparseable deadlines return `freshness: 'malformed'`. It does not execute
14
+ computations or attest values.
15
+
16
+ `@astrokjs/okf/site` exports `loadSite({ root, base, strictLinks })`, returning
17
+ `{ bundle, documents, manifest, pages, raw }`. Documents contain source IDs, metadata, transformed
18
+ Markdown bodies without frontmatter, page URLs and raw source URLs. A plain Astro route can render
19
+ those bodies using its Markdown renderer. `generateSite` also accepts `docsDir`, `publicDir` and
20
+ `presentation: 'plain' | 'starlight'` and publishes raw sources and the manifest; plain mode skips
21
+ generated Starlight content. URL prefixes do not change disk paths: `/portal/okf/topic.md` is still
22
+ published at `publicDir/okf/topic.md`.
23
+
24
+ `strictLinks: true` makes `loadSite` and `generateSite` reject unresolved local links, missing
25
+ headings, malformed URLs and paths that escape the bundle. Diagnostics include source paths and line
26
+ numbers. Validation happens before claiming or changing generated output, so rejected edits preserve
27
+ the last good publication. External URLs are not fetched or checked for availability.
28
+
29
+ The low-level helpers default to `strictLinks: false`, retaining link warnings in the returned
30
+ bundle. Other warnings, such as skipped untyped Markdown, remain non-fatal in strict mode. Unknown
31
+ OKF metadata and types are still preserved.
32
+
33
+ Outputs claim absent or empty directories with `.astrok-owned.json`; subsequent runs can prune those
34
+ directories. Existing directories without the marker, canonical source ancestors/descendants and
35
+ symbolic links are refused. Use fresh, dedicated generated output paths; do not add caller-authored
36
+ files to them.
37
+
38
+ `@astrokjs/okf/graph` exports the SQL-free graph and Node publication helpers.
39
+ `@astrokjs/okf/sqlite` explicitly loads the optional SQLite WASM dependency. `publishIndex()`
40
+ defaults to SQL-free JSON publication; opt in with `publishIndex({ sqlite: true })`. Install with
41
+ `npm ci --omit=optional` to omit optional dependencies, including SQLite (and optional hypermedia
42
+ dependencies). These are Node build/query entry points and must remain off browser import graphs.
43
+ Low-level publication writes known filenames, so supply a dedicated generated public tree.
44
+
45
+ The graph includes concept references from OKF path fields, with the field name in each evidence
46
+ record. Relative paths start at the containing file; unversioned and <=0.2 bundles may fall back to
47
+ the bundle root. SQLite schema 3 migrates the previous evidence table; JSON snapshots use schema 2
48
+ and readers still accept schema 1. Index/log navigation nodes are not concepts.
49
+
50
+ Build with Node 24 and `npm run build --workspace=@astrokjs/okf` before packing. The package
51
+ contains executable ESM plus generated declarations, including an explicit declaration-specifier
52
+ rewrite after TypeScript compilation. Parser/site JavaScript remains maintained JavaScript; graph
53
+ TypeScript is not duplicated.
54
+
55
+ The graph entry point also exports `OKF_SPEC` and the Node filesystem helpers `atomicWrite`,
56
+ `assertOutside` and `physicalPath` used by the repository CLI. The SQLite entry point exports
57
+ `migrate` and `SCHEMA_VERSION` for migration verification. Repository scripts and tests consume
58
+ these emitted package exports.
@@ -0,0 +1,14 @@
1
+ export { atomicWrite } from './files.js';
2
+ export { COMPILER_VERSION } from './metadata.js';
3
+ import { WasmDatabase } from './wasm.js';
4
+ import type { Graph } from './model.js';
5
+ export declare function storeGraph(db: WasmDatabase, graph: Graph): void;
6
+ export declare function compileIndex({ root, database, }?: {
7
+ root?: string | undefined;
8
+ database?: string | undefined;
9
+ }): Promise<{
10
+ graph: Graph;
11
+ database: string;
12
+ }>;
13
+ /** Materialize an already projected graph; never reread canonical documents. */
14
+ export declare function serializeGraph(graph: Graph, previous?: Uint8Array): Promise<Uint8Array>;
@@ -0,0 +1,75 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { atomicWrite, assertOutside } from "./files.js";
3
+ export { atomicWrite } from "./files.js";
4
+ import { graphMetadata } from "./metadata.js";
5
+ export { COMPILER_VERSION } from "./metadata.js";
6
+ import { readBundle } from '../okf/bundle.mjs';
7
+ import { WasmDatabase } from "./wasm.js";
8
+ import { projectGraph } from "./project.js";
9
+ import { migrate, SCHEMA_VERSION } from "./schema.js";
10
+ export function storeGraph(db, graph) {
11
+ migrate(db);
12
+ db.exec('BEGIN IMMEDIATE');
13
+ try {
14
+ db.exec('DELETE FROM edge_contexts; DELETE FROM evidence; DELETE FROM edges; DELETE FROM contexts; DELETE FROM relations; DELETE FROM nodes; DELETE FROM sources; DELETE FROM diagnostics; DELETE FROM graph_meta;');
15
+ const source = db.prepare('INSERT INTO sources VALUES (?, ?)');
16
+ for (const item of graph.sources)
17
+ source.run(item.path, item.hash);
18
+ const node = db.prepare('INSERT INTO nodes VALUES (?, ?, ?, ?, ?, ?, ?, ?)');
19
+ for (const item of graph.nodes)
20
+ node.run(item.id, item.kind, item.title, item.description, item.type, item.body, JSON.stringify(item.metadata), item.sourcePath);
21
+ const relation = db.prepare('INSERT INTO relations VALUES (?, ?, ?, ?, ?)');
22
+ for (const item of graph.relations)
23
+ relation.run(item.id, item.name, item.inverse, item.family, item.stType);
24
+ const edge = db.prepare('INSERT INTO edges VALUES (?, ?, ?, ?, ?, ?, ?)');
25
+ const context = db.prepare('INSERT OR IGNORE INTO contexts VALUES (?)');
26
+ const edgeContext = db.prepare('INSERT INTO edge_contexts VALUES (?, ?)');
27
+ for (const item of graph.edges) {
28
+ edge.run(item.id, item.source, item.target, item.relation, item.origin, item.weight, item.confidence);
29
+ for (const value of item.contexts) {
30
+ context.run(value);
31
+ edgeContext.run(item.id, value);
32
+ }
33
+ }
34
+ const evidence = db.prepare('INSERT INTO evidence VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)');
35
+ for (const item of graph.evidence)
36
+ evidence.run(item.id, item.edgeId, item.sourcePath, item.sourceFragment, item.sourceLine, item.sourceColumn, item.targetFragment, item.kind, item.detail);
37
+ for (const message of graph.diagnostics)
38
+ db.prepare('INSERT INTO diagnostics VALUES (?)').run(message);
39
+ for (const [key, value] of Object.entries({
40
+ ...graphMetadata(graph),
41
+ schema_version: String(SCHEMA_VERSION),
42
+ runtime: 'sqlite-wasm',
43
+ }))
44
+ db.prepare('INSERT INTO graph_meta VALUES (?, ?)').run(key, value);
45
+ if (db.prepare('PRAGMA foreign_key_check').all().length)
46
+ throw new Error('Graph foreign key validation failed');
47
+ db.exec('COMMIT');
48
+ }
49
+ catch (error) {
50
+ db.exec('ROLLBACK');
51
+ throw error;
52
+ }
53
+ }
54
+ export async function compileIndex({ root = 'knowledge', database = '.generated/public/graph/knowledge.sqlite', } = {}) {
55
+ await assertOutside(root, database);
56
+ const graph = projectGraph((await readBundle(root)));
57
+ const previous = await readFile(database).catch((error) => {
58
+ if (error.code !== 'ENOENT')
59
+ throw error;
60
+ return undefined;
61
+ });
62
+ await atomicWrite(database, await serializeGraph(graph, previous));
63
+ return { graph, database };
64
+ }
65
+ /** Materialize an already projected graph; never reread canonical documents. */
66
+ export async function serializeGraph(graph, previous) {
67
+ const db = await WasmDatabase.open(previous);
68
+ try {
69
+ storeGraph(db, graph);
70
+ return db.serialize();
71
+ }
72
+ finally {
73
+ db.close();
74
+ }
75
+ }
@@ -0,0 +1,7 @@
1
+ export declare function atomicWrite(file: string, bytes: Uint8Array | string): Promise<void>;
2
+ export declare function physicalPath(file: string): Promise<string>;
3
+ export declare function assertOutside(root: string, output: string): Promise<void>;
4
+ /** Stage every artifact before replacing any; restore prior files on commit failure.
5
+ * Single-writer publication. Concurrent readers must still compare source hashes.
6
+ */
7
+ export declare function publishFiles(outputs: Map<string, string | Uint8Array | null>): Promise<void>;
@@ -0,0 +1,102 @@
1
+ import { mkdir, writeFile, rename, rm, realpath, copyFile } from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ export async function atomicWrite(file, bytes) {
6
+ await mkdir(path.dirname(file), { recursive: true });
7
+ const temporary = `${file}.${randomUUID()}.tmp`;
8
+ try {
9
+ await writeFile(temporary, bytes, { flag: 'wx' });
10
+ await rename(temporary, file);
11
+ }
12
+ finally {
13
+ await rm(temporary, { force: true });
14
+ }
15
+ }
16
+ export async function physicalPath(file) {
17
+ const suffix = [];
18
+ let current = path.resolve(file);
19
+ for (;;) {
20
+ try {
21
+ return path.join(await realpath(current), ...suffix.reverse());
22
+ }
23
+ catch (error) {
24
+ if (error.code !== 'ENOENT')
25
+ throw error;
26
+ suffix.push(path.basename(current));
27
+ const parent = path.dirname(current);
28
+ if (parent === current)
29
+ throw error;
30
+ current = parent;
31
+ }
32
+ }
33
+ }
34
+ export async function assertOutside(root, output) {
35
+ const relative = path.relative(await realpath(root), await physicalPath(output));
36
+ if (relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative))
37
+ throw new Error('Graph output must be outside the canonical knowledge directory');
38
+ }
39
+ /** Stage every artifact before replacing any; restore prior files on commit failure.
40
+ * Single-writer publication. Concurrent readers must still compare source hashes.
41
+ */
42
+ export async function publishFiles(outputs) {
43
+ const staged = [];
44
+ const committed = [];
45
+ let preserveBackups = false;
46
+ try {
47
+ for (const [file, bytes] of outputs) {
48
+ await mkdir(path.dirname(file), { recursive: true });
49
+ const item = {
50
+ file,
51
+ temporary: `${file}.${randomUUID()}.tmp`,
52
+ backup: `${file}.${randomUUID()}.bak`,
53
+ existed: false,
54
+ remove: bytes === null,
55
+ };
56
+ staged.push(item);
57
+ try {
58
+ await copyFile(file, item.backup, constants.COPYFILE_EXCL);
59
+ item.existed = true;
60
+ }
61
+ catch (error) {
62
+ if (error.code !== 'ENOENT')
63
+ throw error;
64
+ }
65
+ if (bytes !== null)
66
+ await writeFile(item.temporary, bytes, { flag: 'wx' });
67
+ }
68
+ for (const item of staged) {
69
+ if (item.remove)
70
+ await rm(item.file, { force: true });
71
+ else
72
+ await rename(item.temporary, item.file);
73
+ committed.push(item);
74
+ }
75
+ }
76
+ catch (error) {
77
+ const failures = [error];
78
+ for (const item of [...committed].reverse()) {
79
+ try {
80
+ if (item.existed)
81
+ await rename(item.backup, item.file);
82
+ else
83
+ await rm(item.file, { force: true });
84
+ }
85
+ catch (restoreError) {
86
+ failures.push(restoreError);
87
+ }
88
+ }
89
+ if (failures.length > 1) {
90
+ preserveBackups = true;
91
+ throw new AggregateError(failures, 'Publication and rollback failed; .bak files retained for recovery');
92
+ }
93
+ throw error;
94
+ }
95
+ finally {
96
+ for (const item of staged) {
97
+ await rm(item.temporary, { force: true });
98
+ if (!preserveBackups)
99
+ await rm(item.backup, { force: true });
100
+ }
101
+ }
102
+ }
@@ -0,0 +1,9 @@
1
+ export { KnowledgeGraph } from './memory.js';
2
+ export { projectGraph } from './project.js';
3
+ export { publishIndex } from './publish.js';
4
+ export { readSnapshot } from './snapshot.js';
5
+ export * from './model.js';
6
+ export type { GraphSnapshot } from './snapshot.js';
7
+ export type { IndexedNode, Citation, Filters, Neighbor, WalkOptions } from './query-core.js';
8
+ export { atomicWrite, assertOutside, physicalPath } from './files.js';
9
+ export { OKF_SPEC } from './version.js';
@@ -0,0 +1,7 @@
1
+ export { KnowledgeGraph } from "./memory.js";
2
+ export { projectGraph } from "./project.js";
3
+ export { publishIndex } from "./publish.js";
4
+ export { readSnapshot } from "./snapshot.js";
5
+ export * from "./model.js";
6
+ export { atomicWrite, assertOutside, physicalPath } from "./files.js";
7
+ export { OKF_SPEC } from "./version.js";
@@ -0,0 +1,41 @@
1
+ import type { Bundle, Graph } from './model.js';
2
+ import { GraphQueries } from './query-core.js';
3
+ import type { Filters, Neighbor } from './query-core.js';
4
+ import type { GraphSnapshot } from './snapshot.js';
5
+ /** SQL-free graph queries; only open/fromBundle dynamically load Node build tools. */
6
+ export declare class KnowledgeGraph extends GraphQueries {
7
+ private graph;
8
+ private nodes;
9
+ private sourceNodes;
10
+ private relations;
11
+ private adjacent;
12
+ private evidence;
13
+ private constructor();
14
+ static fromGraph(graph: Graph, metadata?: Record<string, string>): KnowledgeGraph;
15
+ static fromJSON(value: unknown): KnowledgeGraph;
16
+ static fromBundle(bundle: Bundle): Promise<KnowledgeGraph>;
17
+ static open(root?: string): Promise<KnowledgeGraph>;
18
+ get runtime(): {
19
+ engine: string;
20
+ wasm: boolean;
21
+ };
22
+ close(): void;
23
+ getNode(id: string): import("./query-core.js").IndexedNode | null;
24
+ search(text: string, { limit }?: {
25
+ limit?: number;
26
+ }): {
27
+ node: import("./query-core.js").IndexedNode;
28
+ score: number;
29
+ excerpt: string;
30
+ }[];
31
+ neighbors(id: string, options?: Filters & {
32
+ limit?: number;
33
+ }): {
34
+ items: Neighbor[];
35
+ truncated: boolean;
36
+ };
37
+ integrity(): {
38
+ ok: boolean;
39
+ };
40
+ export(): GraphSnapshot;
41
+ }