@floless/app 0.87.0 → 0.89.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.
package/dist/floless-server.cjs
CHANGED
|
@@ -53106,7 +53106,7 @@ function appVersion() {
|
|
|
53106
53106
|
return resolveVersion({
|
|
53107
53107
|
isSea: isSea2(),
|
|
53108
53108
|
sqVersionXml: readSqVersionXml(),
|
|
53109
|
-
define: true ? "0.
|
|
53109
|
+
define: true ? "0.89.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.
|
|
53119
|
+
return resolveChannel({ isSea: isSea2(), define: true ? "0.89.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,317 @@ 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
|
+
}
|
|
54983
|
+
var KB_FEED_Q_THRESHOLD = 20;
|
|
54984
|
+
var KB_FEED_MAX_LIMIT = 50;
|
|
54985
|
+
var KB_FEED_SNIPPET_LEN = 200;
|
|
54986
|
+
var KB_FEED_MAX_TOKENS = 12;
|
|
54987
|
+
function countOccurrences(hay, needle) {
|
|
54988
|
+
if (!needle) return 0;
|
|
54989
|
+
let n = 0, i = 0;
|
|
54990
|
+
while ((i = hay.indexOf(needle, i)) !== -1) {
|
|
54991
|
+
n++;
|
|
54992
|
+
i += needle.length;
|
|
54993
|
+
}
|
|
54994
|
+
return n;
|
|
54995
|
+
}
|
|
54996
|
+
function feedSnippet(body, tokens, len) {
|
|
54997
|
+
const flat = body.replace(/\s+/g, " ").trim();
|
|
54998
|
+
if (!flat) return "";
|
|
54999
|
+
const lower = flat.toLowerCase();
|
|
55000
|
+
let at = -1;
|
|
55001
|
+
for (const t of tokens) {
|
|
55002
|
+
const i = lower.indexOf(t);
|
|
55003
|
+
if (i !== -1 && (at === -1 || i < at)) at = i;
|
|
55004
|
+
}
|
|
55005
|
+
if (at === -1) return flat.length > len ? flat.slice(0, len).trimEnd() + "\u2026" : flat;
|
|
55006
|
+
const start = Math.max(0, at - Math.floor(len / 3));
|
|
55007
|
+
const end = Math.min(flat.length, start + len);
|
|
55008
|
+
return (start > 0 ? "\u2026" : "") + flat.slice(start, end).trim() + (end < flat.length ? "\u2026" : "");
|
|
55009
|
+
}
|
|
55010
|
+
function readKnowledgeSummaries(wikiDir, opts = {}, io = REAL_IO) {
|
|
55011
|
+
const limit = Math.max(1, Math.min(opts.limit ?? KB_FEED_Q_THRESHOLD, KB_FEED_MAX_LIMIT));
|
|
55012
|
+
const q = (opts.q ?? "").trim();
|
|
55013
|
+
const tokens = q ? q.toLowerCase().split(/[^a-z0-9]+/).filter(Boolean).slice(0, KB_FEED_MAX_TOKENS) : [];
|
|
55014
|
+
const { pages, incomplete } = collectPages(wikiDir, io);
|
|
55015
|
+
const total = pages.size;
|
|
55016
|
+
let truncated = incomplete;
|
|
55017
|
+
if (tokens.length === 0 && total > KB_FEED_Q_THRESHOLD) {
|
|
55018
|
+
return { pages: [], total, truncated, needsQuery: true };
|
|
55019
|
+
}
|
|
55020
|
+
const parsed = [];
|
|
55021
|
+
let rawBytes = 0;
|
|
55022
|
+
for (const [slug, path] of pages) {
|
|
55023
|
+
const size = safeStat(io, path);
|
|
55024
|
+
if (rawBytes + size > KB_MAX_TOTAL_BYTES) {
|
|
55025
|
+
truncated = true;
|
|
55026
|
+
break;
|
|
55027
|
+
}
|
|
55028
|
+
rawBytes += size;
|
|
55029
|
+
const pp = splitPage(path, io);
|
|
55030
|
+
if (!pp.ok) {
|
|
55031
|
+
truncated = true;
|
|
55032
|
+
continue;
|
|
55033
|
+
}
|
|
55034
|
+
const ft = pp.fm.type;
|
|
55035
|
+
const type = ft === "source" || ft === "concept" || ft === "person" || ft === "index" ? ft : "concept";
|
|
55036
|
+
const title = titleOf(pp.body, slug);
|
|
55037
|
+
let score = 0;
|
|
55038
|
+
if (tokens.length) {
|
|
55039
|
+
const tl = title.toLowerCase(), bl = pp.body.toLowerCase();
|
|
55040
|
+
score = tokens.reduce((s, tok) => s + countOccurrences(tl, tok) * 3 + countOccurrences(bl, tok), 0);
|
|
55041
|
+
}
|
|
55042
|
+
parsed.push({ slug, title, type, body: pp.body, score });
|
|
55043
|
+
}
|
|
55044
|
+
let rows = tokens.length ? parsed.filter((p) => p.score > 0).sort((a, b) => b.score - a.score || a.slug.localeCompare(b.slug)) : parsed.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
55045
|
+
if (rows.length > limit) {
|
|
55046
|
+
rows = rows.slice(0, limit);
|
|
55047
|
+
truncated = true;
|
|
55048
|
+
}
|
|
55049
|
+
return {
|
|
55050
|
+
pages: rows.map((p) => ({ slug: p.slug, title: p.title, type: p.type, snippet: feedSnippet(p.body, tokens, KB_FEED_SNIPPET_LEN) })),
|
|
55051
|
+
total,
|
|
55052
|
+
truncated
|
|
55053
|
+
};
|
|
55054
|
+
}
|
|
54743
55055
|
var organizePath = (id) => (0, import_node_path19.join)(projectKnowledgeDir(id), "organize.json");
|
|
54744
55056
|
function writeOrganizeFile(id, org) {
|
|
54745
55057
|
const dir = projectKnowledgeDir(id);
|
|
@@ -54874,7 +55186,10 @@ function resolveOrganizeRequest(projectId, requestId) {
|
|
|
54874
55186
|
return kreq;
|
|
54875
55187
|
}
|
|
54876
55188
|
function knowledgeErrorStatus(e) {
|
|
54877
|
-
|
|
55189
|
+
if (e.code === "conflict") return 409;
|
|
55190
|
+
if (e.code === "too-large") return 503;
|
|
55191
|
+
if (e.code === "io-error") return 500;
|
|
55192
|
+
return 400;
|
|
54878
55193
|
}
|
|
54879
55194
|
function registerKnowledgeRoutes(app) {
|
|
54880
55195
|
app.post(
|
|
@@ -55014,6 +55329,33 @@ function registerKnowledgeRoutes(app) {
|
|
|
55014
55329
|
throw e;
|
|
55015
55330
|
}
|
|
55016
55331
|
});
|
|
55332
|
+
app.get("/api/projects/:id/knowledge/graph", async (req, reply) => {
|
|
55333
|
+
try {
|
|
55334
|
+
const project = getProject(req.params.id);
|
|
55335
|
+
if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
|
|
55336
|
+
const wikiDir = currentGenerationWikiDir(project.id);
|
|
55337
|
+
const graph = wikiDir ? readGraph(wikiDir) : { nodes: [], edges: [], index: null, truncated: false };
|
|
55338
|
+
return { ok: true, graph };
|
|
55339
|
+
} catch (e) {
|
|
55340
|
+
if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
|
|
55341
|
+
if (e instanceof KnowledgeError) return reply.status(knowledgeErrorStatus(e)).send({ ok: false, error: e.message });
|
|
55342
|
+
throw e;
|
|
55343
|
+
}
|
|
55344
|
+
});
|
|
55345
|
+
app.get("/api/projects/:id/knowledge/page/:slug", async (req, reply) => {
|
|
55346
|
+
try {
|
|
55347
|
+
const project = getProject(req.params.id);
|
|
55348
|
+
if (!project) return reply.status(404).send({ ok: false, error: `unknown project: ${req.params.id}` });
|
|
55349
|
+
const wikiDir = currentGenerationWikiDir(project.id);
|
|
55350
|
+
const pg = wikiDir ? readPage(wikiDir, req.params.slug) : null;
|
|
55351
|
+
if (!pg) return reply.status(404).send({ ok: false, error: "page not found" });
|
|
55352
|
+
return { ok: true, page: pg };
|
|
55353
|
+
} catch (e) {
|
|
55354
|
+
if (e instanceof ProjectError) return reply.status(400).send({ ok: false, error: e.message });
|
|
55355
|
+
if (e instanceof KnowledgeError) return reply.status(knowledgeErrorStatus(e)).send({ ok: false, error: e.message });
|
|
55356
|
+
throw e;
|
|
55357
|
+
}
|
|
55358
|
+
});
|
|
55017
55359
|
app.post(
|
|
55018
55360
|
"/api/projects/:id/knowledge/requests/:requestId/start",
|
|
55019
55361
|
async (req, reply) => {
|
|
@@ -55437,6 +55779,36 @@ function registerWorkspaceDataRoutes(app) {
|
|
|
55437
55779
|
}
|
|
55438
55780
|
return body;
|
|
55439
55781
|
});
|
|
55782
|
+
app.get(
|
|
55783
|
+
"/api/workspace-projects/:projectId/knowledge",
|
|
55784
|
+
async (req, reply) => {
|
|
55785
|
+
let project;
|
|
55786
|
+
try {
|
|
55787
|
+
project = getProject(req.params.projectId);
|
|
55788
|
+
} catch (e) {
|
|
55789
|
+
if (e instanceof ProjectError) return sendError(reply, 400, e.message);
|
|
55790
|
+
throw e;
|
|
55791
|
+
}
|
|
55792
|
+
if (!project) return sendError(reply, 404, `unknown project: ${req.params.projectId}`);
|
|
55793
|
+
const appGuard = optionalString(req.query.app);
|
|
55794
|
+
if (req.query.app !== void 0 && !appGuard) return sendError(reply, 400, "invalid app");
|
|
55795
|
+
if (appGuard && appGuard !== project.app) {
|
|
55796
|
+
return sendError(reply, 404, `project "${project.id}" belongs to app "${project.app}", not "${appGuard}"`);
|
|
55797
|
+
}
|
|
55798
|
+
const limit = parseIntParam(req.query.limit, "limit");
|
|
55799
|
+
if (limit === null) return sendError(reply, 400, "invalid limit");
|
|
55800
|
+
const q = optionalString(req.query.q);
|
|
55801
|
+
const wikiDir = currentGenerationWikiDir(project.id);
|
|
55802
|
+
if (!wikiDir) return { ok: true, generation: null, pages: [], total: 0, truncated: false };
|
|
55803
|
+
try {
|
|
55804
|
+
const feed = readKnowledgeSummaries(wikiDir, { q, limit: limit ?? void 0 });
|
|
55805
|
+
return { ok: true, generation: readCurrentGeneration(project.id), ...feed };
|
|
55806
|
+
} catch (e) {
|
|
55807
|
+
if (e instanceof KnowledgeError) return sendError(reply, knowledgeErrorStatus(e), e.message);
|
|
55808
|
+
throw e;
|
|
55809
|
+
}
|
|
55810
|
+
}
|
|
55811
|
+
);
|
|
55440
55812
|
}
|
|
55441
55813
|
|
|
55442
55814
|
// workspace-agent-manifest.ts
|
|
@@ -55453,19 +55825,21 @@ function syncWorkspaceAgentManifest(port) {
|
|
|
55453
55825
|
const dir = workspaceAgentDir();
|
|
55454
55826
|
(0, import_node_fs26.mkdirSync)(dir, { recursive: true });
|
|
55455
55827
|
const manifest = `agent: floless-workspace
|
|
55456
|
-
version: 0.
|
|
55828
|
+
version: 0.2.0
|
|
55457
55829
|
sdk-target: 2.4.0
|
|
55458
55830
|
display-name: FloLess Workspace
|
|
55459
55831
|
description: |
|
|
55460
|
-
Read
|
|
55461
|
-
|
|
55462
|
-
|
|
55832
|
+
Read a FloLess workspace project from the local floless.app server: its APPROVED model
|
|
55833
|
+
snapshots (list-approved / read-approved) and its compiled KNOWLEDGE BASE (read-knowledge) \u2014 the
|
|
55834
|
+
project's own reference context such as company/shop standards, RFIs, and spec notes, which is
|
|
55835
|
+
NOT approved model data. This is runtime-generated integration glue; FloLess owns the workspace
|
|
55836
|
+
API and AWARE only sees a normal loopback REST agent.
|
|
55463
55837
|
|
|
55464
55838
|
stateful: false
|
|
55465
55839
|
vendor: floless
|
|
55466
55840
|
license: MIT
|
|
55467
55841
|
homepage: https://github.com/aware-aeco/floless.app
|
|
55468
|
-
keywords: [floless, workspace, project, approved, local]
|
|
55842
|
+
keywords: [floless, workspace, project, approved, knowledge, reference, context, local]
|
|
55469
55843
|
|
|
55470
55844
|
requires:
|
|
55471
55845
|
network:
|
|
@@ -55550,6 +55924,34 @@ commands:
|
|
|
55550
55924
|
status: int
|
|
55551
55925
|
headers: object
|
|
55552
55926
|
body: object
|
|
55927
|
+
|
|
55928
|
+
read-knowledge:
|
|
55929
|
+
lifecycle: single
|
|
55930
|
+
mode: read
|
|
55931
|
+
description: Read this project's compiled knowledge base as ranked summaries \u2014 the project's own reference context (company/shop standards, RFIs, spec notes), NOT approved model data. Consult it before acting (q = the subject you are about to work on), then honor and cite the source page it returns.
|
|
55932
|
+
method: GET
|
|
55933
|
+
path: /api/workspace-projects/{project-id}/knowledge
|
|
55934
|
+
inputs:
|
|
55935
|
+
project-id:
|
|
55936
|
+
type: string
|
|
55937
|
+
in: path
|
|
55938
|
+
description: Durable FloLess workspace project id.
|
|
55939
|
+
q:
|
|
55940
|
+
type: string
|
|
55941
|
+
in: query
|
|
55942
|
+
required: false
|
|
55943
|
+
description: Search terms to rank the knowledge pages by; required past a small knowledge base.
|
|
55944
|
+
app:
|
|
55945
|
+
type: string
|
|
55946
|
+
in: query
|
|
55947
|
+
required: false
|
|
55948
|
+
description: Optional app id guard; mismatches return 404.
|
|
55949
|
+
outputs:
|
|
55950
|
+
type: single
|
|
55951
|
+
schema:
|
|
55952
|
+
status: int
|
|
55953
|
+
headers: object
|
|
55954
|
+
body: object
|
|
55553
55955
|
`;
|
|
55554
55956
|
const path = (0, import_node_path23.join)(dir, "manifest.yaml");
|
|
55555
55957
|
if (!(0, import_node_fs26.existsSync)(path) || manifest !== "") (0, import_node_fs26.writeFileSync)(path, manifest, "utf8");
|
|
@@ -55908,15 +56310,15 @@ function saveSource(id, file) {
|
|
|
55908
56310
|
|
|
55909
56311
|
// contract-bake.ts
|
|
55910
56312
|
var import_node_fs28 = require("node:fs");
|
|
55911
|
-
var
|
|
56313
|
+
var import_yaml6 = __toESM(require_dist6(), 1);
|
|
55912
56314
|
function bakeContractIntoApp(sourcePath, contract) {
|
|
55913
|
-
const doc = (0,
|
|
56315
|
+
const doc = (0, import_yaml6.parseDocument)((0, import_node_fs28.readFileSync)(sourcePath, "utf8"));
|
|
55914
56316
|
if (doc.errors.length > 0) {
|
|
55915
56317
|
throw new Error(`contract bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
|
|
55916
56318
|
}
|
|
55917
56319
|
const seq = doc.get("nodes");
|
|
55918
|
-
const items = (0,
|
|
55919
|
-
const nodeOf = (it) => (0,
|
|
56320
|
+
const items = (0, import_yaml6.isSeq)(seq) ? seq.items : [];
|
|
56321
|
+
const nodeOf = (it) => (0, import_yaml6.isMap)(it) ? it.toJSON() : null;
|
|
55920
56322
|
let idx = items.findIndex((it) => nodeOf(it)?.config?.contract === contract.type);
|
|
55921
56323
|
if (idx < 0) idx = items.findIndex((it) => nodeOf(it)?.agent === "steel-takeoff-us");
|
|
55922
56324
|
if (idx < 0) throw new Error("no contract-emitting node to bake the contract into");
|
|
@@ -61166,27 +61568,27 @@ async function bomToXlsx(bom) {
|
|
|
61166
61568
|
// scene-bake.ts
|
|
61167
61569
|
var import_node_fs30 = require("node:fs");
|
|
61168
61570
|
var import_node_path26 = require("node:path");
|
|
61169
|
-
var
|
|
61571
|
+
var import_yaml7 = __toESM(require_dist6(), 1);
|
|
61170
61572
|
function bakeSceneIntoApp(sourcePath, scene, agent = "viewer-3d") {
|
|
61171
|
-
const doc = (0,
|
|
61573
|
+
const doc = (0, import_yaml7.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
|
|
61172
61574
|
if (doc.errors.length > 0) {
|
|
61173
61575
|
throw new Error(`scene bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
|
|
61174
61576
|
}
|
|
61175
61577
|
const seq = doc.get("nodes");
|
|
61176
|
-
const items = (0,
|
|
61177
|
-
const idx = items.findIndex((it) => ((0,
|
|
61578
|
+
const items = (0, import_yaml7.isSeq)(seq) ? seq.items : [];
|
|
61579
|
+
const idx = items.findIndex((it) => ((0, import_yaml7.isMap)(it) ? it.toJSON() : null)?.agent === agent);
|
|
61178
61580
|
if (idx < 0) throw new Error(`no ${agent} render node to bake the scene into`);
|
|
61179
61581
|
doc.setIn(["nodes", idx, "config", "scene"], scene);
|
|
61180
61582
|
(0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
|
|
61181
61583
|
}
|
|
61182
61584
|
function bakeNodeConfigById(sourcePath, nodeId, patch2) {
|
|
61183
|
-
const doc = (0,
|
|
61585
|
+
const doc = (0, import_yaml7.parseDocument)((0, import_node_fs30.readFileSync)(sourcePath, "utf8"));
|
|
61184
61586
|
if (doc.errors.length > 0) {
|
|
61185
61587
|
throw new Error(`node bake: source is not valid YAML: ${doc.errors[0]?.message ?? "parse error"}`);
|
|
61186
61588
|
}
|
|
61187
61589
|
const seq = doc.get("nodes");
|
|
61188
|
-
const items = (0,
|
|
61189
|
-
const idx = items.findIndex((it) => ((0,
|
|
61590
|
+
const items = (0, import_yaml7.isSeq)(seq) ? seq.items : [];
|
|
61591
|
+
const idx = items.findIndex((it) => ((0, import_yaml7.isMap)(it) ? it.toJSON() : null)?.id === nodeId);
|
|
61190
61592
|
if (idx < 0) throw new Error(`no node with id "${nodeId}"`);
|
|
61191
61593
|
for (const [key, value] of Object.entries(patch2)) doc.setIn(["nodes", idx, "config", key], value);
|
|
61192
61594
|
(0, import_node_fs30.writeFileSync)(sourcePath, doc.toString());
|
|
@@ -61857,7 +62259,7 @@ function clientCount() {
|
|
|
61857
62259
|
var import_node_fs31 = require("node:fs");
|
|
61858
62260
|
var import_node_os16 = require("node:os");
|
|
61859
62261
|
var import_node_path27 = require("node:path");
|
|
61860
|
-
var
|
|
62262
|
+
var import_yaml8 = __toESM(require_dist6(), 1);
|
|
61861
62263
|
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
62264
|
function summarizeFire(data) {
|
|
61863
62265
|
if (!data) return "event";
|
|
@@ -61878,7 +62280,7 @@ function isHostBacked(agent, agentsDir = AGENTS_DIR2) {
|
|
|
61878
62280
|
const manifestPath2 = (0, import_node_path27.join)(agentsDir, agent, "manifest.yaml");
|
|
61879
62281
|
if (!(0, import_node_fs31.existsSync)(manifestPath2)) return false;
|
|
61880
62282
|
try {
|
|
61881
|
-
const doc = (0,
|
|
62283
|
+
const doc = (0, import_yaml8.parse)((0, import_node_fs31.readFileSync)(manifestPath2, "utf8"));
|
|
61882
62284
|
const transport = doc?.transport;
|
|
61883
62285
|
return !!(transport && typeof transport === "object" && "cli" in transport);
|
|
61884
62286
|
} catch {
|
|
@@ -63819,7 +64221,7 @@ var import_node_fs38 = require("node:fs");
|
|
|
63819
64221
|
var import_node_os20 = require("node:os");
|
|
63820
64222
|
var import_node_path34 = require("node:path");
|
|
63821
64223
|
var import_node_url4 = require("node:url");
|
|
63822
|
-
var
|
|
64224
|
+
var import_yaml9 = __toESM(require_dist6(), 1);
|
|
63823
64225
|
|
|
63824
64226
|
// build/ship-skills.mjs
|
|
63825
64227
|
var PRODUCT_SKILLS = [
|
|
@@ -63888,7 +64290,7 @@ function skillVersion(skillMdPath) {
|
|
|
63888
64290
|
const text = (0, import_node_fs38.readFileSync)(skillMdPath, "utf8");
|
|
63889
64291
|
const m = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
|
|
63890
64292
|
if (!m || m[1] === void 0) return null;
|
|
63891
|
-
const fm = (0,
|
|
64293
|
+
const fm = (0, import_yaml9.parse)(m[1]);
|
|
63892
64294
|
const meta = fm?.metadata;
|
|
63893
64295
|
const v = meta?.version;
|
|
63894
64296
|
return typeof v === "string" || typeof v === "number" ? String(v) : null;
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
name: floless-app-knowledge
|
|
3
3
|
description: This skill should be used when there is a pending floless `knowledge-organize` or `knowledge-adjust` request — the user pressed Organize on a floless.app project's Knowledge step, or asked to reshape that project's knowledge base. Also triggers on asks like "organize my project knowledge base", "compile the project wiki", "drain my knowledge-organize request", or "fold these shop standards into the project's knowledge". It teaches the host AI to claim the server-owned organize lock, project the enabled reference sources into that project's vault, compile a cross-linked LLM-wiki into the server-minted generation directory, and publish it — never writing the server-owned manifest, pointer, or lock.
|
|
4
4
|
metadata:
|
|
5
|
-
version: 0.
|
|
5
|
+
version: 0.2.0
|
|
6
6
|
---
|
|
7
7
|
|
|
8
8
|
# Organize a project's Knowledge Base
|
|
@@ -157,11 +157,42 @@ The request carries the user's prose in `instruction` — for example "treat RFI
|
|
|
157
157
|
- A `knowledge-adjust` request is an ordinary request — apply it, then `DELETE
|
|
158
158
|
<base>/api/requests/<requestId>`. Only `knowledge-organize` is lifecycle-cleared.
|
|
159
159
|
|
|
160
|
-
## Consulting the KB from other work
|
|
160
|
+
## Consulting the KB from other work (the Feed)
|
|
161
161
|
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
162
|
+
Once a project has a knowledge base, everything else that works on the project — the reader, the
|
|
163
|
+
connection engine, the drawing generator, the shipped `floless-app-*` skills, and any bundled `aware`
|
|
164
|
+
agent — should **consult it as project context before acting**. The KB is served read-only over the
|
|
165
|
+
loopback `floless-workspace` agent (and directly on the floless server).
|
|
166
|
+
|
|
167
|
+
### Required first step — read the relevant summaries
|
|
168
|
+
|
|
169
|
+
Before you act on the project, ask the KB for the summaries relevant to what you're about to do:
|
|
170
|
+
|
|
171
|
+
```
|
|
172
|
+
GET <base>/api/workspace-projects/<projectId>/knowledge?q=<the subject you're about to work on>
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
- `?q=` ranks the pages by your subject (plain lexical match). Omit it only on a small KB to get the
|
|
176
|
+
whole table of contents — past a threshold the response comes back `{ needsQuery: true }`, asking you
|
|
177
|
+
to narrow with a `q`.
|
|
178
|
+
- The response is **summaries only**: `{ generation, pages: [{ slug, title, type, snippet }], total,
|
|
179
|
+
truncated, needsQuery? }`. It never returns raw files or filesystem paths.
|
|
180
|
+
- **Honor and cite.** Let the returned pages steer the decision — a shop standard, an RFI that governs,
|
|
181
|
+
a fabricator's preference — and cite the `slug`/`title` you relied on so the user can trace it. This
|
|
182
|
+
is the guardrail: *reliably-consulted context*, not a mechanical run-gate. You must actually consult it.
|
|
183
|
+
- When a summary looks decisive and you need the full page, read it from the project route
|
|
184
|
+
`GET <base>/api/projects/<projectId>/knowledge/page/<slug>` (plain-text body).
|
|
185
|
+
|
|
186
|
+
### Identity propagation — thread the KB's identity into every subagent
|
|
187
|
+
|
|
188
|
+
A subagent can only consult a KB it can **name**. So every dispatch / Request that expects KB use
|
|
189
|
+
**carries `{ projectId, workspaceBaseUrl }`**, and you **must thread those into each subagent's
|
|
190
|
+
prompt**. Thread the **identity**, never the KB contents — one rule for the top-level task and its
|
|
191
|
+
subagents alike.
|
|
192
|
+
|
|
193
|
+
> A running `.flo` consults the same Feed by calling the `floless-workspace` agent's **read-knowledge**
|
|
194
|
+
> command (same route, summaries only) — the workflow is handed `{ projectId, workspaceBaseUrl }` as
|
|
195
|
+
> inputs, exactly as it is for `read-approved`.
|
|
165
196
|
|
|
166
197
|
## Happy path (end to end)
|
|
167
198
|
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
app: floless-workspace-knowledge
|
|
2
|
+
version: 0.1.0
|
|
3
|
+
display-name: Consult Workspace Knowledge Base
|
|
4
|
+
description: |
|
|
5
|
+
Reads a FloLess Workspace project's compiled KNOWLEDGE BASE inside a running
|
|
6
|
+
workflow — the Feed — and renders what it consulted as a styled HTML report. The
|
|
7
|
+
reference demo for the Workspaces knowledge base (Slice 8 Stage D2).
|
|
8
|
+
|
|
9
|
+
Give it a durable Workspace project id and a subject to look up. The first node
|
|
10
|
+
calls the local `floless-workspace` REST agent's `read-knowledge` command, which
|
|
11
|
+
returns ranked SUMMARIES (slug, title, type, snippet) of the project's own
|
|
12
|
+
reference context — company/shop standards, RFIs, spec notes. It is never approved
|
|
13
|
+
model data and never a raw file: the response carries no bytes and no filesystem
|
|
14
|
+
paths. The gate stops the run cleanly on a failed read, and the report node renders
|
|
15
|
+
the generation, the total page count, and the top-ranked page so the run visibly
|
|
16
|
+
proves the knowledge base was consulted through a real AWARE node.
|
|
17
|
+
|
|
18
|
+
No Tekla model is required: the report node runs on the host bridge with nothing
|
|
19
|
+
open. It proves a `.flo` can consult a project's knowledge base through the real
|
|
20
|
+
floless-workspace seam, without the web UI composing the workflow.
|
|
21
|
+
exposes-as-agent: false
|
|
22
|
+
inputs:
|
|
23
|
+
project_id:
|
|
24
|
+
type: string
|
|
25
|
+
default: ""
|
|
26
|
+
description: Workspace project whose knowledge base to consult (any project — not approval-gated).
|
|
27
|
+
subject:
|
|
28
|
+
type: string
|
|
29
|
+
default: ""
|
|
30
|
+
description: The subject to rank the knowledge pages by (the read-knowledge q query).
|
|
31
|
+
requires:
|
|
32
|
+
- floless-workspace@0.2.x
|
|
33
|
+
- tekla@0.1.x
|
|
34
|
+
layout: linear
|
|
35
|
+
nodes:
|
|
36
|
+
# ── node 1: consult the knowledge base through the loopback REST seam ──
|
|
37
|
+
# Calls floless-workspace/read-knowledge. AWARE's REST transport returns
|
|
38
|
+
# { status, headers, body }, so downstream nodes read kb.body.* — the body carries
|
|
39
|
+
# { ok, generation, pages: [{ slug, title, type, snippet }], total, truncated }.
|
|
40
|
+
- id: kb
|
|
41
|
+
agent: floless-workspace
|
|
42
|
+
command: read-knowledge
|
|
43
|
+
mode: read
|
|
44
|
+
config:
|
|
45
|
+
project-id: "{{ inputs.project_id }}"
|
|
46
|
+
q: "{{ inputs.subject }}"
|
|
47
|
+
# ── node 2: gate — only continue when the read succeeded (HTTP 200) ──
|
|
48
|
+
# AWARE has no conditional branch and its templating errors if a downstream node
|
|
49
|
+
# references a field absent on a non-2xx body. This predicate stops the run cleanly
|
|
50
|
+
# on a failed read instead of letting the report node blow up on a missing field.
|
|
51
|
+
- id: gate
|
|
52
|
+
inline:
|
|
53
|
+
kind: predicate
|
|
54
|
+
description: Continue to the report only when the knowledge-base read returned HTTP 200.
|
|
55
|
+
code: "e.status == 200"
|
|
56
|
+
# ── node 3: render what the workflow consulted as a report (terminal node) ──
|
|
57
|
+
- id: report
|
|
58
|
+
agent: tekla
|
|
59
|
+
command: exec
|
|
60
|
+
mode: read
|
|
61
|
+
config:
|
|
62
|
+
version: "2026.0"
|
|
63
|
+
args:
|
|
64
|
+
status: "{{ kb.status }}"
|
|
65
|
+
ok: "{{ kb.body.ok }}"
|
|
66
|
+
subject: "{{ inputs.subject }}"
|
|
67
|
+
# `{% if %}` guards the fields that are legitimately absent on a 200 response: generation is null
|
|
68
|
+
# (no published KB) and pages is [] (no KB, no match for q, or a KB large enough to need a query).
|
|
69
|
+
# AWARE's renderer ERRORS on an undefined value, and a filter default() does not help (the error is
|
|
70
|
+
# raised resolving the path, before the filter). But minijinja is Jinja2-lenient, where an empty
|
|
71
|
+
# list / null is FALSY, so the {% if %} short-circuits and the deep reference is never evaluated
|
|
72
|
+
# when empty — rendering "" instead. The C# below then presents each empty shape as a clear message.
|
|
73
|
+
gen: "{% if kb.body.generation %}{{ kb.body.generation.generationId }}{% endif %}"
|
|
74
|
+
total: "{{ kb.body.total }}"
|
|
75
|
+
truncated: "{{ kb.body.truncated }}"
|
|
76
|
+
top_slug: "{% if kb.body.pages %}{{ kb.body.pages[0].slug }}{% endif %}"
|
|
77
|
+
top_title: "{% if kb.body.pages %}{{ kb.body.pages[0].title }}{% endif %}"
|
|
78
|
+
top_type: "{% if kb.body.pages %}{{ kb.body.pages[0].type }}{% endif %}"
|
|
79
|
+
top_snippet: "{% if kb.body.pages %}{{ kb.body.pages[0].snippet }}{% endif %}"
|
|
80
|
+
code: |
|
|
81
|
+
// Report — turns the knowledge-base summaries this workflow consulted (the Feed)
|
|
82
|
+
// into a styled HTML report the in-app viewer renders. It checks the HTTP status
|
|
83
|
+
// first: any non-200 (or ok != true) renders a plain error card so a failed read
|
|
84
|
+
// never masquerades as success. Touches no Tekla model, so it runs with nothing
|
|
85
|
+
// open. Manual HTML-escape (no System.Net available here).
|
|
86
|
+
using System;
|
|
87
|
+
using System.IO;
|
|
88
|
+
using System.Text;
|
|
89
|
+
|
|
90
|
+
Func<string,string> A = k => (args != null && args.TryGetValue(k, out var v) && v != null) ? v.ToString() : "";
|
|
91
|
+
Func<string,string> E = s => (s ?? "").Replace("&","&").Replace("<","<").Replace(">",">").Replace("\"",""");
|
|
92
|
+
Func<string,string> D = s => (s == null || s == "" || s == "none") ? "—" : s;
|
|
93
|
+
|
|
94
|
+
string status = A("status");
|
|
95
|
+
string ok = A("ok");
|
|
96
|
+
bool good = status == "200" && (ok.Equals("true", StringComparison.OrdinalIgnoreCase) || ok == "True");
|
|
97
|
+
|
|
98
|
+
string subject = A("subject"), gen = A("gen"), total = A("total"), truncated = A("truncated");
|
|
99
|
+
string topSlug = A("top_slug"), topTitle = A("top_title"), topType = A("top_type"), topSnippet = A("top_snippet");
|
|
100
|
+
string truncText = (truncated.Equals("true", StringComparison.OrdinalIgnoreCase) || truncated == "1") ? "Yes" : "No";
|
|
101
|
+
string now = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
|
|
102
|
+
|
|
103
|
+
var sb = new StringBuilder();
|
|
104
|
+
sb.Append("<!DOCTYPE html><html lang=\"en\"><head><meta charset=\"UTF-8\">");
|
|
105
|
+
sb.Append("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
|
|
106
|
+
sb.Append("<title>Knowledge Base consulted</title><style>");
|
|
107
|
+
sb.Append("*{margin:0;padding:0;box-sizing:border-box}");
|
|
108
|
+
sb.Append("body{font-family:-apple-system,'Segoe UI',Roboto,sans-serif;background:#f1f5f9;color:#0f172a;padding:2.5rem;line-height:1.6}");
|
|
109
|
+
sb.Append(".wrap{max-width:760px;margin:0 auto;background:#fff;border:1px solid #e2e8f0;border-radius:12px;padding:2rem 2.25rem;box-shadow:0 10px 30px rgba(2,6,23,.06)}");
|
|
110
|
+
sb.Append(".hd{border-bottom:2px solid #4a9eff;padding-bottom:1rem;margin-bottom:1.5rem}");
|
|
111
|
+
sb.Append(".hd h1{font-size:1.6rem;font-weight:800}");
|
|
112
|
+
sb.Append(".hd p{color:#64748b;font-size:.85rem;margin-top:.3rem}");
|
|
113
|
+
sb.Append(".cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:.85rem;margin-bottom:1.75rem}");
|
|
114
|
+
sb.Append(".card{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:.9rem 1rem}");
|
|
115
|
+
sb.Append(".card .l{font-size:.68rem;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8}");
|
|
116
|
+
sb.Append(".card .v{font-size:1.15rem;font-weight:700;margin-top:.15rem}");
|
|
117
|
+
sb.Append("table{width:100%;border-collapse:collapse;font-size:.9rem;margin-top:.25rem}");
|
|
118
|
+
sb.Append("th,td{text-align:left;padding:.6rem .75rem;border-bottom:1px solid #eef2f7}");
|
|
119
|
+
sb.Append("th{font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:#94a3b8}");
|
|
120
|
+
sb.Append("td:first-child{font-weight:600;color:#334155;width:34%}");
|
|
121
|
+
sb.Append(".snip{background:#f8fafc;border:1px solid #e2e8f0;border-radius:8px;padding:.85rem 1rem;font-size:.88rem;color:#334155;margin-top:.5rem}");
|
|
122
|
+
sb.Append(".err{background:#fef2f2;border:1px solid #fecaca;color:#991b1b;border-radius:8px;padding:1rem 1.15rem;font-size:.9rem}");
|
|
123
|
+
sb.Append(".ft{margin-top:1.75rem;padding-top:1rem;border-top:1px solid #eef2f7;color:#94a3b8;font-size:.78rem;text-align:center}");
|
|
124
|
+
sb.Append("</style></head><body><div class=\"wrap\">");
|
|
125
|
+
|
|
126
|
+
if (!good)
|
|
127
|
+
{
|
|
128
|
+
sb.Append("<div class=\"hd\"><h1>Could not read the knowledge base</h1>");
|
|
129
|
+
sb.Append("<p>The Workspace knowledge seam did not return summaries.</p></div>");
|
|
130
|
+
sb.Append("<div class=\"err\">HTTP status <b>" + E(status) + "</b> · ok=<b>" + E(ok) + "</b>. ");
|
|
131
|
+
sb.Append("Check that the project id exists and has a published knowledge base (press Organize on its Knowledge step).</div>");
|
|
132
|
+
sb.Append("<div class=\"ft\">Generated by FloLess · " + E(now) + "</div></div></body></html>");
|
|
133
|
+
return new { ok = false, status, html = sb.ToString() };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
sb.Append("<div class=\"hd\"><h1>Knowledge base consulted</h1>");
|
|
137
|
+
sb.Append("<p>Read live by a workflow through the floless-workspace seam · " + E(now) + "</p></div>");
|
|
138
|
+
sb.Append("<div class=\"cards\">");
|
|
139
|
+
sb.Append("<div class=\"card\"><div class=\"l\">Subject</div><div class=\"v\">" + E(D(subject)) + "</div></div>");
|
|
140
|
+
sb.Append("<div class=\"card\"><div class=\"l\">Pages in KB</div><div class=\"v\">" + E(D(total)) + "</div></div>");
|
|
141
|
+
sb.Append("<div class=\"card\"><div class=\"l\">Truncated</div><div class=\"v\">" + E(truncText) + "</div></div>");
|
|
142
|
+
sb.Append("</div>");
|
|
143
|
+
// The Feed can return three legitimate 200 shapes: a populated match, a published KB with no
|
|
144
|
+
// match for this subject, and a project with no published KB at all. Present each clearly rather
|
|
145
|
+
// than a row of dashes — and never assume a top page exists.
|
|
146
|
+
bool hasKb = total != "" && total != "0";
|
|
147
|
+
bool hasTop = topTitle != "";
|
|
148
|
+
if (!hasKb)
|
|
149
|
+
{
|
|
150
|
+
sb.Append("<div class=\"snip\">This project has no knowledge base yet — drop references on its Knowledge step and press Organize, then run again.</div>");
|
|
151
|
+
}
|
|
152
|
+
else if (!hasTop)
|
|
153
|
+
{
|
|
154
|
+
sb.Append("<table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>");
|
|
155
|
+
sb.Append("<tr><td>Generation</td><td>" + E(D(gen)) + "</td></tr></tbody></table>");
|
|
156
|
+
sb.Append("<div class=\"snip\">No knowledge pages matched “" + E(D(subject)) + "” — try a broader subject.</div>");
|
|
157
|
+
}
|
|
158
|
+
else
|
|
159
|
+
{
|
|
160
|
+
sb.Append("<table><thead><tr><th>Field</th><th>Value</th></tr></thead><tbody>");
|
|
161
|
+
sb.Append("<tr><td>Generation</td><td>" + E(D(gen)) + "</td></tr>");
|
|
162
|
+
sb.Append("<tr><td>Top page</td><td>" + E(D(topTitle)) + " <span style=\"color:#94a3b8\">(" + E(D(topType)) + " · " + E(D(topSlug)) + ")</span></td></tr>");
|
|
163
|
+
sb.Append("</tbody></table>");
|
|
164
|
+
sb.Append("<div class=\"snip\">" + E(D(topSnippet)) + "</div>");
|
|
165
|
+
}
|
|
166
|
+
sb.Append("<div class=\"ft\">Consulted through the floless-workspace seam · summaries only, no model data</div>");
|
|
167
|
+
sb.Append("</div></body></html>");
|
|
168
|
+
|
|
169
|
+
string html = sb.ToString();
|
|
170
|
+
|
|
171
|
+
// Save a copy so the viewer's Open file / Reveal buttons have a real file.
|
|
172
|
+
string savedPath = null;
|
|
173
|
+
try {
|
|
174
|
+
var outPath = Path.Combine(Path.GetTempPath(), "floless-workspace-knowledge.html");
|
|
175
|
+
File.WriteAllText(outPath, html);
|
|
176
|
+
savedPath = outPath;
|
|
177
|
+
} catch { savedPath = null; }
|
|
178
|
+
|
|
179
|
+
return new { ok = true, status, top_page = topTitle, html, saved_path = savedPath };
|
|
180
|
+
connections:
|
|
181
|
+
- { from: kb, to: gate }
|
|
182
|
+
- { from: gate, to: report }
|
package/dist/web/app.css
CHANGED
|
@@ -3836,6 +3836,36 @@ tr.hist-diff-row[hidden] { display:none; }
|
|
|
3836
3836
|
border-color:var(--border-strong); color:var(--text-muted); box-shadow:none; }
|
|
3837
3837
|
.kb-organize[aria-disabled="true"]:hover { background:var(--surface-2); border-color:var(--border-strong); box-shadow:none; }
|
|
3838
3838
|
.kb-organize:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
|
3839
|
+
/* Stage D — Adjust: steer the compiled wiki in plain English. A collapsed disclosure below Organize
|
|
3840
|
+
(only once a wiki exists), same idiom as .ws-archived. The submit is class="primary kb-adjust-submit"
|
|
3841
|
+
so .kb-refs-foot .primary already colours it — only the disabled/focus overrides live here. */
|
|
3842
|
+
.kb-adjust { margin-top:10px; border-top:1px solid var(--border); padding-top:10px; }
|
|
3843
|
+
.kb-adjust-summary { list-style:none; cursor:pointer; display:inline-flex; align-items:center; gap:7px;
|
|
3844
|
+
font-size:10px; text-transform:uppercase; letter-spacing:.18em; color:var(--text-dim);
|
|
3845
|
+
padding:5px 6px; border-radius:4px; user-select:none; }
|
|
3846
|
+
.kb-adjust-summary::-webkit-details-marker { display:none; }
|
|
3847
|
+
.kb-adjust-summary:hover { color:var(--text-muted); }
|
|
3848
|
+
.kb-adjust-summary:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
|
3849
|
+
.kb-adjust-caret { display:inline-block; transition:transform .15s; }
|
|
3850
|
+
.kb-adjust[open] > .kb-adjust-summary .kb-adjust-caret { transform:rotate(90deg); }
|
|
3851
|
+
.kb-adjust-body { margin-top:8px; display:flex; flex-direction:column; gap:8px; }
|
|
3852
|
+
.kb-adjust-label { font-size:10px; text-transform:uppercase; letter-spacing:.14em; color:var(--text-muted); }
|
|
3853
|
+
.kb-adjust-input { width:100%; background:var(--surface-2); border:1px solid var(--border-strong); color:var(--text);
|
|
3854
|
+
padding:9px 11px; font-family:var(--ui); font-size:13px; border-radius:4px; outline:none; resize:vertical;
|
|
3855
|
+
min-height:56px; line-height:1.5; transition:border-color .15s;
|
|
3856
|
+
scrollbar-width:thin; scrollbar-color:var(--border-strong) transparent; }
|
|
3857
|
+
.kb-adjust-input:focus { border-color:var(--accent); }
|
|
3858
|
+
.kb-adjust-input:disabled { opacity:.6; cursor:default; }
|
|
3859
|
+
.kb-adjust-input::-webkit-scrollbar { width:10px; }
|
|
3860
|
+
.kb-adjust-input::-webkit-scrollbar-thumb { background:var(--border-strong); border-radius:6px; }
|
|
3861
|
+
.kb-adjust-input::-webkit-scrollbar-track { background:transparent; }
|
|
3862
|
+
.kb-adjust-foot { display:flex; align-items:flex-start; justify-content:space-between; gap:10px; }
|
|
3863
|
+
.kb-adjust-hint { font-size:11px; color:var(--text-muted); line-height:1.4; }
|
|
3864
|
+
.kb-adjust-submit { flex:none; }
|
|
3865
|
+
.kb-adjust-submit[aria-disabled="true"] { opacity:.6; cursor:default; background:var(--surface-2);
|
|
3866
|
+
border-color:var(--border-strong); color:var(--text-muted); }
|
|
3867
|
+
.kb-adjust-submit[aria-disabled="true"]:hover { background:var(--surface-2); border-color:var(--border-strong); box-shadow:none; }
|
|
3868
|
+
.kb-adjust-submit:focus-visible { outline:2px solid var(--accent); outline-offset:2px; }
|
|
3839
3869
|
.kb-status { font-size:10.5px; color:var(--text-muted); font-family:var(--mono); line-height:1.5; }
|
|
3840
3870
|
.kb-status .ok { color:var(--ok); } .kb-status .err { color:var(--err); }
|
|
3841
3871
|
.kb-pending { display:flex; align-items:flex-start; gap:8px; font-size:11px; color:var(--accent-bright); line-height:1.45; }
|
|
@@ -3924,3 +3954,44 @@ tr.hist-diff-row[hidden] { display:none; }
|
|
|
3924
3954
|
.kb-view-spin { width:26px; height:26px; border:3px solid var(--accent-dim); border-top-color:var(--accent-bright);
|
|
3925
3955
|
border-radius:50%; animation:spin .8s linear infinite; }
|
|
3926
3956
|
@media (prefers-reduced-motion: reduce) { .kb-view-spin { animation:none; } }
|
|
3957
|
+
|
|
3958
|
+
/* ── Stage C: the knowledge graph + page viewer ───────────────────────────────── */
|
|
3959
|
+
.kb-graph { display: flex; flex-direction: column; height: 100%; min-height: 0; }
|
|
3960
|
+
.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); }
|
|
3961
|
+
.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); }
|
|
3962
|
+
.kb-g-legend { display: flex; gap: 12px; }
|
|
3963
|
+
.kb-gleg { display: inline-flex; align-items: center; gap: 5px; font-size: 10px; color: var(--text-muted); }
|
|
3964
|
+
.kb-gleg::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); flex: none; }
|
|
3965
|
+
.kb-gleg.con::before { background: color-mix(in srgb, var(--accent) 55%, var(--text-muted)); }
|
|
3966
|
+
.kb-gleg.per::before { background: color-mix(in srgb, var(--accent) 25%, var(--text-muted)); }
|
|
3967
|
+
.kb-g-hint { font-size: 10.5px; color: var(--text-dim); }
|
|
3968
|
+
.kb-graph-body { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 8px; }
|
|
3969
|
+
.kb-graph-svg { width: 100%; height: 100%; }
|
|
3970
|
+
.kb-g-edge { stroke: color-mix(in srgb, var(--border-strong) 90%, transparent); stroke-width: 1.5; }
|
|
3971
|
+
.kb-g-node { cursor: pointer; }
|
|
3972
|
+
.kb-g-hit { fill: transparent; } /* wider click/focus target */
|
|
3973
|
+
.kb-g-dot { fill: var(--accent); stroke: var(--surface); stroke-width: 2; }
|
|
3974
|
+
.kb-g-node text { fill: var(--text); font-size: 12px; } /* label is a click target too (not just the dot) */
|
|
3975
|
+
.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)); }
|
|
3976
|
+
.kb-g-node:focus-visible { outline: none; }
|
|
3977
|
+
.kb-g-node:focus-visible .kb-g-dot { stroke: var(--accent-bright); }
|
|
3978
|
+
.kb-g-source .kb-g-dot { fill: var(--accent); }
|
|
3979
|
+
.kb-g-concept .kb-g-dot { fill: color-mix(in srgb, var(--accent) 55%, var(--text-muted)); }
|
|
3980
|
+
.kb-g-person .kb-g-dot { fill: color-mix(in srgb, var(--accent) 25%, var(--text-muted)); }
|
|
3981
|
+
.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; }
|
|
3982
|
+
.kb-g-overview:hover { color: var(--text); border-color: var(--accent); }
|
|
3983
|
+
.kb-page-type { margin-left: 8px; font-size: 11px; color: var(--text-muted); text-transform: uppercase; letter-spacing: .04em; }
|
|
3984
|
+
/* Tint the type chip to echo the graph dot the user just clicked (same --accent ramp as .kb-g-*),
|
|
3985
|
+
reinforcing the taxonomy across the graph→page transition. index is the hub page, not a dot type. */
|
|
3986
|
+
.kb-page-type-source { color: var(--accent); }
|
|
3987
|
+
.kb-page-type-concept { color: color-mix(in srgb, var(--accent) 55%, var(--text-muted)); }
|
|
3988
|
+
.kb-page-type-person { color: color-mix(in srgb, var(--accent) 25%, var(--text-muted)); }
|
|
3989
|
+
.kb-page-type-index { color: var(--accent-bright); font-weight: 600; }
|
|
3990
|
+
/* The scroll box stays full-width so its themed scrollbar hugs the pane's right edge; only the inner
|
|
3991
|
+
measure box caps the reading width (~68ch) and centres, leaving quiet side margins on a wide pane.
|
|
3992
|
+
margin:0 auto collapses to 0 under 68ch, so a narrow pane degrades for free — no media query. */
|
|
3993
|
+
.kb-page-body { flex: 1; min-height: 0; overflow-y: auto; padding: 16px; scrollbar-width: thin; scrollbar-color: var(--border-strong) transparent; }
|
|
3994
|
+
.kb-page-body-measure { max-width: 68ch; margin: 0 auto; white-space: pre-wrap; word-break: break-word; overflow-wrap: anywhere; line-height: 1.6; color: var(--text); font-size: 14px; }
|
|
3995
|
+
.kb-page-body::-webkit-scrollbar { width: 10px; }
|
|
3996
|
+
.kb-page-body::-webkit-scrollbar-thumb { background: var(--border-strong); border-radius: 6px; }
|
|
3997
|
+
.kb-page-body::-webkit-scrollbar-track { background: transparent; }
|
package/dist/web/workspaces.js
CHANGED
|
@@ -691,6 +691,9 @@
|
|
|
691
691
|
let lastRefsHtml = null; // exact rendered HTML of the refs host, or null to force a repaint
|
|
692
692
|
let lastViewKey = null; // identity of what the viewer host is currently showing
|
|
693
693
|
let kbFocusSourceId = null; // consumed once after a repaint, to restore focus to a filename button
|
|
694
|
+
let kbAdjustBusy = null; // project id of an in-flight Adjust submit (or null) — scoped to the
|
|
695
|
+
// project so switching away can't strand another project's box; also the
|
|
696
|
+
// re-entry guard (no duplicate queue). See kbAdjustActive.
|
|
694
697
|
|
|
695
698
|
const kbUrl = (id, tail = '') => `/api/projects/${encodeURIComponent(id)}/knowledge${tail}`;
|
|
696
699
|
const kbRawUrl = (id, sourceId) => kbUrl(id, `/sources/${encodeURIComponent(sourceId)}/raw`);
|
|
@@ -701,6 +704,21 @@
|
|
|
701
704
|
* freshly rendered HTML would EQUAL the cache and the wrong optimistic state would persist. */
|
|
702
705
|
const kbInvalidateRefs = () => { lastRefsHtml = null; };
|
|
703
706
|
|
|
707
|
+
/** True while the Adjust box is "actively in use" — a poll repaint must NOT replace the refs DOM under
|
|
708
|
+
* the user then, since the box's transient state (draft text, caret, focus, the in-flight submit) lives
|
|
709
|
+
* ONLY in the DOM. Suppressing the repaint while active (paintKnowledge + kbPaintRefsMessage) is simpler
|
|
710
|
+
* and safer than snapshotting/restoring every piece across an innerHTML swap. Active when: a submit is in
|
|
711
|
+
* flight for THIS project, OR any adjust control (textarea/summary/submit) holds focus, OR an open box
|
|
712
|
+
* has a non-empty draft. Self-heals — the moment it's none of those, the next tick repaints fresh. */
|
|
713
|
+
function kbAdjustActive() {
|
|
714
|
+
if (kbAdjustBusy && current && kbAdjustBusy === current.id) return true;
|
|
715
|
+
const det = $wsKnowledge.querySelector('.kb-adjust');
|
|
716
|
+
if (!det) return false;
|
|
717
|
+
if (det.contains(document.activeElement)) return true;
|
|
718
|
+
const ta = det.querySelector('#kb-adjust-input');
|
|
719
|
+
return !!(det.open && ta && ta.value.trim());
|
|
720
|
+
}
|
|
721
|
+
|
|
704
722
|
/** Bump the epoch (so in-flight loads drop their DOM writes) and abort the in-flight fetch. Called by
|
|
705
723
|
* setViewer, and ALSO when the view key changes with no setViewer() — a poll can swap a row's
|
|
706
724
|
* blobSha256 under an open preview, and without this the superseded text download keeps streaming
|
|
@@ -872,29 +890,109 @@
|
|
|
872
890
|
const organizeBtn = `<button type="button" class="primary kb-organize" id="kb-organize"` +
|
|
873
891
|
`${off ? ' aria-disabled="true"' : ''} data-tip="${escapeAttr(why)}">✦ Organize</button>`;
|
|
874
892
|
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
893
|
+
// Adjust: steer the compiled wiki in plain English. Only once a wiki exists (you can't reshape what
|
|
894
|
+
// hasn't been compiled). Queues a knowledge-adjust request the terminal AI applies — the UI never
|
|
895
|
+
// edits the wiki. A queued adjust is invisible to /status by design, so its ONLY pending signal is the
|
|
896
|
+
// footer Requests counter; nothing here fakes per-request progress. The textarea always renders empty
|
|
897
|
+
// and the submit disabled — the live draft/enabled state and the in-flight "Queuing…" state are
|
|
898
|
+
// DOM-owned and never repainted away, because paintKnowledge suppresses the refs repaint while the box
|
|
899
|
+
// is active (kbAdjustActive), so what the user is typing in / submitting is never swapped out.
|
|
900
|
+
const adjustBox = gen
|
|
901
|
+
? '<details class="kb-adjust">' +
|
|
902
|
+
'<summary class="kb-adjust-summary"><span class="kb-adjust-caret" aria-hidden="true">▸</span>Adjust the wiki</summary>' +
|
|
903
|
+
'<div class="kb-adjust-body">' +
|
|
904
|
+
'<label class="kb-adjust-label" for="kb-adjust-input">Tell your terminal AI what to change</label>' +
|
|
905
|
+
'<textarea id="kb-adjust-input" class="kb-adjust-input" rows="2" maxlength="2000" placeholder="e.g. “Merge the two RFI pages”"></textarea>' +
|
|
906
|
+
'<div class="kb-adjust-foot">' +
|
|
907
|
+
'<span class="kb-adjust-hint">Queues an instruction — your terminal AI edits the wiki notes, then re-organizes.</span>' +
|
|
908
|
+
'<button type="button" class="primary kb-adjust-submit" id="kb-adjust-submit" aria-disabled="true" data-tip="Type an instruction first">✎ Adjust</button>' +
|
|
909
|
+
'</div>' +
|
|
910
|
+
'</div>' +
|
|
911
|
+
'</details>'
|
|
912
|
+
: '';
|
|
878
913
|
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
//
|
|
884
|
-
|
|
914
|
+
return `<div class="kb-refs-foot">${pendingLine}` +
|
|
915
|
+
(status ? `<div class="kb-status">${status}</div>` : '') + organizeBtn + adjustBox + '</div>';
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// ── Stage C: the knowledge graph — seeded force layout + SVG render ─────────────
|
|
919
|
+
// A deterministic hash seeds each node's starting angle so the SAME graph always lays out the same
|
|
920
|
+
// way across re-renders (no visual jitter on a poll tick / repaint) without needing a persisted
|
|
921
|
+
// layout. The force pass then relaxes overlaps via simple repulsion + edge-spring + centering.
|
|
922
|
+
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; }
|
|
923
|
+
function kbLayout(nodes, edges) {
|
|
924
|
+
const W = 600, H = 440, N = nodes.length;
|
|
925
|
+
const iters = N <= 60 ? 300 : N <= 150 ? 150 : 60;
|
|
926
|
+
const R = Math.min(W, H) / 2 - 40;
|
|
927
|
+
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);
|
|
928
|
+
return { id: n.id, x: W / 2 + Math.cos(ang) * rad, y: H / 2 + Math.sin(ang) * rad }; });
|
|
929
|
+
const idx = new Map(pos.map((p, i) => [p.id, i]));
|
|
930
|
+
const K = 140;
|
|
931
|
+
for (let it = 0; it < iters; it++) {
|
|
932
|
+
const fx = new Array(N).fill(0), fy = new Array(N).fill(0);
|
|
933
|
+
for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) {
|
|
934
|
+
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;
|
|
935
|
+
fx[i] += dx / d * rep; fy[i] += dy / d * rep; fx[j] -= dx / d * rep; fy[j] -= dy / d * rep; }
|
|
936
|
+
for (const e of edges) { const i = idx.get(e.a), j = idx.get(e.b); if (i == null || j == null) continue;
|
|
937
|
+
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;
|
|
938
|
+
fx[i] += dx / d * s; fy[i] += dy / d * s; fx[j] -= dx / d * s; fy[j] -= dy / d * s; }
|
|
939
|
+
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;
|
|
940
|
+
pos[i].x = Math.max(24, Math.min(W - 24, pos[i].x + Math.max(-20, Math.min(20, fx[i]))));
|
|
941
|
+
pos[i].y = Math.max(24, Math.min(H - 24, pos[i].y + Math.max(-20, Math.min(20, fy[i])))); }
|
|
942
|
+
}
|
|
943
|
+
return { pos, idx, W, H };
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// Node fields are ALL escaped (title/slug/type are LLM-derived). Each node carries an aria-label AND
|
|
947
|
+
// a type-bearing data-tip so its taxonomy is available to AT + sighted users, not encoded by colour
|
|
948
|
+
// alone (WCAG 1.4.1). An invisible r=16 hit circle widens the click/focus target behind the r=9 dot.
|
|
949
|
+
function kbGraphSvg(graph) {
|
|
950
|
+
if (!graph || !graph.nodes.length) return graph && graph.truncated ? kbGraphTruncatedEmpty() : kbGraphEmpty(knowledgeState);
|
|
951
|
+
const { pos, idx, W, H } = kbLayout(graph.nodes, graph.edges);
|
|
952
|
+
const lines = graph.edges.map((e) => { const a = pos[idx.get(e.a)], b = pos[idx.get(e.b)];
|
|
953
|
+
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('');
|
|
954
|
+
const dots = graph.nodes.map((n, i) => { const p = pos[i];
|
|
955
|
+
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)})">` +
|
|
956
|
+
`<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('');
|
|
957
|
+
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>` : '';
|
|
958
|
+
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>';
|
|
959
|
+
const note = graph.truncated ? `<div class="kb-view-note">Showing ${graph.nodes.length} — graph truncated (some pages omitted)</div>` : '';
|
|
960
|
+
return '<section class="kb-col kb-graph"><div class="kb-graph-head"><span>Knowledge graph</span>' + overview + '</div>' +
|
|
961
|
+
'<div class="kb-graph-sub">' + legend + '<span class="kb-g-hint">Click a node to open its page</span></div>' +
|
|
962
|
+
`<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>`;
|
|
963
|
+
}
|
|
964
|
+
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>'; }
|
|
965
|
+
function kbGraphEmpty(st) {
|
|
885
966
|
const done = st && st.currentGeneration;
|
|
886
|
-
return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner">' +
|
|
887
|
-
'<
|
|
888
|
-
'<div class="kb-ph-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
967
|
+
return '<section class="kb-col kb-placeholder"><div class="kb-ph-inner"><span class="kb-ph-ico" aria-hidden="true">✦</span>' +
|
|
968
|
+
'<div class="kb-ph-title">' + (done ? 'Nothing to graph yet' : 'No knowledge base yet') + '</div>' +
|
|
969
|
+
'<div class="kb-ph-sub">' + (done
|
|
970
|
+
? '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.'
|
|
971
|
+
: '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>';
|
|
972
|
+
}
|
|
973
|
+
// loading + error REUSE the file viewer's own message idiom (.kb-view-msg / .kb-view-spin /
|
|
974
|
+
// .kb-view-ico.err / .primary Retry) so the graph's "can't show content yet" states look identical
|
|
975
|
+
// to the file preview's — one learned pattern, not a second near-duplicate.
|
|
976
|
+
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>'; }
|
|
977
|
+
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>'; }
|
|
978
|
+
// Whitelist the LLM-derived page type into a SAFE single class token — never interpolate it raw (a
|
|
979
|
+
// space would inject extra classes). Same discipline as KB_CHIP; an unknown type falls back to the
|
|
980
|
+
// bare muted chip.
|
|
981
|
+
const KB_PAGE_TYPE_CLASS = { source: 'kb-page-type-source', concept: 'kb-page-type-concept', person: 'kb-page-type-person', index: 'kb-page-type-index' };
|
|
982
|
+
function kbPageShell(pg) {
|
|
983
|
+
// typeof guard, not `|| ''`: a prototype key (pg.type === "constructor"/"__proto__"/…) would
|
|
984
|
+
// otherwise resolve to an inherited truthy value and stringify into the class attribute. Only a
|
|
985
|
+
// real whitelisted string is a valid class token; anything else falls back to the bare muted chip.
|
|
986
|
+
const cls = KB_PAGE_TYPE_CLASS[pg.type];
|
|
987
|
+
const tint = typeof cls === 'string' ? cls : '';
|
|
988
|
+
const type = pg.type ? `<span class="kb-page-type ${tint}">${escapeHtml(pg.type)}</span>` : '';
|
|
989
|
+
return '<section class="kb-col kb-viewer kb-page"><div class="kb-view-head">' +
|
|
990
|
+
`<span class="kb-view-name" data-tip="${escapeAttr(pg.title)}">${escapeHtml(pg.title)}</span>${type}` +
|
|
991
|
+
'<button type="button" class="kb-x" data-kb-close data-tip="Back to graph" aria-label="Back to graph">✕</button></div>' +
|
|
992
|
+
`<div class="kb-page-body"><div class="kb-page-body-measure">${escapeHtml(pg.body)}</div></div></section>`;
|
|
993
|
+
}
|
|
994
|
+
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>'; }
|
|
995
|
+
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
996
|
|
|
899
997
|
// ── The file viewer ───────────────────────────────────────────────────────────
|
|
900
998
|
// SECURITY: `filename` is user-authored and every state below interpolates it — escapeHtml for text,
|
|
@@ -992,6 +1090,42 @@
|
|
|
992
1090
|
else kbPaintText(row, url, ac, alive);
|
|
993
1091
|
}
|
|
994
1092
|
|
|
1093
|
+
// ── Stage C: the knowledge graph + page viewer ──────────────────────────────────
|
|
1094
|
+
// Same alive()/epoch/key contract as kbLoadPreview above — the render only happens if nothing else
|
|
1095
|
+
// (a new epoch, a changed key, a project switch, or leaving the pane) superseded this fetch meanwhile.
|
|
1096
|
+
async function kbLoadGraph(proj) {
|
|
1097
|
+
const epoch = viewEpoch, key = lastViewKey;
|
|
1098
|
+
const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
|
|
1099
|
+
const ac = new AbortController(); kbTextAbort = ac;
|
|
1100
|
+
try {
|
|
1101
|
+
const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/graph`, { signal: ac.signal, cache: 'no-store' });
|
|
1102
|
+
if (!r.ok) throw new Error(`graph ${r.status}`);
|
|
1103
|
+
const body = await r.json();
|
|
1104
|
+
if (!body || !body.graph || !Array.isArray(body.graph.nodes)) throw new Error('bad graph envelope');
|
|
1105
|
+
if (!alive()) return;
|
|
1106
|
+
const h = kbViewHost(); if (h) h.innerHTML = kbGraphSvg(body.graph);
|
|
1107
|
+
} catch (err) {
|
|
1108
|
+
if (err && err.name === 'AbortError') return;
|
|
1109
|
+
if (alive()) { const h = kbViewHost(); if (h) h.innerHTML = kbGraphError(); } // Retry re-keys via setViewer — matches the file-viewer idiom (no poll-flicker)
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
async function kbLoadPage(proj, slug) {
|
|
1113
|
+
const epoch = viewEpoch, key = lastViewKey;
|
|
1114
|
+
const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
|
|
1115
|
+
const ac = new AbortController(); kbTextAbort = ac;
|
|
1116
|
+
try {
|
|
1117
|
+
const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/page/${encodeURIComponent(slug)}`, { signal: ac.signal, cache: 'no-store' });
|
|
1118
|
+
if (!r.ok) throw new Error(`page ${r.status}`);
|
|
1119
|
+
const body = await r.json();
|
|
1120
|
+
if (!body || !body.page || typeof body.page.body !== 'string') throw new Error('bad page envelope');
|
|
1121
|
+
if (!alive()) return;
|
|
1122
|
+
const h = kbViewHost(); if (h) h.innerHTML = kbPageShell(body.page);
|
|
1123
|
+
} catch (err) {
|
|
1124
|
+
if (err && err.name === 'AbortError') return;
|
|
1125
|
+
if (alive()) { const h = kbViewHost(); if (h) h.innerHTML = kbPageError(); } // ✕ re-keys via setViewer; no poll-flicker
|
|
1126
|
+
}
|
|
1127
|
+
}
|
|
1128
|
+
|
|
995
1129
|
/** Accept a freshly-read /status as the current truth. EVERY writer of `knowledgeState` goes through
|
|
996
1130
|
* here, because committing state also decides whether the poll runs: a caller that claims the render
|
|
997
1131
|
* epoch can supersede the very render that would have discovered a newly queued organize, and
|
|
@@ -1146,6 +1280,7 @@
|
|
|
1146
1280
|
/** Identity of what the viewer host is showing. `blobSha256` is in the key because a hand-edited
|
|
1147
1281
|
* manifest (and, later, Stage D) can swap a row's bytes without changing its sourceId. */
|
|
1148
1282
|
function kbViewKey(st) {
|
|
1283
|
+
if (viewer.mode === 'page') { const gen = st.currentGeneration ? st.currentGeneration.generationId : ''; return 'page:' + gen + ':' + (viewer.slug || ''); }
|
|
1149
1284
|
const row = viewer.mode === 'file' ? st.sources.find((s) => s.sourceId === viewer.sourceId) : null;
|
|
1150
1285
|
const gen = viewer.mode === 'graph' && st.currentGeneration ? st.currentGeneration.generationId : '';
|
|
1151
1286
|
return [current && current.id, viewer.mode, viewer.sourceId || '', row ? row.blobSha256 : '', gen].join('|');
|
|
@@ -1164,7 +1299,12 @@
|
|
|
1164
1299
|
// a signature enumerating inputs would rot as kbColumn grows, and would miss the footer's
|
|
1165
1300
|
// time-dependent parts (pending age, the 10-minute stale flip, publishedAt, lastLintSummary).
|
|
1166
1301
|
const html = kbColumn(st);
|
|
1167
|
-
|
|
1302
|
+
// Never repaint the refs column out from under an in-use Adjust box — a wholesale innerHTML swap would
|
|
1303
|
+
// wipe the draft, caret, focus, and the in-flight submit. The box's transient state lives only in the
|
|
1304
|
+
// DOM; suppressing the repaint while it's active (kbAdjustActive) is simpler and safer than
|
|
1305
|
+
// snapshotting/restoring every piece. lastRefsHtml is left stale, so the next tick (once the box is
|
|
1306
|
+
// inactive) catches the column up to the latest state.
|
|
1307
|
+
if (html !== lastRefsHtml && !kbAdjustActive()) {
|
|
1168
1308
|
const oldBody = refsHost.querySelector('.kb-refs-body');
|
|
1169
1309
|
const scrollTop = oldBody ? oldBody.scrollTop : 0;
|
|
1170
1310
|
refsHost.innerHTML = html;
|
|
@@ -1194,8 +1334,16 @@
|
|
|
1194
1334
|
if (viewHost) viewHost.innerHTML = kbViewShell(row, kbViewLoading(row));
|
|
1195
1335
|
kbLoadPreview(current, row);
|
|
1196
1336
|
}
|
|
1337
|
+
} else if (viewer.mode === 'page') {
|
|
1338
|
+
if (viewHost) viewHost.innerHTML = kbPageLoading();
|
|
1339
|
+
kbLoadPage(current, viewer.slug);
|
|
1197
1340
|
} else if (viewHost) {
|
|
1198
|
-
|
|
1341
|
+
if (!st.currentGeneration) {
|
|
1342
|
+
viewHost.innerHTML = kbGraphEmpty(st);
|
|
1343
|
+
} else {
|
|
1344
|
+
viewHost.innerHTML = kbGraphLoading();
|
|
1345
|
+
kbLoadGraph(current);
|
|
1346
|
+
}
|
|
1199
1347
|
}
|
|
1200
1348
|
}
|
|
1201
1349
|
}
|
|
@@ -1204,13 +1352,14 @@
|
|
|
1204
1352
|
* a failed /status poll is no reason to tear down a file the user is reading. Nulls the cache so the
|
|
1205
1353
|
* next successful render always repaints. */
|
|
1206
1354
|
function kbPaintRefsMessage(inner) {
|
|
1355
|
+
if (kbAdjustActive()) return; // a failed /status poll must not wipe an in-use Adjust box (draft/focus/in-flight)
|
|
1207
1356
|
kbEnsureShell();
|
|
1208
1357
|
const refsHost = $wsKnowledge.querySelector('.kb-refs-host');
|
|
1209
1358
|
refsHost.innerHTML = '<section class="kb-col"><div class="kb-head"><span>References</span></div>' +
|
|
1210
1359
|
`<div class="kb-refs-body">${inner}</div></section>`;
|
|
1211
1360
|
lastRefsHtml = null;
|
|
1212
1361
|
const host = kbViewHost();
|
|
1213
|
-
if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML =
|
|
1362
|
+
if (host && viewer.mode === 'graph' && !host.innerHTML) host.innerHTML = kbGraphEmpty(null);
|
|
1214
1363
|
}
|
|
1215
1364
|
|
|
1216
1365
|
async function renderKnowledge() {
|
|
@@ -1299,6 +1448,67 @@
|
|
|
1299
1448
|
if (current === proj) renderKnowledge();
|
|
1300
1449
|
}
|
|
1301
1450
|
|
|
1451
|
+
// Live-toggle the Adjust submit from the textarea content (the generated HTML always renders it
|
|
1452
|
+
// empty+disabled; this reflects what the user has actually typed, between repaints). An IMPERATIVE
|
|
1453
|
+
// refs-DOM mutation the generated HTML never encodes — so it must NOT kbInvalidateRefs() (that would
|
|
1454
|
+
// force a repaint every keystroke); paintKnowledge re-derives it after any repaint instead.
|
|
1455
|
+
function kbSyncAdjustSubmit() {
|
|
1456
|
+
if (kbAdjustBusy && current && kbAdjustBusy === current.id) return; // this project's submit is a real `disabled` in-flight — don't override with aria
|
|
1457
|
+
const ta = $wsKnowledge.querySelector('#kb-adjust-input');
|
|
1458
|
+
const btn = $wsKnowledge.querySelector('#kb-adjust-submit');
|
|
1459
|
+
if (!ta || !btn) return;
|
|
1460
|
+
if (ta.value.trim()) { btn.removeAttribute('aria-disabled'); btn.setAttribute('data-tip', 'Queue this adjustment for your terminal AI'); }
|
|
1461
|
+
else { btn.setAttribute('aria-disabled', 'true'); btn.setAttribute('data-tip', 'Type an instruction first'); }
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
async function kbAdjustSubmit() {
|
|
1465
|
+
const proj = current;
|
|
1466
|
+
if (!proj || kbAdjustBusy) return; // re-entry guard (also blocks a double Ctrl+Enter)
|
|
1467
|
+
const ta = $wsKnowledge.querySelector('#kb-adjust-input');
|
|
1468
|
+
const btn = $wsKnowledge.querySelector('#kb-adjust-submit');
|
|
1469
|
+
if (!ta || !btn) return;
|
|
1470
|
+
const prompt = ta.value.trim();
|
|
1471
|
+
if (!prompt) return;
|
|
1472
|
+
// Busy is a module flag (kbFoot renders it) so a repaint mid-POST re-renders the in-flight state
|
|
1473
|
+
// instead of a fresh submittable box; mirror it on the live elements too for feedback before the
|
|
1474
|
+
// next repaint. Real `disabled` on both — a disabled control emits no click/keydown, so neither the
|
|
1475
|
+
// delegated click nor Ctrl+Enter can re-enter.
|
|
1476
|
+
// Mark busy FOR THIS PROJECT and disable both controls (a disabled control emits no click/keydown, so
|
|
1477
|
+
// neither submit path can re-enter). While busy the box counts as active, so paintKnowledge /
|
|
1478
|
+
// kbPaintRefsMessage suppress the refs repaint — these live elements and the draft are never replaced
|
|
1479
|
+
// under the in-flight POST, so `ta`/`btn` stay valid throughout.
|
|
1480
|
+
kbAdjustBusy = proj.id;
|
|
1481
|
+
ta.disabled = true; btn.disabled = true; btn.textContent = '✎ Queuing…';
|
|
1482
|
+
let ok = false, msg = '';
|
|
1483
|
+
try {
|
|
1484
|
+
await api(kbUrl(proj.id, '/request'), { method: 'POST', body: JSON.stringify({ prompt }) });
|
|
1485
|
+
ok = true;
|
|
1486
|
+
if (bridge.loadRequests) await bridge.loadRequests(); // bump the footer Requests counter (nothing else moves it here)
|
|
1487
|
+
} catch (err) { msg = (err && err.message) || String(err); }
|
|
1488
|
+
kbAdjustBusy = null;
|
|
1489
|
+
// Re-check by ID after every await: the user may have switched — or renamed — the project mid-flight
|
|
1490
|
+
// (rename replaces the `current` object, so an identity check would false-mismatch). Bail without
|
|
1491
|
+
// touching it; the queued request is durable server-side.
|
|
1492
|
+
if (!current || current.id !== proj.id) { kbInvalidateRefs(); return; }
|
|
1493
|
+
if (ok) {
|
|
1494
|
+
// Reset the controls to rest (hidden inside the box we collapse below, but correct if the user
|
|
1495
|
+
// reopens it before the next repaint), then collapse and return focus to the summary.
|
|
1496
|
+
ta.value = ''; ta.disabled = false; // suppression kept `ta` alive
|
|
1497
|
+
btn.disabled = false; btn.textContent = '✎ Adjust';
|
|
1498
|
+
kbSyncAdjustSubmit(); // empty draft → submit aria-disabled + rest tooltip
|
|
1499
|
+
const det = ta.closest('.kb-adjust');
|
|
1500
|
+
if (det) { det.open = false; const sum = det.querySelector('.kb-adjust-summary'); if (sum) sum.focus(); } // a11y: focus doesn't vanish
|
|
1501
|
+
showToast('Adjustment queued for your terminal AI', 'ok');
|
|
1502
|
+
track('kb_adjust_queued', { app: proj.app });
|
|
1503
|
+
} else {
|
|
1504
|
+
ta.disabled = false; ta.focus(); // preserve the text + caret, return focus for a retry
|
|
1505
|
+
btn.disabled = false; btn.textContent = '✎ Adjust';
|
|
1506
|
+
kbSyncAdjustSubmit();
|
|
1507
|
+
showToast('Couldn’t queue the adjustment: ' + msg, 'warn');
|
|
1508
|
+
}
|
|
1509
|
+
kbInvalidateRefs(); // the box stays active (focus) → next inactive tick settles the footer
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1302
1512
|
// Remove confirm — the themed anchored popover (.hist-confirm), NEVER a native confirm().
|
|
1303
1513
|
function kbCloseConfirm() {
|
|
1304
1514
|
const pop = $wsKnowledge.querySelector('.hist-confirm');
|
|
@@ -1367,6 +1577,10 @@
|
|
|
1367
1577
|
if (knowledgeState) paintKnowledge(knowledgeState);
|
|
1368
1578
|
return;
|
|
1369
1579
|
}
|
|
1580
|
+
// Open a graph node's page.
|
|
1581
|
+
const nodeEl = e.target.closest('[data-kb-node]');
|
|
1582
|
+
if (nodeEl) { setViewer({ mode: 'page', slug: nodeEl.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
|
|
1583
|
+
if (e.target.closest('[data-kb-graph-retry]')) { setViewer({ mode: 'graph', sourceId: null }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
|
|
1370
1584
|
if (e.target.closest('[data-kb-close]')) {
|
|
1371
1585
|
const wasOpen = viewer.sourceId;
|
|
1372
1586
|
setViewer({ mode: 'graph', sourceId: null });
|
|
@@ -1392,8 +1606,26 @@
|
|
|
1392
1606
|
}
|
|
1393
1607
|
const org = e.target.closest('#kb-organize');
|
|
1394
1608
|
if (org) { if (org.getAttribute('aria-disabled') !== 'true') kbOrganize(); return; } // aria-disabled still receives clicks
|
|
1609
|
+
const adjBtn = e.target.closest('#kb-adjust-submit');
|
|
1610
|
+
if (adjBtn) { if (adjBtn.getAttribute('aria-disabled') !== 'true') kbAdjustSubmit(); return; } // aria-disabled still receives clicks
|
|
1395
1611
|
if (e.target.closest('#kb-drop')) $wsKnowledgeFile.click();
|
|
1396
1612
|
});
|
|
1613
|
+
// Graph nodes are keyboard-focusable (tabindex="0" role="button") but SVG <g> elements have no
|
|
1614
|
+
// native activation behaviour, so Enter/Space must be wired explicitly.
|
|
1615
|
+
$wsKnowledge.addEventListener('keydown', (e) => {
|
|
1616
|
+
// Cmd/Ctrl+Enter submits the Adjust box; bare Enter keeps inserting a newline (prose stays multi-line).
|
|
1617
|
+
if (e.key === 'Enter' && (e.metaKey || e.ctrlKey) && e.target.id === 'kb-adjust-input') {
|
|
1618
|
+
e.preventDefault();
|
|
1619
|
+
const btn = $wsKnowledge.querySelector('#kb-adjust-submit');
|
|
1620
|
+
if (btn && btn.getAttribute('aria-disabled') !== 'true') kbAdjustSubmit();
|
|
1621
|
+
return;
|
|
1622
|
+
}
|
|
1623
|
+
if (e.key !== 'Enter' && e.key !== ' ') return;
|
|
1624
|
+
const n = e.target.closest('[data-kb-node]');
|
|
1625
|
+
if (n) { e.preventDefault(); setViewer({ mode: 'page', slug: n.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); }
|
|
1626
|
+
});
|
|
1627
|
+
// Live-enable the Adjust submit as the user types (the draft is DOM-owned; see kbSyncAdjustSubmit).
|
|
1628
|
+
$wsKnowledge.addEventListener('input', (e) => { if (e.target && e.target.id === 'kb-adjust-input') kbSyncAdjustSubmit(); });
|
|
1397
1629
|
$wsKnowledgeFile.addEventListener('change', () => {
|
|
1398
1630
|
kbUpload($wsKnowledgeFile.files);
|
|
1399
1631
|
$wsKnowledgeFile.value = ''; // let the same file be picked twice in a row
|