chapterhouse 0.8.1 → 0.9.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/api/korg.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { sendToAgentSession } from "../copilot/orchestrator.js";
2
2
  export async function routeKorgMessage(input) {
3
3
  const message = input.message.trim();
4
- const sessionId = input.session_id?.trim() || `korg-${Date.now()}`;
5
- const sessionName = input.session_id?.trim() || message.slice(0, 80).trim() || sessionId;
4
+ const sessionId = input.sessionKey?.trim() || `korg-${Date.now()}`;
5
+ const sessionName = input.sessionKey?.trim() || message.slice(0, 80).trim() || sessionId;
6
6
  const prompt = [
7
7
  "Handle this request as Korg via the API.",
8
8
  `Research session id: ${sessionId}`,
@@ -13,7 +13,7 @@ export async function routeKorgMessage(input) {
13
13
  message,
14
14
  ].join("\n");
15
15
  const reply = await sendToAgentSession("korg", prompt);
16
- return { ok: true, session_id: sessionId, reply };
16
+ return { ok: true, sessionKey: sessionId, reply };
17
17
  }
18
18
  export function listKorgResearchSessions(db) {
19
19
  return db.prepare(`
@@ -21,8 +21,8 @@ export function listKorgResearchSessions(db) {
21
21
  session_id AS id,
22
22
  COALESCE(NULLIF(TRIM(session_name), ''), session_id) AS name,
23
23
  COUNT(*) AS source_count,
24
- 0 AS open_questions,
25
- MAX(ingested_at) AS last_activity
24
+ 0 AS open_questions_count,
25
+ MAX(ingested_at) AS last_activity_at
26
26
  FROM wiki_sources
27
27
  WHERE status = 'active'
28
28
  AND session_id IS NOT NULL
@@ -13,7 +13,7 @@ test("routeKorgMessage creates a research session id and delegates to the persis
13
13
  const mod = await import(new URL(`./korg.js?case=${Date.now()}-${Math.random()}`, import.meta.url).href);
14
14
  const result = await mod.routeKorgMessage({ message: "Research local-first PKB patterns." });
15
15
  assert.equal(result.ok, true);
16
- assert.match(result.session_id, /^korg-/);
16
+ assert.match(result.sessionKey, /^korg-/);
17
17
  assert.equal(result.reply, "Korg reply");
18
18
  assert.deepEqual(calls, [{
19
19
  slug: "korg",
@@ -33,8 +33,8 @@ test("routeKorgMessage preserves an existing research session id in the delegate
33
33
  },
34
34
  });
35
35
  const mod = await import(new URL(`./korg.js?case=${Date.now()}-${Math.random()}`, import.meta.url).href);
36
- const result = await mod.routeKorgMessage({ message: "Add two more sources.", session_id: "compiler-research" });
37
- assert.equal(result.session_id, "compiler-research");
36
+ const result = await mod.routeKorgMessage({ message: "Add two more sources.", sessionKey: "compiler-research" });
37
+ assert.equal(result.sessionKey, "compiler-research");
38
38
  assert.equal(result.reply, "Continuing session");
39
39
  assert.match(prompt, /compiler-research/);
40
40
  assert.match(prompt, /Add two more sources\./);
@@ -0,0 +1,225 @@
1
+ // Route & SSE coverage — static analysis CI safeguard (P0 remediation, issue #369)
2
+ //
3
+ // Coverage status as of 2026-05-15:
4
+ // ──────────────────────────────────────────────────────────────────────────────
5
+ // GET /api/wiki/pages — tested (server.test.ts: coerced updated, frontmatter)
6
+ // GET /api/wiki/browser-pages — tested (server.test.ts: browser contract, orphan fallback)
7
+ // GET /api/wiki/sources — tested (server.test.ts: empty payload, page filter)
8
+ // GET /api/wiki/links — tested (server.test.ts: all links, empty, page filter)
9
+ // GET /api/wiki/page — tested (server.test.ts: CRUD, welcome page synthesis, 404)
10
+ // PUT /api/wiki/page — tested (server.test.ts: wiki CRUD create flow)
11
+ // DELETE /api/wiki/page — tested (server.test.ts: wiki CRUD delete flow)
12
+ // GET /api/wiki/search — NOT tested (add in Phase 3c)
13
+ // POST /api/wiki/update — static auth guard tested below
14
+ // POST /api/wiki/page/pin — auth + traversal guard tested
15
+ // POST /api/wiki/ingest — NOT tested (add in Phase 3c)
16
+ // GET /api/wiki/korg/sessions — NOT tested (add in Phase 3c)
17
+ // POST /api/wiki/korg — NOT tested (add in Phase 3c)
18
+ // ──────────────────────────────────────────────────────────────────────────────
19
+ import { describe, test } from "node:test";
20
+ import assert from "node:assert/strict";
21
+ import { readFileSync } from "node:fs";
22
+ import { join } from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ const __dirname = fileURLToPath(new URL(".", import.meta.url));
25
+ const ROOT = join(__dirname, "..", "..");
26
+ const FRONTEND_API_PATH = join(ROOT, "web", "src", "api.ts");
27
+ const SERVER_TS_PATH = join(ROOT, "src", "api", "server.ts");
28
+ const WEB_SCHEMAS_PATH = join(ROOT, "src", "shared", "api-schemas.ts");
29
+ /**
30
+ * Normalise a URL path for comparison:
31
+ * - Replace complete template-literal expressions ${...} with :param
32
+ * - Strip incomplete trailing template expressions (e.g. `${query ` cut by `?`)
33
+ * - Replace Express named params :slug with :param
34
+ * - Strip trailing slashes
35
+ */
36
+ function normalizePath(raw) {
37
+ return raw
38
+ .replace(/\$\{[^}]*\}/g, ":param") // complete ${...} → :param
39
+ .replace(/\$\{[^}]*$/, "") // trailing incomplete ${... (cut by `?` in regex)
40
+ .replace(/:[a-zA-Z_][a-zA-Z0-9_]*/g, ":param") // :slug → :param
41
+ .replace(/\/+$/, "") // strip trailing slash
42
+ .trim();
43
+ }
44
+ /**
45
+ * Extract all unique normalised API paths called via authedFetch() in the
46
+ * frontend api.ts. Only static string / template-literal arguments are
47
+ * detected — calls that pass a pre-constructed variable are skipped.
48
+ */
49
+ function extractFrontendPaths(src) {
50
+ // Matches authedFetch( then an opening quote/backtick then /api/...
51
+ // Stops at the same quote character, or at `?` (query string start).
52
+ const re = /authedFetch\(["'`](\/api\/[^"'`?]+)/g;
53
+ const paths = new Set();
54
+ for (const m of src.matchAll(re)) {
55
+ const normalised = normalizePath(m[1]);
56
+ if (normalised) {
57
+ paths.add(normalised);
58
+ }
59
+ }
60
+ return paths;
61
+ }
62
+ /**
63
+ * Extract all unique normalised API paths registered via app.METHOD() in
64
+ * server.ts. Only /api/ prefixed paths are considered.
65
+ */
66
+ function extractServerPaths(src) {
67
+ const re = /app\.(get|post|put|delete|patch)\(["'`](\/api\/[^"'`?]+)/g;
68
+ const paths = new Set();
69
+ for (const m of src.matchAll(re)) {
70
+ const normalised = normalizePath(m[2]);
71
+ if (normalised) {
72
+ paths.add(normalised);
73
+ }
74
+ }
75
+ return paths;
76
+ }
77
+ /**
78
+ * Extract SSE type literals emitted inline via formatSseData({ type: "X", ... })
79
+ * in server.ts. Pass-through calls like formatSseData(event) are not detected.
80
+ */
81
+ function extractSseDataTypes(src) {
82
+ // Allow up to ~200 chars between `formatSseData({` and `type: "X"` to
83
+ // handle multi-line object literals (queued, queue-advance, etc.).
84
+ const re = /formatSseData\(\{[\s\S]{0,200}?type:\s*["']([^"']+)["']/g;
85
+ const types = new Set();
86
+ for (const m of src.matchAll(re)) {
87
+ types.add(m[1]);
88
+ }
89
+ return types;
90
+ }
91
+ /**
92
+ * Extract the first argument (event name) from all formatSseEvent("name", ...)
93
+ * calls in server.ts.
94
+ */
95
+ function extractSseEventNames(src) {
96
+ const re = /formatSseEvent\(["']([^"']+)["']/g;
97
+ const names = new Set();
98
+ for (const m of src.matchAll(re)) {
99
+ names.add(m[1]);
100
+ }
101
+ return names;
102
+ }
103
+ /**
104
+ * Extract the `type` literal values from StreamEventSchema in web/src/api-schemas.ts
105
+ * by scanning for `type: z.literal("X")` patterns.
106
+ *
107
+ * These are the only valid SSE frame types the frontend will parse via the
108
+ * default `message` EventSource handler.
109
+ */
110
+ function extractStreamEventSchemaTypes(src) {
111
+ // Locate the StreamEventSchema block first so we don't accidentally pick up
112
+ // literals from other schemas.
113
+ const startIdx = src.indexOf("export const StreamEventSchema");
114
+ if (startIdx === -1) {
115
+ throw new Error("StreamEventSchema not found in src/shared/api-schemas.ts");
116
+ }
117
+ // Take a generous slice (10 000 chars) — the schema is large but finite.
118
+ const block = src.slice(startIdx, startIdx + 10_000);
119
+ const re = /type:\s*z\.literal\(["']([^"']+)["']\)/g;
120
+ const types = new Set();
121
+ for (const m of block.matchAll(re)) {
122
+ types.add(m[1]);
123
+ }
124
+ return types;
125
+ }
126
+ // ─────────────────────────────────────────────────────────────────────────────
127
+ // Tests
128
+ // ─────────────────────────────────────────────────────────────────────────────
129
+ describe("route coverage — static analysis", () => {
130
+ test("all frontend authedFetch paths have a matching server route registration", () => {
131
+ const frontendSrc = readFileSync(FRONTEND_API_PATH, "utf8");
132
+ const serverSrc = readFileSync(SERVER_TS_PATH, "utf8");
133
+ const frontendPaths = extractFrontendPaths(frontendSrc);
134
+ const serverPaths = extractServerPaths(serverSrc);
135
+ const missing = [];
136
+ for (const fp of [...frontendPaths].sort()) {
137
+ if (!serverPaths.has(fp)) {
138
+ missing.push(fp);
139
+ }
140
+ }
141
+ assert.ok(missing.length === 0, `Frontend calls ${missing.length} route(s) with no matching server registration:\n` +
142
+ missing.map((p) => ` MISSING: ${p}`).join("\n") +
143
+ "\n\nAdd the missing route(s) to src/api/server.ts");
144
+ });
145
+ test("server routes cover every unique normalised path (no obvious duplicates leaked)", () => {
146
+ const serverSrc = readFileSync(SERVER_TS_PATH, "utf8");
147
+ const serverPaths = extractServerPaths(serverSrc);
148
+ // Sanity: the server must expose at least 30 /api/ routes.
149
+ assert.ok(serverPaths.size >= 30, `Expected ≥30 server routes, found ${serverPaths.size}. Check extractServerPaths regex.`);
150
+ });
151
+ });
152
+ describe("wiki write route safeguards — static analysis", () => {
153
+ test("wiki update and pin routes declare authMiddleware explicitly", () => {
154
+ const serverSrc = readFileSync(SERVER_TS_PATH, "utf8");
155
+ assert.match(serverSrc, /app\.post\("\/api\/wiki\/update",\s*authMiddleware,\s*async \(req: Request, res: Response\) => \{/);
156
+ assert.match(serverSrc, /app\.post\("\/api\/wiki\/page\/pin",\s*authMiddleware,\s*async \(req: Request, res: Response\) => \{/);
157
+ });
158
+ });
159
+ describe("SSE exhaustiveness — static analysis", () => {
160
+ // ───────────────────────────────────────────────────────────────────────────
161
+ // REGRESSION CANARY for issues #367 / #368:
162
+ //
163
+ // `formatSseEvent("status", payload)` generates an SSE *named event*:
164
+ // event: status\ndata: {...}\n\n
165
+ //
166
+ // The frontend's EventSource only handles the default `message` event.
167
+ // Named events are silently dropped — the frontend never sees them.
168
+ //
169
+ // If any future code adds `formatSseEvent("X", ...)` where "X" is also a
170
+ // type in StreamEventSchema, this test FAILS, preventing the regression.
171
+ // ───────────────────────────────────────────────────────────────────────────
172
+ test("formatSseEvent is not used with names that belong in the StreamEventSchema data channel", () => {
173
+ const serverSrc = readFileSync(SERVER_TS_PATH, "utf8");
174
+ const schemaSrc = readFileSync(WEB_SCHEMAS_PATH, "utf8");
175
+ const namedEventNames = extractSseEventNames(serverSrc);
176
+ const schemaTypes = extractStreamEventSchemaTypes(schemaSrc);
177
+ const conflicts = [];
178
+ for (const name of namedEventNames) {
179
+ if (schemaTypes.has(name)) {
180
+ conflicts.push(name);
181
+ }
182
+ }
183
+ assert.ok(conflicts.length === 0, `formatSseEvent() is being used with name(s) that are also StreamEventSchema types:\n` +
184
+ conflicts.map((n) => ` CONFLICT: formatSseEvent("${n}", ...) — must use formatSseData({ type: "${n}", ... }) instead`).join("\n") +
185
+ "\n\nNamed SSE events are silently dropped by the frontend's default 'message' handler (issues #367/#368).");
186
+ });
187
+ test("all inline formatSseData type literals are known StreamEventSchema types or agent-stream-only types", () => {
188
+ const serverSrc = readFileSync(SERVER_TS_PATH, "utf8");
189
+ const schemaSrc = readFileSync(WEB_SCHEMAS_PATH, "utf8");
190
+ const emittedTypes = extractSseDataTypes(serverSrc);
191
+ const schemaTypes = extractStreamEventSchemaTypes(schemaSrc);
192
+ // Types emitted only on /api/agents/stream — not part of the main chat
193
+ // StreamEventSchema but intentional (received by a separate subscriber).
194
+ const agentStreamOnlyTypes = new Set(["agent_event"]);
195
+ const unknown = [];
196
+ for (const t of [...emittedTypes].sort()) {
197
+ if (!schemaTypes.has(t) && !agentStreamOnlyTypes.has(t)) {
198
+ unknown.push(t);
199
+ }
200
+ }
201
+ assert.ok(unknown.length === 0, `formatSseData emits type(s) not present in StreamEventSchema:\n` +
202
+ unknown.map((t) => ` UNKNOWN: "${t}"`).join("\n") +
203
+ "\n\nEither add these to StreamEventSchema in src/shared/api-schemas.ts, " +
204
+ "or add them to the agentStreamOnlyTypes allowlist in this test.");
205
+ });
206
+ test("StreamEventSchema covers at least the core chat stream types", () => {
207
+ const schemaSrc = readFileSync(WEB_SCHEMAS_PATH, "utf8");
208
+ const schemaTypes = extractStreamEventSchemaTypes(schemaSrc);
209
+ const required = [
210
+ "connected",
211
+ "delta",
212
+ "message",
213
+ "cancelled",
214
+ "status",
215
+ "queued",
216
+ "activity",
217
+ "queue-advance",
218
+ "turn-interrupted",
219
+ ];
220
+ const missing = required.filter((t) => !schemaTypes.has(t));
221
+ assert.ok(missing.length === 0, `StreamEventSchema is missing expected type(s): ${missing.join(", ")}\n` +
222
+ "These types were removed or renamed — update the schema and this test together.");
223
+ });
224
+ });
225
+ //# sourceMappingURL=route-coverage.test.js.map