kcp-harness 0.1.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 (46) hide show
  1. package/LICENSE +201 -0
  2. package/dist/audit.d.ts +73 -0
  3. package/dist/audit.js +142 -0
  4. package/dist/budget-ledger.d.ts +85 -0
  5. package/dist/budget-ledger.js +100 -0
  6. package/dist/classifier.d.ts +35 -0
  7. package/dist/classifier.js +177 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.js +177 -0
  10. package/dist/config.d.ts +65 -0
  11. package/dist/config.js +91 -0
  12. package/dist/downstream.d.ts +50 -0
  13. package/dist/downstream.js +167 -0
  14. package/dist/governor.d.ts +34 -0
  15. package/dist/governor.js +201 -0
  16. package/dist/index.d.ts +12 -0
  17. package/dist/index.js +21 -0
  18. package/dist/integrations/claude-code.d.ts +2 -0
  19. package/dist/integrations/claude-code.js +95 -0
  20. package/dist/integrations/cline.d.ts +2 -0
  21. package/dist/integrations/cline.js +70 -0
  22. package/dist/integrations/continue.d.ts +2 -0
  23. package/dist/integrations/continue.js +39 -0
  24. package/dist/integrations/copilot.d.ts +2 -0
  25. package/dist/integrations/copilot.js +69 -0
  26. package/dist/integrations/crush.d.ts +2 -0
  27. package/dist/integrations/crush.js +48 -0
  28. package/dist/integrations/cursor.d.ts +2 -0
  29. package/dist/integrations/cursor.js +65 -0
  30. package/dist/integrations/generate.d.ts +13 -0
  31. package/dist/integrations/generate.js +60 -0
  32. package/dist/integrations/openclaw.d.ts +2 -0
  33. package/dist/integrations/openclaw.js +67 -0
  34. package/dist/integrations/types.d.ts +51 -0
  35. package/dist/integrations/types.js +78 -0
  36. package/dist/integrations/windsurf.d.ts +2 -0
  37. package/dist/integrations/windsurf.js +67 -0
  38. package/dist/kcp-bridge.d.ts +2 -0
  39. package/dist/kcp-bridge.js +85 -0
  40. package/dist/proxy.d.ts +37 -0
  41. package/dist/proxy.js +394 -0
  42. package/dist/session.d.ts +50 -0
  43. package/dist/session.js +82 -0
  44. package/dist/temporal-watch.d.ts +63 -0
  45. package/dist/temporal-watch.js +147 -0
  46. package/package.json +56 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,73 @@
1
+ import type { Classification } from "./classifier.js";
2
+ import type { GovernanceDecision } from "./governor.js";
3
+ import type { LedgerSnapshot } from "./budget-ledger.js";
4
+ import type { DriftResult } from "./temporal-watch.js";
5
+ /** Event types for structured audit logging. */
6
+ export type AuditEventType = "tool_call" | "session_start" | "session_end" | "budget_spend" | "budget_exceeded" | "temporal_drift" | "plan_invalidated";
7
+ /** A single audit event. */
8
+ export interface AuditEvent {
9
+ /** ISO 8601 timestamp. */
10
+ timestamp: string;
11
+ /** Session ID for correlation. */
12
+ sessionId: string;
13
+ /** Monotonic sequence number within the session. */
14
+ sequence: number;
15
+ /** Event type for structured filtering. */
16
+ type: AuditEventType;
17
+ /** The tool call that was intercepted (for tool_call events). */
18
+ toolCall?: {
19
+ name: string;
20
+ /** Sanitized arguments (sensitive values redacted). */
21
+ args: Record<string, unknown>;
22
+ };
23
+ /** Classification result (for tool_call events). */
24
+ classification?: Classification;
25
+ /** Governance decision (only for governed calls). */
26
+ governance?: GovernanceDecision;
27
+ /** Final outcome. */
28
+ outcome: "approved" | "blocked" | "pass-through" | "error";
29
+ /** Processing time in milliseconds. */
30
+ durationMs: number;
31
+ /** Error message if the call failed. */
32
+ error?: string;
33
+ /** Budget snapshot at time of event (for spend events). */
34
+ budget?: LedgerSnapshot;
35
+ /** Temporal drift details (for drift events). */
36
+ drift?: {
37
+ manifest: string;
38
+ summary: string;
39
+ movedUnits?: number;
40
+ newPlanAsOf?: string;
41
+ };
42
+ }
43
+ /** Append-only audit log writer. */
44
+ export declare class AuditLog {
45
+ private readonly path;
46
+ private initialized;
47
+ constructor(path: string);
48
+ /** Emit an audit event to the log. */
49
+ emit(event: AuditEvent): void;
50
+ /** Get the log file path. */
51
+ getPath(): string;
52
+ private ensureDir;
53
+ }
54
+ /** Create an in-memory audit log for testing. */
55
+ export declare class InMemoryAuditLog {
56
+ readonly events: AuditEvent[];
57
+ emit(event: AuditEvent): void;
58
+ getPath(): string;
59
+ }
60
+ export type AuditWriter = AuditLog | InMemoryAuditLog;
61
+ /** Build a tool_call audit event from the processing pipeline. */
62
+ export declare function buildEvent(sessionId: string, sequence: number, toolName: string, args: Record<string, unknown>, classification: Classification, governance: GovernanceDecision | undefined, outcome: AuditEvent["outcome"], durationMs: number, error?: string): AuditEvent;
63
+ /** Build a session lifecycle event. */
64
+ export declare function buildLifecycleEvent(sessionId: string, sequence: number, type: "session_start" | "session_end", details?: Record<string, unknown>): AuditEvent;
65
+ /** Build a budget spend event. */
66
+ export declare function buildBudgetEvent(sessionId: string, sequence: number, accepted: boolean, snapshot: LedgerSnapshot, details?: {
67
+ manifest?: string;
68
+ unitId?: string;
69
+ amount?: number;
70
+ currency?: string;
71
+ }): AuditEvent;
72
+ /** Build a temporal drift event. */
73
+ export declare function buildDriftEvent(sessionId: string, sequence: number, drift: DriftResult): AuditEvent;
package/dist/audit.js ADDED
@@ -0,0 +1,142 @@
1
+ // Audit log — append-only compliance log for every governance decision.
2
+ //
3
+ // Every tool call processed by the harness produces an audit event — even
4
+ // pass-throughs (logged as "ungoverned"). The audit log is a JSONL file:
5
+ // one JSON object per line, append-only, never truncated or rotated by
6
+ // the harness itself. External log management handles rotation.
7
+ //
8
+ // The log is compliance-grade:
9
+ // - Every event has a session ID, sequence number, and ISO timestamp
10
+ // - Classification, governance decision, and outcome are recorded
11
+ // - Events are atomic (one write per line, fsync'd)
12
+ // - The log can be replayed to reconstruct the session's governance history
13
+ // - Session lifecycle events mark boundaries (start, end, drift)
14
+ // - Budget snapshots recorded on every spend event
15
+ import { appendFileSync, mkdirSync } from "node:fs";
16
+ import { dirname } from "node:path";
17
+ /** Append-only audit log writer. */
18
+ export class AuditLog {
19
+ path;
20
+ initialized = false;
21
+ constructor(path) {
22
+ this.path = path;
23
+ }
24
+ /** Emit an audit event to the log. */
25
+ emit(event) {
26
+ this.ensureDir();
27
+ const line = JSON.stringify(event) + "\n";
28
+ appendFileSync(this.path, line, "utf-8");
29
+ }
30
+ /** Get the log file path. */
31
+ getPath() {
32
+ return this.path;
33
+ }
34
+ ensureDir() {
35
+ if (this.initialized)
36
+ return;
37
+ mkdirSync(dirname(this.path), { recursive: true });
38
+ this.initialized = true;
39
+ }
40
+ }
41
+ /** Create an in-memory audit log for testing. */
42
+ export class InMemoryAuditLog {
43
+ events = [];
44
+ emit(event) {
45
+ this.events.push(event);
46
+ }
47
+ getPath() {
48
+ return ":memory:";
49
+ }
50
+ }
51
+ /** Build a tool_call audit event from the processing pipeline. */
52
+ export function buildEvent(sessionId, sequence, toolName, args, classification, governance, outcome, durationMs, error) {
53
+ return {
54
+ timestamp: new Date().toISOString(),
55
+ sessionId,
56
+ sequence,
57
+ type: "tool_call",
58
+ toolCall: { name: toolName, args: sanitizeArgs(toolName, args) },
59
+ classification,
60
+ governance: governance ? sanitizeDecision(governance) : undefined,
61
+ outcome,
62
+ durationMs,
63
+ error,
64
+ };
65
+ }
66
+ /** Build a session lifecycle event. */
67
+ export function buildLifecycleEvent(sessionId, sequence, type, details) {
68
+ return {
69
+ timestamp: new Date().toISOString(),
70
+ sessionId,
71
+ sequence,
72
+ type,
73
+ outcome: "approved",
74
+ durationMs: 0,
75
+ ...(details ? { toolCall: { name: type, args: details } } : {}),
76
+ };
77
+ }
78
+ /** Build a budget spend event. */
79
+ export function buildBudgetEvent(sessionId, sequence, accepted, snapshot, details) {
80
+ return {
81
+ timestamp: new Date().toISOString(),
82
+ sessionId,
83
+ sequence,
84
+ type: accepted ? "budget_spend" : "budget_exceeded",
85
+ outcome: accepted ? "approved" : "blocked",
86
+ durationMs: 0,
87
+ budget: snapshot,
88
+ ...(details ? { toolCall: { name: accepted ? "budget_spend" : "budget_exceeded", args: details } } : {}),
89
+ };
90
+ }
91
+ /** Build a temporal drift event. */
92
+ export function buildDriftEvent(sessionId, sequence, drift) {
93
+ return {
94
+ timestamp: new Date().toISOString(),
95
+ sessionId,
96
+ sequence,
97
+ type: "temporal_drift",
98
+ outcome: "blocked",
99
+ durationMs: 0,
100
+ drift: {
101
+ manifest: drift.manifest,
102
+ summary: drift.summary,
103
+ movedUnits: drift.diff?.moves.length,
104
+ newPlanAsOf: drift.diff?.b.asOf,
105
+ },
106
+ };
107
+ }
108
+ /** Redact sensitive values from tool arguments for audit logging. */
109
+ function sanitizeArgs(toolName, args) {
110
+ const sanitized = { ...args };
111
+ // Redact content from Write calls (could be large/sensitive)
112
+ if (toolName === "Write" && sanitized["content"]) {
113
+ const content = String(sanitized["content"]);
114
+ sanitized["content"] = `[${content.length} chars redacted]`;
115
+ }
116
+ // Redact Bash commands that might contain secrets
117
+ if (toolName === "Bash" && sanitized["command"]) {
118
+ const cmd = String(sanitized["command"]);
119
+ // Redact values after common secret-passing patterns
120
+ sanitized["command"] = cmd.replace(/(?:password|secret|token|key|api[_-]?key)\s*[=:]\s*\S+/gi, (match) => match.replace(/[=:]\s*\S+/, "=[REDACTED]"));
121
+ }
122
+ return sanitized;
123
+ }
124
+ /** Strip the full plan from governance decisions to keep logs compact. */
125
+ function sanitizeDecision(decision) {
126
+ const { plan, trace, ...rest } = decision;
127
+ return {
128
+ ...rest,
129
+ // Keep plan metadata but strip unit content
130
+ plan: plan
131
+ ? {
132
+ ...plan,
133
+ selected: plan.selected.map((u) => ({
134
+ ...u,
135
+ // Keep everything — PlannedUnit doesn't contain content
136
+ })),
137
+ }
138
+ : undefined,
139
+ // Omit full trace from audit (it's large); the trace is available via kcp_trace
140
+ trace: undefined,
141
+ };
142
+ }
@@ -0,0 +1,85 @@
1
+ /** A single spend event. */
2
+ export interface LedgerEntry {
3
+ /** Monotonic sequence within the ledger. */
4
+ seq: number;
5
+ /** ISO 8601 timestamp. */
6
+ timestamp: string;
7
+ /** What triggered the spend. */
8
+ source: LedgerSource;
9
+ /** The cost. */
10
+ cost: LedgerCost;
11
+ /** Running total after this entry (per currency). */
12
+ runningTotal: Record<string, number>;
13
+ }
14
+ /** What triggered a spend event. */
15
+ export interface LedgerSource {
16
+ /** The manifest that produced the plan. */
17
+ manifest: string;
18
+ /** The unit that incurred the cost (if unit-level). */
19
+ unitId?: string;
20
+ /** The task that prompted the plan. */
21
+ task: string;
22
+ /** Audit sequence number for correlation. */
23
+ auditSequence?: number;
24
+ }
25
+ /** The cost of a spend event. */
26
+ export interface LedgerCost {
27
+ /** Amount spent. */
28
+ amount: number;
29
+ /** Currency (default: USDC). */
30
+ currency: string;
31
+ /** Payment method used. */
32
+ method: string;
33
+ /** Human-readable note. */
34
+ note?: string;
35
+ }
36
+ /** Budget ceiling configuration. */
37
+ export interface BudgetCeiling {
38
+ amount: number;
39
+ currency: string;
40
+ }
41
+ /** Result of attempting to record a spend. */
42
+ export interface SpendResult {
43
+ /** Whether the spend was recorded (false if it would exceed ceiling). */
44
+ accepted: boolean;
45
+ /** The ledger entry (if accepted). */
46
+ entry?: LedgerEntry;
47
+ /** Running total after this entry. */
48
+ total: number;
49
+ /** Remaining budget (if ceiling is set). */
50
+ remaining?: number;
51
+ /** Reason for rejection (if not accepted). */
52
+ reason?: string;
53
+ }
54
+ /** Budget ledger — append-only spend tracking for a session. */
55
+ export declare class BudgetLedger {
56
+ private entries;
57
+ private totals;
58
+ private ceiling?;
59
+ private nextSeq;
60
+ constructor(ceiling?: BudgetCeiling);
61
+ /** Record a spend event. Returns whether it was accepted. */
62
+ record(source: LedgerSource, cost: LedgerCost): SpendResult;
63
+ /** Record spend from a plan's projected costs (convenience). */
64
+ recordPlanSpend(manifest: string, task: string, projectedSpend: number, currency: string, auditSequence?: number): SpendResult;
65
+ /** Record spend for a specific unit (fine-grained). */
66
+ recordUnitSpend(manifest: string, unitId: string, task: string, amount: number, currency: string, method: string, auditSequence?: number): SpendResult;
67
+ /** Get the current total for a currency. */
68
+ getTotal(currency?: string): number;
69
+ /** Get remaining budget (if ceiling is set). */
70
+ getRemaining(): number | undefined;
71
+ /** Get all entries. */
72
+ getEntries(): readonly LedgerEntry[];
73
+ /** Get the ceiling configuration. */
74
+ getCeiling(): BudgetCeiling | undefined;
75
+ /** Get a summary snapshot. */
76
+ snapshot(): LedgerSnapshot;
77
+ }
78
+ /** A point-in-time snapshot of the ledger. */
79
+ export interface LedgerSnapshot {
80
+ ceiling?: BudgetCeiling;
81
+ totals: Record<string, number>;
82
+ remaining?: number;
83
+ entryCount: number;
84
+ lastEntry?: LedgerEntry;
85
+ }
@@ -0,0 +1,100 @@
1
+ // Budget ledger — itemized session spend tracking.
2
+ //
3
+ // The budget ledger records every cost event in the session: what was spent,
4
+ // on which unit, from which manifest, and why. It maintains a running total
5
+ // that the governor uses to enforce budget ceilings across calls.
6
+ //
7
+ // The ledger is the single source of truth for "how much did this session
8
+ // cost?" — the audit log cites it, the governor consults it, and the
9
+ // harness_budget tool exposes it.
10
+ //
11
+ // Design:
12
+ // - Append-only: entries are never modified or removed
13
+ // - Deterministic totals: running total is recomputed from entries (no drift)
14
+ // - Currency-aware: tracks spend per currency
15
+ // - Overflow-safe: rejects entries that would exceed the ceiling
16
+ /** Budget ledger — append-only spend tracking for a session. */
17
+ export class BudgetLedger {
18
+ entries = [];
19
+ totals = new Map();
20
+ ceiling;
21
+ nextSeq = 1;
22
+ constructor(ceiling) {
23
+ this.ceiling = ceiling;
24
+ }
25
+ /** Record a spend event. Returns whether it was accepted. */
26
+ record(source, cost) {
27
+ const currency = cost.currency || "USDC";
28
+ const currentTotal = this.totals.get(currency) ?? 0;
29
+ const newTotal = round6(currentTotal + cost.amount);
30
+ // Check ceiling
31
+ if (this.ceiling && currency === this.ceiling.currency) {
32
+ if (newTotal > this.ceiling.amount + 1e-9) {
33
+ return {
34
+ accepted: false,
35
+ total: currentTotal,
36
+ remaining: round6(this.ceiling.amount - currentTotal),
37
+ reason: `would exceed budget ceiling: ${newTotal} > ${this.ceiling.amount} ${currency}`,
38
+ };
39
+ }
40
+ }
41
+ // Accept
42
+ this.totals.set(currency, newTotal);
43
+ const runningTotal = Object.fromEntries(this.totals);
44
+ const entry = {
45
+ seq: this.nextSeq++,
46
+ timestamp: new Date().toISOString(),
47
+ source,
48
+ cost: { ...cost, currency },
49
+ runningTotal,
50
+ };
51
+ this.entries.push(entry);
52
+ return {
53
+ accepted: true,
54
+ entry,
55
+ total: newTotal,
56
+ remaining: this.ceiling && currency === this.ceiling.currency
57
+ ? round6(this.ceiling.amount - newTotal)
58
+ : undefined,
59
+ };
60
+ }
61
+ /** Record spend from a plan's projected costs (convenience). */
62
+ recordPlanSpend(manifest, task, projectedSpend, currency, auditSequence) {
63
+ return this.record({ manifest, task, auditSequence }, { amount: projectedSpend, currency, method: "plan-projected", note: "from plan budget projection" });
64
+ }
65
+ /** Record spend for a specific unit (fine-grained). */
66
+ recordUnitSpend(manifest, unitId, task, amount, currency, method, auditSequence) {
67
+ return this.record({ manifest, unitId, task, auditSequence }, { amount, currency, method });
68
+ }
69
+ /** Get the current total for a currency. */
70
+ getTotal(currency = "USDC") {
71
+ return this.totals.get(currency) ?? 0;
72
+ }
73
+ /** Get remaining budget (if ceiling is set). */
74
+ getRemaining() {
75
+ if (!this.ceiling)
76
+ return undefined;
77
+ return round6(this.ceiling.amount - this.getTotal(this.ceiling.currency));
78
+ }
79
+ /** Get all entries. */
80
+ getEntries() {
81
+ return this.entries;
82
+ }
83
+ /** Get the ceiling configuration. */
84
+ getCeiling() {
85
+ return this.ceiling;
86
+ }
87
+ /** Get a summary snapshot. */
88
+ snapshot() {
89
+ return {
90
+ ceiling: this.ceiling,
91
+ totals: Object.fromEntries(this.totals),
92
+ remaining: this.getRemaining(),
93
+ entryCount: this.entries.length,
94
+ lastEntry: this.entries.length > 0 ? this.entries[this.entries.length - 1] : undefined,
95
+ };
96
+ }
97
+ }
98
+ function round6(n) {
99
+ return Math.round(n * 1e6) / 1e6;
100
+ }
@@ -0,0 +1,35 @@
1
+ import type { GovernedDomain } from "./config.js";
2
+ /** The result of classifying a tool call. */
3
+ export interface Classification {
4
+ /** Whether this call targets a governed knowledge domain. */
5
+ governed: boolean;
6
+ /** Which governed domain matched (if any). */
7
+ domain?: GovernedDomain;
8
+ /** The path or URL that triggered the match. */
9
+ target?: string;
10
+ /** Human-readable reason for the classification. */
11
+ reason: string;
12
+ }
13
+ /**
14
+ * Classify a tool call: is it knowledge-navigation targeting a governed domain?
15
+ *
16
+ * Classification rules (in order):
17
+ * 1. KCP tools → always governed (route to kcp-agent directly)
18
+ * 2. Tool name in domain's `tools` list → governed by that domain
19
+ * 3. File path extracted from arguments → match against domain paths
20
+ * 4. URL extracted from arguments → match against domain URLs
21
+ * 5. Otherwise → pass-through (ungoverned)
22
+ */
23
+ export declare function classify(toolName: string, args: Record<string, unknown>, domains: GovernedDomain[]): Classification;
24
+ /**
25
+ * Extract known targets from any tool call arguments.
26
+ * Useful for audit logging even when not governed.
27
+ */
28
+ export declare function extractTargets(toolName: string, args: Record<string, unknown>): {
29
+ paths: string[];
30
+ urls: string[];
31
+ };
32
+ /** Normalize a file path: strip leading ./ and trailing /, collapse //. */
33
+ export declare function normalizePath(p: string): string;
34
+ /** Check if a path starts with a prefix (directory-boundary-aware). */
35
+ export declare function matchesPrefix(path: string, prefix: string): boolean;