karajan-code 3.1.0 → 3.2.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.
Files changed (59) hide show
  1. package/README.md +12 -4
  2. package/package.json +6 -1
  3. package/packages/hu-board/package.json +3 -1
  4. package/packages/hu-board/public/index.html +1 -0
  5. package/packages/hu-board/public/styles.css +32 -0
  6. package/packages/hu-board/public/utils/board-view.js +10 -1
  7. package/packages/hu-board/public/utils/formatters.js +41 -0
  8. package/packages/hu-board/public/wiki.html +32 -0
  9. package/packages/hu-board/public/wiki.js +53 -0
  10. package/packages/hu-board/src/db.js +78 -0
  11. package/packages/hu-board/src/format.js +79 -0
  12. package/packages/hu-board/src/plan-mutations.js +4 -4
  13. package/packages/hu-board/src/routes/api.js +16 -1
  14. package/packages/hu-board/src/routes/rag.js +1 -1
  15. package/packages/hu-board/src/routes/wiki.js +43 -0
  16. package/packages/hu-board/src/run-tracker.js +1 -1
  17. package/packages/hu-board/src/server.js +4 -2
  18. package/packages/hu-board/src/sync.js +1 -1
  19. package/scripts/git-hooks/post-merge +13 -2
  20. package/src/audit/ai-slop-findings.js +102 -0
  21. package/src/audit/deterministic-summary.js +18 -0
  22. package/src/brain/standby-scheduler.js +10 -92
  23. package/src/brain/standby-store.js +12 -168
  24. package/src/checks/ai-trash.js +34 -0
  25. package/src/checks/qmd.js +41 -0
  26. package/src/checks/squeezr.js +36 -0
  27. package/src/cli/register-meta.js +21 -0
  28. package/src/cli/register-pipeline.js +3 -0
  29. package/src/commands/audit.js +6 -4
  30. package/src/commands/board.js +34 -0
  31. package/src/commands/doctor.js +6 -0
  32. package/src/commands/init.js +73 -8
  33. package/src/commands/qmd.js +86 -0
  34. package/src/commands/resume.js +6 -45
  35. package/src/commands/run.js +6 -50
  36. package/src/git/hu-snapshot.js +10 -105
  37. package/src/orchestrator/drivers/pre-loop-phases/inject-loaded-plan.js +16 -0
  38. package/src/orchestrator/drivers/run-hu-batch.js +5 -1
  39. package/src/orchestrator/hu-sub-pipeline.js +52 -8
  40. package/src/plan/plan-hu-ops.js +16 -338
  41. package/src/plan/plan-id.js +4 -45
  42. package/src/plan/plan-validation.js +4 -82
  43. package/src/rag/vec-store.js +17 -253
  44. package/src/roles/audit-role.js +11 -1
  45. package/src/utils/ai-trash.js +48 -0
  46. package/src/utils/atomic-write.js +6 -43
  47. package/src/utils/cli-ask-question.js +76 -0
  48. package/src/utils/doc-links.js +2 -0
  49. package/src/utils/os-detect.js +10 -0
  50. package/src/utils/paths.js +14 -123
  51. package/src/utils/port-check.js +6 -45
  52. package/src/utils/process.js +4 -188
  53. package/src/utils/qmd-collection.js +72 -0
  54. package/src/utils/qmd-detect.js +18 -0
  55. package/src/utils/qmd-install.js +37 -0
  56. package/src/utils/run-registry.js +9 -116
  57. package/src/utils/shared-paths.js +12 -41
  58. package/src/utils/squeezr-detect.js +18 -0
  59. package/src/utils/squeezr-install.js +37 -0
@@ -1,253 +1,17 @@
1
- // KJC-PCS-0049 Step 1 — Vector store sobre better-sqlite3 + sqlite-vec.
2
- // El RAG indexer (Step 4) escribe; el retriever (Step 5) lee. Una sola
3
- // DB en `~/.karajan/rag.db` por instalación.
4
- import { mkdirSync, existsSync } from "node:fs";
5
- import { dirname, join } from "node:path";
6
- import Database from "better-sqlite3";
7
- import * as sqliteVec from "sqlite-vec";
8
-
9
- import { getKarajanHome } from "../utils/paths.js";
10
-
11
- const DEFAULT_DIM = 768;
12
-
13
- export function dbPath() {
14
- return process.env.KJ_RAG_DB || join(getKarajanHome(), "rag.db");
15
- }
16
-
17
- /**
18
- * Open the rag.db, load the sqlite-vec extension, and ensure the
19
- * chunks + vec_chunks tables exist. Idempotent: a second call against
20
- * the same file is a no-op past the schema creation.
21
- *
22
- * Returns the open Database handle. Caller owns close().
23
- *
24
- * @param {Object} [opts]
25
- * @param {number} [opts.dim=768] — embedding dimension. Must match
26
- * the embedder configured for the project (Step 2). Changing it
27
- * later requires a fresh DB; the constant is captured in the
28
- * virtual table DDL.
29
- */
30
- export function openVecStore({ dim = DEFAULT_DIM, path = dbPath() } = {}) {
31
- if (!existsSync(dirname(path))) mkdirSync(dirname(path), { recursive: true });
32
- const db = new Database(path);
33
- sqliteVec.load(db);
34
- db.pragma("journal_mode = WAL");
35
- db.pragma("foreign_keys = ON");
36
- db.exec(`
37
- CREATE TABLE IF NOT EXISTS chunks (
38
- id INTEGER PRIMARY KEY AUTOINCREMENT,
39
- source TEXT NOT NULL,
40
- kind TEXT NOT NULL CHECK (kind IN ('plan', 'code', 'onboarding')),
41
- text TEXT NOT NULL,
42
- metadata TEXT,
43
- created_at TEXT NOT NULL DEFAULT (datetime('now'))
44
- );
45
- CREATE INDEX IF NOT EXISTS chunks_by_source ON chunks(source);
46
- CREATE INDEX IF NOT EXISTS chunks_by_kind ON chunks(kind);
47
- `);
48
- // KJC-TSK-0438 — Project isolation. project_slug = basename of projectDir
49
- // normalized; chunks indexed before the migration carry NULL and remain
50
- // queryable when `--project all` (or no slug detected at query time).
51
- const cols = db.prepare("PRAGMA table_info(chunks)").all().map((c) => c.name);
52
- if (!cols.includes("project_slug")) {
53
- db.exec("ALTER TABLE chunks ADD COLUMN project_slug TEXT;");
54
- db.exec("CREATE INDEX IF NOT EXISTS chunks_by_project ON chunks(project_slug);");
55
- }
56
- // KJC-TSK-0484 — Content-hash dedup. SHA-256 of the chunk text lets the
57
- // indexer skip embedding bodies it has already seen for the same project.
58
- // Older rows keep NULL; the lookup ignores NULLs so they neither dedup
59
- // nor get deduped until they are re-indexed and stamped.
60
- if (!cols.includes("content_hash")) {
61
- db.exec("ALTER TABLE chunks ADD COLUMN content_hash TEXT;");
62
- db.exec("CREATE INDEX IF NOT EXISTS chunks_by_hash ON chunks(content_hash, project_slug);");
63
- }
64
- // KJC-TSK-0455 — Auto-update by commit diff. Per-project metadata tracks
65
- // the last commit whose changes were reflected in the index, so subsequent
66
- // `kj rag index --since auto` invocations (and the post-merge hook / pre-run
67
- // drift check landed in PR2) only re-embed the actual delta instead of the
68
- // whole project.
69
- db.exec(`
70
- CREATE TABLE IF NOT EXISTS vec_store_meta (
71
- project_slug TEXT PRIMARY KEY,
72
- last_indexed_commit TEXT,
73
- last_indexed_at TEXT NOT NULL DEFAULT (datetime('now'))
74
- );
75
- `);
76
- db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS vec_chunks USING vec0(embedding float[${dim}]);`);
77
- // KJC-TSK-0443 — FTS5 keyword index for BM25 hybrid scoring. content='chunks'
78
- // makes it a contentless mirror linked by id (no double storage); triggers
79
- // sync the FTS5 rows on insert/update/delete. Rebuilds idempotently when
80
- // the FTS5 table exists but is empty (e.g. created post-migration on a
81
- // DB with pre-v2.28 chunks).
82
- db.exec(`
83
- CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(text, content='chunks', content_rowid='id');
84
- CREATE TRIGGER IF NOT EXISTS chunks_ai AFTER INSERT ON chunks BEGIN
85
- INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
86
- END;
87
- CREATE TRIGGER IF NOT EXISTS chunks_ad AFTER DELETE ON chunks BEGIN
88
- INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
89
- END;
90
- CREATE TRIGGER IF NOT EXISTS chunks_au AFTER UPDATE ON chunks BEGIN
91
- INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
92
- INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
93
- END;
94
- `);
95
- const ftsCount = db.prepare("SELECT COUNT(*) AS n FROM chunks_fts").get().n;
96
- const chunksCount = db.prepare("SELECT COUNT(*) AS n FROM chunks").get().n;
97
- if (ftsCount === 0 && chunksCount > 0) {
98
- db.exec("INSERT INTO chunks_fts(chunks_fts) VALUES('rebuild');");
99
- }
100
- return db;
101
- }
102
-
103
- /**
104
- * Persist one chunk. The chunks.id and vec_chunks.rowid stay in sync
105
- * because the virtual table rowid is set explicitly to the freshly
106
- * minted chunks.id. Returns that id.
107
- */
108
- export function insertChunk(db, { source, kind, text, metadata = null, embedding, project = null, contentHash = null }) {
109
- if (!Array.isArray(embedding) && !ArrayBuffer.isView(embedding)) {
110
- throw new Error("insertChunk: embedding must be an array or typed array of floats");
111
- }
112
- const meta = metadata == null ? null : (typeof metadata === "string" ? metadata : JSON.stringify(metadata));
113
- const ins = db.prepare("INSERT INTO chunks (source, kind, text, metadata, project_slug, content_hash) VALUES (?, ?, ?, ?, ?, ?)");
114
- const info = ins.run(source, kind, text, meta, project, contentHash);
115
- // sqlite-vec's vec0 virtual table requires the rowid to arrive as a BigInt
116
- // even for values that comfortably fit in a Number. Better-sqlite3 returns
117
- // lastInsertRowid as BigInt only when safeIntegers mode is on; force it.
118
- const id = typeof info.lastInsertRowid === "bigint" ? info.lastInsertRowid : BigInt(info.lastInsertRowid);
119
- const buf = embedding instanceof Float32Array ? embedding : Float32Array.from(embedding);
120
- db.prepare("INSERT INTO vec_chunks(rowid, embedding) VALUES (?, ?)").run(id, Buffer.from(buf.buffer));
121
- return Number(id);
122
- }
123
-
124
- /**
125
- * Cosine-ordered nearest-neighbour search. Returns `[{ id, source, kind,
126
- * text, metadata, distance }]` for the topK best matches; lower
127
- * distance = closer. Returns `[]` when the store is empty.
128
- */
129
- export function searchSimilar(db, embedding, topK = 5, { kind = null, project = null, whereSql = "", whereParams = [] } = {}) {
130
- const buf = embedding instanceof Float32Array ? embedding : Float32Array.from(embedding);
131
- const kindClause = kind ? "AND c.kind = ?" : "";
132
- const projectClause = project ? "AND c.project_slug = ?" : "";
133
- const sql = `
134
- SELECT c.id, c.source, c.kind, c.text, c.metadata, c.project_slug, v.distance
135
- FROM vec_chunks v
136
- JOIN chunks c ON c.id = v.rowid
137
- WHERE v.embedding MATCH ? AND k = ? ${kindClause} ${projectClause}${whereSql}
138
- ORDER BY v.distance
139
- `;
140
- const params = [Buffer.from(buf.buffer), topK];
141
- if (kind) params.push(kind);
142
- if (project) params.push(project);
143
- if (whereParams.length) params.push(...whereParams);
144
- const rows = db.prepare(sql).all(...params);
145
- return rows.map((r) => ({ ...r, metadata: r.metadata ? safeParse(r.metadata) : null }));
146
- }
147
-
148
- /**
149
- * Normalize a projectDir into a stable slug used for project isolation.
150
- * Basename → lowercased → non-alphanumeric stripped to dashes.
151
- * KJC-TSK-0438.
152
- */
153
- export function projectSlug(projectDir) {
154
- if (!projectDir) return null;
155
- const base = String(projectDir).replace(/\/+$/, "").split("/").pop();
156
- if (!base) return null;
157
- return base.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "");
158
- }
159
-
160
- function safeParse(s) { try { return JSON.parse(s); } catch { return s; } }
161
-
162
- /**
163
- * Remove every chunk that came from a given source path. Both tables
164
- * are touched explicitly because vec0 virtual tables do not honour
165
- * SQLite foreign-key cascades.
166
- */
167
- export function deleteChunksBySource(db, source) {
168
- const ids = db.prepare("SELECT id FROM chunks WHERE source = ?").all(source).map((r) => r.id);
169
- if (ids.length === 0) return 0;
170
- const placeholders = ids.map(() => "?").join(",");
171
- db.prepare(`DELETE FROM vec_chunks WHERE rowid IN (${placeholders})`).run(...ids);
172
- db.prepare(`DELETE FROM chunks WHERE id IN (${placeholders})`).run(...ids);
173
- return ids.length;
174
- }
175
-
176
- // KJC-TSK-0455 — Per-project commit watermark for `kj rag index --since auto`
177
- // and the post-merge / pre-run drift hooks landing in PR2.
178
- export function getLastIndexedCommit(db, projectSlug) {
179
- if (!projectSlug) return null;
180
- const row = db.prepare("SELECT last_indexed_commit FROM vec_store_meta WHERE project_slug = ?").get(projectSlug);
181
- return row?.last_indexed_commit ?? null;
182
- }
183
-
184
- export function setLastIndexedCommit(db, projectSlug, commit) {
185
- if (!projectSlug || !commit) return;
186
- db.prepare(`
187
- INSERT INTO vec_store_meta (project_slug, last_indexed_commit, last_indexed_at)
188
- VALUES (?, ?, datetime('now'))
189
- ON CONFLICT(project_slug) DO UPDATE SET
190
- last_indexed_commit = excluded.last_indexed_commit,
191
- last_indexed_at = excluded.last_indexed_at
192
- `).run(projectSlug, commit);
193
- }
194
-
195
- // KJC-TSK-0484 PR-B — Bulk fetch embeddings for an explicit set of chunk ids.
196
- // Returns Map<id, Float32Array>. Used by MMR diversification in retriever.js.
197
- export function getEmbeddingsByIds(db, ids) {
198
- const out = new Map();
199
- if (!ids?.length) return out;
200
- const placeholders = ids.map(() => "?").join(",");
201
- const rows = db.prepare(`SELECT rowid AS id, embedding FROM vec_chunks WHERE rowid IN (${placeholders})`).all(...ids);
202
- for (const row of rows) {
203
- if (!row.embedding) continue;
204
- const buf = Buffer.isBuffer(row.embedding) ? row.embedding : Buffer.from(row.embedding);
205
- out.set(Number(row.id), new Float32Array(buf.buffer, buf.byteOffset, buf.byteLength / 4));
206
- }
207
- return out;
208
- }
209
-
210
- // KJC-TSK-0484 — Lookup an already-indexed chunk by content_hash. Scoped to a
211
- // project so two repos with the same boilerplate file don't cross-pollute.
212
- // Returns `{ id, source }` or null. Pass `project=null` to match NULL slugs.
213
- export function findChunkByHash(db, hash, project = null) {
214
- if (!hash) return null;
215
- const sql = project
216
- ? "SELECT id, source FROM chunks WHERE content_hash = ? AND project_slug = ? LIMIT 1"
217
- : "SELECT id, source FROM chunks WHERE content_hash = ? AND project_slug IS NULL LIMIT 1";
218
- const row = project ? db.prepare(sql).get(hash, project) : db.prepare(sql).get(hash);
219
- return row || null;
220
- }
221
-
222
- export function countChunks(db, { kind = null } = {}) {
223
- if (kind) return db.prepare("SELECT COUNT(*) AS n FROM chunks WHERE kind = ?").get(kind).n;
224
- return db.prepare("SELECT COUNT(*) AS n FROM chunks").get().n;
225
- }
226
-
227
- /**
228
- * KJC-TSK-0443 — BM25 keyword search over chunks_fts. Returns
229
- * [{ id, source, kind, text, metadata, project_slug, bm25 }] ordered by
230
- * relevance (lower bm25 = better in SQLite FTS5). `query` is sanitized for
231
- * the FTS5 grammar: special chars are stripped, words split on whitespace.
232
- */
233
- export function searchBM25(db, queryText, topK = 10, { kind = null, project = null, whereSql = "", whereParams = [] } = {}) {
234
- const cleaned = String(queryText || "").replace(/["'()]/g, " ").split(/\s+/).filter(Boolean).join(" OR ");
235
- if (!cleaned) return [];
236
- const kindClause = kind ? "AND c.kind = ?" : "";
237
- const projectClause = project ? "AND c.project_slug = ?" : "";
238
- const sql = `
239
- SELECT c.id, c.source, c.kind, c.text, c.metadata, c.project_slug, bm25(chunks_fts) AS bm25
240
- FROM chunks_fts JOIN chunks c ON c.id = chunks_fts.rowid
241
- WHERE chunks_fts MATCH ? ${kindClause} ${projectClause}${whereSql}
242
- ORDER BY bm25 LIMIT ?
243
- `;
244
- const params = [cleaned];
245
- if (kind) params.push(kind);
246
- if (project) params.push(project);
247
- if (whereParams.length) params.push(...whereParams);
248
- params.push(topK);
249
- try {
250
- const rows = db.prepare(sql).all(...params);
251
- return rows.map((r) => ({ ...r, metadata: r.metadata ? safeParse(r.metadata) : null }));
252
- } catch { return []; }
253
- }
1
+ // Shim: vec-store primitives now live in @karajan/core/vec-store so
2
+ // the hu-board workspace can consume them without a relative dep on the
3
+ // CLI src tree. KJC-TSK-0511 PR4.
4
+ export {
5
+ dbPath,
6
+ openVecStore,
7
+ insertChunk,
8
+ searchSimilar,
9
+ projectSlug,
10
+ deleteChunksBySource,
11
+ getLastIndexedCommit,
12
+ setLastIndexedCommit,
13
+ getEmbeddingsByIds,
14
+ findChunkByHash,
15
+ countChunks,
16
+ searchBM25,
17
+ } from "@karajan/core/vec-store";
@@ -9,6 +9,7 @@ import { collectSemgrepFindings } from "../audit/semgrep-findings.js";
9
9
  import { collectCircularDeps } from "../audit/circular-deps.js";
10
10
  import { collectDeadExports } from "../audit/dead-exports.js";
11
11
  import { collectInjectionFindings } from "../audit/injection-findings.js";
12
+ import { collectAiSlop } from "../audit/ai-slop-findings.js";
12
13
 
13
14
  function parseDimensions(dimensionsStr) {
14
15
  if (!dimensionsStr || dimensionsStr === "all") return null;
@@ -53,6 +54,7 @@ export class AuditRole extends AgentRole {
53
54
  const noMadge = typeof input === "object" ? Boolean(input?.noMadge) : false;
54
55
  const noKnip = typeof input === "object" ? Boolean(input?.noKnip) : false;
55
56
  const noInjectionScan = typeof input === "object" ? Boolean(input?.noInjectionScan) : false;
57
+ const noAiSlop = typeof input === "object" ? Boolean(input?.noAiSlop) : false;
56
58
  const projectDir = this.config?.projectDir || process.cwd();
57
59
  let basalCost = null;
58
60
  let growthDelta = null;
@@ -64,6 +66,7 @@ export class AuditRole extends AgentRole {
64
66
  let circularDeps = null;
65
67
  let deadExports = null;
66
68
  let injectionFindings = null;
69
+ let aiSlop = null;
67
70
  try {
68
71
  basalCost = await measureBasalCost(projectDir);
69
72
  const previous = await loadPreviousAudit(projectDir);
@@ -116,7 +119,14 @@ export class AuditRole extends AgentRole {
116
119
  injectionFindings = await collectInjectionFindings(projectDir, this.logger);
117
120
  } catch { /* injection scan is best-effort (KJC-TSK-0498) */ }
118
121
  }
119
- return { projectDir, basalCost, growthDelta, stack, sonarFindings, webperf, osvFindings, semgrepFindings, circularDeps, deadExports, injectionFindings };
122
+ // AI-slop tells (KJC-TSK-0503). Deterministic, offline, regex-based.
123
+ // Local equivalent of Deslopify-style review. Best-effort.
124
+ if (!noAiSlop) {
125
+ try {
126
+ aiSlop = await collectAiSlop(projectDir);
127
+ } catch { /* ai-slop scan is best-effort */ }
128
+ }
129
+ return { projectDir, basalCost, growthDelta, stack, sonarFindings, webperf, osvFindings, semgrepFindings, circularDeps, deadExports, injectionFindings, aiSlop };
120
130
  }
121
131
 
122
132
  /**
@@ -0,0 +1,48 @@
1
+ // ai-trash detection + Claude Code hook install (KJC-TSK-0391).
2
+ // `kj-trash` is the binary shipped by the @karajan/ai-trash workspace.
3
+ // detectAiTrash() probes the binary; installAiTrashHook() invokes
4
+ // `kj-trash install --claude-code`, which idempotently patches
5
+ // ~/.claude/settings.json to register the PreToolUse hook.
6
+
7
+ import { runCommand } from "./process.js";
8
+
9
+ /**
10
+ * @returns {Promise<{ available: boolean, version: string|null }>}
11
+ */
12
+ export async function detectAiTrash() {
13
+ try {
14
+ const res = await runCommand("kj-trash", ["--help"]);
15
+ if (res.exitCode === 0 || res.exitCode === 2) {
16
+ return { available: true, version: "0.0.0" };
17
+ }
18
+ return { available: false, version: null };
19
+ } catch {
20
+ return { available: false, version: null };
21
+ }
22
+ }
23
+
24
+ /**
25
+ * Register the kj-trash PreToolUse hook in ~/.claude/settings.json.
26
+ * Idempotent: second run reports "already installed" without rewriting.
27
+ *
28
+ * @param {object} logger - logger with info/warn methods
29
+ * @returns {Promise<{ ok: boolean, mutated: boolean, error: string|null }>}
30
+ */
31
+ export async function installAiTrashHook(logger) {
32
+ logger.info("Registering ai-trash Claude Code hook...");
33
+ try {
34
+ const res = await runCommand("kj-trash", ["install", "--claude-code"], { timeout: 30_000 });
35
+ if (res.exitCode !== 0) {
36
+ const error = (res.stderr || "").trim() || `exit code ${res.exitCode}`;
37
+ logger.warn(`ai-trash hook install failed: ${error}`);
38
+ return { ok: false, mutated: false, error };
39
+ }
40
+ const mutated = !(res.stdout || "").includes("already installed");
41
+ logger.info(mutated ? "ai-trash hook installed." : "ai-trash hook already installed.");
42
+ return { ok: true, mutated, error: null };
43
+ } catch (err) {
44
+ const error = err.message || String(err);
45
+ logger.warn(`ai-trash hook install failed: ${error}`);
46
+ return { ok: false, mutated: false, error };
47
+ }
48
+ }
@@ -1,43 +1,6 @@
1
- // Atomic JSON writes for persistent state (resilience audit, Phase 2).
2
- //
3
- // A plain `writeFile(path, JSON.stringify(...))` truncates the live file
4
- // before the new content lands. If the process is killed mid-write
5
- // (SIGKILL, crash, power loss) the file is left truncated and the only
6
- // good copy is already gone — the plan / session / standby JSON
7
- // silently corrupts.
8
- //
9
- // write-temp + rename fixes it: `rename` is atomic on the same
10
- // filesystem, so a reader sees either the old file or the complete new
11
- // one, never a half-written one. The temp file sits next to the target
12
- // (same dir → same FS) and is uniquely named so concurrent writers do
13
- // not clobber each other's temp. A crash before the rename leaves an
14
- // orphan `.tmp` but never a corrupt target.
15
-
16
- import { writeFileSync, renameSync } from "node:fs";
17
- import { writeFile, rename } from "node:fs/promises";
18
-
19
- function tempPath(target) {
20
- return `${target}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}.tmp`;
21
- }
22
-
23
- /**
24
- * Atomically write `obj` as pretty JSON to `target` (synchronous).
25
- * @param {string} target - destination path; its directory must exist
26
- * @param {unknown} obj
27
- */
28
- export function writeJsonAtomicSync(target, obj) {
29
- const tmp = tempPath(target);
30
- writeFileSync(tmp, JSON.stringify(obj, null, 2), "utf-8");
31
- renameSync(tmp, target);
32
- }
33
-
34
- /**
35
- * Atomically write `obj` as pretty JSON to `target` (async).
36
- * @param {string} target - destination path; its directory must exist
37
- * @param {unknown} obj
38
- */
39
- export async function writeJsonAtomic(target, obj) {
40
- const tmp = tempPath(target);
41
- await writeFile(tmp, JSON.stringify(obj, null, 2), "utf-8");
42
- await rename(tmp, target);
43
- }
1
+ // Shim — the real implementation now lives in @karajan/core/atomic-write.
2
+ // Kept here so CLI callers (src/**/*.js) keep importing
3
+ // "#utils/atomic-write.js" without churn during KJC-TSK-0511 (decouple
4
+ // @karajan/hu-board). Will be retired once every consumer migrates to
5
+ // the @karajan/core import.
6
+ export { writeJsonAtomic, writeJsonAtomicSync } from "@karajan/core/atomic-write";
@@ -0,0 +1,76 @@
1
+ import readline from "node:readline";
2
+
3
+ /**
4
+ * Shared askQuestion factory used by `kj run` and `kj resume`.
5
+ *
6
+ * Pre-fix (KJC-BUG-0081 round 1), `src/commands/run.js` got the guard
7
+ * but `src/commands/resume.js` kept its own copy without the guard, so
8
+ * `kj resume --yes` in non-TTY mode still hung on the HU Board bridge.
9
+ * Centralising the three paths here means both commands honour the
10
+ * same contract and a future fix only needs to land in one place.
11
+ *
12
+ * Three paths:
13
+ * 1. Interactive TTY: prompt via readline (developer terminal).
14
+ * 2. No TTY + `flags.yes`: caller asked NOT to be prompted → write
15
+ * question + context to stderr, return null so the run aborts
16
+ * fast and loud (CI / scripted / `kj audit --yes` desatendido).
17
+ * 3. No TTY without `flags.yes` (HU Board ▶ Run plan with
18
+ * `stdio=ignore`): publish through the file-based bridge so the
19
+ * board can surface a modal; block until the user answers.
20
+ *
21
+ * @param {object} [opts]
22
+ * @param {string|null} [opts.sessionId]
23
+ * @param {object} [opts.flags]
24
+ * @returns {(question: string, context?: object) => Promise<string|null>}
25
+ */
26
+ export function createCliAskQuestion(opts = {}) {
27
+ const { sessionId = null, flags = {} } = opts;
28
+ return async (question, context) => {
29
+ const stdinReadable = process.stdin && process.stdin.readable !== false;
30
+ const isInteractive = Boolean(process.stdin?.isTTY) && stdinReadable;
31
+ if (!isInteractive) {
32
+ if (flags?.yes) {
33
+ process.stderr.write(
34
+ `\n[non-interactive --yes] Pipeline asked a question that cannot be auto-answered:\n`
35
+ + ` ❓ ${question}\n`
36
+ + (context?.detail ? ` Context: ${JSON.stringify(context.detail)}\n` : "")
37
+ + ` Stopping the session. Re-run without --yes (TTY or HU Board) to answer it,\n`
38
+ + ` or pass --skip-spec-review / a more complete spec so the question never appears.\n`
39
+ );
40
+ return null;
41
+ }
42
+ const { askThroughBoard } = await import("./board-prompt-bridge.js");
43
+ console.log(`\n❓ ${question}`);
44
+ if (context?.detail) {
45
+ console.log(` Context: ${JSON.stringify(context.detail, null, 2)}`);
46
+ }
47
+ console.log(
48
+ "\n[non-interactive] Routing the prompt to the HU Board.\n"
49
+ + " Open http://localhost:4000 — a modal will appear asking for your answer.\n"
50
+ + " This process is now waiting; closing the board does NOT cancel the run."
51
+ );
52
+ try {
53
+ return await askThroughBoard({ sessionId, question, context });
54
+ } catch (err) {
55
+ console.log(`\n[prompt-bridge] ${err.message} — stopping the session.`);
56
+ return null;
57
+ }
58
+ }
59
+
60
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
61
+ return new Promise((resolve) => {
62
+ console.log(`\n❓ ${question}`);
63
+ if (context?.detail) {
64
+ console.log(` Context: ${JSON.stringify(context.detail, null, 2)}`);
65
+ }
66
+ rl.question("\n> Your response (or 'stop' to exit): ", (answer) => {
67
+ rl.close();
68
+ if (answer.trim().toLowerCase() === "stop") {
69
+ resolve(null);
70
+ } else {
71
+ resolve(answer.trim());
72
+ }
73
+ });
74
+ });
75
+ };
76
+ }
@@ -15,6 +15,8 @@ const ERROR_DOCS = {
15
15
  config_missing: `${BASE_URL}/getting-started/quick-start/`,
16
16
  branch_error: `${BASE_URL}/guides/pipeline/#git-workflow`,
17
17
  rtk_install: `${BASE_URL}/guides/configuration/#rtk`,
18
+ squeezr_install: `${BASE_URL}/guides/configuration/#squeezr`,
19
+ qmd_install: `${BASE_URL}/guides/configuration/#qmd`,
18
20
  };
19
21
 
20
22
  export function docLink(errorType) {
@@ -16,6 +16,16 @@ const INSTALL_COMMANDS = {
16
16
  linux: "curl -fsSL https://raw.githubusercontent.com/rtk-ai/rtk/refs/heads/master/install.sh | sh && rtk init --global",
17
17
  windows: "Download from https://github.com/rtk-ai/rtk/releases and add to PATH"
18
18
  },
19
+ squeezr: {
20
+ macos: "npm install -g squeezr-ai",
21
+ linux: "npm install -g squeezr-ai",
22
+ windows: "npm install -g squeezr-ai"
23
+ },
24
+ qmd: {
25
+ macos: "npm install -g @tobilu/qmd",
26
+ linux: "npm install -g @tobilu/qmd",
27
+ windows: "npm install -g @tobilu/qmd"
28
+ },
19
29
  claude: {
20
30
  macos: "npm install -g @anthropic-ai/claude-code",
21
31
  linux: "npm install -g @anthropic-ai/claude-code",
@@ -1,123 +1,14 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
-
5
- // Per-process vitest root. We memoise the *root* (not the suffixed
6
- // `.karajan` / `.kj` path) so callers with different legacy defaults
7
- // — plan-store wants `.kj`, db.js wants `.karajan` — can share one
8
- // random tmp prefix per test run without colliding.
9
- let _vitestRoot = null;
10
- function vitestRoot() {
11
- if (_vitestRoot) return _vitestRoot;
12
- _vitestRoot = path.join(
13
- os.tmpdir(),
14
- `karajan-vitest-${process.pid}-${Math.random().toString(36).slice(2, 10)}`
15
- );
16
- // KJC-BUG-0075: clean up on clean exit so /tmp doesn't accumulate one
17
- // dir per fork × run. `process.on('exit')` runs synchronously and only
18
- // for graceful exits — SIGKILL leaks survive but are caught by the
19
- // global-setup mtime purge at the start of the next run.
20
- process.on("exit", () => {
21
- try {
22
- fs.rmSync(_vitestRoot, { recursive: true, force: true });
23
- } catch {
24
- // best-effort: never crash a test process on cleanup failure
25
- }
26
- });
27
- return _vitestRoot;
28
- }
29
-
30
- function vitestTmpHome(defaultSegment) {
31
- return path.join(vitestRoot(), defaultSegment);
32
- }
33
-
34
- // One-shot warning so users with KJ_HOME set in their shell rcfile do
35
- // not get spammed once per `kj` invocation. Reset across processes,
36
- // which is the granularity that matters for a humans-reading-stderr
37
- // audience.
38
- let _kjHomeWarned = false;
39
- function emitKjHomeDeprecationWarning() {
40
- if (_kjHomeWarned) return;
41
- _kjHomeWarned = true;
42
- // eslint-disable-next-line no-console
43
- console.warn(
44
- "\x1b[33m[warn]\x1b[0m KJ_HOME is deprecated, rename to KARAJAN_HOME (KJ_HOME will be removed in a future release)"
45
- );
46
- }
47
-
48
- /**
49
- * Unified resolver for Karajan's HOME-level storage root. Used by every
50
- * helper that previously rolled its own `getKjHome()` with subtly
51
- * different defaults and VITEST handling.
52
- *
53
- * Precedence (highest first):
54
- * 1. KARAJAN_HOME env var — explicit, no warning
55
- * 2. KJ_HOME env var — explicit, prints deprecation warning once
56
- * 3. VITEST tmp dir — auto-isolation under `os.tmpdir()/karajan-vitest-<pid>-<rand>/<defaultSegment>`
57
- * 4. `~/<defaultSegment>` — production default
58
- *
59
- * Callers pass `defaultSegment` so we can preserve `.kj` for legacy
60
- * paths (plan-store, standby-store) and `.karajan` for the canonical
61
- * root, until PR 3 unifies the defaults too.
62
- *
63
- * @param {object} [options]
64
- * @param {string} [options.defaultSegment=".karajan"] HOME subdir name
65
- * @returns {string} absolute path
66
- */
67
- export function resolveHome({ defaultSegment = ".karajan" } = {}) {
68
- if (process.env.KARAJAN_HOME) {
69
- return path.resolve(process.env.KARAJAN_HOME);
70
- }
71
- if (process.env.KJ_HOME) {
72
- emitKjHomeDeprecationWarning();
73
- return path.resolve(process.env.KJ_HOME);
74
- }
75
- if (process.env.VITEST) {
76
- return vitestTmpHome(defaultSegment);
77
- }
78
- return path.join(os.homedir(), defaultSegment);
79
- }
80
-
81
- /**
82
- * Canonical Karajan home (`~/.karajan` by default). Every helper that
83
- * used to roll its own `getKjHome()` now goes through this one — see
84
- * KJC-PCS-0047 PR 3 for the consolidation.
85
- */
86
- export function getKarajanHome() {
87
- return resolveHome({ defaultSegment: ".karajan" });
88
- }
89
-
90
- // Test-only export. Tests that depend on observing the deprecation
91
- // warning being emitted exactly once need to reset the latch between
92
- // cases.
93
- export function __resetKjHomeWarningForTests() {
94
- _kjHomeWarned = false;
95
- }
96
-
97
- export function getSessionRoot() {
98
- return path.join(getKarajanHome(), "sessions");
99
- }
100
-
101
- export function getSonarComposePath() {
102
- return path.join(getKarajanHome(), "docker-compose.sonar.yml");
103
- }
104
-
105
- /** Ollama RAG embedder compose: `<karajan-home>/docker-compose.ollama.yml` — KJC-TSK-0435. */
106
- export function getOllamaComposePath() {
107
- return path.join(getKarajanHome(), "docker-compose.ollama.yml");
108
- }
109
-
110
- /** Webperf cache: `<karajan-home>/webperf/` — KJC-TSK-0420. */
111
- export function getWebperfDir() {
112
- return path.join(getKarajanHome(), "webperf");
113
- }
114
-
115
- /** Run-registry: `<karajan-home>/runs/` — KJC-TSK-0420. */
116
- export function getRunsDir() {
117
- return path.join(getKarajanHome(), "runs");
118
- }
119
-
120
- /** Board prompt bridge: `<karajan-home>/prompts/` — KJC-TSK-0420. */
121
- export function getPromptsDir() {
122
- return path.join(getKarajanHome(), "prompts");
123
- }
1
+ // Shim: paths primitives now live in @karajan/core/paths so the
2
+ // hu-board workspace can consume them without a relative dep on the
3
+ // CLI src tree. KJC-TSK-0511 PR3.
4
+ export {
5
+ resolveHome,
6
+ getKarajanHome,
7
+ __resetKjHomeWarningForTests,
8
+ getSessionRoot,
9
+ getSonarComposePath,
10
+ getOllamaComposePath,
11
+ getWebperfDir,
12
+ getRunsDir,
13
+ getPromptsDir,
14
+ } from "@karajan/core/paths";