Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions cli/src/commands/kb.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { dirname as parentOf, join as pathJoin, resolve as pathResolve } from "n

import { ApiError } from "../api.mjs";
import { ConflictError, UsageError } from "../errors.mjs";
import { apiMutation, batches, changedPaths, commitFiles, planMirror, planReconcile, recordedVersions, repositoryName, resolveCommit } from "../knowledgePublish.mjs";
import { apiMutation, batches, changedPaths, commitFiles, planMirror, planPublish, recordedVersions, repositoryName, resolveCommit } from "../knowledgePublish.mjs";
import { enc, fields, integer, optionalString, positional, table } from "../format.mjs";
import { apiFor } from "../session.mjs";
import { copyKnowledgeDocument, exportKnowledgeDocument } from "./kb-transfer.mjs";
Expand Down Expand Up @@ -49,7 +49,8 @@ Usage
dataops kb publish [--head REV] [--repo DIR] [--changed-since REV] [--dry-run]
Make prod match a knowledge-repo commit; files
edited in prod that Git has not seen are left
alone, and real conflicts exit 5
alone, and real conflicts exit 5. Refresh the
business-system map while preserving its live intro.
dataops kb mirror [--head REV] [--repo DIR] [--dry-run]
Bring prod's web edits into the Git working tree:
prod-ahead files byte for byte, files both sides
Expand Down Expand Up @@ -406,9 +407,11 @@ export async function publish(args, io) {
const diverged = [...new Set([...files.keys(), ...Object.keys(prod)])]
.filter((file) => (prod[file]?.sha256 ?? null) !== (files.get(file)?.sha ?? null));
const recorded = recordedVersions(repo, head, manifest.roots, diverged);
const plan = await planReconcile({
const plan = await planPublish({
files, prod, known: (file) => recorded.get(file)?.states ?? new Set(),
recordedBytes: (file) => recorded.get(file)?.bytes ?? new Map(),
page: (file, cursor) => api.get("/knowledge/history", { query: { path: file, cursor } }),
version: (file) => downloadKnowledgeVersion(api, file, manifest.revision),
});
let revision = manifest.revision;
if (!args.dryRun && plan.mutations.length) {
Expand All @@ -431,7 +434,11 @@ export async function publish(args, io) {
else io.print(`Nothing to publish: ${result.unchanged} file(s) already match prod.`);
}
if (plan.conflicts.length) {
const lines = plan.conflicts.map((item) => ` ${item.path} (prod ${item.prod === "absent" ? "deleted it" : "edited it"} in a way Git has not seen, and Git's copy differs from where that edit started)`);
const lines = plan.conflicts.map((item) => {
const change = item.prod === "absent" ? "deleted it" : "edited it";
const reason = item.reason ?? `prod ${change} in a way Git has not seen, and Git's copy differs from where that edit started`;
return ` ${item.path} (${reason})`;
});
throw new ConflictError(
`${plan.conflicts.length} file(s) changed both in prod and in Git; they were left untouched${args.dryRun ? "" : ", everything else was published"}:\n${lines.join("\n")}\n`
+ "Merge the prod edit into Git (copy it from the web editor or wait for the daily mirror), then push again.",
Expand Down
75 changes: 75 additions & 0 deletions cli/src/knowledgePublish.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ export function isManagedPath(file, roots) {

const DERIVED_ID = /^id:\s*["']?(task-template\.tasks\.[a-z0-9-]+|reference\.indexes\.document-index)["']?\s*$/m;
const GENERATED_SYSTEM_MARKER = "<!-- This system page is seeded from the audit register.";
const SYSTEM_MAP_PATH = "content/00-start-here/business-system-map/system-overview.md";
const SYSTEM_MAP_ID = /^id:[ \t]*["']?system\.start-here\.business-system-map["']?[ \t]*\r?$/m;

/**
* True when a Git copy is a derived document that the server regenerates:
Expand Down Expand Up @@ -151,6 +153,79 @@ export async function planReconcile({ files, prod, known, page, concurrency = 12
return plan;
}

function systemMapSections(bytes) {
const text = bytes.toString("utf8");
if (!Buffer.from(text).equals(bytes)) return null;
const frontmatter = /^(?:\uFEFF)?---\r?\n([\s\S]*?)\r?\n---[ \t]*\r?\n/.exec(text);
if (!frontmatter || !SYSTEM_MAP_ID.test(frontmatter[1]) || frontmatter[1].match(/^id:/gm).length !== 1) return null;
const body = text.slice(frontmatter[0].length);
const title = /^(?:[ \t]*\r?\n)*# [^\r\n]+\r?\n/.exec(body);
const boundary = [...body.matchAll(/^## Core systems[ \t]*\r?$/gm)];
if (!title || boundary.length !== 1 || title[0].length > boundary[0].index) return null;
const start = boundary[0].index;
return { frontmatter: frontmatter[0], title: title[0], intro: body.slice(title[0].length, start), navigation: body.slice(start) };
}

/** The live map owns the introduction. The generator owns navigation. Both can edit frontmatter. */
export async function planPublish(options) {
const { files, prod, known, page, version, recordedBytes } = options;
const head = files.get(SYSTEM_MAP_PATH);
const prodSha = prod[SYSTEM_MAP_PATH]?.sha256;
if (!head || !prodSha || head.sha === prodSha) return planReconcile(options);

const otherFiles = new Map(files);
otherFiles.delete(SYSTEM_MAP_PATH);
const otherProd = { ...prod };
delete otherProd[SYSTEM_MAP_PATH];
const [plan, current] = await Promise.all([
planReconcile({ ...options, files: otherFiles, prod: otherProd }),
version(SYSTEM_MAP_PATH),
]);
if (!current || sha256(current) !== prodSha) {
throw new Error(`${SYSTEM_MAP_PATH}: prod bytes do not match the manifest sha256`);
}
const conflict = (reason) => {
plan.conflicts.push({ path: SYSTEM_MAP_PATH, prod: "differs", reason });
return plan;
};
const incoming = systemMapSections(head.bytes);
const live = systemMapSections(current);
if (!incoming || !live) return conflict("expected the map ID and one Core systems boundary");

// The full published blob can differ from every Git blob because of its intro.
// Recognize Git-recorded metadata, title and navigation by exact section bytes.
const recorded = recordedBytes(SYSTEM_MAP_PATH);
const sections = [...recorded.values()].map(systemMapSections).filter(Boolean);
const fields = ["frontmatter", "title", "navigation"];
const unresolved = fields.filter((field) => incoming[field] !== live[field]
&& !sections.some((section) => section[field] === live[field]));
let base;
if (unresolved.length) {
const lineage = await walkLineage(page, SYSTEM_MAP_PATH, known(SYSTEM_MAP_PATH));
const shared = lineage.states.find(({ sha }) => known(SYSTEM_MAP_PATH).has(sha));
const sharedBytes = shared && recorded.get(shared.sha);
base = sharedBytes && systemMapSections(sharedBytes);
if (!base) return conflict("no common map version with a verified section boundary");
}

const merged = { ...incoming, intro: live.intro };
for (const field of unresolved) {
const result = threeWayMerge({
ours: Buffer.from(incoming[field]), baseBytes: Buffer.from(base[field]), theirs: Buffer.from(live[field]),
});
if (result.conflicts) return conflict(`both sides changed the same ${field} lines`);
merged[field] = result.bytes.toString("utf8");
}
const bytes = Buffer.from(merged.frontmatter + merged.title + merged.intro + merged.navigation);
if (!systemMapSections(bytes)) return conflict("merged map does not have one verified section boundary");
if (bytes.equals(current)) plan.unchanged += 1;
else {
plan.mutations.push({ path: SYSTEM_MAP_PATH, operation: "edit", base64: bytes.toString("base64") });
plan.mutations.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
}
return plan;
}

/**
* Classify one path from its /knowledge/history pages, newest first. Each
* page is fetched only while the verdict is still undecided: classification
Expand Down
78 changes: 77 additions & 1 deletion cli/test/kb-publish.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, test } from "node:test";
Expand Down Expand Up @@ -248,6 +248,10 @@ describe("kb publish from a Git checkout", () => {
versions: (history[query.path] || []).map((body) => ({ sha256: h(body), deleted: body === null })),
cursor: null,
}),
"GET /knowledge/download": ({ query }) => ({
url: `https://portal.test/storage?path=${encodeURIComponent(query.path)}`,
}),
"GET /storage": ({ query }) => new Response(prodFiles[query.path] ?? ""),
"POST /knowledge/publish": ({ body }) => {
if (body.expectedRevision !== current) return { status: 409, body: { error: "Knowledge changed" } };
current = `${current}+`;
Expand All @@ -256,6 +260,78 @@ describe("kb publish from a Git checkout", () => {
});
}

const mapPath = "content/00-start-here/business-system-map/system-overview.md";
function systemMap({ title = "Business system map", heading = "Business system map", intro = "Original introduction.", related = "old-system", row = "Old row" } = {}) {
return [
"---", "id: system.start-here.business-system-map", "doc_type: system-overview",
`title: ${title}`, "related_docs:", `- ${related}`, "---", "", `# ${heading}`,
"", intro, "", "## Core systems", "", `- ${row}`, "",
].join("\n");
}

test("refreshes generated map navigation while preserving the owner introduction across a mirror round trip", async () => {
const base = systemMap();
const intro = "The owner's current explanation.";
const edited = systemMap({ intro });
const firstNavigation = { related: "new-system", row: "New row" };
const refreshed = systemMap({ intro, ...firstNavigation });
write(mapPath, base);
commit("base generated map");
write(mapPath, systemMap(firstNavigation));
commit("first navigation refresh");

const args = ["kb", "publish", "--repo", repo, "--json"];
const firstCalls = portal({ [mapPath]: edited }, { [mapPath]: [edited, base] });
const preview = captureIo();
assert.equal(await run([...args, "--dry-run"], preview), 0);
assert.deepEqual(preview.json().published, [{ path: mapPath, operation: "edit" }]);
assert.equal(firstCalls.some((call) => call.method === "POST"), false);
const publish = captureIo();
assert.equal(await run(args, publish), 0);
assert.deepEqual(publish.json().published, preview.json().published);
const firstMutation = firstCalls.find((call) => call.method === "POST").body.mutations[0];
assert.equal(Buffer.from(firstMutation.base64, "base64").toString(), refreshed);

const repeatedCalls = portal({ [mapPath]: refreshed });
assert.equal(await run(args, captureIo()), 0);
assert.equal(repeatedCalls.some((call) => call.method === "POST"), false);

portal({ [mapPath]: refreshed }, { [mapPath]: [refreshed, edited, base] });
assert.equal(await run(["kb", "mirror", "--repo", repo], captureIo()), 0);
assert.equal(readFileSync(path.join(repo, mapPath), "utf8"), refreshed);
commit("mirror records the published map");

const secondNavigation = { related: "next-system", row: "Next row" };
write(mapPath, systemMap(secondNavigation));
commit("generator refreshes navigation and emits its standard introduction");
const afterMirror = portal({ [mapPath]: refreshed }, { [mapPath]: [refreshed] });
assert.equal(await run(args, captureIo()), 0);
const secondMutation = afterMirror.find((call) => call.method === "POST").body.mutations[0];
assert.equal(Buffer.from(secondMutation.base64, "base64").toString(), systemMap({ intro, ...secondNavigation }));
});

test("keeps map metadata and navigation conflicts visible, and rejects an ambiguous boundary", async () => {
const cases = [
[systemMap({ title: "Operator title" }), systemMap({ title: "Generator title" }), /frontmatter/],
[systemMap({ heading: "Operator title" }), systemMap({ heading: "Generator title" }), /same title lines/],
[systemMap({ row: "Operator row" }), systemMap({ row: "Generator row" }), /navigation/],
[systemMap({ intro: "Owner introduction." }), systemMap().replace("## Core systems", "## Systems"), /boundary/],
];
const base = systemMap();
write(mapPath, base);
const baseline = commit("base generated map");
for (const [live, generated, reason] of cases) {
git("checkout", "-q", "--detach", baseline);
write(mapPath, generated);
commit("competing edit");
const calls = portal({ [mapPath]: live }, { [mapPath]: [live, base] });
const io = captureIo();
assert.equal(await run(["kb", "publish", "--repo", repo], io), 5);
assert.match(io.errors.join("\n"), reason);
assert.equal(calls.some((call) => call.method === "POST"), false);
}
});

test("repairs files Git restored to an older version, with exact bytes and the commit in the message", async () => {
write("content/sop.md", "good");
write("content/gone.md", "bye");
Expand Down