neurastream 0.2.37 → 0.2.40
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -1
- package/blockers/knowledge-scope.sh +34 -0
- package/package.json +1 -1
- package/src/adapters/omp/index.ts +72 -5
- package/src/adapters/omp/install.ts +188 -17
- package/src/cli/diagram.ts +27 -0
- package/src/cli/dispatch.ts +7 -0
- package/src/cli/notes.ts +36 -0
- package/src/cli/pages.ts +11 -3
- package/src/core/blockers.ts +14 -1
- package/src/core/config.ts +12 -0
- package/src/core/diagram-check.ts +128 -0
- package/src/core/guards.ts +30 -4
- package/src/core/knowledge.ts +224 -0
- package/src/core/owner-ui.ts +64 -6
- package/src/core/page-notes.ts +308 -0
- package/src/core/pages-setup.ts +35 -3
- package/src/core/pages.ts +38 -2
- package/src/core/plan-approval.ts +95 -0
- package/src/core/queue-cancel.ts +2 -0
- package/src/core/repo-rules.ts +95 -0
- package/src/core/wip-snapshot.ts +3 -1
- package/templates/config.yml +9 -0
package/src/core/config.ts
CHANGED
|
@@ -19,6 +19,11 @@ export class ConfigError extends Error {
|
|
|
19
19
|
export interface Config {
|
|
20
20
|
/** Which adapter (src/adapters/index.ts) serves runs, traces, launch, install and doctor. The template ships the only one; a second harness adds its name here (docs/adapter.md). */
|
|
21
21
|
harness: string;
|
|
22
|
+
/** Live project rules (src/core/repo-rules.ts): a repo's own AGENTS.md, handed to the agent that works in it. */
|
|
23
|
+
rules: {
|
|
24
|
+
/** Largest rules text a hook injects; past it the text is cut and one line names the file. */
|
|
25
|
+
max_bytes: number;
|
|
26
|
+
};
|
|
22
27
|
paths: {
|
|
23
28
|
home: string;
|
|
24
29
|
work_roots: string[];
|
|
@@ -153,6 +158,8 @@ export interface Config {
|
|
|
153
158
|
ui: { enabled: boolean; port: number; owner_login: string };
|
|
154
159
|
/** Static pages hosted over the tailnet. */
|
|
155
160
|
pages: { enabled: boolean; port: number; dir: string; keep_days: number };
|
|
161
|
+
/** Repo-local HTML explainers under docs/knowledge/ (owner page Knowledge tab). */
|
|
162
|
+
knowledge: { roots: string[]; max_age_s: number };
|
|
156
163
|
rollover: { enabled: boolean; max_session_mb: number; exit_grace_s: number };
|
|
157
164
|
metrics: { report_days: number; correction_patterns: string[]; ci_pipelines_cmd: string };
|
|
158
165
|
/** Incident detectors (src/core/incident-detectors.ts): when a sighting becomes an incident. */
|
|
@@ -449,6 +456,11 @@ function check(cfg: Config): void {
|
|
|
449
456
|
if (!Number.isInteger(cfg.pages.port) || cfg.pages.port < 1 || cfg.pages.port > 65535) throw new ConfigError("pages.port must be an integer between 1 and 65535");
|
|
450
457
|
if (typeof cfg.pages.dir !== "string" || cfg.pages.dir.length === 0) throw new ConfigError("pages.dir must be a non-empty path");
|
|
451
458
|
if (!Number.isInteger(cfg.pages.keep_days) || cfg.pages.keep_days < 1) throw new ConfigError("pages.keep_days must be an integer >= 1");
|
|
459
|
+
if (!Array.isArray(cfg.knowledge.roots) || cfg.knowledge.roots.length === 0) throw new ConfigError("knowledge.roots must be a non-empty list of paths");
|
|
460
|
+
for (const r of cfg.knowledge.roots) {
|
|
461
|
+
if (typeof r !== "string" || r.length === 0) throw new ConfigError("knowledge.roots entries must be non-empty paths");
|
|
462
|
+
}
|
|
463
|
+
if (!Number.isInteger(cfg.knowledge.max_age_s) || cfg.knowledge.max_age_s < 1) throw new ConfigError("knowledge.max_age_s must be an integer >= 1");
|
|
452
464
|
for (const p of cfg.metrics.correction_patterns) {
|
|
453
465
|
try {
|
|
454
466
|
new RegExp(p, "i");
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Diagram coverage (plan 20261026_0930 P10, INCIDENT I-20261027-73: the owner's "the architecture
|
|
2
|
+
// diagram should fucking have everything … from smallest to biggest, everything should be drilled
|
|
3
|
+
// down"). A plan's diagram is checked against the plan itself: every phase and every file or command
|
|
4
|
+
// path its phase lines name must appear in the page's diagram data, and a box that drills down must
|
|
5
|
+
// drill into at least two things. The styling half — no arrow crossing a box, no arrow label on a box
|
|
6
|
+
// at 1280 and 390 width — is a browser check the architecture-drilldown skill runs; no code here can
|
|
7
|
+
// see a rendered arrow.
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
|
|
10
|
+
export interface DiagramReport {
|
|
11
|
+
/** Phases and paths the plan names that no box mentions. */
|
|
12
|
+
missing: string[];
|
|
13
|
+
/** Boxes that drill down into one thing (or none). */
|
|
14
|
+
thin: string[];
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Index of the bracket matching the one at `open`, skipping string contents; -1 when unbalanced. */
|
|
18
|
+
function matchBracket(text: string, open: number): number {
|
|
19
|
+
let depth = 0;
|
|
20
|
+
let quote = "";
|
|
21
|
+
for (let i = open; i < text.length; i++) {
|
|
22
|
+
const c = text[i]!;
|
|
23
|
+
if (quote !== "") {
|
|
24
|
+
if (c === "\\") i++;
|
|
25
|
+
else if (c === quote) quote = "";
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (c === '"' || c === "'" || c === "`") quote = c;
|
|
29
|
+
else if (c === "{" || c === "[") depth++;
|
|
30
|
+
else if (c === "}" || c === "]") {
|
|
31
|
+
depth--;
|
|
32
|
+
if (depth === 0) return i;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return -1;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** The diagram data a drilldown page carries: `const T={…}` up to its matching brace. */
|
|
39
|
+
export function diagramData(html: string): string | null {
|
|
40
|
+
const at = /\b(?:const|let|var)\s+[A-Za-z_$][\w$]*\s*=\s*\{/.exec(html);
|
|
41
|
+
if (at === null) return null;
|
|
42
|
+
const open = at.index + at[0].length - 1;
|
|
43
|
+
const end = matchBracket(html, open);
|
|
44
|
+
return end < 0 ? null : html.slice(open, end + 1);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** How many objects a `kids:[` array holds directly. */
|
|
48
|
+
function kidCount(data: string, open: number): number {
|
|
49
|
+
const end = matchBracket(data, open);
|
|
50
|
+
if (end < 0) return 0;
|
|
51
|
+
let n = 0;
|
|
52
|
+
for (let i = open + 1; i < end; i++) {
|
|
53
|
+
if (data[i] !== "{") continue;
|
|
54
|
+
n++;
|
|
55
|
+
const close = matchBracket(data, i);
|
|
56
|
+
if (close < 0) break;
|
|
57
|
+
i = close;
|
|
58
|
+
}
|
|
59
|
+
return n;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The id of the box whose `kids` sits at `at`, for the message. */
|
|
63
|
+
function boxId(data: string, at: number): string {
|
|
64
|
+
const head = data.slice(Math.max(0, at - 4000), at);
|
|
65
|
+
const ids = [...head.matchAll(/\bid\s*:\s*"([^"]+)"/g)];
|
|
66
|
+
return ids.length === 0 ? "a box" : ids[ids.length - 1]![1]!;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const PHASE = /^\s*[-*]\s+\[[ x]\]\s+(P\d+[a-z]?)\b/;
|
|
70
|
+
const SPAN = /`([^`\n]+)`/g;
|
|
71
|
+
/** A word that looks like a file or a path: it has a directory part or a short extension. */
|
|
72
|
+
const PATHISH = /[A-Za-z0-9_~/.-]*(?:\/[A-Za-z0-9_~/.-]+|\.[A-Za-z][A-Za-z0-9]{0,4}\b)/g;
|
|
73
|
+
|
|
74
|
+
export interface PlanItems {
|
|
75
|
+
phases: string[];
|
|
76
|
+
/** path → the phase whose line names it (first one wins). */
|
|
77
|
+
paths: Map<string, string>;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function clean(word: string): string {
|
|
81
|
+
return word.replace(/^[("'`]+/, "").replace(/[)"'`,;:.]+$/, "");
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** The phases of a plan and the files or commands their lines name in backticks. */
|
|
85
|
+
export function planItems(markdown: string): PlanItems {
|
|
86
|
+
const phases: string[] = [];
|
|
87
|
+
const paths = new Map<string, string>();
|
|
88
|
+
for (const line of markdown.split("\n")) {
|
|
89
|
+
const phase = PHASE.exec(line);
|
|
90
|
+
if (phase === null) continue;
|
|
91
|
+
const id = phase[1]!;
|
|
92
|
+
if (!phases.includes(id)) phases.push(id);
|
|
93
|
+
for (const span of line.matchAll(SPAN)) {
|
|
94
|
+
for (const raw of span[1]!.matchAll(PATHISH)) {
|
|
95
|
+
const word = clean(raw[0]);
|
|
96
|
+
// Short noise ("e.g", "y/N", "Pn") and web addresses are not what a box must name.
|
|
97
|
+
if (word.length < 4 || /^https?:/i.test(word) || word.includes("…")) continue;
|
|
98
|
+
if (!paths.has(word)) paths.set(word, id);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return { phases, paths };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** What the diagram of `planText` is missing, checked against the page's own data. */
|
|
106
|
+
export function checkDiagram(html: string, planText: string): DiagramReport {
|
|
107
|
+
const data = diagramData(html);
|
|
108
|
+
if (data === null) return { missing: ["the page carries no diagram data (expected `const NAME={` … `}`)"], thin: [] };
|
|
109
|
+
const items = planItems(planText);
|
|
110
|
+
const missing: string[] = [];
|
|
111
|
+
for (const phase of items.phases) {
|
|
112
|
+
if (!new RegExp(`\\b${phase}\\b`).test(data)) missing.push(`${phase}: the phase is in no box`);
|
|
113
|
+
}
|
|
114
|
+
for (const [path, phase] of items.paths) {
|
|
115
|
+
if (!data.includes(path)) missing.push(`${path} (${phase}): named in the plan, in no box`);
|
|
116
|
+
}
|
|
117
|
+
const thin: string[] = [];
|
|
118
|
+
for (const hit of data.matchAll(/kids\s*:\s*\[/g)) {
|
|
119
|
+
const count = kidCount(data, hit.index + hit[0].length - 1);
|
|
120
|
+
if (count < 2) thin.push(`${boxId(data, hit.index)} has ${count} kid${count === 1 ? "" : "s"}`);
|
|
121
|
+
}
|
|
122
|
+
return { missing, thin };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** The check for two files on disk; a page without data reads as one missing item, never a crash. */
|
|
126
|
+
export function checkDiagramFiles(htmlFile: string, planFile: string): DiagramReport {
|
|
127
|
+
return checkDiagram(readFileSync(htmlFile, "utf8"), readFileSync(planFile, "utf8"));
|
|
128
|
+
}
|
package/src/core/guards.ts
CHANGED
|
@@ -26,6 +26,7 @@ import { appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from
|
|
|
26
26
|
import path from "node:path";
|
|
27
27
|
import type { Decision, InjectEvent, PlanEditEvent, SpawnEvent, StopEvent, ToolEvent } from "./adapter.ts";
|
|
28
28
|
import { currentTier, takeGo, type Tier } from "./autonomy.ts";
|
|
29
|
+
import { approvalProblem } from "./plan-approval.ts";
|
|
29
30
|
import type { Config } from "./config.ts";
|
|
30
31
|
import { addIncident, openIncidents, type IncidentView } from "./incidents.ts";
|
|
31
32
|
import { notifyProtectedPaths, notifySecretReadHit } from "./notify.ts";
|
|
@@ -335,7 +336,7 @@ function unticked(p: Plan): string[] {
|
|
|
335
336
|
}
|
|
336
337
|
|
|
337
338
|
// Plans an implementer brief may run on; returns [reason, null] or [null, plan files].
|
|
338
|
-
export function planGate(text: string, label: string): [string | null, string[]] {
|
|
339
|
+
export function planGate(text: string, label: string, cfg?: Config): [string | null, string[]] {
|
|
339
340
|
const plans = q.activePlans();
|
|
340
341
|
const unclosed = plans.filter(p => (p.status === "complete" || p.status === "cancelled") && !q.awaitingMerge(p));
|
|
341
342
|
if (unclosed.length)
|
|
@@ -370,6 +371,10 @@ export function planGate(text: string, label: string): [string | null, string[]]
|
|
|
370
371
|
`${label}: plan ${p.file} has no new "## Progress" entry since the last agent ran on it. Write that run's progress (from its report) into the plan first.`,
|
|
371
372
|
[],
|
|
372
373
|
];
|
|
374
|
+
if (cfg) {
|
|
375
|
+
const approval = approvalProblem(p.text, p.file, cfg.pages.dir);
|
|
376
|
+
if (approval) return [approval, []];
|
|
377
|
+
}
|
|
373
378
|
const open = unticked(p);
|
|
374
379
|
if (!open.length) return [`${label}: plan ${p.file} has no unticked phase left.`, []];
|
|
375
380
|
if (!open.some(id => new RegExp(`\\b${id}\\b`).test(text)))
|
|
@@ -523,7 +528,7 @@ export function spawnProblem(
|
|
|
523
528
|
const agent = String(t?.agent ?? "task");
|
|
524
529
|
const label = String(t?.name ?? agent);
|
|
525
530
|
if (!allowed.has(agent)) return `${label}: agent "${agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`;
|
|
526
|
-
const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label);
|
|
531
|
+
const [why, plans] = planGate(`${context}\n${String(t?.task ?? "")}`, label, cfg);
|
|
527
532
|
if (why) return why;
|
|
528
533
|
// The task's own `Call budget:` line wins over the shared context's.
|
|
529
534
|
const budget = briefBudget(String(t?.task ?? "")) ?? shared;
|
|
@@ -633,12 +638,33 @@ function landingCommand(input: Record<string, unknown>): boolean {
|
|
|
633
638
|
});
|
|
634
639
|
}
|
|
635
640
|
|
|
641
|
+
// The read tool's stand-in for a value it hid. A file may hold one only where it is produced
|
|
642
|
+
// (secret-redact.ts) or exercised (its tests).
|
|
643
|
+
const PLACEHOLDER = "[REDACTED:";
|
|
644
|
+
const PLACEHOLDER_FILES = [/\/src\/core\/secret-redact\.ts$/, /\/tests\/secret-redact[^/]*\.test\.ts$/];
|
|
645
|
+
/** What a write/edit/ast_edit call would add: every text argument but the targets and the replaced text. */
|
|
646
|
+
function addedText(input: Record<string, unknown>): string {
|
|
647
|
+
const skip = ["path", "file", "cwd", "old_string", "old", "oldText", "i"];
|
|
648
|
+
return Object.entries(input)
|
|
649
|
+
.filter(([key, value]) => typeof value === "string" && !skip.includes(key))
|
|
650
|
+
.map(([, value]) => value as string)
|
|
651
|
+
.join("\n");
|
|
652
|
+
}
|
|
653
|
+
|
|
636
654
|
// Subagent half of a tool call (the original plan-guard checkCall without the main return).
|
|
637
655
|
// `cap` is the sub's hard call cap: its recorded per-spawn budget, else the global sub_max_calls.
|
|
638
656
|
function subRules(e: ToolEvent, input: Record<string, unknown>, paths: string[], writes: string[], cfg: Config, cap: number): string | null {
|
|
639
657
|
// Closing and cancelling are Main's decisions: a shell that runs the tool is refused; one that only names its path is not.
|
|
640
658
|
if (cfg.guards.shell_tools.includes(e.tool) && runsCloser(input))
|
|
641
659
|
return 'queue-close and queue-cancel are Main\'s; report in your plan\'s "## Progress" instead.';
|
|
660
|
+
// The read tool prints a placeholder for a value it hid, never the value (I-20261027-158,
|
|
661
|
+
// I-20261027-160: one copy silently broke the shipped config template). Writing that text back
|
|
662
|
+
// is refused; the file that produces one and the tests that exercise it are the exceptions.
|
|
663
|
+
if ((e.tool === "write" || e.tool === "edit" || e.tool === "ast_edit") && addedText(input).includes(PLACEHOLDER)) {
|
|
664
|
+
const keeper = writes.length > 0 && writes.every(p => PLACEHOLDER_FILES.some(rx => rx.test(p)));
|
|
665
|
+
if (!keeper)
|
|
666
|
+
return "this is the read tool's redaction placeholder, not the real value; re-read the file raw or keep the original line";
|
|
667
|
+
}
|
|
642
668
|
const plans = q.activePlans();
|
|
643
669
|
if (e.calls >= cap) {
|
|
644
670
|
// Plan edit targets come from writeTargets (write and structured/hashline edit)
|
|
@@ -786,7 +812,7 @@ function mainTool(e: ToolEvent, input: Record<string, unknown>, cfg: Config): De
|
|
|
786
812
|
log(cfg.paths.guard_log, `BLOCK bypass launch: cancel pending (${pending.words})`);
|
|
787
813
|
return deny(`main-guard: ${CANCEL_TODO} Flagged: "${pending.words}"`);
|
|
788
814
|
}
|
|
789
|
-
const [why, named] = planGate(command, entry);
|
|
815
|
+
const [why, named] = planGate(command, entry, cfg);
|
|
790
816
|
if (why) {
|
|
791
817
|
log(cfg.paths.guard_log, `BLOCK bypass launch: ${why}`);
|
|
792
818
|
return deny(`main-guard: ${why}`);
|
|
@@ -975,7 +1001,7 @@ export function checkSpawn(e: SpawnEvent, cfg: Config): Decision {
|
|
|
975
1001
|
return deny(`main-guard: ${e.agent}: agent "${e.agent}" is not in "## Allowed" of ${q.SUBAGENTS_MD} (no expensive or unpinned models).`);
|
|
976
1002
|
if (e.invocationKind !== "task")
|
|
977
1003
|
return deny("main-guard: spawn implementers with the task tool (the plan gate checks its brief).");
|
|
978
|
-
const [why, named] = planGate(e.brief, e.agent);
|
|
1004
|
+
const [why, named] = planGate(e.brief, e.agent, cfg);
|
|
979
1005
|
if (why) {
|
|
980
1006
|
log(cfg.paths.guard_log, `BLOCK spawn ${e.agent}: ${why}`);
|
|
981
1007
|
return deny(`main-guard: ${why}`);
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import { closeSync, existsSync, lstatSync, openSync, readdirSync, readFileSync, statSync, writeSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import type { Config } from "./config.ts";
|
|
4
|
+
import { expandHome } from "./queue/lib.ts";
|
|
5
|
+
import { gitRaw } from "./proc.ts";
|
|
6
|
+
|
|
7
|
+
export interface KnowledgeEntry {
|
|
8
|
+
repo: string;
|
|
9
|
+
topic: string;
|
|
10
|
+
title: string;
|
|
11
|
+
/** ISO-8601 date (commit date or mtime fallback). */
|
|
12
|
+
updated: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
interface ManifestFile {
|
|
16
|
+
built: number;
|
|
17
|
+
entries: KnowledgeEntry[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const KNOWLEDGE_DIR = join("docs", "knowledge");
|
|
21
|
+
|
|
22
|
+
/** Text order for the lists: code-unit order, so the same list on every machine. */
|
|
23
|
+
export function byText(a: string, b: string): number {
|
|
24
|
+
return a < b ? -1 : a > b ? 1 : 0;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** One URL path segment or query value: every byte outside the unreserved set becomes %XX. */
|
|
28
|
+
export function urlValue(s: string): string {
|
|
29
|
+
let out = "";
|
|
30
|
+
for (const byte of new TextEncoder().encode(s)) {
|
|
31
|
+
const ch = String.fromCharCode(byte);
|
|
32
|
+
out += /[A-Za-z0-9\-._~]/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`;
|
|
33
|
+
}
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Inverse of urlValue: %XX byte runs come back as UTF-8 text. */
|
|
38
|
+
export function urlField(s: string): string {
|
|
39
|
+
const bytes: number[] = [];
|
|
40
|
+
for (let i = 0; i < s.length; i++) {
|
|
41
|
+
const hex = s.slice(i + 1, i + 3);
|
|
42
|
+
if (s[i] === "%" && /^[0-9A-Fa-f]{2}$/.test(hex)) {
|
|
43
|
+
bytes.push(parseInt(hex, 16));
|
|
44
|
+
i += 2;
|
|
45
|
+
} else {
|
|
46
|
+
bytes.push(...new TextEncoder().encode(s[i]!));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return new TextDecoder().decode(new Uint8Array(bytes));
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function repoKey(repoPath: string): string {
|
|
53
|
+
const remote = gitRaw(repoPath, ["remote", "get-url", "origin"]).stdout.trim();
|
|
54
|
+
if (remote) {
|
|
55
|
+
const base = basename(remote.replace(/\/$/, ""));
|
|
56
|
+
return base.endsWith(".git") ? base.slice(0, -4) : base;
|
|
57
|
+
}
|
|
58
|
+
return basename(repoPath);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function parseTitle(html: string, fallback: string): string {
|
|
62
|
+
const m = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);
|
|
63
|
+
if (!m) return fallback;
|
|
64
|
+
const t = m[1]!.replace(/\s+/g, " ").trim();
|
|
65
|
+
return t || fallback;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function topicUpdated(repoPath: string, rel: string, abs: string, now: number): string {
|
|
69
|
+
const log = gitRaw(repoPath, ["log", "-1", "--format=%cI", "--", rel]).stdout.trim();
|
|
70
|
+
if (log) return log;
|
|
71
|
+
const mtime = statSync(abs).mtimeMs;
|
|
72
|
+
return new Date(mtime).toISOString();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isLinkedWorktree(repoPath: string): boolean {
|
|
76
|
+
const dot = join(repoPath, ".git");
|
|
77
|
+
return existsSync(dot) && lstatSync(dot).isFile();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isGitCheckout(dir: string): boolean {
|
|
81
|
+
const dot = join(dir, ".git");
|
|
82
|
+
return existsSync(dot) && (lstatSync(dot).isDirectory() || lstatSync(dot).isFile());
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function scanRepo(repoPath: string, now: number): KnowledgeEntry[] {
|
|
86
|
+
if (isLinkedWorktree(repoPath)) return [];
|
|
87
|
+
const knowDir = join(repoPath, KNOWLEDGE_DIR);
|
|
88
|
+
if (!existsSync(knowDir) || !lstatSync(knowDir).isDirectory()) return [];
|
|
89
|
+
const repo = repoKey(repoPath);
|
|
90
|
+
const out: KnowledgeEntry[] = [];
|
|
91
|
+
for (const ent of readdirSync(knowDir, { withFileTypes: true })) {
|
|
92
|
+
if (!ent.isFile() || !ent.name.endsWith(".html")) continue;
|
|
93
|
+
const topic = ent.name.slice(0, -".html".length);
|
|
94
|
+
const abs = join(knowDir, ent.name);
|
|
95
|
+
let html = "";
|
|
96
|
+
try {
|
|
97
|
+
html = readFileSync(abs, "utf8");
|
|
98
|
+
} catch {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
out.push({
|
|
102
|
+
repo,
|
|
103
|
+
topic,
|
|
104
|
+
title: parseTitle(html, topic),
|
|
105
|
+
updated: topicUpdated(repoPath, join(KNOWLEDGE_DIR, ent.name), abs, now),
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
out.sort((a, b) => byText(a.repo, b.repo) || byText(a.topic, b.topic));
|
|
109
|
+
return out;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Pure scan: repos directly under expanded roots; unreadable dirs skipped. */
|
|
113
|
+
export function scanKnowledge(roots: string[], now: number): KnowledgeEntry[] {
|
|
114
|
+
const entries: KnowledgeEntry[] = [];
|
|
115
|
+
for (const raw of roots) {
|
|
116
|
+
let root = "";
|
|
117
|
+
try {
|
|
118
|
+
root = expandHome(raw);
|
|
119
|
+
} catch {
|
|
120
|
+
continue;
|
|
121
|
+
}
|
|
122
|
+
if (!existsSync(root)) continue;
|
|
123
|
+
let names: string[] = [];
|
|
124
|
+
try {
|
|
125
|
+
names = readdirSync(root);
|
|
126
|
+
} catch {
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
for (const name of names) {
|
|
130
|
+
const repoPath = join(root, name);
|
|
131
|
+
try {
|
|
132
|
+
if (!lstatSync(repoPath).isDirectory()) continue;
|
|
133
|
+
if (!isGitCheckout(repoPath)) continue;
|
|
134
|
+
entries.push(...scanRepo(repoPath, now));
|
|
135
|
+
} catch {
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
entries.sort((a, b) => byText(a.repo, b.repo) || byText(a.topic, b.topic));
|
|
141
|
+
return entries;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function knowledgeManifestPath(cfg: Config): string {
|
|
145
|
+
return join(expandHome(cfg.paths.queue_state), "knowledge.json");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function readManifest(path: string): ManifestFile | null {
|
|
149
|
+
if (!existsSync(path)) return null;
|
|
150
|
+
try {
|
|
151
|
+
const raw: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
152
|
+
if (!raw || typeof raw !== "object") return null;
|
|
153
|
+
const built = (raw as ManifestFile).built;
|
|
154
|
+
const entries = (raw as ManifestFile).entries;
|
|
155
|
+
if (typeof built !== "number" || !Array.isArray(entries)) return null;
|
|
156
|
+
return { built, entries };
|
|
157
|
+
} catch {
|
|
158
|
+
return null;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function writeManifest(path: string, data: ManifestFile): void {
|
|
163
|
+
const fd = openSync(path, "w");
|
|
164
|
+
try {
|
|
165
|
+
writeSync(fd, JSON.stringify(data));
|
|
166
|
+
} finally {
|
|
167
|
+
closeSync(fd);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Cached manifest in queue state; rescans when older than cfg.knowledge.max_age_s. */
|
|
172
|
+
export function knowledgeManifest(cfg: Config, nowSec = Math.floor(Date.now() / 1000)): KnowledgeEntry[] {
|
|
173
|
+
const path = knowledgeManifestPath(cfg);
|
|
174
|
+
const cached = readManifest(path);
|
|
175
|
+
const maxAge = cfg.knowledge.max_age_s;
|
|
176
|
+
if (cached && nowSec - cached.built < maxAge) return cached.entries;
|
|
177
|
+
const entries = scanKnowledge(cfg.knowledge.roots, nowSec * 1000);
|
|
178
|
+
const fresh: ManifestFile = { built: nowSec, entries };
|
|
179
|
+
writeManifest(path, fresh);
|
|
180
|
+
return entries;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Absolute path to a topic HTML file, or null when repo/topic is unknown. */
|
|
184
|
+
export function resolveKnowledgeTopic(cfg: Config, repo: string, topic: string): string | null {
|
|
185
|
+
if (!/^[a-zA-Z0-9._-]+$/.test(repo) || !/^[a-zA-Z0-9._-]+$/.test(topic)) return null;
|
|
186
|
+
for (const raw of cfg.knowledge.roots) {
|
|
187
|
+
let root = "";
|
|
188
|
+
try {
|
|
189
|
+
root = expandHome(raw);
|
|
190
|
+
} catch {
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
if (!existsSync(root)) continue;
|
|
194
|
+
let names: string[] = [];
|
|
195
|
+
try {
|
|
196
|
+
names = readdirSync(root);
|
|
197
|
+
} catch {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
for (const name of names) {
|
|
201
|
+
const repoPath = join(root, name);
|
|
202
|
+
try {
|
|
203
|
+
if (!lstatSync(repoPath).isDirectory() || !isGitCheckout(repoPath) || isLinkedWorktree(repoPath)) continue;
|
|
204
|
+
if (repoKey(repoPath) !== repo) continue;
|
|
205
|
+
const file = join(repoPath, KNOWLEDGE_DIR, `${topic}.html`);
|
|
206
|
+
if (existsSync(file) && lstatSync(file).isFile()) return file;
|
|
207
|
+
} catch {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
return null;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/** Read topic bytes for serving; null when missing. */
|
|
216
|
+
export function readKnowledgeTopicFile(cfg: Config, repo: string, topic: string): Buffer<ArrayBuffer> | null {
|
|
217
|
+
const path = resolveKnowledgeTopic(cfg, repo, topic);
|
|
218
|
+
if (!path) return null;
|
|
219
|
+
try {
|
|
220
|
+
return readFileSync(path);
|
|
221
|
+
} catch {
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
}
|
package/src/core/owner-ui.ts
CHANGED
|
@@ -17,6 +17,7 @@ import type { Config } from "./config.ts";
|
|
|
17
17
|
import { nowSec, strftime } from "./clock.ts";
|
|
18
18
|
import { cpuCount } from "./host.ts";
|
|
19
19
|
import { openIncidents } from "./incidents.ts";
|
|
20
|
+
import { byText, knowledgeManifest, readKnowledgeTopicFile, urlField, urlValue, type KnowledgeEntry } from "./knowledge.ts";
|
|
20
21
|
import { log } from "./guards.ts";
|
|
21
22
|
import { readMetricEvents } from "./metrics.ts";
|
|
22
23
|
import { activePlans, chatUnlock, dependencyOrderProblems, expandHome, stateDirPath, unlockPath, type Plan } from "./queue/lib.ts";
|
|
@@ -29,6 +30,9 @@ const MESSAGE_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
|
|
|
29
30
|
/** How long the page keeps an owner message: 12 h, then the sweep removes it (owner, 2026-10-25 19:10). */
|
|
30
31
|
export const OWNER_MESSAGE_KEEP_SEC = 43200;
|
|
31
32
|
const REFRESH_SEC = 20;
|
|
33
|
+
/** The page's tabs, in pill order; anything else in `?tab=` renders Now. */
|
|
34
|
+
const TABS: [string, string][] = [["now", "Now"], ["queue", "Queue"], ["agents", "Agents"], ["spend", "Spend"], ["knowledge", "Base"]];
|
|
35
|
+
const TAB_IDS = TABS.map(([id]) => id);
|
|
32
36
|
// Tailscale hands out addresses from 100.64.0.0/10 (CGNAT) and its own ULA /48 for IPv6.
|
|
33
37
|
const TAILNET6 = /^fd7a:115c:a1e0:/i;
|
|
34
38
|
|
|
@@ -619,8 +623,7 @@ function tilesHtml(data: PageData): string {
|
|
|
619
623
|
|
|
620
624
|
/** The sticky mockup top bar: logo, pill tabs, and the lock pill that posts the unlock/lock and tier forms. */
|
|
621
625
|
function topBarHtml(tab: string, lockMinutesLeft: number | null, cfg: Config): string {
|
|
622
|
-
const
|
|
623
|
-
const pills = tabs.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
|
|
626
|
+
const pills = TABS.map(([id, label]) => `<a href="/?tab=${id}"${tab === id ? ` class="on"` : ""}>${label}</a>`).join("");
|
|
624
627
|
const lockLabel = lockMinutesLeft === null ? "🔒 Off" : `🔓 ${lockMinutesLeft} min`;
|
|
625
628
|
const tabField = `<input type="hidden" name="tab" value="${esc(tab)}">`;
|
|
626
629
|
const unlockForm = (minutes: number) =>
|
|
@@ -715,6 +718,8 @@ export interface PageData {
|
|
|
715
718
|
incidents: IncidentRow[] | null;
|
|
716
719
|
scores: ScoresData | null;
|
|
717
720
|
machine: MachineRow | null;
|
|
721
|
+
/** Repo-local HTML explainers from the knowledge manifest; null when unreadable. */
|
|
722
|
+
knowledge: KnowledgeEntry[] | null;
|
|
718
723
|
/** The 24 h tile numbers; null when the run source is unreadable. */
|
|
719
724
|
stats: NowStats | null;
|
|
720
725
|
/** The owner's messages newer than the keep window, newest first; null when unreadable. */
|
|
@@ -751,6 +756,7 @@ export function buildPageData(cfg: Config, source: RunSource): PageData {
|
|
|
751
756
|
incidents: safe(() => incidentRows(cfg)),
|
|
752
757
|
scores: safe(() => scoresData(cfg)),
|
|
753
758
|
machine: safe(() => machineRow(cfg)),
|
|
759
|
+
knowledge: safe(() => knowledgeManifest(cfg)),
|
|
754
760
|
stats: safe(() => nowStats(cfg, source, nowSec())),
|
|
755
761
|
messages: safe(() => recentOwnerMessages(nowSec())),
|
|
756
762
|
lockMinutesLeft: lockMinutesLeft(cfg),
|
|
@@ -875,11 +881,51 @@ bindDetails(document);
|
|
|
875
881
|
bindPage();
|
|
876
882
|
})();`;
|
|
877
883
|
|
|
884
|
+
/**
|
|
885
|
+
* The Knowledge tab: repo cards, one repo's topic cards, or one topic in a frame. The breadcrumb's
|
|
886
|
+
* earlier segments link back — knowledge-base → every repo, `<repo>` → its topics. Topics are
|
|
887
|
+
* read-only files at docs/knowledge/<topic>.html in a repo under the configured roots; the page
|
|
888
|
+
* bytes come from /knowledge/<repo>/<topic> and there is no route that writes one.
|
|
889
|
+
*/
|
|
890
|
+
function knowledgeHtml(entries: KnowledgeEntry[], repo: string, topic: string): string {
|
|
891
|
+
const repoHref = `/?tab=knowledge&repo=${urlValue(repo)}`;
|
|
892
|
+
const crumb =
|
|
893
|
+
repo === ""
|
|
894
|
+
? ""
|
|
895
|
+
: `<p class="sub"><a href="/?tab=knowledge">knowledge-base</a> / ${topic === "" ? esc(repo) : `<a href="${repoHref}">${esc(repo)}</a>`}${topic === "" ? "" : ` / ${esc(topic)}`}</p>`;
|
|
896
|
+
if (entries.length === 0) {
|
|
897
|
+
return `<h1>Base</h1><div class="card"><p class="empty">No topics yet. Any repo under the configured roots counts: put a page in <span class="mono">docs/knowledge/</span> and it shows up here on the next reload.</p></div>`;
|
|
898
|
+
}
|
|
899
|
+
if (repo === "") {
|
|
900
|
+
const repos = new Map<string, KnowledgeEntry[]>();
|
|
901
|
+
for (const e of entries) repos.set(e.repo, [...(repos.get(e.repo) ?? []), e]);
|
|
902
|
+
const rows = [...repos.entries()]
|
|
903
|
+
.sort((a, b) => byText(a[0], b[0]))
|
|
904
|
+
.map(([name, list]) => {
|
|
905
|
+
const newest = list.map(e => e.updated).sort().at(-1)!.slice(0, 10);
|
|
906
|
+
return `<div class="mrow"><a href="/?tab=knowledge&repo=${urlValue(name)}">${esc(name)}</a><span class="mono">${list.length} topic${list.length === 1 ? "" : "s"} · ${newest}</span></div>`;
|
|
907
|
+
})
|
|
908
|
+
.join("");
|
|
909
|
+
return `<h1>Base</h1><p class="sub">One card per repo with pages in <span class="mono">docs/knowledge/</span> — tap a repo for its topics.</p><div class="card">${rows}</div>`;
|
|
910
|
+
}
|
|
911
|
+
const topics = entries.filter(e => e.repo === repo);
|
|
912
|
+
if (topics.length === 0) return `${crumb}<div class="card"><p class="empty">No repo named "${esc(repo)}" has a page under the configured roots.</p></div>`;
|
|
913
|
+
if (topic === "") {
|
|
914
|
+
const rows = topics
|
|
915
|
+
.map(e => `<div class="mrow"><a href="${repoHref}&topic=${urlValue(e.topic)}">${esc(e.title)}</a><span class="mono">${e.updated.slice(0, 10)}</span></div>`)
|
|
916
|
+
.join("");
|
|
917
|
+
return `${crumb}<div class="card">${rows}</div>`;
|
|
918
|
+
}
|
|
919
|
+
const hit = topics.find(e => e.topic === topic);
|
|
920
|
+
if (hit === undefined) return `${crumb}<div class="card"><p class="empty">No topic "${esc(topic)}" in ${esc(repo)}.</p></div>`;
|
|
921
|
+
return `${crumb}<h1>${esc(hit.title)}</h1><div class="card"><iframe class="knowframe" title="${esc(hit.title)}" src="/knowledge/${urlValue(repo)}/${urlValue(topic)}"></iframe></div>`;
|
|
922
|
+
}
|
|
923
|
+
|
|
878
924
|
/** The whole page as one HTML string. Exported for scripts/ui-preview.ts (no server). */
|
|
879
925
|
export function renderPage(cfg: Config, data: PageData, params: URLSearchParams, nonce: string): string {
|
|
880
926
|
const req = params.get("tab") ?? "";
|
|
881
927
|
// Server-rendered tabs: the pill links carry ?tab=; anything unknown renders Now.
|
|
882
|
-
const tab = req
|
|
928
|
+
const tab = TAB_IDS.includes(req) ? req : "now";
|
|
883
929
|
const needsBody =
|
|
884
930
|
data.questions === null
|
|
885
931
|
? na("Waiting on you")
|
|
@@ -932,7 +978,9 @@ ${merges}
|
|
|
932
978
|
<div class="card">
|
|
933
979
|
${machine}
|
|
934
980
|
</div>`
|
|
935
|
-
:
|
|
981
|
+
: tab === "knowledge"
|
|
982
|
+
? `${data.knowledge === null ? na("Base") : knowledgeHtml(data.knowledge, params.get("repo") ?? "", params.get("topic") ?? "")}`
|
|
983
|
+
: `<h1>Spend</h1>
|
|
936
984
|
<p class="sub">List price over the last 24 hours.</p>
|
|
937
985
|
<div class="card">
|
|
938
986
|
${spendTileHtml(data)}
|
|
@@ -1043,6 +1091,7 @@ tr:last-child td{border-bottom:none}
|
|
|
1043
1091
|
.mrow:last-child{border-bottom:none}
|
|
1044
1092
|
.bad{color:var(--red);font-weight:600}
|
|
1045
1093
|
.empty{color:var(--mut);padding:14px 16px;margin:0}
|
|
1094
|
+
.knowframe{display:block;width:100%;height:calc(100vh - 220px);min-height:360px;border:0;background:#fff}
|
|
1046
1095
|
.na{color:var(--mut);font-style:italic;padding:14px 16px;margin:0}
|
|
1047
1096
|
</style>
|
|
1048
1097
|
</head>
|
|
@@ -1080,7 +1129,7 @@ function redirect(target: string): Response {
|
|
|
1080
1129
|
|
|
1081
1130
|
/** The POST reply target: the tab the owner was on (a hidden `tab` field; unknown = now, the default), then the receipt. */
|
|
1082
1131
|
function sentTo(tab: string, sent: string): string {
|
|
1083
|
-
const t = tab
|
|
1132
|
+
const t = TAB_IDS.includes(tab) ? tab : "now";
|
|
1084
1133
|
return t === "now" ? `/?${sent}` : `/?tab=${t}&${sent}`;
|
|
1085
1134
|
}
|
|
1086
1135
|
|
|
@@ -1091,7 +1140,7 @@ function pageRes(cfg: Config, source: RunSource, params: URLSearchParams): Respo
|
|
|
1091
1140
|
status: 200,
|
|
1092
1141
|
headers: {
|
|
1093
1142
|
"content-type": "text/html; charset=utf-8",
|
|
1094
|
-
"content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
|
|
1143
|
+
"content-security-policy": `default-src 'none'; style-src 'unsafe-inline'; script-src 'nonce-${nonce}'; img-src 'self' data:; connect-src 'self'; frame-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
|
|
1095
1144
|
},
|
|
1096
1145
|
});
|
|
1097
1146
|
}
|
|
@@ -1395,6 +1444,15 @@ export function startOwnerUi(opts: OwnerUiOptions): OwnerUiServer {
|
|
|
1395
1444
|
sweepOwnerMessages(nowSec());
|
|
1396
1445
|
res = pageRes(cfg, source, url.searchParams);
|
|
1397
1446
|
code = 200;
|
|
1447
|
+
} else if (req.method === "GET" && url.pathname.startsWith("/knowledge/")) {
|
|
1448
|
+
// The Knowledge tab's frame: the topic's own file bytes, GET only, no write path.
|
|
1449
|
+
const topicPath = /^\/knowledge\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
1450
|
+
const bytes =
|
|
1451
|
+
topicPath === null
|
|
1452
|
+
? null
|
|
1453
|
+
: readKnowledgeTopicFile(cfg, urlField(topicPath[1]!), urlField(topicPath[2]!));
|
|
1454
|
+
res = bytes === null ? textRes("not found", 404) : new Response(bytes, { headers: { "content-type": "text/html; charset=utf-8" } });
|
|
1455
|
+
code = res.status;
|
|
1398
1456
|
} else if (req.method === "GET" && url.pathname.startsWith("/message-image/")) {
|
|
1399
1457
|
const mim = /^\/message-image\/([^/]+)\/([^/]+)$/.exec(url.pathname);
|
|
1400
1458
|
res = mim ? handleMessageImage(mim[1]!, mim[2]!) : textRes("not found", 404);
|