@crewhaus/runtime-core 0.1.4 → 0.1.5
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/cli-markdown.d.ts +56 -0
- package/dist/cli-markdown.js +164 -0
- package/dist/index.d.ts +368 -0
- package/dist/index.js +1976 -0
- package/dist/observability.d.ts +38 -0
- package/dist/observability.js +69 -0
- package/dist/project-memory.d.ts +28 -0
- package/dist/project-memory.js +104 -0
- package/package.json +46 -43
- package/src/cli-markdown.test.ts +0 -207
- package/src/cli-markdown.ts +0 -190
- package/src/cost-inline.test.ts +0 -58
- package/src/cost-persist.test.ts +0 -113
- package/src/cost-wire-model.test.ts +0 -138
- package/src/index-coverage.test.ts +0 -1671
- package/src/index.test.ts +0 -2471
- package/src/index.ts +0 -2365
- package/src/observability-coverage.test.ts +0 -303
- package/src/observability.test.ts +0 -138
- package/src/observability.ts +0 -116
- package/src/project-memory-coverage.test.ts +0 -119
- package/src/project-memory.test.ts +0 -145
- package/src/project-memory.ts +0 -134
- package/src/tenant-isolation.test.ts +0 -80
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { type CostTracker } from "@crewhaus/cost-tracker";
|
|
2
|
+
import { type AttachedMetrics } from "@crewhaus/metrics-collector";
|
|
3
|
+
import { type AttachedOtelExporter } from "@crewhaus/otel-exporter";
|
|
4
|
+
/**
|
|
5
|
+
* Section 15 — attach the default observability subscribers to a
|
|
6
|
+
* `TraceEventBus` based on environment variables. Returns a single `flushAll`
|
|
7
|
+
* the orchestrator awaits in its `finally` block.
|
|
8
|
+
*
|
|
9
|
+
* CREWHAUS_TRACE=pretty|json → structured-event-printer
|
|
10
|
+
* CREWHAUS_METRICS=stdout|... → metrics-collector (buffered stdout JSON / textfile / http)
|
|
11
|
+
* OTEL_EXPORTER_OTLP_ENDPOINT → otel-exporter (OTLP/HTTP, gen_ai/* attributes)
|
|
12
|
+
* CREWHAUS_COST_TRACKING=1 → cost-tracker (Section 27 — emits cost_accrual events)
|
|
13
|
+
* CREWHAUS_COST_INLINE=1 → CLI inline cost line per turn (requires CREWHAUS_COST_TRACKING)
|
|
14
|
+
*
|
|
15
|
+
* All are opt-in. With no env vars set this function returns a no-op
|
|
16
|
+
* `flushAll` so observability adds zero output and zero overhead.
|
|
17
|
+
*/
|
|
18
|
+
import type { RunContext } from "@crewhaus/run-context";
|
|
19
|
+
import { type AttachedPrinter } from "@crewhaus/structured-event-printer";
|
|
20
|
+
import type { CostAccrualEvent, TraceEventBus, Unsubscribe } from "@crewhaus/trace-event-bus";
|
|
21
|
+
export type AttachedSubscribers = {
|
|
22
|
+
printer: AttachedPrinter | undefined;
|
|
23
|
+
metrics: AttachedMetrics | undefined;
|
|
24
|
+
otel: AttachedOtelExporter | undefined;
|
|
25
|
+
costTracker: CostTracker | undefined;
|
|
26
|
+
costInlineUnsubscribe: Unsubscribe | undefined;
|
|
27
|
+
flushAll(): Promise<void>;
|
|
28
|
+
shutdownAll(): Promise<void>;
|
|
29
|
+
};
|
|
30
|
+
/**
|
|
31
|
+
* Format a single `cost_accrual` event as a one-line CLI status:
|
|
32
|
+
* `[💸 $0.0042 · 12.3k in / 1.1k out · model=claude-sonnet-4-6]`
|
|
33
|
+
*
|
|
34
|
+
* Exported so target-cli's emitted bundle can render the same format
|
|
35
|
+
* without re-implementing it.
|
|
36
|
+
*/
|
|
37
|
+
export declare function formatCostInlineLine(ev: CostAccrualEvent): string;
|
|
38
|
+
export declare function attachDefaultSubscribers(bus: TraceEventBus, runContext: RunContext, env?: NodeJS.ProcessEnv): Promise<AttachedSubscribers>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { createCostTracker, formatUsdMicros } from "@crewhaus/cost-tracker";
|
|
2
|
+
import { attachIfEnvSet as attachMetricsIfEnvSet, } from "@crewhaus/metrics-collector";
|
|
3
|
+
import { attachIfEnvSet as attachOtelIfEnvSet, } from "@crewhaus/otel-exporter";
|
|
4
|
+
import { attachIfEnvSet as attachPrinterIfEnvSet, } from "@crewhaus/structured-event-printer";
|
|
5
|
+
/**
|
|
6
|
+
* Format a single `cost_accrual` event as a one-line CLI status:
|
|
7
|
+
* `[💸 $0.0042 · 12.3k in / 1.1k out · model=claude-sonnet-4-6]`
|
|
8
|
+
*
|
|
9
|
+
* Exported so target-cli's emitted bundle can render the same format
|
|
10
|
+
* without re-implementing it.
|
|
11
|
+
*/
|
|
12
|
+
export function formatCostInlineLine(ev) {
|
|
13
|
+
const cost = formatUsdMicros(ev.costUsdMicros);
|
|
14
|
+
const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
|
|
15
|
+
return `[💸 ${cost} · ${fmtTokens(ev.inputTokens)} in / ${fmtTokens(ev.outputTokens)} out · model=${ev.modelId}]`;
|
|
16
|
+
}
|
|
17
|
+
export async function attachDefaultSubscribers(bus, runContext, env = process.env) {
|
|
18
|
+
const printer = attachPrinterIfEnvSet(bus, env);
|
|
19
|
+
const metrics = await attachMetricsIfEnvSet(bus, env);
|
|
20
|
+
const otel = attachOtelIfEnvSet(bus, env);
|
|
21
|
+
const costTracker = env["CREWHAUS_COST_TRACKING"] === "1" || env["CREWHAUS_COST_TRACKING"] === "true"
|
|
22
|
+
? createCostTracker(bus, {
|
|
23
|
+
...(env["CREWHAUS_TENANT_ID"] !== undefined
|
|
24
|
+
? { tenantId: env["CREWHAUS_TENANT_ID"] }
|
|
25
|
+
: {}),
|
|
26
|
+
})
|
|
27
|
+
: undefined;
|
|
28
|
+
// CLI inline cost line — opt-in via CREWHAUS_COST_INLINE=1. Subscribes to
|
|
29
|
+
// the `cost_accrual` events that cost-tracker emits, prints one tidy line
|
|
30
|
+
// per accrual, and stays out of the trace bus's main printer surface so
|
|
31
|
+
// it doesn't double-print when CREWHAUS_TRACE=pretty is also set.
|
|
32
|
+
const costInlineEnabled = (env["CREWHAUS_COST_INLINE"] === "1" || env["CREWHAUS_COST_INLINE"] === "true") &&
|
|
33
|
+
costTracker !== undefined;
|
|
34
|
+
let costInlineUnsubscribe;
|
|
35
|
+
if (costInlineEnabled) {
|
|
36
|
+
const handler = (event) => {
|
|
37
|
+
if (event.kind !== "cost_accrual")
|
|
38
|
+
return;
|
|
39
|
+
process.stdout.write(`${formatCostInlineLine(event)}\n`);
|
|
40
|
+
};
|
|
41
|
+
costInlineUnsubscribe = bus.subscribe(handler);
|
|
42
|
+
}
|
|
43
|
+
const flushAll = async () => {
|
|
44
|
+
printer?.finalize();
|
|
45
|
+
const tasks = [];
|
|
46
|
+
if (metrics)
|
|
47
|
+
tasks.push(metrics.flush().catch((err) => logFlushError(runContext, "metrics", err)));
|
|
48
|
+
if (otel)
|
|
49
|
+
tasks.push(otel.flush().catch((err) => logFlushError(runContext, "otel", err)));
|
|
50
|
+
tasks.push(bus.flush().catch((err) => logFlushError(runContext, "bus", err)));
|
|
51
|
+
await Promise.all(tasks);
|
|
52
|
+
};
|
|
53
|
+
const shutdownAll = async () => {
|
|
54
|
+
printer?.unsubscribe();
|
|
55
|
+
if (metrics) {
|
|
56
|
+
await metrics.shutdown().catch((err) => logFlushError(runContext, "metrics", err));
|
|
57
|
+
}
|
|
58
|
+
if (otel) {
|
|
59
|
+
await otel.shutdown().catch((err) => logFlushError(runContext, "otel", err));
|
|
60
|
+
}
|
|
61
|
+
costTracker?.unsubscribe();
|
|
62
|
+
costInlineUnsubscribe?.();
|
|
63
|
+
};
|
|
64
|
+
return { printer, metrics, otel, costTracker, costInlineUnsubscribe, flushAll, shutdownAll };
|
|
65
|
+
}
|
|
66
|
+
function logFlushError(runContext, name, err) {
|
|
67
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
68
|
+
runContext.logger.error("observability.flush_failed", { name, message });
|
|
69
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export declare const CANONICAL_MEMORY_FILES: readonly ["AGENTS.md", "CLAUDE.md", "CODE-COMPANION.md", "AGENT.md"];
|
|
2
|
+
export declare const DEFAULT_PROJECT_MEMORY_CAP_BYTES: number;
|
|
3
|
+
export interface ProjectMemoryLoadOptions {
|
|
4
|
+
/** Override cwd. Defaults to `process.cwd()`. */
|
|
5
|
+
readonly cwd?: string;
|
|
6
|
+
/** Override the filename list. Defaults to `CANONICAL_MEMORY_FILES`. */
|
|
7
|
+
readonly filenames?: readonly string[];
|
|
8
|
+
/** Maximum total bytes across all loaded files. Defaults to 64 KB. */
|
|
9
|
+
readonly capBytes?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface LoadedMemoryFile {
|
|
12
|
+
readonly filename: string;
|
|
13
|
+
readonly content: string;
|
|
14
|
+
readonly truncated: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface ProjectMemoryLoadResult {
|
|
17
|
+
readonly files: readonly LoadedMemoryFile[];
|
|
18
|
+
/** Total content bytes across all files (post-truncation). */
|
|
19
|
+
readonly totalBytes: number;
|
|
20
|
+
/** Wrapped + concatenated content ready to prepend to the system prompt. */
|
|
21
|
+
readonly prompt: string;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Scan cwd for project-memory files and return the rendered prompt block.
|
|
25
|
+
* Returns `{ files: [], prompt: "" }` when no files matched — caller can
|
|
26
|
+
* conditionally skip the prepend without a length check.
|
|
27
|
+
*/
|
|
28
|
+
export declare function loadProjectMemory(opts?: ProjectMemoryLoadOptions): Promise<ProjectMemoryLoadResult>;
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Auto-loaded project memory — M3.1 of the heavy-hitter plan.
|
|
3
|
+
*
|
|
4
|
+
* At session-start, the runtime looks for canonical "project memory"
|
|
5
|
+
* files in the current working directory and prepends their contents
|
|
6
|
+
* to the system prompt. Follows the vendor-neutral agents.md convention
|
|
7
|
+
* (https://agents.md) and is compatible with Claude Code's CLAUDE.md
|
|
8
|
+
* auto-load behaviour.
|
|
9
|
+
*
|
|
10
|
+
* Files searched (in priority order, all matches are loaded):
|
|
11
|
+
* - AGENTS.md (vendor-neutral convention — agents.md)
|
|
12
|
+
* - CLAUDE.md (Claude Code convention)
|
|
13
|
+
* - CODE-COMPANION.md (hello-code demo convention)
|
|
14
|
+
* - AGENT.md (legacy singular form; retained for compatibility)
|
|
15
|
+
*
|
|
16
|
+
* Each file's contents are wrapped in:
|
|
17
|
+
* <project_memory file="AGENTS.md">
|
|
18
|
+
* ...contents...
|
|
19
|
+
* </project_memory>
|
|
20
|
+
*
|
|
21
|
+
* Multiple files concatenate with blank-line separators.
|
|
22
|
+
*
|
|
23
|
+
* Pillar 3 — Security fabric: every file's contents are classified via
|
|
24
|
+
* `boundary-classifier` with origin `"user"` (the developer owns their
|
|
25
|
+
* repo). The user-origin default policy is `"pass"`, so classification
|
|
26
|
+
* RUNS (and logs trace events) without blocking — which is the right
|
|
27
|
+
* stance for a developer-trusted source. If a future deployment wants
|
|
28
|
+
* strict policy on these files, pass `severity: "block"` via opts.
|
|
29
|
+
*
|
|
30
|
+
* Size cap: 64 KB total across all matched files. Larger files load
|
|
31
|
+
* the first N bytes plus a `[...truncated]` notice — the prompt cache
|
|
32
|
+
* is more valuable than the tail of a large memory file.
|
|
33
|
+
*/
|
|
34
|
+
import { existsSync } from "node:fs";
|
|
35
|
+
import { readFile, stat } from "node:fs/promises";
|
|
36
|
+
import { join } from "node:path";
|
|
37
|
+
import { classifyBoundary } from "@crewhaus/boundary-classifier";
|
|
38
|
+
export const CANONICAL_MEMORY_FILES = [
|
|
39
|
+
"AGENTS.md",
|
|
40
|
+
"CLAUDE.md",
|
|
41
|
+
"CODE-COMPANION.md",
|
|
42
|
+
"AGENT.md",
|
|
43
|
+
];
|
|
44
|
+
export const DEFAULT_PROJECT_MEMORY_CAP_BYTES = 64 * 1024;
|
|
45
|
+
/**
|
|
46
|
+
* Scan cwd for project-memory files and return the rendered prompt block.
|
|
47
|
+
* Returns `{ files: [], prompt: "" }` when no files matched — caller can
|
|
48
|
+
* conditionally skip the prepend without a length check.
|
|
49
|
+
*/
|
|
50
|
+
export async function loadProjectMemory(opts = {}) {
|
|
51
|
+
const cwd = opts.cwd ?? process.cwd();
|
|
52
|
+
const filenames = opts.filenames ?? CANONICAL_MEMORY_FILES;
|
|
53
|
+
const cap = opts.capBytes ?? DEFAULT_PROJECT_MEMORY_CAP_BYTES;
|
|
54
|
+
const matched = [];
|
|
55
|
+
for (const filename of filenames) {
|
|
56
|
+
const fullPath = join(cwd, filename);
|
|
57
|
+
if (!existsSync(fullPath))
|
|
58
|
+
continue;
|
|
59
|
+
try {
|
|
60
|
+
const st = await stat(fullPath);
|
|
61
|
+
if (!st.isFile())
|
|
62
|
+
continue;
|
|
63
|
+
matched.push({ filename, fullPath, size: st.size });
|
|
64
|
+
}
|
|
65
|
+
catch { }
|
|
66
|
+
}
|
|
67
|
+
if (matched.length === 0) {
|
|
68
|
+
return { files: [], totalBytes: 0, prompt: "" };
|
|
69
|
+
}
|
|
70
|
+
const files = [];
|
|
71
|
+
let remaining = cap;
|
|
72
|
+
for (const m of matched) {
|
|
73
|
+
if (remaining <= 0)
|
|
74
|
+
break;
|
|
75
|
+
let content;
|
|
76
|
+
try {
|
|
77
|
+
content = await readFile(m.fullPath, "utf-8");
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
let truncated = false;
|
|
83
|
+
const contentBytes = Buffer.byteLength(content, "utf8");
|
|
84
|
+
if (contentBytes > remaining) {
|
|
85
|
+
// Truncate at the byte cap, then append a notice.
|
|
86
|
+
const buf = Buffer.from(content, "utf-8").subarray(0, remaining);
|
|
87
|
+
content = `${buf.toString("utf-8")}\n\n[...truncated to ${remaining} bytes; ${contentBytes - remaining} bytes omitted]`;
|
|
88
|
+
truncated = true;
|
|
89
|
+
}
|
|
90
|
+
// Pillar 3: classify with origin "user" — `pass` policy runs the
|
|
91
|
+
// classifier and emits trace events without modifying content.
|
|
92
|
+
await classifyBoundary(content, { origin: "user" }).catch(() => undefined);
|
|
93
|
+
files.push({ filename: m.filename, content, truncated });
|
|
94
|
+
remaining -= Buffer.byteLength(content, "utf8");
|
|
95
|
+
}
|
|
96
|
+
const sections = files
|
|
97
|
+
.map((f) => `<project_memory file="${f.filename}">\n${f.content}\n</project_memory>`)
|
|
98
|
+
.join("\n\n");
|
|
99
|
+
return {
|
|
100
|
+
files,
|
|
101
|
+
totalBytes: files.reduce((sum, f) => sum + Buffer.byteLength(f.content, "utf8"), 0),
|
|
102
|
+
prompt: sections,
|
|
103
|
+
};
|
|
104
|
+
}
|
package/package.json
CHANGED
|
@@ -1,59 +1,62 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@crewhaus/runtime-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Minimal runtime imported by generated harness bundles",
|
|
6
|
-
"main": "
|
|
7
|
-
"types": "
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
8
|
"exports": {
|
|
9
|
-
".":
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
}
|
|
10
13
|
},
|
|
11
14
|
"scripts": {
|
|
12
15
|
"test": "bun test src"
|
|
13
16
|
},
|
|
14
17
|
"dependencies": {
|
|
15
18
|
"@anthropic-ai/sdk": "^0.96.0",
|
|
16
|
-
"@crewhaus/abort-controller": "0.1.
|
|
17
|
-
"@crewhaus/adapter-anthropic": "0.1.
|
|
18
|
-
"@crewhaus/agent-context-isolation": "0.1.
|
|
19
|
-
"@crewhaus/boundary-classifier": "0.1.
|
|
20
|
-
"@crewhaus/circuit-breaker": "0.1.
|
|
21
|
-
"@crewhaus/compaction-autocompact": "0.1.
|
|
22
|
-
"@crewhaus/compaction-snip": "0.1.
|
|
23
|
-
"@crewhaus/cost-tracker": "0.1.
|
|
24
|
-
"@crewhaus/egress-classifier": "0.1.
|
|
25
|
-
"@crewhaus/errors": "0.1.
|
|
26
|
-
"@crewhaus/event-log": "0.1.
|
|
27
|
-
"@crewhaus/hooks-engine": "0.1.
|
|
28
|
-
"@crewhaus/model-router": "0.1.
|
|
29
|
-
"@crewhaus/permission-engine": "0.1.
|
|
30
|
-
"@crewhaus/prompt-cache-manager": "0.1.
|
|
31
|
-
"@crewhaus/prompt-injection-detector": "0.1.
|
|
32
|
-
"@crewhaus/rate-limiter": "0.1.
|
|
33
|
-
"@crewhaus/recovery-engine": "0.1.
|
|
34
|
-
"@crewhaus/run-context": "0.1.
|
|
35
|
-
"@crewhaus/session-store": "0.1.
|
|
36
|
-
"@crewhaus/skills-registry": "0.1.
|
|
37
|
-
"@crewhaus/slash-commands": "0.1.
|
|
38
|
-
"@crewhaus/state-store": "0.1.
|
|
39
|
-
"@crewhaus/tenancy": "0.1.
|
|
40
|
-
"@crewhaus/token-budget": "0.1.
|
|
41
|
-
"@crewhaus/tool-catalog": "0.1.
|
|
42
|
-
"@crewhaus/tool-executor": "0.1.
|
|
43
|
-
"@crewhaus/tool-loop-detection": "0.1.
|
|
44
|
-
"@crewhaus/tool-orchestrator": "0.1.
|
|
45
|
-
"@crewhaus/tool-result-store": "0.1.
|
|
46
|
-
"@crewhaus/streaming-tool-executor": "0.1.
|
|
47
|
-
"@crewhaus/turn-state-machine": "0.1.
|
|
48
|
-
"@crewhaus/trace-event-bus": "0.1.
|
|
49
|
-
"@crewhaus/structured-event-printer": "0.1.
|
|
50
|
-
"@crewhaus/metrics-collector": "0.1.
|
|
51
|
-
"@crewhaus/otel-exporter": "0.1.
|
|
19
|
+
"@crewhaus/abort-controller": "0.1.5",
|
|
20
|
+
"@crewhaus/adapter-anthropic": "0.1.5",
|
|
21
|
+
"@crewhaus/agent-context-isolation": "0.1.5",
|
|
22
|
+
"@crewhaus/boundary-classifier": "0.1.5",
|
|
23
|
+
"@crewhaus/circuit-breaker": "0.1.5",
|
|
24
|
+
"@crewhaus/compaction-autocompact": "0.1.5",
|
|
25
|
+
"@crewhaus/compaction-snip": "0.1.5",
|
|
26
|
+
"@crewhaus/cost-tracker": "0.1.5",
|
|
27
|
+
"@crewhaus/egress-classifier": "0.1.5",
|
|
28
|
+
"@crewhaus/errors": "0.1.5",
|
|
29
|
+
"@crewhaus/event-log": "0.1.5",
|
|
30
|
+
"@crewhaus/hooks-engine": "0.1.5",
|
|
31
|
+
"@crewhaus/model-router": "0.1.5",
|
|
32
|
+
"@crewhaus/permission-engine": "0.1.5",
|
|
33
|
+
"@crewhaus/prompt-cache-manager": "0.1.5",
|
|
34
|
+
"@crewhaus/prompt-injection-detector": "0.1.5",
|
|
35
|
+
"@crewhaus/rate-limiter": "0.1.5",
|
|
36
|
+
"@crewhaus/recovery-engine": "0.1.5",
|
|
37
|
+
"@crewhaus/run-context": "0.1.5",
|
|
38
|
+
"@crewhaus/session-store": "0.1.5",
|
|
39
|
+
"@crewhaus/skills-registry": "0.1.5",
|
|
40
|
+
"@crewhaus/slash-commands": "0.1.5",
|
|
41
|
+
"@crewhaus/state-store": "0.1.5",
|
|
42
|
+
"@crewhaus/tenancy": "0.1.5",
|
|
43
|
+
"@crewhaus/token-budget": "0.1.5",
|
|
44
|
+
"@crewhaus/tool-catalog": "0.1.5",
|
|
45
|
+
"@crewhaus/tool-executor": "0.1.5",
|
|
46
|
+
"@crewhaus/tool-loop-detection": "0.1.5",
|
|
47
|
+
"@crewhaus/tool-orchestrator": "0.1.5",
|
|
48
|
+
"@crewhaus/tool-result-store": "0.1.5",
|
|
49
|
+
"@crewhaus/streaming-tool-executor": "0.1.5",
|
|
50
|
+
"@crewhaus/turn-state-machine": "0.1.5",
|
|
51
|
+
"@crewhaus/trace-event-bus": "0.1.5",
|
|
52
|
+
"@crewhaus/structured-event-printer": "0.1.5",
|
|
53
|
+
"@crewhaus/metrics-collector": "0.1.5",
|
|
54
|
+
"@crewhaus/otel-exporter": "0.1.5",
|
|
52
55
|
"zod-to-json-schema": "^3.23.5"
|
|
53
56
|
},
|
|
54
57
|
"devDependencies": {
|
|
55
|
-
"@crewhaus/logging": "0.1.
|
|
56
|
-
"@crewhaus/tool-builder": "0.1.
|
|
58
|
+
"@crewhaus/logging": "0.1.5",
|
|
59
|
+
"@crewhaus/tool-builder": "0.1.5",
|
|
57
60
|
"zod": "^3.23.8"
|
|
58
61
|
},
|
|
59
62
|
"license": "Apache-2.0",
|
|
@@ -74,5 +77,5 @@
|
|
|
74
77
|
"publishConfig": {
|
|
75
78
|
"access": "public"
|
|
76
79
|
},
|
|
77
|
-
"files": ["
|
|
80
|
+
"files": ["dist", "README.md", "LICENSE", "NOTICE"]
|
|
78
81
|
}
|
package/src/cli-markdown.test.ts
DELETED
|
@@ -1,207 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Unit tests for the CLI markdown → ANSI streaming renderer.
|
|
3
|
-
* Covers: streaming buffer + flush, headings, lists, code fences,
|
|
4
|
-
* inline bold/italic/code, blockquotes, and graceful handling of
|
|
5
|
-
* tokens split across chunks.
|
|
6
|
-
*/
|
|
7
|
-
import { describe, expect, spyOn, test } from "bun:test";
|
|
8
|
-
import { createCliMarkdownRenderer, isCliMarkdownEnabled } from "./cli-markdown";
|
|
9
|
-
|
|
10
|
-
function capture(): { write: (s: string) => void; out: () => string } {
|
|
11
|
-
let buf = "";
|
|
12
|
-
return {
|
|
13
|
-
write: (s: string) => {
|
|
14
|
-
buf += s;
|
|
15
|
-
},
|
|
16
|
-
out: () => buf,
|
|
17
|
-
};
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
// Strip ANSI escape sequences so we can assert on plain content
|
|
21
|
-
// while still letting other tests verify the escape codes are present.
|
|
22
|
-
function strip(s: string): string {
|
|
23
|
-
// biome-ignore lint/suspicious/noControlCharactersInRegex: ANSI escape detection is intentional — the renderer's output IS the control sequences we want to strip.
|
|
24
|
-
return s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
describe("createCliMarkdownRenderer", () => {
|
|
28
|
-
test("plain text passes through line by line", () => {
|
|
29
|
-
const c = capture();
|
|
30
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
31
|
-
r.push("hello\nworld\n");
|
|
32
|
-
expect(c.out()).toBe("hello\nworld\n");
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
test("incomplete line is buffered, flushed by end()", () => {
|
|
36
|
-
const c = capture();
|
|
37
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
38
|
-
r.push("partial");
|
|
39
|
-
expect(c.out()).toBe("");
|
|
40
|
-
r.end();
|
|
41
|
-
expect(c.out()).toBe("partial");
|
|
42
|
-
});
|
|
43
|
-
|
|
44
|
-
test("bold renders with ANSI bold", () => {
|
|
45
|
-
const c = capture();
|
|
46
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
47
|
-
r.push("hello **world** done\n");
|
|
48
|
-
expect(c.out()).toContain("\x1b[1m");
|
|
49
|
-
expect(strip(c.out())).toBe("hello world done\n");
|
|
50
|
-
});
|
|
51
|
-
|
|
52
|
-
test("italic with single asterisks", () => {
|
|
53
|
-
const c = capture();
|
|
54
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
55
|
-
r.push("the *quick* fox\n");
|
|
56
|
-
expect(c.out()).toContain("\x1b[3m");
|
|
57
|
-
expect(strip(c.out())).toBe("the quick fox\n");
|
|
58
|
-
});
|
|
59
|
-
|
|
60
|
-
test("inline code preserves backticks", () => {
|
|
61
|
-
const c = capture();
|
|
62
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
63
|
-
r.push("use `npm install` here\n");
|
|
64
|
-
expect(strip(c.out())).toBe("use `npm install` here\n");
|
|
65
|
-
});
|
|
66
|
-
|
|
67
|
-
test("headings get bold + level color", () => {
|
|
68
|
-
const c = capture();
|
|
69
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
70
|
-
r.push("# H1\n## H2\n### H3\n");
|
|
71
|
-
expect(c.out().split("\n").length).toBe(4);
|
|
72
|
-
// Each header line starts with a bold marker.
|
|
73
|
-
const lines = c.out().split("\n");
|
|
74
|
-
expect(lines[0]).toContain("\x1b[1m");
|
|
75
|
-
expect(lines[1]).toContain("\x1b[1m");
|
|
76
|
-
expect(lines[2]).toContain("\x1b[1m");
|
|
77
|
-
expect(strip(c.out())).toBe("H1\nH2\nH3\n");
|
|
78
|
-
});
|
|
79
|
-
|
|
80
|
-
test("unordered list bullets render with • marker", () => {
|
|
81
|
-
const c = capture();
|
|
82
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
83
|
-
r.push("- one\n- two\n* three\n");
|
|
84
|
-
const stripped = strip(c.out());
|
|
85
|
-
expect(stripped).toContain("• one");
|
|
86
|
-
expect(stripped).toContain("• two");
|
|
87
|
-
expect(stripped).toContain("• three");
|
|
88
|
-
});
|
|
89
|
-
|
|
90
|
-
test("ordered list numbers survive with color", () => {
|
|
91
|
-
const c = capture();
|
|
92
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
93
|
-
r.push("1. first\n2. second\n");
|
|
94
|
-
const stripped = strip(c.out());
|
|
95
|
-
expect(stripped).toContain("1. first");
|
|
96
|
-
expect(stripped).toContain("2. second");
|
|
97
|
-
});
|
|
98
|
-
|
|
99
|
-
test("code fence toggles dim block, multi-line", () => {
|
|
100
|
-
const c = capture();
|
|
101
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
102
|
-
r.push("```python\nprint('hi')\nx = 1\n```\nback to text\n");
|
|
103
|
-
const stripped = strip(c.out());
|
|
104
|
-
expect(stripped).toContain("```python");
|
|
105
|
-
expect(stripped).toContain("print('hi')");
|
|
106
|
-
expect(stripped).toContain("x = 1");
|
|
107
|
-
expect(stripped).toContain("```");
|
|
108
|
-
expect(stripped).toContain("back to text");
|
|
109
|
-
// Dim marker should appear in the code-block lines.
|
|
110
|
-
expect(c.out()).toContain("\x1b[2m");
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
test("chunk-boundary safety: bold marker split across pushes", () => {
|
|
114
|
-
const c = capture();
|
|
115
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
116
|
-
r.push("hello *");
|
|
117
|
-
r.push("*world*");
|
|
118
|
-
r.push("* done\n");
|
|
119
|
-
expect(strip(c.out())).toBe("hello world done\n");
|
|
120
|
-
expect(c.out()).toContain("\x1b[1m");
|
|
121
|
-
});
|
|
122
|
-
|
|
123
|
-
test("blockquote renders with vertical-bar prefix and italic", () => {
|
|
124
|
-
const c = capture();
|
|
125
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
126
|
-
r.push("> a quote here\n");
|
|
127
|
-
expect(strip(c.out())).toContain("│ a quote here");
|
|
128
|
-
expect(c.out()).toContain("\x1b[3m");
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
test("horizontal rule renders as a divider", () => {
|
|
132
|
-
const c = capture();
|
|
133
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
134
|
-
r.push("---\n");
|
|
135
|
-
expect(strip(c.out())).toMatch(/^─{40}/);
|
|
136
|
-
});
|
|
137
|
-
|
|
138
|
-
test("underscore bold (__x__) and underscore italic (_x_) render", () => {
|
|
139
|
-
const c = capture();
|
|
140
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
141
|
-
// __bold__ exercises the __...__ replace callback; a closed _italic_ pair
|
|
142
|
-
// (word-boundary guarded) exercises the _..._ replace callback. Both are
|
|
143
|
-
// distinct from the asterisk variants the other tests cover.
|
|
144
|
-
r.push("make __this__ and _that_ pop\n");
|
|
145
|
-
expect(strip(c.out())).toBe("make this and that pop\n");
|
|
146
|
-
expect(c.out()).toContain("\x1b[1m"); // bold from __this__
|
|
147
|
-
expect(c.out()).toContain("\x1b[3m"); // italic from _that_
|
|
148
|
-
});
|
|
149
|
-
|
|
150
|
-
test("does not false-match snake_case identifiers as italic", () => {
|
|
151
|
-
const c = capture();
|
|
152
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
153
|
-
r.push("call foo_bar_baz now\n");
|
|
154
|
-
expect(strip(c.out())).toBe("call foo_bar_baz now\n");
|
|
155
|
-
// No italic markers because _foo_bar_baz_ isn't a closed pair.
|
|
156
|
-
expect(c.out()).not.toContain("\x1b[3m");
|
|
157
|
-
});
|
|
158
|
-
|
|
159
|
-
test("nested code-fence inside list-item not double-rendered", () => {
|
|
160
|
-
const c = capture();
|
|
161
|
-
const r = createCliMarkdownRenderer({ write: c.write });
|
|
162
|
-
r.push("- item one\n ```\n code\n ```\n- item two\n");
|
|
163
|
-
const stripped = strip(c.out());
|
|
164
|
-
expect(stripped).toContain("• item one");
|
|
165
|
-
expect(stripped).toContain("code");
|
|
166
|
-
expect(stripped).toContain("• item two");
|
|
167
|
-
});
|
|
168
|
-
|
|
169
|
-
test("defaults to process.stdout.write when no write override is supplied", () => {
|
|
170
|
-
// Exercises the default sink arrow `(s) => process.stdout.write(s)` that
|
|
171
|
-
// every other test bypasses by passing an explicit `write`. We spy on
|
|
172
|
-
// stdout so nothing actually prints to the test console.
|
|
173
|
-
const written: string[] = [];
|
|
174
|
-
const spy = spyOn(process.stdout, "write").mockImplementation(((chunk: unknown) => {
|
|
175
|
-
written.push(String(chunk));
|
|
176
|
-
return true;
|
|
177
|
-
}) as typeof process.stdout.write);
|
|
178
|
-
try {
|
|
179
|
-
const r = createCliMarkdownRenderer(); // no opts → default write
|
|
180
|
-
r.push("plain line\n"); // flushes a completed line via the default sink
|
|
181
|
-
r.push("tail-no-newline");
|
|
182
|
-
r.end(); // flushes the buffered tail via the default sink
|
|
183
|
-
} finally {
|
|
184
|
-
spy.mockRestore();
|
|
185
|
-
}
|
|
186
|
-
const joined = strip(written.join(""));
|
|
187
|
-
expect(joined).toContain("plain line");
|
|
188
|
-
expect(joined).toContain("tail-no-newline");
|
|
189
|
-
});
|
|
190
|
-
});
|
|
191
|
-
|
|
192
|
-
describe("isCliMarkdownEnabled", () => {
|
|
193
|
-
test("returns false when env var is unset", () => {
|
|
194
|
-
expect(isCliMarkdownEnabled({})).toBe(false);
|
|
195
|
-
});
|
|
196
|
-
|
|
197
|
-
test("returns true for '1' and 'true' (case sensitive)", () => {
|
|
198
|
-
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "1" })).toBe(true);
|
|
199
|
-
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "true" })).toBe(true);
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
test("returns false for falsy strings", () => {
|
|
203
|
-
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "0" })).toBe(false);
|
|
204
|
-
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "false" })).toBe(false);
|
|
205
|
-
expect(isCliMarkdownEnabled({ CREWHAUS_CLI_MARKDOWN: "" })).toBe(false);
|
|
206
|
-
});
|
|
207
|
-
});
|