@agent-wiki/mcp 0.22.3 → 0.22.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.
- package/README.md +31 -0
- package/dist/cli.js +177 -0
- package/dist/cli.js.map +1 -1
- package/dist/evidence-migration.js +1 -1
- package/dist/evidence-migration.js.map +1 -1
- package/dist/evidence-report.d.ts +70 -1
- package/dist/evidence-report.d.ts.map +1 -1
- package/dist/evidence-report.js +228 -5
- package/dist/evidence-report.js.map +1 -1
- package/dist/evidence-report.test.js +176 -0
- package/dist/evidence-report.test.js.map +1 -1
- package/dist/evidence-search.d.ts +71 -0
- package/dist/evidence-search.d.ts.map +1 -1
- package/dist/evidence-search.js +104 -1
- package/dist/evidence-search.js.map +1 -1
- package/dist/evidence-search.test.js +58 -1
- package/dist/evidence-search.test.js.map +1 -1
- package/dist/index.d.ts +10 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/okf-compat.d.ts +152 -0
- package/dist/okf-compat.d.ts.map +1 -0
- package/dist/okf-compat.js +604 -0
- package/dist/okf-compat.js.map +1 -0
- package/dist/okf-compat.test.d.ts +2 -0
- package/dist/okf-compat.test.d.ts.map +1 -0
- package/dist/okf-compat.test.js +234 -0
- package/dist/okf-compat.test.js.map +1 -0
- package/dist/okf-export.d.ts +63 -0
- package/dist/okf-export.d.ts.map +1 -0
- package/dist/okf-export.js +655 -0
- package/dist/okf-export.js.map +1 -0
- package/dist/okf-export.test.d.ts +2 -0
- package/dist/okf-export.test.d.ts.map +1 -0
- package/dist/okf-export.test.js +469 -0
- package/dist/okf-export.test.js.map +1 -0
- package/dist/okf-import.d.ts +136 -0
- package/dist/okf-import.d.ts.map +1 -0
- package/dist/okf-import.js +471 -0
- package/dist/okf-import.js.map +1 -0
- package/dist/okf-import.test.d.ts +2 -0
- package/dist/okf-import.test.d.ts.map +1 -0
- package/dist/okf-import.test.js +339 -0
- package/dist/okf-import.test.js.map +1 -0
- package/dist/okf-trust.test.d.ts +2 -0
- package/dist/okf-trust.test.d.ts.map +1 -0
- package/dist/okf-trust.test.js +223 -0
- package/dist/okf-trust.test.js.map +1 -0
- package/dist/okf.d.ts +128 -0
- package/dist/okf.d.ts.map +1 -0
- package/dist/okf.js +659 -0
- package/dist/okf.js.map +1 -0
- package/dist/search-currency.d.ts +44 -0
- package/dist/search-currency.d.ts.map +1 -0
- package/dist/search-currency.js +111 -0
- package/dist/search-currency.js.map +1 -0
- package/dist/search.d.ts +19 -0
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js.map +1 -1
- package/dist/server.d.ts +0 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +753 -49
- package/dist/server.js.map +1 -1
- package/dist/server.test.js +848 -0
- package/dist/server.test.js.map +1 -1
- package/dist/wiki-graph.d.ts +126 -0
- package/dist/wiki-graph.d.ts.map +1 -0
- package/dist/wiki-graph.js +479 -0
- package/dist/wiki-graph.js.map +1 -0
- package/dist/wiki-graph.test.d.ts +2 -0
- package/dist/wiki-graph.test.d.ts.map +1 -0
- package/dist/wiki-graph.test.js +216 -0
- package/dist/wiki-graph.test.js.map +1 -0
- package/dist/wiki.d.ts +140 -1
- package/dist/wiki.d.ts.map +1 -1
- package/dist/wiki.js +509 -23
- package/dist/wiki.js.map +1 -1
- package/dist/worklist.d.ts +43 -0
- package/dist/worklist.d.ts.map +1 -0
- package/dist/worklist.js +147 -0
- package/dist/worklist.js.map +1 -0
- package/dist/worklist.test.d.ts +2 -0
- package/dist/worklist.test.d.ts.map +1 -0
- package/dist/worklist.test.js +233 -0
- package/dist/worklist.test.js.map +1 -0
- package/docs/evidence-envelope.md +26 -1
- package/docs/okf-adoption-plan.md +566 -0
- package/docs/okf-compat-plan.md +418 -0
- package/docs/okf-extensions.md +245 -0
- package/docs/open-knowledge-format.md +280 -0
- package/docs/tools.md +264 -2
- package/package.json +1 -1
- package/schemas/agent-wiki-okf.schema.json +130 -0
- package/skills/agent-wiki/SKILL.md +7 -0
- package/skills/agent-wiki/references/tools-reference.md +80 -3
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Export a workspace as an Open Knowledge Format v0.3 bundle (phase 3 of
|
|
3
|
+
* docs/okf-compat-plan.md).
|
|
4
|
+
*
|
|
5
|
+
* Native storage is not changed. The exporter reads `wiki/` and `raw/` and writes a new
|
|
6
|
+
* directory in which
|
|
7
|
+
* - `[[wikilinks]]` are Markdown links (§6.1),
|
|
8
|
+
* - `sources` entries are mappings with a `resource` (§5.1), and cited raw files travel
|
|
9
|
+
* with the bundle under `references/raw/`,
|
|
10
|
+
* - agent-wiki's own frontmatter keys are OKF keys or `x-agent-wiki-*` extension keys,
|
|
11
|
+
* - `index.md` and `log.md` have the §8 and §9 forms.
|
|
12
|
+
*
|
|
13
|
+
* A page that needs none of this is copied byte for byte, so exporting an imported bundle
|
|
14
|
+
* gives the bundle back.
|
|
15
|
+
*/
|
|
16
|
+
import { copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, writeFileSync, } from "node:fs";
|
|
17
|
+
import { dirname, join, posix, resolve, sep } from "node:path";
|
|
18
|
+
import yaml from "js-yaml";
|
|
19
|
+
import { AGENT_WIKI_EXTENSION_KEYS, parseOkfTimestamp, replaceWikilinks, resolveBundlePath } from "./okf-compat.js";
|
|
20
|
+
import { OKF_SPEC_VERSION, checkOkfBundle, readFrontmatter } from "./okf-import.js";
|
|
21
|
+
import { OKF_MANIFEST_FILENAME } from "./okf.js";
|
|
22
|
+
import { rawPathOfSource, safePath } from "./wiki.js";
|
|
23
|
+
import { VERSION } from "./version.js";
|
|
24
|
+
/** Where cited raw files go inside the bundle. */
|
|
25
|
+
export const OKF_RAW_DIR = "references/raw";
|
|
26
|
+
/** Root pages that are derived from the others and would be read as concepts. */
|
|
27
|
+
const DERIVED_ROOT_PAGES = new Set(["timeline.md", "evidence-report.md"]);
|
|
28
|
+
const EXTENSION_KEYS = AGENT_WIKI_EXTENSION_KEYS;
|
|
29
|
+
const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
|
|
30
|
+
function isBlank(v) {
|
|
31
|
+
return v === null || v === undefined || v === "" || (Array.isArray(v) && v.length === 0);
|
|
32
|
+
}
|
|
33
|
+
function listOf(v) {
|
|
34
|
+
if (isBlank(v))
|
|
35
|
+
return [];
|
|
36
|
+
return Array.isArray(v) ? v : [v];
|
|
37
|
+
}
|
|
38
|
+
function toPosix(p) {
|
|
39
|
+
return p.split(sep).join("/");
|
|
40
|
+
}
|
|
41
|
+
/** Split a page into frontmatter and body without touching either. */
|
|
42
|
+
function readPage(rel, text) {
|
|
43
|
+
const fm = readFrontmatter(text);
|
|
44
|
+
if (fm.state !== "ok")
|
|
45
|
+
return { rel, text, data: null, body: text };
|
|
46
|
+
const lines = text.split("\n");
|
|
47
|
+
let end = 1;
|
|
48
|
+
while (lines[end].replace(/\r$/, "") !== "---")
|
|
49
|
+
end++;
|
|
50
|
+
return { rel, text, data: fm.data, body: lines.slice(end + 1).join("\n") };
|
|
51
|
+
}
|
|
52
|
+
function walk(dir, rel = "") {
|
|
53
|
+
const files = [];
|
|
54
|
+
const skipped = [];
|
|
55
|
+
for (const name of readdirSync(join(dir, rel)).sort()) {
|
|
56
|
+
const childRel = rel === "" ? name : `${rel}/${name}`;
|
|
57
|
+
if (name.startsWith(".")) {
|
|
58
|
+
skipped.push({ path: childRel, reason: "dot-paths are not part of a bundle (§3.2)" });
|
|
59
|
+
continue;
|
|
60
|
+
}
|
|
61
|
+
const st = lstatSync(join(dir, childRel));
|
|
62
|
+
if (st.isSymbolicLink()) {
|
|
63
|
+
skipped.push({ path: childRel, reason: "symbolic links are not exported" });
|
|
64
|
+
}
|
|
65
|
+
else if (st.isDirectory()) {
|
|
66
|
+
const sub = walk(dir, childRel);
|
|
67
|
+
files.push(...sub.files);
|
|
68
|
+
skipped.push(...sub.skipped);
|
|
69
|
+
}
|
|
70
|
+
else if (st.isFile()) {
|
|
71
|
+
files.push(childRel);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { files, skipped };
|
|
75
|
+
}
|
|
76
|
+
/** The real path of `p`: links resolved for the part that exists, the rest appended. */
|
|
77
|
+
function canonical(p) {
|
|
78
|
+
let existing = resolve(p);
|
|
79
|
+
const rest = [];
|
|
80
|
+
while (!existsSync(existing)) {
|
|
81
|
+
const parent = dirname(existing);
|
|
82
|
+
if (parent === existing)
|
|
83
|
+
break;
|
|
84
|
+
rest.unshift(existing.slice(parent.length).replace(/^[\\/]+/, ""));
|
|
85
|
+
existing = parent;
|
|
86
|
+
}
|
|
87
|
+
try {
|
|
88
|
+
existing = realpathSync(existing);
|
|
89
|
+
}
|
|
90
|
+
catch { /* keep the lexical path */ }
|
|
91
|
+
return rest.length > 0 ? join(existing, ...rest) : existing;
|
|
92
|
+
}
|
|
93
|
+
/** A path from the bundle root as a `resource` or path value: leading slash, segments encoded (§6.2). */
|
|
94
|
+
function bundlePath(rel) {
|
|
95
|
+
return `/${linkDestination(rel)}`;
|
|
96
|
+
}
|
|
97
|
+
/** A path as a Markdown link destination: no characters that end or confuse the link. */
|
|
98
|
+
function linkDestination(path) {
|
|
99
|
+
return path
|
|
100
|
+
.split("/")
|
|
101
|
+
.map((seg) => seg.replace(/[%\s()<>#?"\\]/g, (c) => encodeURIComponent(c).replace(/[()]/g, (p) => `%${p.charCodeAt(0).toString(16)}`)))
|
|
102
|
+
.join("/");
|
|
103
|
+
}
|
|
104
|
+
function linkText(text) {
|
|
105
|
+
return text.replace(/([\[\]\\])/g, "\\$1").replace(/\s+/g, " ").trim();
|
|
106
|
+
}
|
|
107
|
+
function toTimestamp(value) {
|
|
108
|
+
const ms = parseOkfTimestamp(value);
|
|
109
|
+
return ms === null ? null : new Date(ms).toISOString().replace(/\.000Z$/, "Z");
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The bundle path of a raw file. Markdown evidence is renamed so it is not read as a
|
|
113
|
+
* concept: `report.md` becomes `report.md.txt`. A destination must be free: no file of
|
|
114
|
+
* the wiki is exported to it (a workspace that holds an imported bundle has its own
|
|
115
|
+
* `references/raw/`), and no other raw file would be copied to it. Otherwise the next
|
|
116
|
+
* name is taken (`report.md.raw.txt`, `proof.raw.pdf`, then `.raw2`, …). Decided from
|
|
117
|
+
* what is on disk, not from the order in which pages cite the files.
|
|
118
|
+
*/
|
|
119
|
+
function rawBundlePath(rawDir, wikiFiles, rawRel) {
|
|
120
|
+
const clean = posix.normalize(rawRel.replace(/\\/g, "/")).replace(/^\/+/, "");
|
|
121
|
+
const markdown = /\.md$/i.test(clean);
|
|
122
|
+
const ext = markdown ? "" : posix.extname(clean);
|
|
123
|
+
const stem = clean.slice(0, clean.length - ext.length);
|
|
124
|
+
for (let i = 0;; i++) {
|
|
125
|
+
const mark = i === 0 ? "" : i === 1 ? ".raw" : `.raw${i}`;
|
|
126
|
+
const name = markdown ? `${clean}${mark}.txt` : `${stem}${mark}${ext}`;
|
|
127
|
+
// Another raw file that is exported under its own name already owns that name.
|
|
128
|
+
const ownedByOtherRaw = name !== clean && !/\.md$/i.test(name) && existsSync(join(rawDir, name));
|
|
129
|
+
if (!ownedByOtherRaw && !wikiFiles.has(`${OKF_RAW_DIR}/${name}`))
|
|
130
|
+
return `${OKF_RAW_DIR}/${name}`;
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function dumpFrontmatter(data) {
|
|
134
|
+
return yaml.dump(data, { lineWidth: -1, noRefs: true, sortKeys: false, quotingType: '"' });
|
|
135
|
+
}
|
|
136
|
+
function sameValue(a, b) {
|
|
137
|
+
return yaml.dump(a ?? null, { noRefs: true }) === yaml.dump(b ?? null, { noRefs: true });
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Export the workspace of `wiki` to `outDir` as an OKF v0.3 bundle. Nothing in the
|
|
141
|
+
* workspace is changed, apart from the contradiction and source-drift indexes, which are
|
|
142
|
+
* refreshed first so the bundle carries the current state.
|
|
143
|
+
*/
|
|
144
|
+
export function exportOkfBundle(wiki, outDir, opts = {}) {
|
|
145
|
+
// Real paths, so that a symbolic link on the way cannot hide that the output directory
|
|
146
|
+
// is the workspace (clearing an earlier export would then delete the wiki itself).
|
|
147
|
+
const out = canonical(outDir);
|
|
148
|
+
const wikiDir = canonical(wiki.config.wikiDir);
|
|
149
|
+
const rawDir = canonical(wiki.config.rawDir);
|
|
150
|
+
const generatedBy = opts.generatedBy ?? `agent-wiki/${VERSION}`;
|
|
151
|
+
const report = {
|
|
152
|
+
ok: false,
|
|
153
|
+
out,
|
|
154
|
+
bundle: { okf_version: OKF_SPEC_VERSION, title: "", conformant: false, concepts: 0, other_markdown: 0, assets: 0, raw_files: 0 },
|
|
155
|
+
written: [],
|
|
156
|
+
skipped: [],
|
|
157
|
+
links_converted: 0,
|
|
158
|
+
links_unresolved: [],
|
|
159
|
+
findings: [],
|
|
160
|
+
};
|
|
161
|
+
// ── Where the bundle may go ─────────────────────────────────────
|
|
162
|
+
for (const inside of [wikiDir, rawDir]) {
|
|
163
|
+
if (out === inside || out.startsWith(inside + sep)) {
|
|
164
|
+
report.refused = "the output directory is inside the workspace's wiki/ or raw/ directory";
|
|
165
|
+
return report;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (wikiDir.startsWith(out + sep) || rawDir.startsWith(out + sep)) {
|
|
169
|
+
report.refused = "the output directory contains the workspace";
|
|
170
|
+
return report;
|
|
171
|
+
}
|
|
172
|
+
if (existsSync(out)) {
|
|
173
|
+
if (!lstatSync(out).isDirectory()) {
|
|
174
|
+
report.refused = "the output path exists and is not a directory";
|
|
175
|
+
return report;
|
|
176
|
+
}
|
|
177
|
+
const existing = readdirSync(out);
|
|
178
|
+
if (existing.length > 0) {
|
|
179
|
+
if (!opts.overwrite) {
|
|
180
|
+
report.refused = "the output directory is not empty; pass overwrite to replace an earlier export";
|
|
181
|
+
return report;
|
|
182
|
+
}
|
|
183
|
+
// Only a directory that is recognisably a bundle is cleared.
|
|
184
|
+
const rootIndex = join(out, "index.md");
|
|
185
|
+
const fm = existsSync(rootIndex) ? readFrontmatter(readFileSync(rootIndex, "utf-8")) : { state: "absent" };
|
|
186
|
+
if (fm.state !== "ok" || fm.data.okf_version === undefined) {
|
|
187
|
+
report.refused = "the output directory is not empty and is not an OKF bundle (no root index.md with okf_version); it is not cleared";
|
|
188
|
+
return report;
|
|
189
|
+
}
|
|
190
|
+
for (const name of existing)
|
|
191
|
+
rmSync(join(out, name), { recursive: true, force: true });
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// ── What is in the workspace ────────────────────────────────────
|
|
195
|
+
const tree = walk(wikiDir);
|
|
196
|
+
report.skipped.push(...tree.skipped);
|
|
197
|
+
const pages = [];
|
|
198
|
+
const assets = [];
|
|
199
|
+
let nativeLog = null;
|
|
200
|
+
let rootIndexData = {};
|
|
201
|
+
for (const rel of tree.files) {
|
|
202
|
+
if (!rel.toLowerCase().endsWith(".md")) {
|
|
203
|
+
assets.push(rel);
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const lower = rel.toLowerCase();
|
|
207
|
+
const name = lower.slice(lower.lastIndexOf("/") + 1);
|
|
208
|
+
if (lower === "index.md") {
|
|
209
|
+
rootIndexData = readPage(rel, readFileSync(join(wikiDir, rel), "utf-8")).data ?? {};
|
|
210
|
+
continue; // regenerated below
|
|
211
|
+
}
|
|
212
|
+
if (lower === "log.md") {
|
|
213
|
+
nativeLog = readFileSync(join(wikiDir, rel), "utf-8");
|
|
214
|
+
continue; // converted below
|
|
215
|
+
}
|
|
216
|
+
if (DERIVED_ROOT_PAGES.has(lower)) {
|
|
217
|
+
report.skipped.push({ path: rel, reason: "derived from the other pages; would be read as a concept" });
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
if (name === "index.md")
|
|
221
|
+
continue; // directory indexes are regenerated
|
|
222
|
+
const page = readPage(rel, readFileSync(join(wikiDir, rel), "utf-8"));
|
|
223
|
+
if (name === "log.md" && readFrontmatter(page.text).state !== "absent") {
|
|
224
|
+
report.skipped.push({ path: rel, reason: "a log.md has no frontmatter in OKF (§9); rename the page to export it" });
|
|
225
|
+
continue;
|
|
226
|
+
}
|
|
227
|
+
pages.push(page);
|
|
228
|
+
}
|
|
229
|
+
// ── Bundle metadata (§8.1) ──────────────────────────────────────
|
|
230
|
+
let manifest = {};
|
|
231
|
+
try {
|
|
232
|
+
const loaded = yaml.load(readFileSync(join(wiki.config.workspace, OKF_MANIFEST_FILENAME), "utf-8"));
|
|
233
|
+
if (loaded && typeof loaded === "object" && !Array.isArray(loaded))
|
|
234
|
+
manifest = loaded;
|
|
235
|
+
}
|
|
236
|
+
catch { /* no manifest, or one that does not parse: export without it */ }
|
|
237
|
+
// A wiki that holds an imported bundle keeps that bundle's metadata on its root index.
|
|
238
|
+
const carried = rootIndexData.okf_version !== undefined ? rootIndexData : {};
|
|
239
|
+
const str = (v) => (typeof v === "string" && v.trim() !== "" ? v.trim() : undefined);
|
|
240
|
+
const title = str(carried.title) ?? str(manifest.name) ?? "Knowledge Base";
|
|
241
|
+
const description = str(carried.description) ?? str(manifest.description);
|
|
242
|
+
const license = str(carried.license) ?? str(manifest.license);
|
|
243
|
+
const rootMeta = { okf_version: OKF_SPEC_VERSION, title };
|
|
244
|
+
if (description)
|
|
245
|
+
rootMeta.description = description;
|
|
246
|
+
if (license)
|
|
247
|
+
rootMeta.license = license;
|
|
248
|
+
for (const [k, v] of Object.entries(carried))
|
|
249
|
+
if (k.startsWith("x-"))
|
|
250
|
+
rootMeta[k] = v;
|
|
251
|
+
report.bundle.title = title;
|
|
252
|
+
if (description)
|
|
253
|
+
report.bundle.description = description;
|
|
254
|
+
if (license)
|
|
255
|
+
report.bundle.license = license;
|
|
256
|
+
const policy = manifest.wiki_policy;
|
|
257
|
+
const staleAfterDays = typeof policy?.stale_after_days === "number" && policy.stale_after_days > 0 ? policy.stale_after_days : null;
|
|
258
|
+
// ── State that lives outside the pages ──────────────────────────
|
|
259
|
+
let disputes = {};
|
|
260
|
+
let drift = {};
|
|
261
|
+
try {
|
|
262
|
+
disputes = wiki.refreshContradictionIndex().pages;
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
disputes = wiki.contradictionIndex()?.pages ?? {};
|
|
266
|
+
}
|
|
267
|
+
try {
|
|
268
|
+
drift = wiki.refreshSourceDriftIndex().pages;
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
drift = wiki.sourceDriftIndex()?.pages ?? {};
|
|
272
|
+
}
|
|
273
|
+
// ── Link resolution, as wiki_graph does it: exact path, then a unique basename ──
|
|
274
|
+
const pagePaths = new Set(pages.map((p) => p.rel));
|
|
275
|
+
const wikiFiles = new Set(tree.files);
|
|
276
|
+
const linkable = new Set([...pagePaths, "index.md", "log.md"]);
|
|
277
|
+
// Every directory with a page gets an index.md below; a link to one of those resolves.
|
|
278
|
+
for (const rel of pagePaths) {
|
|
279
|
+
if (rel.toLowerCase().endsWith("/log.md"))
|
|
280
|
+
continue;
|
|
281
|
+
for (let d = posix.dirname(rel); d !== "." && d !== ""; d = posix.dirname(d))
|
|
282
|
+
linkable.add(`${d}/index.md`);
|
|
283
|
+
}
|
|
284
|
+
const byBasename = new Map();
|
|
285
|
+
for (const rel of pagePaths) {
|
|
286
|
+
const base = rel.slice(rel.lastIndexOf("/") + 1, -3);
|
|
287
|
+
byBasename.set(base, [...(byBasename.get(base) ?? []), rel]);
|
|
288
|
+
}
|
|
289
|
+
const titles = new Map();
|
|
290
|
+
for (const p of pages) {
|
|
291
|
+
const t = str(p.data?.title);
|
|
292
|
+
titles.set(p.rel, t ?? p.rel.slice(p.rel.lastIndexOf("/") + 1, -3));
|
|
293
|
+
}
|
|
294
|
+
const resolveWikilink = (target) => {
|
|
295
|
+
const slug = target.replace(/\\/g, "/").replace(/^\/+/, "").replace(/\.md$/i, "");
|
|
296
|
+
if (linkable.has(`${slug}.md`))
|
|
297
|
+
return `${slug}.md`;
|
|
298
|
+
const candidates = byBasename.get(slug);
|
|
299
|
+
return candidates && candidates.length === 1 ? candidates[0] : null;
|
|
300
|
+
};
|
|
301
|
+
const convertLinks = (body, fromRel) => replaceWikilinks(body, (rawTarget, alias) => {
|
|
302
|
+
const hash = rawTarget.indexOf("#");
|
|
303
|
+
const target = hash === -1 ? rawTarget : rawTarget.slice(0, hash);
|
|
304
|
+
// The fragment is part of the destination: a space in it would end the link.
|
|
305
|
+
const anchor = hash === -1 ? "" : `#${linkDestination(rawTarget.slice(hash + 1).trim())}`;
|
|
306
|
+
const dest = resolveWikilink(target);
|
|
307
|
+
if (dest === null) {
|
|
308
|
+
report.links_unresolved.push({ page: fromRel, link: rawTarget });
|
|
309
|
+
return alias ?? rawTarget; // a link to nothing would be a broken link in the bundle
|
|
310
|
+
}
|
|
311
|
+
report.links_converted++;
|
|
312
|
+
const rel = posix.relative(posix.dirname(fromRel), dest) || posix.basename(dest);
|
|
313
|
+
return `[${linkText(alias ?? titles.get(dest) ?? target)}](${linkDestination(rel)}${anchor})`;
|
|
314
|
+
});
|
|
315
|
+
// ── Raw files the bundle needs ──────────────────────────────────
|
|
316
|
+
const rawNeeded = new Map(); // raw-relative path → bundle path
|
|
317
|
+
const needRaw = (rawRel) => {
|
|
318
|
+
const clean = posix.normalize(rawRel.replace(/\\/g, "/")).replace(/^\/+/, "");
|
|
319
|
+
const dest = rawBundlePath(rawDir, wikiFiles, clean);
|
|
320
|
+
rawNeeded.set(clean, dest);
|
|
321
|
+
return bundlePath(dest);
|
|
322
|
+
};
|
|
323
|
+
/** A cited location as an OKF `resource`: a URL, or a path from the bundle root. */
|
|
324
|
+
/**
|
|
325
|
+
* A native string citation as an OKF `resource`: a URL as it is, a raw file as its path
|
|
326
|
+
* in the bundle, a wiki page as a path from the bundle root. Raw files are found the way
|
|
327
|
+
* wiki_write finds them when it seals a page: `raw/report.pdf`, `./raw/report.pdf` and
|
|
328
|
+
* the bare `report.pdf` all name raw/report.pdf.
|
|
329
|
+
*/
|
|
330
|
+
const toResource = (entry) => {
|
|
331
|
+
const s = entry.trim();
|
|
332
|
+
if (HAS_SCHEME.test(s) || s.startsWith("//") || s.startsWith("/"))
|
|
333
|
+
return s;
|
|
334
|
+
const norm = s.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
335
|
+
const rawRel = rawPathOfSource(s);
|
|
336
|
+
if (rawRel !== null) {
|
|
337
|
+
const inRaw = existsSync(join(rawDir, rawRel)) && lstatSync(join(rawDir, rawRel)).isFile();
|
|
338
|
+
// An explicit raw/ prefix names the raw layer even when the file is gone (reported).
|
|
339
|
+
if (inRaw || norm.startsWith("raw/"))
|
|
340
|
+
return needRaw(rawRel);
|
|
341
|
+
}
|
|
342
|
+
if (pagePaths.has(norm))
|
|
343
|
+
return bundlePath(norm);
|
|
344
|
+
if (pagePaths.has(`${norm}.md`))
|
|
345
|
+
return bundlePath(`${norm}.md`);
|
|
346
|
+
return s;
|
|
347
|
+
};
|
|
348
|
+
const mapFrontmatter = (page) => {
|
|
349
|
+
const src = page.data;
|
|
350
|
+
const outFm = {};
|
|
351
|
+
const sealed = (src.sources_sha && typeof src.sources_sha === "object" && !Array.isArray(src.sources_sha)
|
|
352
|
+
? src.sources_sha
|
|
353
|
+
: {});
|
|
354
|
+
const mapSources = () => {
|
|
355
|
+
const entries = [];
|
|
356
|
+
const seen = new Set();
|
|
357
|
+
for (const entry of listOf(src.sources)) {
|
|
358
|
+
if (typeof entry === "string") {
|
|
359
|
+
const mapped = { resource: toResource(entry) };
|
|
360
|
+
if (typeof sealed[entry] === "string")
|
|
361
|
+
mapped["x-agent-wiki-sha256"] = sealed[entry];
|
|
362
|
+
entries.push(mapped);
|
|
363
|
+
seen.add(String(mapped.resource));
|
|
364
|
+
}
|
|
365
|
+
else if (entry && typeof entry === "object" && !Array.isArray(entry) && typeof entry.resource === "string") {
|
|
366
|
+
const e = entry;
|
|
367
|
+
const original = e.resource;
|
|
368
|
+
const inBundle = resolveBundlePath(original, page.rel);
|
|
369
|
+
// A mapping may still cite the raw layer the native way ({ resource: raw/proof.pdf });
|
|
370
|
+
// wiki_write seals those too. It is raw evidence when nothing in the wiki is at
|
|
371
|
+
// the path the resource resolves to from this page (§6.2) and raw/ has the file.
|
|
372
|
+
const inWiki = inBundle !== null && wikiFiles.has(inBundle);
|
|
373
|
+
const mappedRaw = !inWiki && !original.trim().startsWith("/") ? toResource(original) : original;
|
|
374
|
+
if (mappedRaw !== original && mappedRaw.startsWith(`/${OKF_RAW_DIR}/`)) {
|
|
375
|
+
const mapped = { ...e, resource: mappedRaw };
|
|
376
|
+
if (typeof sealed[original] === "string" && mapped["x-agent-wiki-sha256"] === undefined) {
|
|
377
|
+
mapped["x-agent-wiki-sha256"] = sealed[original];
|
|
378
|
+
}
|
|
379
|
+
entries.push(mapped);
|
|
380
|
+
seen.add(mappedRaw);
|
|
381
|
+
}
|
|
382
|
+
else {
|
|
383
|
+
// Already an OKF entry: its resource resolves from this page and is kept.
|
|
384
|
+
entries.push(entry);
|
|
385
|
+
seen.add(inBundle === null ? original : bundlePath(inBundle));
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
else {
|
|
389
|
+
entries.push(entry);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
for (const d of listOf(src.derived_from)) {
|
|
393
|
+
if (typeof d !== "string" || d.trim() === "")
|
|
394
|
+
continue;
|
|
395
|
+
const norm = d.trim().replace(/\\/g, "/").replace(/^\/+/, "");
|
|
396
|
+
const resource = bundlePath(resolveWikilink(norm) ?? (norm.toLowerCase().endsWith(".md") ? norm : `${norm}.md`));
|
|
397
|
+
if (seen.has(resource)) {
|
|
398
|
+
// Cited and derived from: the entry that is already there gets the marker.
|
|
399
|
+
const at = entries.findIndex((e) => {
|
|
400
|
+
if (!e || typeof e !== "object" || Array.isArray(e))
|
|
401
|
+
return false;
|
|
402
|
+
const r = e.resource;
|
|
403
|
+
if (typeof r !== "string")
|
|
404
|
+
return false;
|
|
405
|
+
const inBundle = resolveBundlePath(r, page.rel);
|
|
406
|
+
return r === resource || (inBundle !== null && bundlePath(inBundle) === resource);
|
|
407
|
+
});
|
|
408
|
+
if (at !== -1 && entries[at]["x-agent-wiki-relation"] === undefined) {
|
|
409
|
+
entries[at] = { ...entries[at], "x-agent-wiki-relation": "derived_from" };
|
|
410
|
+
}
|
|
411
|
+
continue;
|
|
412
|
+
}
|
|
413
|
+
seen.add(resource);
|
|
414
|
+
entries.push({ resource, "x-agent-wiki-relation": "derived_from" });
|
|
415
|
+
}
|
|
416
|
+
return entries;
|
|
417
|
+
};
|
|
418
|
+
let sourcesWritten = false;
|
|
419
|
+
for (const [key, value] of Object.entries(src)) {
|
|
420
|
+
if (key === "sources" || key === "derived_from") {
|
|
421
|
+
if (!sourcesWritten) {
|
|
422
|
+
const mapped = mapSources();
|
|
423
|
+
if (mapped.length > 0)
|
|
424
|
+
outFm.sources = mapped;
|
|
425
|
+
else if (key === "sources")
|
|
426
|
+
outFm.sources = value;
|
|
427
|
+
sourcesWritten = true;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
else if (key === "sources_sha" || key === "updated") {
|
|
431
|
+
// merged into `sources` entries and `generated.at`
|
|
432
|
+
}
|
|
433
|
+
else if (EXTENSION_KEYS[key]) {
|
|
434
|
+
outFm[EXTENSION_KEYS[key]] = value;
|
|
435
|
+
}
|
|
436
|
+
else {
|
|
437
|
+
outFm[key] = value;
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
const updated = toTimestamp(src.updated);
|
|
441
|
+
if (updated && isBlank(src.generated))
|
|
442
|
+
outFm.generated = { by: generatedBy, at: updated };
|
|
443
|
+
if (staleAfterDays !== null && updated && isBlank(src.stale_after)) {
|
|
444
|
+
outFm.stale_after = new Date(Date.parse(updated) + staleAfterDays * 86_400_000).toISOString().replace(/\.000Z$/, "Z");
|
|
445
|
+
}
|
|
446
|
+
const disputedBy = [...new Set((disputes[page.rel] ?? []).map((d) => bundlePath(d.page.replace(/\\/g, "/"))))].sort();
|
|
447
|
+
if (disputedBy.length > 0)
|
|
448
|
+
outFm["x-agent-wiki-disputed-by"] = disputedBy;
|
|
449
|
+
// Drift that this page already carries from an earlier export (it has no seal of its
|
|
450
|
+
// own to check) is kept as it is; only drift found against this workspace's raw/ is written.
|
|
451
|
+
const carriesDrift = isBlank(src.sources_sha) && !isBlank(src["x-agent-wiki-source-drift"]);
|
|
452
|
+
const drifted = carriesDrift ? [] : drift[page.rel] ?? [];
|
|
453
|
+
if (drifted.length > 0) {
|
|
454
|
+
outFm["x-agent-wiki-source-drift"] = drifted.map((d) => ({
|
|
455
|
+
resource: toResource(d.source),
|
|
456
|
+
reason: d.reason,
|
|
457
|
+
...(d.newerVersion ? { newer: needRaw(d.newerVersion.replace(/^raw\//, "")) } : {}),
|
|
458
|
+
}));
|
|
459
|
+
}
|
|
460
|
+
return outFm;
|
|
461
|
+
};
|
|
462
|
+
// ── Write ───────────────────────────────────────────────────────
|
|
463
|
+
const write = (rel, content) => {
|
|
464
|
+
const target = safePath(out, rel);
|
|
465
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
466
|
+
writeFileSync(target, content);
|
|
467
|
+
report.written.push(rel);
|
|
468
|
+
};
|
|
469
|
+
mkdirSync(out, { recursive: true });
|
|
470
|
+
const descriptions = new Map();
|
|
471
|
+
const types = new Map();
|
|
472
|
+
for (const page of pages) {
|
|
473
|
+
const body = convertLinks(page.body, page.rel);
|
|
474
|
+
if (page.data === null) {
|
|
475
|
+
write(page.rel, body);
|
|
476
|
+
continue;
|
|
477
|
+
}
|
|
478
|
+
const mapped = mapFrontmatter(page);
|
|
479
|
+
const d = str(mapped.description);
|
|
480
|
+
if (d)
|
|
481
|
+
descriptions.set(page.rel, d.replace(/\s+/g, " "));
|
|
482
|
+
const t = str(mapped.type);
|
|
483
|
+
if (t)
|
|
484
|
+
types.set(page.rel, t);
|
|
485
|
+
// Nothing to translate: the file is already in OKF form and is copied as it is.
|
|
486
|
+
if (body === page.body && sameValue(mapped, page.data))
|
|
487
|
+
write(page.rel, page.text);
|
|
488
|
+
else
|
|
489
|
+
write(page.rel, `---\n${dumpFrontmatter(mapped)}---\n${body}`);
|
|
490
|
+
}
|
|
491
|
+
for (const rel of assets) {
|
|
492
|
+
const target = safePath(out, rel);
|
|
493
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
494
|
+
copyFileSync(join(wikiDir, rel), target);
|
|
495
|
+
report.written.push(rel);
|
|
496
|
+
}
|
|
497
|
+
const written = new Set(report.written);
|
|
498
|
+
for (const [rawRel, dest] of [...rawNeeded.entries()].sort()) {
|
|
499
|
+
let source;
|
|
500
|
+
try {
|
|
501
|
+
source = safePath(rawDir, rawRel);
|
|
502
|
+
}
|
|
503
|
+
catch {
|
|
504
|
+
report.findings.push({ level: "warning", code: "AW04", path: dest, message: `cited raw path raw/${rawRel} leaves raw/; not copied` });
|
|
505
|
+
continue;
|
|
506
|
+
}
|
|
507
|
+
if (written.has(dest)) {
|
|
508
|
+
report.findings.push({ level: "warning", code: "AW04", path: dest, message: `raw/${rawRel} not copied: the wiki already has a file at this path` });
|
|
509
|
+
continue;
|
|
510
|
+
}
|
|
511
|
+
// raw/ may hold a link to somewhere else; a bundle is made to be shared, so only
|
|
512
|
+
// files that really are inside raw/ go into it.
|
|
513
|
+
const reallyInRaw = (file) => {
|
|
514
|
+
try {
|
|
515
|
+
const real = realpathSync(file);
|
|
516
|
+
return real.startsWith(rawDir + sep) && lstatSync(real).isFile();
|
|
517
|
+
}
|
|
518
|
+
catch {
|
|
519
|
+
return false;
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
if (existsSync(source) && !reallyInRaw(source)) {
|
|
523
|
+
report.findings.push({ level: "warning", code: "AW04", path: dest, message: `raw/${rawRel} is reached through a symbolic link that leaves raw/; not copied` });
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (!existsSync(source) || !lstatSync(source).isFile()) {
|
|
527
|
+
report.findings.push({ level: "warning", code: "AW04", path: dest, message: `cited raw file raw/${rawRel} does not exist; the bundle has no copy of it` });
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
const target = safePath(out, dest);
|
|
531
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
532
|
+
copyFileSync(source, target);
|
|
533
|
+
report.written.push(dest);
|
|
534
|
+
written.add(dest);
|
|
535
|
+
report.bundle.raw_files++;
|
|
536
|
+
const sidecar = `${source}.meta.yaml`;
|
|
537
|
+
// Next to the copy, under the raw file's own name unless that had to change.
|
|
538
|
+
const natural = dest === `${OKF_RAW_DIR}/${rawRel}` || dest === `${OKF_RAW_DIR}/${rawRel}.txt`;
|
|
539
|
+
const sidecarDest = natural ? `${OKF_RAW_DIR}/${rawRel}.meta.yaml` : `${dest}.meta.yaml`;
|
|
540
|
+
if (existsSync(sidecar) && reallyInRaw(sidecar) && !written.has(sidecarDest)) {
|
|
541
|
+
copyFileSync(sidecar, safePath(out, sidecarDest));
|
|
542
|
+
report.written.push(sidecarDest);
|
|
543
|
+
written.add(sidecarDest);
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
// ── index.md per directory (§8) ─────────────────────────────────
|
|
547
|
+
const dirs = new Map(); // directory → pages directly in it
|
|
548
|
+
for (const rel of pagePaths) {
|
|
549
|
+
const name = rel.slice(rel.lastIndexOf("/") + 1).toLowerCase();
|
|
550
|
+
if (name === "log.md")
|
|
551
|
+
continue;
|
|
552
|
+
let dir = posix.dirname(rel);
|
|
553
|
+
if (dir === ".")
|
|
554
|
+
dir = "";
|
|
555
|
+
dirs.set(dir, [...(dirs.get(dir) ?? []), rel]);
|
|
556
|
+
for (let up = dir; up !== "";) {
|
|
557
|
+
up = up.includes("/") ? up.slice(0, up.lastIndexOf("/")) : "";
|
|
558
|
+
if (!dirs.has(up))
|
|
559
|
+
dirs.set(up, []);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
if (!dirs.has(""))
|
|
563
|
+
dirs.set("", []);
|
|
564
|
+
const countBelow = (dir) => [...pagePaths].filter((p) => p.startsWith(`${dir}/`) && !p.toLowerCase().endsWith("/log.md")).length;
|
|
565
|
+
for (const [dir, direct] of dirs) {
|
|
566
|
+
const lines = [];
|
|
567
|
+
const subdirs = [...dirs.keys()]
|
|
568
|
+
.filter((d) => d !== "" && d !== dir && (dir === "" ? !d.includes("/") : d.startsWith(`${dir}/`) && !d.slice(dir.length + 1).includes("/")))
|
|
569
|
+
.sort();
|
|
570
|
+
if (subdirs.length > 0) {
|
|
571
|
+
lines.push("# Subdirectories", "");
|
|
572
|
+
for (const sub of subdirs) {
|
|
573
|
+
const name = sub.slice(sub.lastIndexOf("/") + 1);
|
|
574
|
+
const n = countBelow(sub);
|
|
575
|
+
lines.push(`* [${linkText(name)}](${linkDestination(name)}/index.md) - ${n} ${n === 1 ? "page" : "pages"}`);
|
|
576
|
+
}
|
|
577
|
+
lines.push("");
|
|
578
|
+
}
|
|
579
|
+
const groups = new Map();
|
|
580
|
+
for (const rel of direct) {
|
|
581
|
+
const type = types.get(rel) ?? "Other";
|
|
582
|
+
groups.set(type, [...(groups.get(type) ?? []), rel]);
|
|
583
|
+
}
|
|
584
|
+
for (const type of [...groups.keys()].sort((a, b) => (a === "Other" ? 1 : b === "Other" ? -1 : a.localeCompare(b)))) {
|
|
585
|
+
lines.push(`# ${type}`, "");
|
|
586
|
+
for (const rel of groups.get(type).sort()) {
|
|
587
|
+
const desc = descriptions.get(rel);
|
|
588
|
+
lines.push(`* [${linkText(titles.get(rel))}](${linkDestination(posix.basename(rel))})${desc ? ` - ${desc}` : ""}`);
|
|
589
|
+
}
|
|
590
|
+
lines.push("");
|
|
591
|
+
}
|
|
592
|
+
if (lines.length === 0)
|
|
593
|
+
lines.push("# Contents", "", "This bundle has no pages yet.", "");
|
|
594
|
+
const body = lines.join("\n");
|
|
595
|
+
if (dir === "")
|
|
596
|
+
write("index.md", `---\n${dumpFrontmatter(rootMeta)}---\n\n${body}`);
|
|
597
|
+
else
|
|
598
|
+
write(`${dir}/index.md`, body);
|
|
599
|
+
}
|
|
600
|
+
// ── log.md (§9) ─────────────────────────────────────────────────
|
|
601
|
+
write("log.md", convertLog(nativeLog, (text) => convertLinks(text, "log.md"), linkable));
|
|
602
|
+
// ── Check what was written, with the same rules the importer applies ──
|
|
603
|
+
report.written.sort();
|
|
604
|
+
const check = checkOkfBundle(out);
|
|
605
|
+
report.findings.push(...check.findings);
|
|
606
|
+
report.bundle.conformant = check.conformant;
|
|
607
|
+
report.bundle.concepts = check.concepts.length;
|
|
608
|
+
report.bundle.other_markdown = check.otherMarkdown.length;
|
|
609
|
+
report.bundle.assets = check.assets.length;
|
|
610
|
+
report.ok = check.conformant;
|
|
611
|
+
if (!check.conformant)
|
|
612
|
+
report.refused = "the exported bundle is not conformant with OKF v0.3 (§11.1); see findings";
|
|
613
|
+
return report;
|
|
614
|
+
}
|
|
615
|
+
const NATIVE_LOG_ROW = /^\|\s*(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2})(?::\d{2})?(?:\s*(UTC|Z))?)?\s*\|(.*)\|\s*$/;
|
|
616
|
+
/**
|
|
617
|
+
* agent-wiki's operation log (frontmatter and one table) in the §9 form: no frontmatter,
|
|
618
|
+
* entries grouped under `## YYYY-MM-DD`, newest first. A log that is already in that form
|
|
619
|
+
* (no frontmatter, no table) is kept.
|
|
620
|
+
*/
|
|
621
|
+
function convertLog(native, links, linkable) {
|
|
622
|
+
const heading = "# Update Log\n";
|
|
623
|
+
if (native === null)
|
|
624
|
+
return heading;
|
|
625
|
+
const page = readPage("log.md", native);
|
|
626
|
+
const rows = [];
|
|
627
|
+
for (const line of page.body.split("\n")) {
|
|
628
|
+
const m = line.match(NATIVE_LOG_ROW);
|
|
629
|
+
if (!m)
|
|
630
|
+
continue;
|
|
631
|
+
const cells = m[4].split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, "|"));
|
|
632
|
+
const [operation = "", target = "", ...rest] = cells;
|
|
633
|
+
const summary = links(rest.join(" | ").trim());
|
|
634
|
+
const kind = operation === "" ? "Update" : operation.charAt(0).toUpperCase() + operation.slice(1);
|
|
635
|
+
const where = target === "" || target === "—" || target === "-"
|
|
636
|
+
? ""
|
|
637
|
+
: linkable.has(target)
|
|
638
|
+
? ` ([${linkText(target)}](${linkDestination(target)}))`
|
|
639
|
+
: ` (\`${target.replace(/`/g, "'")}\`)`;
|
|
640
|
+
const time = m[2] ? ` at ${m[2]} UTC` : "";
|
|
641
|
+
rows.push({ date: m[1], line: `* **${kind}**${time}: ${summary === "" ? "(no summary)" : summary}${where}` });
|
|
642
|
+
}
|
|
643
|
+
if (rows.length === 0) {
|
|
644
|
+
return page.data === null && page.body.trim() !== "" ? native : heading;
|
|
645
|
+
}
|
|
646
|
+
const byDate = new Map();
|
|
647
|
+
for (const row of rows)
|
|
648
|
+
byDate.set(row.date, [...(byDate.get(row.date) ?? []), row.line]);
|
|
649
|
+
const out = [heading];
|
|
650
|
+
for (const date of [...byDate.keys()].sort().reverse()) {
|
|
651
|
+
out.push(`## ${date}`, ...byDate.get(date).reverse(), "");
|
|
652
|
+
}
|
|
653
|
+
return out.join("\n");
|
|
654
|
+
}
|
|
655
|
+
//# sourceMappingURL=okf-export.js.map
|