@floless/app 0.86.1 → 0.88.0

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.
@@ -53106,7 +53106,7 @@ function appVersion() {
53106
53106
  return resolveVersion({
53107
53107
  isSea: isSea2(),
53108
53108
  sqVersionXml: readSqVersionXml(),
53109
- define: true ? "0.86.1" : void 0,
53109
+ define: true ? "0.88.0" : void 0,
53110
53110
  pkgVersion: readPkgVersion()
53111
53111
  });
53112
53112
  }
@@ -53116,7 +53116,7 @@ function resolveChannel(s) {
53116
53116
  return "dev";
53117
53117
  }
53118
53118
  function appChannel() {
53119
- return resolveChannel({ isSea: isSea2(), define: true ? "0.86.1" : void 0 });
53119
+ return resolveChannel({ isSea: isSea2(), define: true ? "0.88.0" : void 0 });
53120
53120
  }
53121
53121
 
53122
53122
  // workflow-update.ts
@@ -54329,6 +54329,9 @@ function slugify(name) {
54329
54329
  function projectDir(id) {
54330
54330
  return (0, import_node_path18.join)(DIR2, safeProjectId(id));
54331
54331
  }
54332
+ function archiveDir(id) {
54333
+ return (0, import_node_path18.join)(ARCHIVE, safeProjectId(id));
54334
+ }
54332
54335
  function projectExportsDir(id) {
54333
54336
  return (0, import_node_path18.join)(projectDir(id), "exports");
54334
54337
  }
@@ -54336,17 +54339,19 @@ function projectKnowledgeDir(id) {
54336
54339
  return (0, import_node_path18.join)(projectDir(id), "knowledge");
54337
54340
  }
54338
54341
  var metaPath = (id) => (0, import_node_path18.join)(projectDir(id), "project.json");
54339
- function readMeta(id) {
54340
- const p = metaPath(id);
54341
- if (!(0, import_node_fs20.existsSync)(p)) return null;
54342
+ function readMetaFile(jsonPath, id) {
54343
+ if (!(0, import_node_fs20.existsSync)(jsonPath)) return null;
54342
54344
  try {
54343
- const meta = JSON.parse((0, import_node_fs20.readFileSync)(p, "utf8"));
54345
+ const meta = JSON.parse((0, import_node_fs20.readFileSync)(jsonPath, "utf8"));
54344
54346
  return meta && meta.id === id ? meta : null;
54345
54347
  } catch (e) {
54346
- console.warn(`projects-store: ignoring unreadable project.json at ${p}: ${e instanceof Error ? e.message : e}`);
54348
+ console.warn(`projects-store: ignoring unreadable project.json at ${jsonPath}: ${e instanceof Error ? e.message : e}`);
54347
54349
  return null;
54348
54350
  }
54349
54351
  }
54352
+ function readMeta(id) {
54353
+ return readMetaFile(metaPath(id), id);
54354
+ }
54350
54355
  var writeMeta = (meta) => (0, import_node_fs20.writeFileSync)(metaPath(meta.id), JSON.stringify(meta, null, 2));
54351
54356
  function listProjects() {
54352
54357
  if (!(0, import_node_fs20.existsSync)(DIR2)) return [];
@@ -54415,8 +54420,35 @@ function archiveProject(id) {
54415
54420
  (0, import_node_fs20.mkdirSync)(ARCHIVE, { recursive: true });
54416
54421
  const dest = (0, import_node_path18.join)(ARCHIVE, id);
54417
54422
  if ((0, import_node_fs20.existsSync)(dest)) throw new ProjectError(`already archived: ${id}`);
54423
+ const meta = readMeta(id);
54424
+ if (meta) writeMeta({ ...meta, updatedAt: (/* @__PURE__ */ new Date()).toISOString() });
54418
54425
  (0, import_node_fs20.renameSync)(dir, dest);
54419
54426
  }
54427
+ function listArchivedProjects() {
54428
+ if (!(0, import_node_fs20.existsSync)(ARCHIVE)) return [];
54429
+ const out = [];
54430
+ for (const entry2 of (0, import_node_fs20.readdirSync)(ARCHIVE, { withFileTypes: true })) {
54431
+ if (!entry2.isDirectory() || entry2.name.startsWith(".")) continue;
54432
+ const meta = readMetaFile((0, import_node_path18.join)(ARCHIVE, entry2.name, "project.json"), entry2.name);
54433
+ if (meta) out.push(meta);
54434
+ }
54435
+ return out.sort((a, b) => a.updatedAt < b.updatedAt ? 1 : -1);
54436
+ }
54437
+ function unarchiveProject(id) {
54438
+ const src = archiveDir(id);
54439
+ if (!(0, import_node_fs20.existsSync)(src)) throw new ProjectError(`not archived: ${id}`);
54440
+ const meta = readMetaFile((0, import_node_path18.join)(src, "project.json"), id);
54441
+ if (!meta) throw new ProjectError(`archived project has missing or unreadable metadata: ${id}`);
54442
+ const dest = projectDir(id);
54443
+ if ((0, import_node_fs20.existsSync)(dest)) throw new ProjectError(`a live project with that id already exists: ${id}`);
54444
+ (0, import_node_fs20.renameSync)(src, dest);
54445
+ return meta;
54446
+ }
54447
+ function deleteArchivedProject(id) {
54448
+ const dir = archiveDir(id);
54449
+ if (!(0, import_node_fs20.existsSync)(dir)) throw new ProjectError(`not archived: ${id}`);
54450
+ (0, import_node_fs20.rmSync)(dir, { recursive: true, force: true });
54451
+ }
54420
54452
 
54421
54453
  // knowledge-routes.ts
54422
54454
  var import_node_fs22 = require("node:fs");
@@ -54425,6 +54457,7 @@ var import_node_fs22 = require("node:fs");
54425
54457
  var import_node_crypto7 = require("node:crypto");
54426
54458
  var import_node_fs21 = require("node:fs");
54427
54459
  var import_node_path19 = require("node:path");
54460
+ var import_yaml5 = __toESM(require_dist6(), 1);
54428
54461
  var KnowledgeError = class extends Error {
54429
54462
  code;
54430
54463
  constructor(message, code) {
@@ -54708,6 +54741,245 @@ function readCurrentGeneration(id) {
54708
54741
  return null;
54709
54742
  }
54710
54743
  }
54744
+ function currentGenerationWikiDir(id) {
54745
+ const current = readCurrentGeneration(id);
54746
+ if (!current) return null;
54747
+ const dir = generationWikiDir(id, current.generationId);
54748
+ return (0, import_node_fs21.existsSync)(dir) ? dir : null;
54749
+ }
54750
+ var WIKI_SLUG_RE = /^[a-z0-9][a-z0-9._-]*$/;
54751
+ var KB_MAX_NODES = 300;
54752
+ var KB_MAX_TOTAL_BYTES = 8 * 1024 * 1024;
54753
+ var KB_MAX_VISITS = 5e3;
54754
+ var KB_MAX_PAGE_BYTES = 512 * 1024;
54755
+ var REAL_IO = {
54756
+ readdir: (dir) => (0, import_node_fs21.readdirSync)(dir, { withFileTypes: true }),
54757
+ readFile: (path) => (0, import_node_fs21.readFileSync)(path, "utf8"),
54758
+ statSize: (path) => (0, import_node_fs21.statSync)(path).size
54759
+ };
54760
+ var VAULT_START = "<!-- vault:generated:start -->";
54761
+ var VAULT_END = "<!-- vault:generated:end -->";
54762
+ var FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/;
54763
+ var WIKILINK_RE = /(!?)\[\[([^\]]+)\]\]/g;
54764
+ function normalizeText(raw) {
54765
+ return raw.replace(/^/, "").replace(/\r\n/g, "\n");
54766
+ }
54767
+ function eachPage(wikiDir, io, onPage) {
54768
+ let visits = 0;
54769
+ let ioError = false;
54770
+ let limitHit = false;
54771
+ let found = false;
54772
+ const walk2 = (dir) => {
54773
+ let entries;
54774
+ try {
54775
+ entries = io.readdir(dir);
54776
+ } catch (e) {
54777
+ console.warn(`knowledge-store: cannot read wiki dir ${dir}: ${e instanceof Error ? e.message : e}`);
54778
+ ioError = true;
54779
+ return "go";
54780
+ }
54781
+ for (const ent of [...entries].sort((x, y) => x.name.localeCompare(y.name))) {
54782
+ if (++visits > KB_MAX_VISITS) {
54783
+ console.warn(`knowledge-store: wiki exceeds KB_MAX_VISITS=${KB_MAX_VISITS}, truncating`);
54784
+ limitHit = true;
54785
+ return "stop";
54786
+ }
54787
+ if (ent.isDirectory()) {
54788
+ if (walk2((0, import_node_path19.join)(dir, ent.name)) === "stop") return "stop";
54789
+ } else if (ent.isFile() && ent.name.endsWith(".md")) {
54790
+ const slug = ent.name.slice(0, -3);
54791
+ if (!WIKI_SLUG_RE.test(slug)) {
54792
+ console.warn(`knowledge-store: skipping non-canonical wiki basename "${slug}" (${(0, import_node_path19.join)(dir, ent.name)})`);
54793
+ continue;
54794
+ }
54795
+ if (onPage(slug, (0, import_node_path19.join)(dir, ent.name))) {
54796
+ found = true;
54797
+ return "stop";
54798
+ }
54799
+ }
54800
+ }
54801
+ return "go";
54802
+ };
54803
+ walk2(wikiDir);
54804
+ return found ? "found" : limitHit ? "limit" : ioError ? "io-error" : "complete";
54805
+ }
54806
+ function collectPages(wikiDir, io) {
54807
+ const pages = /* @__PURE__ */ new Map();
54808
+ const dupes = /* @__PURE__ */ new Set();
54809
+ const status = eachPage(wikiDir, io, (slug, path) => {
54810
+ if (pages.has(slug)) dupes.add(slug);
54811
+ else pages.set(slug, path);
54812
+ return false;
54813
+ });
54814
+ if (dupes.size) console.warn(`knowledge-store: duplicate wiki basenames (kept first): ${[...dupes].join(", ")}`);
54815
+ return { pages, incomplete: status !== "complete" };
54816
+ }
54817
+ function splitPage(path, io) {
54818
+ let size;
54819
+ try {
54820
+ size = io.statSize(path);
54821
+ } catch (e) {
54822
+ console.warn(`knowledge-store: cannot stat ${path}: ${e instanceof Error ? e.message : e}`);
54823
+ return { ok: false, reason: "io-error" };
54824
+ }
54825
+ if (size > KB_MAX_PAGE_BYTES) {
54826
+ console.warn(`knowledge-store: wiki page ${path} exceeds KB_MAX_PAGE_BYTES=${KB_MAX_PAGE_BYTES}, skipping`);
54827
+ return { ok: false, reason: "oversize" };
54828
+ }
54829
+ let raw;
54830
+ try {
54831
+ raw = normalizeText(io.readFile(path));
54832
+ } catch (e) {
54833
+ console.warn(`knowledge-store: cannot read wiki page ${path}: ${e instanceof Error ? e.message : e}`);
54834
+ return { ok: false, reason: "io-error" };
54835
+ }
54836
+ const m = FRONTMATTER_RE.exec(raw);
54837
+ let fm = {};
54838
+ let rest = raw;
54839
+ if (m) {
54840
+ rest = raw.slice(m[0].length);
54841
+ try {
54842
+ const parsed = (0, import_yaml5.parse)(m[1] ?? "");
54843
+ if (parsed && typeof parsed === "object") fm = parsed;
54844
+ } catch (e) {
54845
+ console.warn(`knowledge-store: malformed frontmatter in ${path}: ${e instanceof Error ? e.message : e}`);
54846
+ }
54847
+ }
54848
+ const s = rest.indexOf(VAULT_START), en = rest.indexOf(VAULT_END);
54849
+ const body = s !== -1 && en !== -1 && en > s ? rest.slice(s + VAULT_START.length, en) : rest;
54850
+ return { ok: true, fm, body: body.trim() };
54851
+ }
54852
+ function titleOf(body, slug) {
54853
+ const m = /^#\s+(.+?)\s*$/m.exec(body);
54854
+ return m && m[1] ? m[1].trim() : slug;
54855
+ }
54856
+ function stripCode(body) {
54857
+ return body.replace(/<!--[\s\S]*?-->/g, " ").replace(/```[\s\S]*?```/g, " ").replace(/~~~[\s\S]*?~~~/g, " ").replace(/`[^`\n]*`/g, " ");
54858
+ }
54859
+ function linkSlug(inner) {
54860
+ return (inner.split(/[|#]/)[0] ?? "").trim();
54861
+ }
54862
+ function outboundTargets(fm, body) {
54863
+ const targets = [];
54864
+ for (const m of stripCode(body).matchAll(WIKILINK_RE)) {
54865
+ if (m[1] === "!") continue;
54866
+ const s = linkSlug(m[2] ?? "");
54867
+ if (s) targets.push(s);
54868
+ }
54869
+ const src = fm.sources;
54870
+ if (Array.isArray(src)) for (const entry2 of src) {
54871
+ if (typeof entry2 !== "string") continue;
54872
+ const mm = /^\[\[([^\]]+)\]\]$/.exec(entry2.trim());
54873
+ if (mm) {
54874
+ const s = linkSlug(mm[1] ?? "");
54875
+ if (s) targets.push(s);
54876
+ }
54877
+ }
54878
+ return targets;
54879
+ }
54880
+ function readGraph(wikiDir, io = REAL_IO) {
54881
+ const { pages, incomplete } = collectPages(wikiDir, io);
54882
+ let truncated = incomplete;
54883
+ const parse = (slug, path) => {
54884
+ const pp = splitPage(path, io);
54885
+ return pp.ok ? { slug, fm: pp.fm, body: pp.body, title: titleOf(pp.body, slug) } : null;
54886
+ };
54887
+ const indexPath2 = pages.get("index");
54888
+ let index = null;
54889
+ let indexParsed = null;
54890
+ if (indexPath2) {
54891
+ indexParsed = parse("index", indexPath2);
54892
+ if (indexParsed) index = { slug: "index", title: indexParsed.title };
54893
+ else truncated = true;
54894
+ }
54895
+ const content = [];
54896
+ let rawBytes = indexPath2 ? safeStat(io, indexPath2) : 0;
54897
+ for (const [slug, path] of pages) {
54898
+ if (slug === "index") continue;
54899
+ const size = safeStat(io, path);
54900
+ if (rawBytes + size > KB_MAX_TOTAL_BYTES) {
54901
+ truncated = true;
54902
+ console.warn(`knowledge-store: graph exceeds KB_MAX_TOTAL_BYTES, truncating`);
54903
+ break;
54904
+ }
54905
+ rawBytes += size;
54906
+ const pp = parse(slug, path);
54907
+ if (!pp) {
54908
+ truncated = true;
54909
+ continue;
54910
+ }
54911
+ content.push(pp);
54912
+ }
54913
+ if (!index) {
54914
+ const alt = content.find((p) => p.fm.type === "index");
54915
+ if (alt) {
54916
+ index = { slug: alt.slug, title: alt.title };
54917
+ console.warn(`knowledge-store: no index.md; using "${alt.slug}" (type:index) as the index`);
54918
+ }
54919
+ }
54920
+ const nodes = [];
54921
+ for (const p of content) {
54922
+ if (index && p.slug === index.slug) continue;
54923
+ if (p.fm.type === "index") {
54924
+ console.warn(`knowledge-store: misplaced type:index page "${p.slug}", skipping`);
54925
+ continue;
54926
+ }
54927
+ if (nodes.length >= KB_MAX_NODES) {
54928
+ truncated = true;
54929
+ continue;
54930
+ }
54931
+ const ft = p.fm.type;
54932
+ nodes.push({ id: p.slug, slug: p.slug, title: p.title, type: ft === "source" || ft === "person" ? ft : "concept" });
54933
+ }
54934
+ const nodeIds = new Set(nodes.map((n) => n.id));
54935
+ const seen = /* @__PURE__ */ new Set();
54936
+ const edges = [];
54937
+ for (const p of content) {
54938
+ if (!nodeIds.has(p.slug)) continue;
54939
+ for (const to of outboundTargets(p.fm, p.body)) {
54940
+ if (to === p.slug || to === "index" || !nodeIds.has(to)) continue;
54941
+ const pair = p.slug <= to ? [p.slug, to] : [to, p.slug];
54942
+ const key = JSON.stringify(pair);
54943
+ if (seen.has(key)) continue;
54944
+ seen.add(key);
54945
+ edges.push({ a: pair[0], b: pair[1] });
54946
+ }
54947
+ }
54948
+ return { nodes, edges, index, truncated };
54949
+ }
54950
+ function safeStat(io, path) {
54951
+ try {
54952
+ return io.statSize(path);
54953
+ } catch {
54954
+ return 0;
54955
+ }
54956
+ }
54957
+ function readPage(wikiDir, slug, io = REAL_IO) {
54958
+ if (typeof slug !== "string" || !WIKI_SLUG_RE.test(slug)) return null;
54959
+ let found = null;
54960
+ const status = eachPage(wikiDir, io, (s, path) => {
54961
+ if (s === slug) {
54962
+ found = path;
54963
+ return true;
54964
+ }
54965
+ return false;
54966
+ });
54967
+ if (!found) {
54968
+ if (status === "limit") throw new KnowledgeError("knowledge base too large to resolve this page", "too-large");
54969
+ if (status === "io-error") throw new KnowledgeError("failed to read the knowledge base", "io-error");
54970
+ return null;
54971
+ }
54972
+ const full = (0, import_node_path19.resolve)(found), root = (0, import_node_path19.resolve)(wikiDir);
54973
+ if (full !== root && !full.startsWith(root + import_node_path19.sep)) return null;
54974
+ const pp = splitPage(full, io);
54975
+ if (!pp.ok) {
54976
+ if (pp.reason === "oversize") throw new KnowledgeError("knowledge page too large to serve", "too-large");
54977
+ throw new KnowledgeError("failed to read the knowledge page", "io-error");
54978
+ }
54979
+ const t = pp.fm.type;
54980
+ const type = t === "source" || t === "concept" || t === "person" || t === "index" ? t : "concept";
54981
+ return { slug, title: titleOf(pp.body, slug), type, body: pp.body };
54982
+ }
54711
54983
  var organizePath = (id) => (0, import_node_path19.join)(projectKnowledgeDir(id), "organize.json");
54712
54984
  function writeOrganizeFile(id, org) {
54713
54985
  const dir = projectKnowledgeDir(id);
@@ -54842,7 +55114,10 @@ function resolveOrganizeRequest(projectId, requestId) {
54842
55114
  return kreq;
54843
55115
  }
54844
55116
  function knowledgeErrorStatus(e) {
54845
- return e.code === "conflict" ? 409 : 400;
55117
+ if (e.code === "conflict") return 409;
55118
+ if (e.code === "too-large") return 503;
55119
+ if (e.code === "io-error") return 500;
55120
+ return 400;
54846
55121
  }
54847
55122
  function registerKnowledgeRoutes(app) {
54848
55123
  app.post(
@@ -54982,6 +55257,33 @@ function registerKnowledgeRoutes(app) {
54982
55257
  throw e;
54983
55258
  }
54984
55259
  });
55260
+ app.get("/api/projects/:id/knowledge/graph", async (req, reply) => {
55261
+ try {
55262
+ const project = getProject(req.params.id);
55263
+ if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
55264
+ const wikiDir = currentGenerationWikiDir(project.id);
55265
+ const graph = wikiDir ? readGraph(wikiDir) : { nodes: [], edges: [], index: null, truncated: false };
55266
+ return { ok: true, graph };
55267
+ } catch (e) {
55268
+ if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
55269
+ if (e instanceof KnowledgeError) return reply.status(knowledgeErrorStatus(e)).send({ ok: false, error: e.message });
55270
+ throw e;
55271
+ }
55272
+ });
55273
+ app.get("/api/projects/:id/knowledge/page/:slug", async (req, reply) => {
55274
+ try {
55275
+ const project = getProject(req.params.id);
55276
+ if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
55277
+ const wikiDir = currentGenerationWikiDir(project.id);
55278
+ const pg = wikiDir ? readPage(wikiDir, req.params.slug) : null;
55279
+ if (!pg) return reply.status(404).send({ ok: false, error: "page not found" });
55280
+ return { ok: true, page: pg };
55281
+ } catch (e) {
55282
+ if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
55283
+ if (e instanceof KnowledgeError) return reply.status(knowledgeErrorStatus(e)).send({ ok: false, error: e.message });
55284
+ throw e;
55285
+ }
55286
+ });
54985
55287
  app.post(
54986
55288
  "/api/projects/:id/knowledge/requests/:requestId/start",
54987
55289
  async (req, reply) => {
@@ -55876,15 +56178,15 @@ function saveSource(id, file) {
55876
56178
 
55877
56179
  // contract-bake.ts
55878
56180
  var import_node_fs28 = require("node:fs");
55879
- var import_yaml5 = __toESM(require_dist6(), 1);
56181
+ var import_yaml6 = __toESM(require_dist6(), 1);
55880
56182
  function bakeContractIntoApp(sourcePath, contract) {
55881
- const doc = (0, import_yaml5.parseDocument)((0, import_node_fs28.readFileSync)(sourcePath, "utf8"));
56183
+ const doc = (0, import_yaml6.parseDocument)((0, import_node_fs28.readFileSync)(sourcePath, "utf8"));
55882
56184
  if (doc.errors.length > 0) {
55883
56185
  throw new Error(`contract bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
55884
56186
  }
55885
56187
  const seq = doc.get("nodes");
55886
- const items = (0, import_yaml5.isSeq)(seq) ? seq.items : [];
55887
- const nodeOf = (it) => (0, import_yaml5.isMap)(it) ? it.toJSON() : null;
56188
+ const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
56189
+ const nodeOf = (it) => (0, import_yaml6.isMap)(it) ? it.toJSON() : null;
55888
56190
  let idx = items.findIndex((it) => nodeOf(it)?.config?.contract === contract.type);
55889
56191
  if (idx < 0) idx = items.findIndex((it) => nodeOf(it)?.agent === "steel-takeoff-us");
55890
56192
  if (idx < 0) throw new Error("no contract-emitting node to bake the contract into");
@@ -61134,27 +61436,27 @@ async function bomToXlsx(bom) {
61134
61436
  // scene-bake.ts
61135
61437
  var import_node_fs30 = require("node:fs");
61136
61438
  var import_node_path26 = require("node:path");
61137
- var import_yaml6 = __toESM(require_dist6(), 1);
61439
+ var import_yaml7 = __toESM(require_dist6(), 1);
61138
61440
  function bakeSceneIntoApp(sourcePath, scene, agent = "viewer-3d") {
61139
- const doc = (0, import_yaml6.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
61441
+ const doc = (0, import_yaml7.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
61140
61442
  if (doc.errors.length > 0) {
61141
61443
  throw new Error(`scene bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
61142
61444
  }
61143
61445
  const seq = doc.get("nodes");
61144
- const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
61145
- const idx = items.findIndex((it) => ((0, import_yaml6.isMap)(it) ? it.toJSON() : null)?.agent === agent);
61446
+ const items = (0, import_yaml7.isSeq)(seq) ? seq.items : [];
61447
+ const idx = items.findIndex((it) => ((0, import_yaml7.isMap)(it) ? it.toJSON() : null)?.agent === agent);
61146
61448
  if (idx < 0) throw new Error(`no ${agent} render node to bake the scene into`);
61147
61449
  doc.setIn(["nodes", idx, "config", "scene"], scene);
61148
61450
  (0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
61149
61451
  }
61150
61452
  function bakeNodeConfigById(sourcePath, nodeId, patch2) {
61151
- const doc = (0, import_yaml6.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
61453
+ const doc = (0, import_yaml7.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
61152
61454
  if (doc.errors.length > 0) {
61153
61455
  throw new Error(`node bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
61154
61456
  }
61155
61457
  const seq = doc.get("nodes");
61156
- const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
61157
- const idx = items.findIndex((it) => ((0, import_yaml6.isMap)(it) ? it.toJSON() : null)?.id === nodeId);
61458
+ const items = (0, import_yaml7.isSeq)(seq) ? seq.items : [];
61459
+ const idx = items.findIndex((it) => ((0, import_yaml7.isMap)(it) ? it.toJSON() : null)?.id === nodeId);
61158
61460
  if (idx < 0) throw new Error(`no node with id "${nodeId}"`);
61159
61461
  for (const [key, value] of Object.entries(patch2)) doc.setIn(["nodes", idx, "config", key], value);
61160
61462
  (0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
@@ -61825,7 +62127,7 @@ function clientCount() {
61825
62127
  var import_node_fs31 = require("node:fs");
61826
62128
  var import_node_os16 = require("node:os");
61827
62129
  var import_node_path27 = require("node:path");
61828
- var import_yaml7 = __toESM(require_dist6(), 1);
62130
+ var import_yaml8 = __toESM(require_dist6(), 1);
61829
62131
  var AGENTS_DIR2 = process.env.AWARE_HOME ? (0, import_node_path27.join)(process.env.AWARE_HOME, "agents") : (0, import_node_path27.join)((0, import_node_os16.homedir)(), ".aware", "agents");
61830
62132
  function summarizeFire(data) {
61831
62133
  if (!data) return "event";
@@ -61846,7 +62148,7 @@ function isHostBacked(agent, agentsDir = AGENTS_DIR2) {
61846
62148
  const manifestPath2 = (0, import_node_path27.join)(agentsDir, agent, "manifest.yaml");
61847
62149
  if (!(0, import_node_fs31.existsSync)(manifestPath2)) return false;
61848
62150
  try {
61849
- const doc = (0, import_yaml7.parse)((0, import_node_fs31.readFileSync)(manifestPath2, "utf8"));
62151
+ const doc = (0, import_yaml8.parse)((0, import_node_fs31.readFileSync)(manifestPath2, "utf8"));
61850
62152
  const transport = doc?.transport;
61851
62153
  return !!(transport && typeof transport === "object" && "cli" in transport);
61852
62154
  } catch {
@@ -63787,7 +64089,7 @@ var import_node_fs38 = require("node:fs");
63787
64089
  var import_node_os20 = require("node:os");
63788
64090
  var import_node_path34 = require("node:path");
63789
64091
  var import_node_url4 = require("node:url");
63790
- var import_yaml8 = __toESM(require_dist6(), 1);
64092
+ var import_yaml9 = __toESM(require_dist6(), 1);
63791
64093
 
63792
64094
  // build/ship-skills.mjs
63793
64095
  var PRODUCT_SKILLS = [
@@ -63856,7 +64158,7 @@ function skillVersion(skillMdPath) {
63856
64158
  const text = (0, import_node_fs38.readFileSync)(skillMdPath, "utf8");
63857
64159
  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
63858
64160
  if (!m || m[1] === void 0) return null;
63859
- const fm = (0, import_yaml8.parse)(m[1]);
64161
+ const fm = (0, import_yaml9.parse)(m[1]);
63860
64162
  const meta = fm?.metadata;
63861
64163
  const v = meta?.version;
63862
64164
  return typeof v === "string" || typeof v === "number" ? String(v) : null;
@@ -66277,6 +66579,24 @@ async function startServer() {
66277
66579
  throw e;
66278
66580
  }
66279
66581
  });
66582
+ app.get("/api/projects/archived", async () => ({ ok: true, projects: listArchivedProjects() }));
66583
+ app.post("/api/projects/:id/unarchive", async (req, reply) => {
66584
+ try {
66585
+ return { ok: true, project: unarchiveProject(req.params.id) };
66586
+ } catch (e) {
66587
+ if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
66588
+ throw e;
66589
+ }
66590
+ });
66591
+ app.delete("/api/projects/:id/archived", async (req, reply) => {
66592
+ try {
66593
+ deleteArchivedProject(req.params.id);
66594
+ return { ok: true };
66595
+ } catch (e) {
66596
+ if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
66597
+ throw e;
66598
+ }
66599
+ });
66280
66600
  app.get("/api/projects/:id/versions", async (req, reply) => {
66281
66601
  const p = getProject(req.params.id);
66282
66602
  if (!p) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
package/dist/web/app.css CHANGED
@@ -3473,6 +3473,34 @@ body.mode-workspaces #menu .menu-item[data-action="bake"] { display:none; }
3473
3473
  .ws-card .ws-kebab { background:transparent; border:1px solid transparent; color:var(--text-dim);
3474
3474
  padding:2px 7px; border-radius:4px; font-size:14px; line-height:1; flex:none; }
3475
3475
  .ws-card .ws-kebab:hover { border-color:var(--border-strong); color:var(--text); }
3476
+ /* Archived projects ("Trash") — a collapsed disclosure below the live grid. Demoted vs .ws-card:
3477
+ flat rows in one contained panel, muted text — reads as "put away", not "open me". */
3478
+ .ws-archived { margin-top:22px; border-top:1px solid var(--border); padding-top:10px; }
3479
+ .ws-archived-summary { list-style:none; cursor:pointer; display:inline-flex; align-items:center; gap:7px;
3480
+ font-size:10px; text-transform:uppercase; letter-spacing:.18em; color:var(--text-dim);
3481
+ padding:5px 6px; border-radius:4px; user-select:none; }
3482
+ .ws-archived-summary::-webkit-details-marker { display:none; }
3483
+ .ws-archived-summary:hover { color:var(--text-muted); }
3484
+ .ws-archived-summary:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
3485
+ .ws-archived[open] > .ws-archived-summary .ws-archived-caret { transform:rotate(90deg); }
3486
+ .ws-archived-count { font-family:var(--mono); letter-spacing:0; color:var(--text-muted); }
3487
+ .ws-archived-list { margin-top:8px; border:1px solid var(--border); border-radius:10px; background:var(--surface);
3488
+ max-height:320px; overflow-y:auto; scrollbar-width:thin; scrollbar-color:var(--border-strong) transparent; }
3489
+ .ws-archived-row { display:flex; align-items:center; justify-content:space-between; gap:12px;
3490
+ padding:10px 13px; border-bottom:1px solid var(--border); }
3491
+ .ws-archived-row:last-child { border-bottom:none; }
3492
+ .ws-archived-info { min-width:0; display:flex; flex-direction:column; gap:3px; }
3493
+ .ws-archived-name { font-size:13px; font-weight:600; color:var(--text-muted);
3494
+ overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
3495
+ .ws-archived-meta { font-size:11px; color:var(--text-dim); }
3496
+ .ws-archived-meta .t { font-family:var(--mono); font-size:10px; }
3497
+ .ws-archived-actions { display:flex; gap:8px; flex:none; }
3498
+ .ws-archived-list .btn-mini { background:none; border:1px solid var(--border-strong); color:var(--text-muted);
3499
+ border-radius:6px; padding:4px 10px; font-size:11px; cursor:pointer; white-space:nowrap; }
3500
+ .ws-archived-list .ws-restore:hover { color:var(--text); border-color:var(--accent); }
3501
+ /* Destructive: neutral at rest, danger only on hover (same restraint as #rtn-delete-confirm). */
3502
+ .ws-archived-list .ws-del:hover { color:var(--err); border-color:var(--err);
3503
+ background:color-mix(in srgb, var(--err) 10%, transparent); }
3476
3504
  .ws-seed { border:2px dashed var(--accent-dim); background:transparent; border-radius:8px; min-height:150px;
3477
3505
  display:flex; flex-direction:column; align-items:center; justify-content:center; gap:8px; cursor:pointer;
3478
3506
  color:var(--text-muted); font-size:12px; width:100%; text-align:center; padding:12px; }
@@ -3896,3 +3924,34 @@ tr.hist-diff-row[hidden] { display:none; }
3896
3924
  .kb-view-spin { width:26px; height:26px; border:3px solid var(--accent-dim); border-top-color:var(--accent-bright);
3897
3925
  border-radius:50%; animation:spin .8s linear infinite; }
3898
3926
  @media (prefers-reduced-motion: reduce) { .kb-view-spin { animation:none; } }
3927
+
3928
+ /* ── Stage C: the knowledge graph + page viewer ───────────────────────────────── */
3929
+ .kb-graph { display: flex; flex-direction: column; height: 100%; min-height: 0; }
3930
+ .kb-graph-head { display: flex; align-items: center; justify-content: space-between; padding: 8px 12px; border-bottom: 1px solid var(--border); font-size: 13px; color: var(--text-muted); }
3931
+ .kb-graph-sub { display: flex; align-items: center; justify-content: space-between; gap: 8px; flex-wrap: wrap; padding: 5px 12px; border-bottom: 1px solid var(--border); }
3932
+ .kb-g-legend { display: flex; gap: 12px; }
3933
+ .kb-gleg { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: var(--text-muted); }
3934
+ .kb-gleg::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; }
3935
+ .kb-gleg.con::before { background: color-mix(in srgb, var(--accent) 55%, var(--text-muted)); }
3936
+ .kb-gleg.per::before { background: color-mix(in srgb, var(--accent) 25%, var(--text-muted)); }
3937
+ .kb-g-hint { font-size: 10.5px; color: var(--text-dim); }
3938
+ .kb-graph-body { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 8px; }
3939
+ .kb-graph-svg { width: 100%; height: 100%; }
3940
+ .kb-g-edge { stroke: color-mix(in srgb, var(--border-strong) 90%, transparent); stroke-width: 1.5; }
3941
+ .kb-g-node { cursor: pointer; }
3942
+ .kb-g-hit { fill: transparent; } /* wider click/focus target */
3943
+ .kb-g-dot { fill: var(--accent); stroke: var(--surface); stroke-width: 2; }
3944
+ .kb-g-node text { fill: var(--text); font-size: 12px; } /* label is a click target too (not just the dot) */
3945
+ .kb-g-node:hover .kb-g-dot, .kb-g-node:focus-visible .kb-g-dot { fill: var(--accent-bright); filter: drop-shadow(0 0 5px var(--accent-glow)); }
3946
+ .kb-g-node:focus-visible { outline: none; }
3947
+ .kb-g-node:focus-visible .kb-g-dot { stroke: var(--accent-bright); }
3948
+ .kb-g-source .kb-g-dot { fill: var(--accent); }
3949
+ .kb-g-concept .kb-g-dot { fill: color-mix(in srgb, var(--accent) 55%, var(--text-muted)); }
3950
+ .kb-g-person .kb-g-dot { fill: color-mix(in srgb, var(--accent) 25%, var(--text-muted)); }
3951
+ .kb-g-overview { background: transparent; border: 1px solid var(--border-strong); color: var(--text-muted); border-radius: 6px; padding: 2px 8px; font-size: 12px; cursor: pointer; font: inherit; }
3952
+ .kb-g-overview:hover { color: var(--text); border-color: var(--accent); }
3953
+ .kb-page-type { margin-left: 8px; font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: .04em; }
3954
+ .kb-page-body { flex: 1; min-height: 0; overflow-y: auto; padding: 16px; white-space: pre-wrap; word-break: break-word; overflow-wrap: anywhere; line-height: 1.6; color: var(--text); font-size: 14px; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
3955
+ .kb-page-body::-webkit-scrollbar { width: 10px; }
3956
+ .kb-page-body::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 6px; }
3957
+ .kb-page-body::-webkit-scrollbar-track { background: transparent; }
@@ -174,6 +174,7 @@
174
174
  let mode = 'workflows';
175
175
  try { if (localStorage.getItem(LS_MODE) === 'workspaces') mode = 'workspaces'; } catch { /* private mode */ }
176
176
  let projects = [];
177
+ let archived = []; // archived projects (the "Trash") — listed under a collapsed section on the landing
177
178
  // Installed workspace apps, in descriptor order. Populated from /api/apps in loadProjects():
178
179
  // the set = apps flagged workspace===true that ALSO have a WORKSPACE_APPS descriptor (an app
179
180
  // flagged workspace with no descriptor is skipped with a console note — never a broken open).
@@ -262,6 +263,11 @@
262
263
  // (the empty-state CTA would be a lie: "no projects yet" when the truth is "load failed").
263
264
  try { ({ projects } = await api('/api/projects')); }
264
265
  catch (err) { projects = []; showToast('Couldn’t load projects: ' + (err && err.message || err), 'warn'); }
266
+ // Archived ("Trash") list is a secondary concern — never let its failure blank the main workspace,
267
+ // but don't swallow it silently either: warn so a broken archive listing is diagnosable (a bare
268
+ // catch here would hide a real 500 and leave the "Archived" section invisible with no breadcrumb).
269
+ try { ({ projects: archived } = await api('/api/projects/archived')); }
270
+ catch (err) { archived = []; console.warn('[workspaces] archived list failed to load: ' + (err && err.message || err)); }
265
271
  // Which workspace apps to offer a create card for: those flagged workspace===true on /api/apps
266
272
  // that we ALSO know how to render (have a WORKSPACE_APPS descriptor). Keep descriptor order for a
267
273
  // stable card order. A load failure leaves wsAppIds at its descriptor-key fallback (still usable).
@@ -341,7 +347,29 @@
341
347
  : hasDrawingSeed
342
348
  ? 'No projects yet — drop a drawing above, or ask your terminal AI to trace a drawing set.'
343
349
  : 'No projects yet — import your current steel model above, or ask your terminal AI to read a drawing set.';
344
- html += `<div class="ws-empty-note">${escapeHtml(note)}</div>`;
350
+ html += `<div class="ws-empty-note">${escapeHtml(note)}${archived.length ? ' You have archived projects below.' : ''}</div>`;
351
+ }
352
+ // Archived ("Trash") section — a collapsed disclosure below the live grid, only when non-empty.
353
+ // Demoted rows (muted, no thumb) read as "put away"; each offers Restore + a guarded Delete.
354
+ if (archived.length) {
355
+ let rows = '';
356
+ for (const p of archived) {
357
+ const displayApp = appDisplayName(p.app);
358
+ rows += `<div class="ws-archived-row">` +
359
+ `<span class="ws-archived-info">` +
360
+ `<span class="ws-archived-name">${escapeHtml(p.name)}</span>` +
361
+ `<span class="ws-archived-meta">${escapeHtml(displayApp)} · archived <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span>` +
362
+ `</span>` +
363
+ `<span class="ws-archived-actions">` +
364
+ `<button type="button" class="btn-mini ws-restore" data-restore="${escapeAttr(p.id)}" data-tip="Un-archive — returns to the live grid">↺ Restore</button>` +
365
+ `<button type="button" class="btn-mini ws-del" data-delete-archived="${escapeAttr(p.id)}" data-tip="Permanently erase this project from disk">Delete…</button>` +
366
+ `</span>` +
367
+ `</div>`;
368
+ }
369
+ html += `<details class="ws-archived">` +
370
+ `<summary class="ws-archived-summary"><span class="ws-archived-caret hd-caret" aria-hidden="true">▸</span>Archived <span class="ws-archived-count">${archived.length}</span></summary>` +
371
+ `<div class="ws-archived-list">${rows}</div>` +
372
+ `</details>`;
345
373
  }
346
374
  $landing.innerHTML = html;
347
375
  }
@@ -349,6 +377,10 @@
349
377
  $landing.addEventListener('click', async (e) => {
350
378
  const kebab = e.target.closest('[data-kebab]');
351
379
  if (kebab) { e.stopPropagation(); openProjMenu(kebab.dataset.kebab, kebab); return; }
380
+ const restore = e.target.closest('[data-restore]');
381
+ if (restore) { e.stopPropagation(); unarchiveProject(restore.dataset.restore); return; }
382
+ const del = e.target.closest('[data-delete-archived]');
383
+ if (del) { e.stopPropagation(); deleteArchivedProject(del.dataset.deleteArchived); return; }
352
384
  const card = e.target.closest('[data-open]');
353
385
  if (card) { openProject(card.dataset.open); return; }
354
386
  const seed = e.target.closest('[data-seed-app]');
@@ -844,25 +876,75 @@
844
876
  (status ? `<div class="kb-status">${status}</div>` : '') + organizeBtn + '</div>';
845
877
  }
846
878
 
847
- // Stage C/D live here. After a real Organize the user's eye lands on this big empty canvas, so it
848
- // must CONFIRM the action worked rather than look unchanged. Glyph reuses the app's existing ✦
849
- // vocabulary — no new iconography.
850
- // The copy also teaches the Stage-B2 affordance: this pane is where a clicked filename opens, and
851
- // it is the first thing the eye lands on when the viewer closes.
852
- const kbPlaceholder = (st) => {
879
+ // ── Stage C: the knowledge graph — seeded force layout + SVG render ─────────────
880
+ // A deterministic hash seeds each node's starting angle so the SAME graph always lays out the same
881
+ // way across re-renders (no visual jitter on a poll tick / repaint) without needing a persisted
882
+ // layout. The force pass then relaxes overlaps via simple repulsion + edge-spring + centering.
883
+ function kbHash(s) { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
884
+ function kbLayout(nodes, edges) {
885
+ const W = 600, H = 440, N = nodes.length;
886
+ const iters = N <= 60 ? 300 : N <= 150 ? 150 : 60;
887
+ const R = Math.min(W, H) / 2 - 40;
888
+ const pos = nodes.map((n, i) => { const ang = i * 2.399963 + (kbHash(n.id) % 628) / 100; const rad = 18 + (N > 1 ? (i / (N - 1)) * R : 0);
889
+ return { id: n.id, x: W / 2 + Math.cos(ang) * rad, y: H / 2 + Math.sin(ang) * rad }; });
890
+ const idx = new Map(pos.map((p, i) => [p.id, i]));
891
+ const K = 140;
892
+ for (let it = 0; it < iters; it++) {
893
+ const fx = new Array(N).fill(0), fy = new Array(N).fill(0);
894
+ for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) {
895
+ let dx = pos[i].x - pos[j].x, dy = pos[i].y - pos[j].y; const d2 = dx * dx + dy * dy || 0.01, d = Math.sqrt(d2), rep = 9000 / d2;
896
+ fx[i] += dx / d * rep; fy[i] += dy / d * rep; fx[j] -= dx / d * rep; fy[j] -= dy / d * rep; }
897
+ for (const e of edges) { const i = idx.get(e.a), j = idx.get(e.b); if (i == null || j == null) continue;
898
+ let dx = pos[j].x - pos[i].x, dy = pos[j].y - pos[i].y; const d = Math.sqrt(dx * dx + dy * dy) || 0.01, s = (d - K) * 0.02;
899
+ fx[i] += dx / d * s; fy[i] += dy / d * s; fx[j] -= dx / d * s; fy[j] -= dy / d * s; }
900
+ for (let i = 0; i < N; i++) { fx[i] += (W / 2 - pos[i].x) * 0.01; fy[i] += (H / 2 - pos[i].y) * 0.01;
901
+ pos[i].x = Math.max(24, Math.min(W - 24, pos[i].x + Math.max(-20, Math.min(20, fx[i]))));
902
+ pos[i].y = Math.max(24, Math.min(H - 24, pos[i].y + Math.max(-20, Math.min(20, fy[i])))); }
903
+ }
904
+ return { pos, idx, W, H };
905
+ }
906
+
907
+ // Node fields are ALL escaped (title/slug/type are LLM-derived). Each node carries an aria-label AND
908
+ // a type-bearing data-tip so its taxonomy is available to AT + sighted users, not encoded by colour
909
+ // alone (WCAG 1.4.1). An invisible r=16 hit circle widens the click/focus target behind the r=9 dot.
910
+ function kbGraphSvg(graph) {
911
+ if (!graph || !graph.nodes.length) return graph && graph.truncated ? kbGraphTruncatedEmpty() : kbGraphEmpty(knowledgeState);
912
+ const { pos, idx, W, H } = kbLayout(graph.nodes, graph.edges);
913
+ const lines = graph.edges.map((e) => { const a = pos[idx.get(e.a)], b = pos[idx.get(e.b)];
914
+ return (a && b) ? `<line class="kb-g-edge" x1="${a.x.toFixed(1)}" y1="${a.y.toFixed(1)}" x2="${b.x.toFixed(1)}" y2="${b.y.toFixed(1)}"/>` : ''; }).join('');
915
+ const dots = graph.nodes.map((n, i) => { const p = pos[i];
916
+ return `<g class="kb-g-node kb-g-${escapeAttr(n.type)}" tabindex="0" role="button" aria-label="${escapeAttr(n.title + ', ' + n.type)}" data-kb-node="${escapeAttr(n.slug)}" data-tip="${escapeAttr(n.title + ' · ' + n.type)}" transform="translate(${p.x.toFixed(1)},${p.y.toFixed(1)})">` +
917
+ `<circle class="kb-g-hit" r="16"/><circle class="kb-g-dot" r="9"/><text x="13" y="4">${escapeHtml(n.title)}</text></g>`; }).join('');
918
+ const overview = graph.index ? `<button type="button" class="kb-g-overview" data-kb-node="${escapeAttr(graph.index.slug)}" data-tip="Open the overview">✦ Overview</button>` : '';
919
+ const legend = '<div class="kb-g-legend"><span class="kb-gleg src">Source</span><span class="kb-gleg con">Concept</span><span class="kb-gleg per">Person</span></div>';
920
+ const note = graph.truncated ? `<div class="kb-view-note">Showing ${graph.nodes.length} — graph truncated (some pages omitted)</div>` : '';
921
+ return '<section class="kb-col kb-graph"><div class="kb-graph-head"><span>Knowledge graph</span>' + overview + '</div>' +
922
+ '<div class="kb-graph-sub">' + legend + '<span class="kb-g-hint">Click a node to open its page</span></div>' +
923
+ `<div class="kb-graph-body"><svg viewBox="0 0 ${W} ${H}" class="kb-graph-svg" role="group" aria-label="Knowledge graph">${lines}${dots}</svg></div>${note}</section>`;
924
+ }
925
+ function kbGraphTruncatedEmpty() { return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner"><span class="kb-ph-ico" aria-hidden="true">✦</span><div class="kb-ph-title">Graph incomplete</div><div class="kb-ph-sub">Some knowledge pages couldn’t be loaded, so the graph is incomplete and nothing could be shown. Click a file on the left to preview it.</div></div></section>'; }
926
+ function kbGraphEmpty(st) {
853
927
  const done = st && st.currentGeneration;
854
- return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner">' +
855
- '<span class="kb-ph-ico" aria-hidden="true">✦</span>' +
856
- '<div class="kb-ph-title">Graph &amp; Notes — coming soon</div>' +
857
- '<div class="kb-ph-sub">' +
858
- (done
859
- ? 'This project’s references are organized. The visual graph — sources, concepts and people, ' +
860
- 'linked — opens here in a later update. Click any file on the left to preview it in the meantime.'
861
- : 'Once references are organized, this space maps your knowledge base — sources, concepts and ' +
862
- 'people, linked — and lets you open any note. For now, click a file on the left to preview it, ' +
863
- 'or add references and Organize.') +
864
- '</div></div></section>';
865
- };
928
+ return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner"><span class="kb-ph-ico" aria-hidden="true">✦</span>' +
929
+ '<div class="kb-ph-title">' + (done ? 'Nothing to graph yet' : 'No knowledge base yet') + '</div>' +
930
+ '<div class="kb-ph-sub">' + (done
931
+ ? 'This project’s references are organized, but their pages aren’t linked to each other yet. Click a file on the left to preview it.'
932
+ : 'No knowledge base yet — add references and Organize to build one. Click a file on the left to preview it in the meantime.') + '</div></div></section>';
933
+ }
934
+ // loading + error REUSE the file viewer's own message idiom (.kb-view-msg / .kb-view-spin /
935
+ // .kb-view-ico.err / .primary Retry) so the graph's "can't show content yet" states look identical
936
+ // to the file preview's — one learned pattern, not a second near-duplicate.
937
+ function kbGraphLoading() { return '<section class="kb-col"><div class="kb-view-msg"><div class="kb-view-spin" role="status" aria-label="Building graph"></div><div class="kb-view-msg-title">Building graph…</div></div></section>'; }
938
+ function kbGraphError() { return '<section class="kb-col"><div class="kb-view-msg"><span class="kb-view-ico err" aria-hidden="true">⚠</span><div class="kb-view-msg-title">Couldn’t load the graph.</div><div class="kb-view-act"><button type="button" class="primary" data-kb-graph-retry>↻ Retry</button></div></div></section>'; }
939
+ function kbPageShell(pg) {
940
+ const type = pg.type ? `<span class="kb-page-type">${escapeHtml(pg.type)}</span>` : '';
941
+ return '<section class="kb-col kb-viewer kb-page"><div class="kb-view-head">' +
942
+ `<span class="kb-view-name" data-tip="${escapeAttr(pg.title)}">${escapeHtml(pg.title)}</span>${type}` +
943
+ '<button type="button" class="kb-x" data-kb-close data-tip="Back to graph" aria-label="Back to graph">✕</button></div>' +
944
+ `<div class="kb-page-body">${escapeHtml(pg.body)}</div></section>`;
945
+ }
946
+ function kbPageLoading() { return '<section class="kb-col kb-viewer kb-page"><div class="kb-view-head"><span class="kb-view-name">Loading…</span></div><div class="kb-view-msg"><div class="kb-view-spin" role="status" aria-label="Loading page"></div></div></section>'; }
947
+ function kbPageError() { return '<section class="kb-col kb-viewer kb-page"><div class="kb-view-head"><span class="kb-view-name">Couldn’t load page</span><button type="button" class="kb-x" data-kb-close data-tip="Back to graph" aria-label="Back to graph">✕</button></div><div class="kb-view-msg"><span class="kb-view-ico err" aria-hidden="true">⚠</span><div class="kb-view-msg-title">This page could not be loaded.</div></div></section>'; }
866
948
 
867
949
  // ── The file viewer ───────────────────────────────────────────────────────────
868
950
  // SECURITY: `filename` is user-authored and every state below interpolates it — escapeHtml for text,
@@ -960,6 +1042,42 @@
960
1042
  else kbPaintText(row, url, ac, alive);
961
1043
  }
962
1044
 
1045
+ // ── Stage C: the knowledge graph + page viewer ──────────────────────────────────
1046
+ // Same alive()/epoch/key contract as kbLoadPreview above — the render only happens if nothing else
1047
+ // (a new epoch, a changed key, a project switch, or leaving the pane) superseded this fetch meanwhile.
1048
+ async function kbLoadGraph(proj) {
1049
+ const epoch = viewEpoch, key = lastViewKey;
1050
+ const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
1051
+ const ac = new AbortController(); kbTextAbort = ac;
1052
+ try {
1053
+ const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/graph`, { signal: ac.signal, cache: 'no-store' });
1054
+ if (!r.ok) throw new Error(`graph ${r.status}`);
1055
+ const body = await r.json();
1056
+ if (!body || !body.graph || !Array.isArray(body.graph.nodes)) throw new Error('bad graph envelope');
1057
+ if (!alive()) return;
1058
+ const h = kbViewHost(); if (h) h.innerHTML = kbGraphSvg(body.graph);
1059
+ } catch (err) {
1060
+ if (err && err.name === 'AbortError') return;
1061
+ if (alive()) { const h = kbViewHost(); if (h) h.innerHTML = kbGraphError(); } // Retry re-keys via setViewer — matches the file-viewer idiom (no poll-flicker)
1062
+ }
1063
+ }
1064
+ async function kbLoadPage(proj, slug) {
1065
+ const epoch = viewEpoch, key = lastViewKey;
1066
+ const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
1067
+ const ac = new AbortController(); kbTextAbort = ac;
1068
+ try {
1069
+ const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/page/${encodeURIComponent(slug)}`, { signal: ac.signal, cache: 'no-store' });
1070
+ if (!r.ok) throw new Error(`page ${r.status}`);
1071
+ const body = await r.json();
1072
+ if (!body || !body.page || typeof body.page.body !== 'string') throw new Error('bad page envelope');
1073
+ if (!alive()) return;
1074
+ const h = kbViewHost(); if (h) h.innerHTML = kbPageShell(body.page);
1075
+ } catch (err) {
1076
+ if (err && err.name === 'AbortError') return;
1077
+ if (alive()) { const h = kbViewHost(); if (h) h.innerHTML = kbPageError(); } // ✕ re-keys via setViewer; no poll-flicker
1078
+ }
1079
+ }
1080
+
963
1081
  /** Accept a freshly-read /status as the current truth. EVERY writer of `knowledgeState` goes through
964
1082
  * here, because committing state also decides whether the poll runs: a caller that claims the render
965
1083
  * epoch can supersede the very render that would have discovered a newly queued organize, and
@@ -1114,6 +1232,7 @@
1114
1232
  /** Identity of what the viewer host is showing. `blobSha256` is in the key because a hand-edited
1115
1233
  * manifest (and, later, Stage D) can swap a row's bytes without changing its sourceId. */
1116
1234
  function kbViewKey(st) {
1235
+ if (viewer.mode === 'page') { const gen = st.currentGeneration ? st.currentGeneration.generationId : ''; return 'page:' + gen + ':' + (viewer.slug || ''); }
1117
1236
  const row = viewer.mode === 'file' ? st.sources.find((s) => s.sourceId === viewer.sourceId) : null;
1118
1237
  const gen = viewer.mode === 'graph' && st.currentGeneration ? st.currentGeneration.generationId : '';
1119
1238
  return [current && current.id, viewer.mode, viewer.sourceId || '', row ? row.blobSha256 : '', gen].join('|');
@@ -1162,8 +1281,16 @@
1162
1281
  if (viewHost) viewHost.innerHTML = kbViewShell(row, kbViewLoading(row));
1163
1282
  kbLoadPreview(current, row);
1164
1283
  }
1284
+ } else if (viewer.mode === 'page') {
1285
+ if (viewHost) viewHost.innerHTML = kbPageLoading();
1286
+ kbLoadPage(current, viewer.slug);
1165
1287
  } else if (viewHost) {
1166
- viewHost.innerHTML = kbPlaceholder(st);
1288
+ if (!st.currentGeneration) {
1289
+ viewHost.innerHTML = kbGraphEmpty(st);
1290
+ } else {
1291
+ viewHost.innerHTML = kbGraphLoading();
1292
+ kbLoadGraph(current);
1293
+ }
1167
1294
  }
1168
1295
  }
1169
1296
  }
@@ -1178,7 +1305,7 @@
1178
1305
  `<div class="kb-refs-body">${inner}</div></section>`;
1179
1306
  lastRefsHtml = null;
1180
1307
  const host = kbViewHost();
1181
- if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbPlaceholder(null);
1308
+ if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbGraphEmpty(null);
1182
1309
  }
1183
1310
 
1184
1311
  async function renderKnowledge() {
@@ -1335,6 +1462,10 @@
1335
1462
  if (knowledgeState) paintKnowledge(knowledgeState);
1336
1463
  return;
1337
1464
  }
1465
+ // Open a graph node's page.
1466
+ const nodeEl = e.target.closest('[data-kb-node]');
1467
+ if (nodeEl) { setViewer({ mode: 'page', slug: nodeEl.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
1468
+ if (e.target.closest('[data-kb-graph-retry]')) { setViewer({ mode: 'graph', sourceId: null }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
1338
1469
  if (e.target.closest('[data-kb-close]')) {
1339
1470
  const wasOpen = viewer.sourceId;
1340
1471
  setViewer({ mode: 'graph', sourceId: null });
@@ -1362,6 +1493,13 @@
1362
1493
  if (org) { if (org.getAttribute('aria-disabled') !== 'true') kbOrganize(); return; } // aria-disabled still receives clicks
1363
1494
  if (e.target.closest('#kb-drop')) $wsKnowledgeFile.click();
1364
1495
  });
1496
+ // Graph nodes are keyboard-focusable (tabindex="0" role="button") but SVG <g> elements have no
1497
+ // native activation behaviour, so Enter/Space must be wired explicitly.
1498
+ $wsKnowledge.addEventListener('keydown', (e) => {
1499
+ if (e.key !== 'Enter' && e.key !== ' ') return;
1500
+ const n = e.target.closest('[data-kb-node]');
1501
+ if (n) { e.preventDefault(); setViewer({ mode: 'page', slug: n.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); }
1502
+ });
1365
1503
  $wsKnowledgeFile.addEventListener('change', () => {
1366
1504
  kbUpload($wsKnowledgeFile.files);
1367
1505
  $wsKnowledgeFile.value = ''; // let the same file be picked twice in a row
@@ -2078,6 +2216,38 @@
2078
2216
  loadProjects();
2079
2217
  }
2080
2218
 
2219
+ // Restore an archived project to the live grid (the inverse of Archive). Fully reversible — Archive
2220
+ // puts it right back — so no confirm: a toast is consistent with how Rename/Duplicate/Archive confirm.
2221
+ async function unarchiveProject(id) {
2222
+ const p = archived.find((x) => x.id === id);
2223
+ try {
2224
+ await api(`/api/projects/${encodeURIComponent(id)}/unarchive`, { method: 'POST', body: '{}' });
2225
+ showToast(`Restored${p ? ` “${p.name}”` : ''}`, 'ok');
2226
+ } catch (err) { showToast('Restore failed: ' + (err && err.message || err), 'warn'); }
2227
+ loadProjects();
2228
+ }
2229
+
2230
+ // Permanently delete an archived project. Irreversible → a themed DANGER confirm (red commit, Cancel
2231
+ // focused) spells out exactly what is erased before the DELETE fires. Never a native confirm().
2232
+ async function deleteArchivedProject(id) {
2233
+ const p = archived.find((x) => x.id === id);
2234
+ const name = p ? p.name : id;
2235
+ if (!bridge.formModal) { showToast('Couldn’t open the confirm dialog', 'warn'); return; }
2236
+ const ok = await bridge.formModal({
2237
+ title: `Delete “${name}” permanently?`,
2238
+ sub: 'This erases the project’s contract, version history, and exports from disk. It cannot be undone.',
2239
+ fields: [],
2240
+ okLabel: 'Delete permanently',
2241
+ danger: true,
2242
+ });
2243
+ if (!ok) return;
2244
+ try {
2245
+ await api(`/api/projects/${encodeURIComponent(id)}/archived`, { method: 'DELETE' });
2246
+ showToast(`Deleted “${name}”`, 'ok');
2247
+ } catch (err) { showToast('Delete failed: ' + (err && err.message || err), 'warn'); }
2248
+ loadProjects();
2249
+ }
2250
+
2081
2251
  // ── header project picker ── mirrors #wf-combo/#wf-popover exactly (same DOM shape, same
2082
2252
  // CSS classes): search + flat list of ALL projects, each row showing name + app ·
2083
2253
  // last-touched, with inline Rename/Duplicate/Archive icons. Clicking a row opens/switches
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.86.1",
3
+ "version": "0.88.0",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {