@floless/app 0.87.0 → 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.87.0" : 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.87.0" : void 0 });
53119
+ return resolveChannel({ isSea: isSea2(), define: true ? "0.88.0" : void 0 });
53120
53120
  }
53121
53121
 
53122
53122
  // workflow-update.ts
@@ -54457,6 +54457,7 @@ var import_node_fs22 = require("node:fs");
54457
54457
  var import_node_crypto7 = require("node:crypto");
54458
54458
  var import_node_fs21 = require("node:fs");
54459
54459
  var import_node_path19 = require("node:path");
54460
+ var import_yaml5 = __toESM(require_dist6(), 1);
54460
54461
  var KnowledgeError = class extends Error {
54461
54462
  code;
54462
54463
  constructor(message, code) {
@@ -54740,6 +54741,245 @@ function readCurrentGeneration(id) {
54740
54741
  return null;
54741
54742
  }
54742
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
+ }
54743
54983
  var organizePath = (id) => (0, import_node_path19.join)(projectKnowledgeDir(id), "organize.json");
54744
54984
  function writeOrganizeFile(id, org) {
54745
54985
  const dir = projectKnowledgeDir(id);
@@ -54874,7 +55114,10 @@ function resolveOrganizeRequest(projectId, requestId) {
54874
55114
  return kreq;
54875
55115
  }
54876
55116
  function knowledgeErrorStatus(e) {
54877
- 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;
54878
55121
  }
54879
55122
  function registerKnowledgeRoutes(app) {
54880
55123
  app.post(
@@ -55014,6 +55257,33 @@ function registerKnowledgeRoutes(app) {
55014
55257
  throw e;
55015
55258
  }
55016
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
+ });
55017
55287
  app.post(
55018
55288
  "/api/projects/:id/knowledge/requests/:requestId/start",
55019
55289
  async (req, reply) => {
@@ -55908,15 +56178,15 @@ function saveSource(id, file) {
55908
56178
 
55909
56179
  // contract-bake.ts
55910
56180
  var import_node_fs28 = require("node:fs");
55911
- var import_yaml5 = __toESM(require_dist6(), 1);
56181
+ var import_yaml6 = __toESM(require_dist6(), 1);
55912
56182
  function bakeContractIntoApp(sourcePath, contract) {
55913
- 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"));
55914
56184
  if (doc.errors.length > 0) {
55915
56185
  throw new Error(`contract bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
55916
56186
  }
55917
56187
  const seq = doc.get("nodes");
55918
- const items = (0, import_yaml5.isSeq)(seq) ? seq.items : [];
55919
- 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;
55920
56190
  let idx = items.findIndex((it) => nodeOf(it)?.config?.contract === contract.type);
55921
56191
  if (idx < 0) idx = items.findIndex((it) => nodeOf(it)?.agent === "steel-takeoff-us");
55922
56192
  if (idx < 0) throw new Error("no contract-emitting node to bake the contract into");
@@ -61166,27 +61436,27 @@ async function bomToXlsx(bom) {
61166
61436
  // scene-bake.ts
61167
61437
  var import_node_fs30 = require("node:fs");
61168
61438
  var import_node_path26 = require("node:path");
61169
- var import_yaml6 = __toESM(require_dist6(), 1);
61439
+ var import_yaml7 = __toESM(require_dist6(), 1);
61170
61440
  function bakeSceneIntoApp(sourcePath, scene, agent = "viewer-3d") {
61171
- 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"));
61172
61442
  if (doc.errors.length > 0) {
61173
61443
  throw new Error(`scene bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
61174
61444
  }
61175
61445
  const seq = doc.get("nodes");
61176
- const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
61177
- 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);
61178
61448
  if (idx < 0) throw new Error(`no ${agent} render node to bake the scene into`);
61179
61449
  doc.setIn(["nodes", idx, "config", "scene"], scene);
61180
61450
  (0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
61181
61451
  }
61182
61452
  function bakeNodeConfigById(sourcePath, nodeId, patch2) {
61183
- 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"));
61184
61454
  if (doc.errors.length > 0) {
61185
61455
  throw new Error(`node bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
61186
61456
  }
61187
61457
  const seq = doc.get("nodes");
61188
- const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
61189
- 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);
61190
61460
  if (idx < 0) throw new Error(`no node with id "${nodeId}"`);
61191
61461
  for (const [key, value] of Object.entries(patch2)) doc.setIn(["nodes", idx, "config", key], value);
61192
61462
  (0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
@@ -61857,7 +62127,7 @@ function clientCount() {
61857
62127
  var import_node_fs31 = require("node:fs");
61858
62128
  var import_node_os16 = require("node:os");
61859
62129
  var import_node_path27 = require("node:path");
61860
- var import_yaml7 = __toESM(require_dist6(), 1);
62130
+ var import_yaml8 = __toESM(require_dist6(), 1);
61861
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");
61862
62132
  function summarizeFire(data) {
61863
62133
  if (!data) return "event";
@@ -61878,7 +62148,7 @@ function isHostBacked(agent, agentsDir = AGENTS_DIR2) {
61878
62148
  const manifestPath2 = (0, import_node_path27.join)(agentsDir, agent, "manifest.yaml");
61879
62149
  if (!(0, import_node_fs31.existsSync)(manifestPath2)) return false;
61880
62150
  try {
61881
- 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"));
61882
62152
  const transport = doc?.transport;
61883
62153
  return !!(transport && typeof transport === "object" && "cli" in transport);
61884
62154
  } catch {
@@ -63819,7 +64089,7 @@ var import_node_fs38 = require("node:fs");
63819
64089
  var import_node_os20 = require("node:os");
63820
64090
  var import_node_path34 = require("node:path");
63821
64091
  var import_node_url4 = require("node:url");
63822
- var import_yaml8 = __toESM(require_dist6(), 1);
64092
+ var import_yaml9 = __toESM(require_dist6(), 1);
63823
64093
 
63824
64094
  // build/ship-skills.mjs
63825
64095
  var PRODUCT_SKILLS = [
@@ -63888,7 +64158,7 @@ function skillVersion(skillMdPath) {
63888
64158
  const text = (0, import_node_fs38.readFileSync)(skillMdPath, "utf8");
63889
64159
  const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
63890
64160
  if (!m || m[1] === void 0) return null;
63891
- const fm = (0, import_yaml8.parse)(m[1]);
64161
+ const fm = (0, import_yaml9.parse)(m[1]);
63892
64162
  const meta = fm?.metadata;
63893
64163
  const v = meta?.version;
63894
64164
  return typeof v === "string" || typeof v === "number" ? String(v) : null;
package/dist/web/app.css CHANGED
@@ -3924,3 +3924,34 @@ tr.hist-diff-row[hidden] { display:none; }
3924
3924
  .kb-view-spin { width:26px; height:26px; border:3px solid var(--accent-dim); border-top-color:var(--accent-bright);
3925
3925
  border-radius:50%; animation:spin .8s linear infinite; }
3926
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; }
@@ -876,25 +876,75 @@
876
876
  (status ? `<div class="kb-status">${status}</div>` : '') + organizeBtn + '</div>';
877
877
  }
878
878
 
879
- // Stage C/D live here. After a real Organize the user's eye lands on this big empty canvas, so it
880
- // must CONFIRM the action worked rather than look unchanged. Glyph reuses the app's existing ✦
881
- // vocabulary — no new iconography.
882
- // The copy also teaches the Stage-B2 affordance: this pane is where a clicked filename opens, and
883
- // it is the first thing the eye lands on when the viewer closes.
884
- 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) {
885
927
  const done = st && st.currentGeneration;
886
- return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner">' +
887
- '<span class="kb-ph-ico" aria-hidden="true">✦</span>' +
888
- '<div class="kb-ph-title">Graph &amp; Notes — coming soon</div>' +
889
- '<div class="kb-ph-sub">' +
890
- (done
891
- ? 'This project’s references are organized. The visual graph — sources, concepts and people, ' +
892
- 'linked — opens here in a later update. Click any file on the left to preview it in the meantime.'
893
- : 'Once references are organized, this space maps your knowledge base — sources, concepts and ' +
894
- 'people, linked — and lets you open any note. For now, click a file on the left to preview it, ' +
895
- 'or add references and Organize.') +
896
- '</div></div></section>';
897
- };
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>'; }
898
948
 
899
949
  // ── The file viewer ───────────────────────────────────────────────────────────
900
950
  // SECURITY: `filename` is user-authored and every state below interpolates it — escapeHtml for text,
@@ -992,6 +1042,42 @@
992
1042
  else kbPaintText(row, url, ac, alive);
993
1043
  }
994
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
+
995
1081
  /** Accept a freshly-read /status as the current truth. EVERY writer of `knowledgeState` goes through
996
1082
  * here, because committing state also decides whether the poll runs: a caller that claims the render
997
1083
  * epoch can supersede the very render that would have discovered a newly queued organize, and
@@ -1146,6 +1232,7 @@
1146
1232
  /** Identity of what the viewer host is showing. `blobSha256` is in the key because a hand-edited
1147
1233
  * manifest (and, later, Stage D) can swap a row's bytes without changing its sourceId. */
1148
1234
  function kbViewKey(st) {
1235
+ if (viewer.mode === 'page') { const gen = st.currentGeneration ? st.currentGeneration.generationId : ''; return 'page:' + gen + ':' + (viewer.slug || ''); }
1149
1236
  const row = viewer.mode === 'file' ? st.sources.find((s) => s.sourceId === viewer.sourceId) : null;
1150
1237
  const gen = viewer.mode === 'graph' && st.currentGeneration ? st.currentGeneration.generationId : '';
1151
1238
  return [current && current.id, viewer.mode, viewer.sourceId || '', row ? row.blobSha256 : '', gen].join('|');
@@ -1194,8 +1281,16 @@
1194
1281
  if (viewHost) viewHost.innerHTML = kbViewShell(row, kbViewLoading(row));
1195
1282
  kbLoadPreview(current, row);
1196
1283
  }
1284
+ } else if (viewer.mode === 'page') {
1285
+ if (viewHost) viewHost.innerHTML = kbPageLoading();
1286
+ kbLoadPage(current, viewer.slug);
1197
1287
  } else if (viewHost) {
1198
- viewHost.innerHTML = kbPlaceholder(st);
1288
+ if (!st.currentGeneration) {
1289
+ viewHost.innerHTML = kbGraphEmpty(st);
1290
+ } else {
1291
+ viewHost.innerHTML = kbGraphLoading();
1292
+ kbLoadGraph(current);
1293
+ }
1199
1294
  }
1200
1295
  }
1201
1296
  }
@@ -1210,7 +1305,7 @@
1210
1305
  `<div class="kb-refs-body">${inner}</div></section>`;
1211
1306
  lastRefsHtml = null;
1212
1307
  const host = kbViewHost();
1213
- if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbPlaceholder(null);
1308
+ if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbGraphEmpty(null);
1214
1309
  }
1215
1310
 
1216
1311
  async function renderKnowledge() {
@@ -1367,6 +1462,10 @@
1367
1462
  if (knowledgeState) paintKnowledge(knowledgeState);
1368
1463
  return;
1369
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; }
1370
1469
  if (e.target.closest('[data-kb-close]')) {
1371
1470
  const wasOpen = viewer.sourceId;
1372
1471
  setViewer({ mode: 'graph', sourceId: null });
@@ -1394,6 +1493,13 @@
1394
1493
  if (org) { if (org.getAttribute('aria-disabled') !== 'true') kbOrganize(); return; } // aria-disabled still receives clicks
1395
1494
  if (e.target.closest('#kb-drop')) $wsKnowledgeFile.click();
1396
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
+ });
1397
1503
  $wsKnowledgeFile.addEventListener('change', () => {
1398
1504
  kbUpload($wsKnowledgeFile.files);
1399
1505
  $wsKnowledgeFile.value = ''; // let the same file be picked twice in a row
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.87.0",
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": {