@dcyfr/ai 3.0.1 → 3.0.3
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/CHANGELOG.md +10 -0
- package/LICENSE +11 -30
- package/README.md +216 -145
- package/dist/.tsbuildinfo +1 -1
- package/dist/ai/agents/agent-router.d.ts.map +1 -1
- package/dist/ai/agents/agent-router.js +3 -1
- package/dist/ai/agents/agent-router.js.map +1 -1
- package/dist/ai/config/loader.d.ts +5 -1
- package/dist/ai/config/loader.d.ts.map +1 -1
- package/dist/ai/config/loader.js +24 -4
- package/dist/ai/config/loader.js.map +1 -1
- package/dist/ai/core/provider-registry.d.ts +9 -1
- package/dist/ai/core/provider-registry.d.ts.map +1 -1
- package/dist/ai/core/provider-registry.js +97 -138
- package/dist/ai/core/provider-registry.js.map +1 -1
- package/dist/ai/core/telemetry-engine.d.ts +1 -1
- package/dist/ai/core/telemetry-engine.d.ts.map +1 -1
- package/dist/ai/core/telemetry-engine.js +14 -10
- package/dist/ai/core/telemetry-engine.js.map +1 -1
- package/dist/ai/delegation/contract-manager.d.ts.map +1 -1
- package/dist/ai/delegation/contract-manager.js +5 -2
- package/dist/ai/delegation/contract-manager.js.map +1 -1
- package/dist/ai/delegation/execution-mode-dashboard.d.ts.map +1 -1
- package/dist/ai/delegation/execution-mode-dashboard.js +4 -2
- package/dist/ai/delegation/execution-mode-dashboard.js.map +1 -1
- package/dist/ai/mcp/servers/shared/utils.d.ts.map +1 -1
- package/dist/ai/mcp/servers/shared/utils.js +4 -2
- package/dist/ai/mcp/servers/shared/utils.js.map +1 -1
- package/dist/ai/memory/file-memory-adapter.d.ts.map +1 -1
- package/dist/ai/memory/file-memory-adapter.js +11 -13
- package/dist/ai/memory/file-memory-adapter.js.map +1 -1
- package/dist/ai/memory/working-memory-persistence.d.ts.map +1 -1
- package/dist/ai/memory/working-memory-persistence.js +4 -2
- package/dist/ai/memory/working-memory-persistence.js.map +1 -1
- package/dist/ai/metacognition/config.d.ts +41 -0
- package/dist/ai/metacognition/config.d.ts.map +1 -0
- package/dist/ai/metacognition/config.js +51 -0
- package/dist/ai/metacognition/config.js.map +1 -0
- package/dist/ai/metacognition/governance.d.ts +68 -0
- package/dist/ai/metacognition/governance.d.ts.map +1 -0
- package/dist/ai/metacognition/governance.js +118 -0
- package/dist/ai/metacognition/governance.js.map +1 -0
- package/dist/ai/metacognition/index.d.ts +24 -0
- package/dist/ai/metacognition/index.d.ts.map +1 -0
- package/dist/ai/metacognition/index.js +18 -0
- package/dist/ai/metacognition/index.js.map +1 -0
- package/dist/ai/metacognition/ledger.d.ts +121 -0
- package/dist/ai/metacognition/ledger.d.ts.map +1 -0
- package/dist/ai/metacognition/ledger.js +268 -0
- package/dist/ai/metacognition/ledger.js.map +1 -0
- package/dist/ai/metacognition/runtime.d.ts +205 -0
- package/dist/ai/metacognition/runtime.d.ts.map +1 -0
- package/dist/ai/metacognition/runtime.js +391 -0
- package/dist/ai/metacognition/runtime.js.map +1 -0
- package/dist/ai/metacognition/telemetry.d.ts +144 -0
- package/dist/ai/metacognition/telemetry.d.ts.map +1 -0
- package/dist/ai/metacognition/telemetry.js +149 -0
- package/dist/ai/metacognition/telemetry.js.map +1 -0
- package/dist/ai/metacognition/transfer.d.ts +153 -0
- package/dist/ai/metacognition/transfer.d.ts.map +1 -0
- package/dist/ai/metacognition/transfer.js +182 -0
- package/dist/ai/metacognition/transfer.js.map +1 -0
- package/dist/ai/metacognition/types.d.ts +302 -0
- package/dist/ai/metacognition/types.d.ts.map +1 -0
- package/dist/ai/metacognition/types.js +79 -0
- package/dist/ai/metacognition/types.js.map +1 -0
- package/dist/ai/runtime/agent-runtime.d.ts.map +1 -1
- package/dist/ai/runtime/agent-runtime.js +12 -18
- package/dist/ai/runtime/agent-runtime.js.map +1 -1
- package/dist/ai/src/capability-manifest-generator.d.ts.map +1 -1
- package/dist/ai/src/capability-manifest-generator.js +11 -5
- package/dist/ai/src/capability-manifest-generator.js.map +1 -1
- package/dist/ai/src/cli/telemetry-dashboard.js +3 -3
- package/dist/ai/src/cli/telemetry-dashboard.js.map +1 -1
- package/dist/ai/src/compaction/memory-compaction.d.ts.map +1 -1
- package/dist/ai/src/compaction/memory-compaction.js +5 -4
- package/dist/ai/src/compaction/memory-compaction.js.map +1 -1
- package/dist/ai/src/integrations/linear/index.d.ts +19 -0
- package/dist/ai/src/integrations/linear/index.d.ts.map +1 -0
- package/dist/ai/src/integrations/linear/index.js +20 -0
- package/dist/ai/src/integrations/linear/index.js.map +1 -0
- package/dist/ai/src/integrations/linear/issue-mapper.d.ts +93 -0
- package/dist/ai/src/integrations/linear/issue-mapper.d.ts.map +1 -0
- package/dist/ai/src/integrations/linear/issue-mapper.js +186 -0
- package/dist/ai/src/integrations/linear/issue-mapper.js.map +1 -0
- package/dist/ai/src/integrations/linear/linear-client.d.ts +199 -0
- package/dist/ai/src/integrations/linear/linear-client.d.ts.map +1 -0
- package/dist/ai/src/integrations/linear/linear-client.js +300 -0
- package/dist/ai/src/integrations/linear/linear-client.js.map +1 -0
- package/dist/ai/src/plugins/security/secret-detector.js +3 -3
- package/dist/ai/src/plugins/security/secret-detector.js.map +1 -1
- package/dist/ai/src/runtime/agent-runtime.js +1 -1
- package/dist/ai/src/runtime/agent-runtime.js.map +1 -1
- package/dist/ai/src/security/prompt-scan-worker.d.ts +63 -0
- package/dist/ai/src/security/prompt-scan-worker.d.ts.map +1 -0
- package/dist/ai/src/security/prompt-scan-worker.js +177 -0
- package/dist/ai/src/security/prompt-scan-worker.js.map +1 -0
- package/dist/ai/src/telemetry/delegation-telemetry.d.ts +10 -0
- package/dist/ai/src/telemetry/delegation-telemetry.d.ts.map +1 -1
- package/dist/ai/src/telemetry/delegation-telemetry.js +23 -0
- package/dist/ai/src/telemetry/delegation-telemetry.js.map +1 -1
- package/dist/ai/types/index.d.ts +8 -3
- package/dist/ai/types/index.d.ts.map +1 -1
- package/dist/ai/types/index.js.map +1 -1
- package/dist/ai/utils/safe-fs.d.ts +19 -0
- package/dist/ai/utils/safe-fs.d.ts.map +1 -0
- package/dist/ai/utils/safe-fs.js +64 -0
- package/dist/ai/utils/safe-fs.js.map +1 -0
- package/package.json +33 -22
|
@@ -0,0 +1,391 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metacognitive Improvement Runtime — Lifecycle State Machine
|
|
3
|
+
* TLP:AMBER - Internal Use Only
|
|
4
|
+
*
|
|
5
|
+
* Implements the governed lifecycle state machine for improvement proposals:
|
|
6
|
+
* propose → evaluate → approve → apply → (rollback)
|
|
7
|
+
*
|
|
8
|
+
* Enforcement rules:
|
|
9
|
+
* - Schema version must be compatible before any proposal is processed.
|
|
10
|
+
* - `production_direct` scope requires at least `third_party_audit`.
|
|
11
|
+
* - TLP:RED context requires `human_required`.
|
|
12
|
+
* - State transitions are validated; invalid transitions throw.
|
|
13
|
+
* - All lifecycle events are written to the injected ImprovementLedger.
|
|
14
|
+
*
|
|
15
|
+
* Feature flag: controlled by `MetacognitiveRuntimeConfig.enabled`.
|
|
16
|
+
* When disabled the runtime is a structural no-op (see task 1.3 for env wiring).
|
|
17
|
+
*
|
|
18
|
+
* @module ai/metacognition/runtime
|
|
19
|
+
* @version 1.0.0
|
|
20
|
+
*/
|
|
21
|
+
import { VALID_LIFECYCLE_TRANSITIONS, DEFAULT_GOVERNANCE_CONFIG, VERIFICATION_POLICY_STRENGTH, isSchemaCompatible, meetsVerificationThreshold, resolveRequiredPolicy, formatSchemaVersion, } from './types.js';
|
|
22
|
+
// ---------------------------------------------------------------------------
|
|
23
|
+
// Runtime errors
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
/** Thrown when an invalid lifecycle transition is attempted. */
|
|
26
|
+
export class InvalidLifecycleTransitionError extends Error {
|
|
27
|
+
proposal_id;
|
|
28
|
+
from;
|
|
29
|
+
to;
|
|
30
|
+
constructor(proposal_id, from, to) {
|
|
31
|
+
super(`Invalid lifecycle transition for proposal ${proposal_id}: ${from} → ${to}`);
|
|
32
|
+
this.proposal_id = proposal_id;
|
|
33
|
+
this.from = from;
|
|
34
|
+
this.to = to;
|
|
35
|
+
this.name = 'InvalidLifecycleTransitionError';
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
/** Thrown when a policy snapshot fails schema version compatibility check. */
|
|
39
|
+
export class SchemaIncompatibleError extends Error {
|
|
40
|
+
snapshot_id;
|
|
41
|
+
snapshot_version;
|
|
42
|
+
runtime_version;
|
|
43
|
+
constructor(snapshot_id, snapshot_version, runtime_version) {
|
|
44
|
+
super(`Policy snapshot ${snapshot_id} schema version ${snapshot_version} is incompatible with runtime version ${runtime_version}`);
|
|
45
|
+
this.snapshot_id = snapshot_id;
|
|
46
|
+
this.snapshot_version = snapshot_version;
|
|
47
|
+
this.runtime_version = runtime_version;
|
|
48
|
+
this.name = 'SchemaIncompatibleError';
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
/** Thrown when an approve request fails governance threshold checks. */
|
|
52
|
+
export class GovernanceViolationError extends Error {
|
|
53
|
+
proposal_id;
|
|
54
|
+
provided;
|
|
55
|
+
required;
|
|
56
|
+
reason;
|
|
57
|
+
constructor(proposal_id, provided, required, reason) {
|
|
58
|
+
super(`Governance violation for proposal ${proposal_id}: provided "${provided}" but required "${required}" — ${reason}`);
|
|
59
|
+
this.proposal_id = proposal_id;
|
|
60
|
+
this.provided = provided;
|
|
61
|
+
this.required = required;
|
|
62
|
+
this.reason = reason;
|
|
63
|
+
this.name = 'GovernanceViolationError';
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/** Thrown when the runtime is disabled and a proposal is submitted. */
|
|
67
|
+
export class RuntimeDisabledError extends Error {
|
|
68
|
+
constructor() {
|
|
69
|
+
super('MetacognitiveImprovementRuntime is disabled. Set ENABLE_METACOG_RUNTIME=true to enable.');
|
|
70
|
+
this.name = 'RuntimeDisabledError';
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function defaultIdGenerator() {
|
|
74
|
+
// crypto.randomUUID is available in Node 19+; fall back to a simple impl
|
|
75
|
+
if (typeof crypto !== 'undefined' && crypto.randomUUID) {
|
|
76
|
+
return crypto.randomUUID();
|
|
77
|
+
}
|
|
78
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
|
|
79
|
+
}
|
|
80
|
+
// ---------------------------------------------------------------------------
|
|
81
|
+
// MetacognitiveImprovementRuntime
|
|
82
|
+
// ---------------------------------------------------------------------------
|
|
83
|
+
/**
|
|
84
|
+
* Governed runtime for the improvement lifecycle state machine.
|
|
85
|
+
*
|
|
86
|
+
* Usage:
|
|
87
|
+
* ```typescript
|
|
88
|
+
* const runtime = new MetacognitiveImprovementRuntime(config, ledger);
|
|
89
|
+
* await runtime.propose(snapshot, proposal);
|
|
90
|
+
* await runtime.evaluate(proposal_id, evaluationResult);
|
|
91
|
+
* await runtime.approve(proposal_id, verificationResult, 'human-reviewer-1');
|
|
92
|
+
* await runtime.apply(proposal_id, resultSnapshot);
|
|
93
|
+
* ```
|
|
94
|
+
*/
|
|
95
|
+
export class MetacognitiveImprovementRuntime {
|
|
96
|
+
config;
|
|
97
|
+
ledger;
|
|
98
|
+
generateId;
|
|
99
|
+
constructor(config, ledger, generateId = defaultIdGenerator) {
|
|
100
|
+
this.config = config;
|
|
101
|
+
this.ledger = ledger;
|
|
102
|
+
this.generateId = generateId;
|
|
103
|
+
if (config.enabled) {
|
|
104
|
+
this.assertGovernanceInvariants(config);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
// -------------------------------------------------------------------------
|
|
108
|
+
// Public lifecycle methods
|
|
109
|
+
// -------------------------------------------------------------------------
|
|
110
|
+
/**
|
|
111
|
+
* Submit an improvement proposal.
|
|
112
|
+
*
|
|
113
|
+
* Validates:
|
|
114
|
+
* 1. Runtime is enabled.
|
|
115
|
+
* 2. Source snapshot schema version is compatible with this runtime.
|
|
116
|
+
*
|
|
117
|
+
* On success appends a `proposed` ledger entry.
|
|
118
|
+
*
|
|
119
|
+
* @throws {RuntimeDisabledError} if the runtime is disabled.
|
|
120
|
+
* @throws {SchemaIncompatibleError} if the snapshot schema is incompatible.
|
|
121
|
+
*/
|
|
122
|
+
async propose(sourceSnapshot, proposal) {
|
|
123
|
+
this.assertEnabled();
|
|
124
|
+
this.assertSchemaCompatible(sourceSnapshot);
|
|
125
|
+
// Reject if this proposal has already been submitted
|
|
126
|
+
const existing = await this.ledger.getLatestEntry(proposal.proposal_id);
|
|
127
|
+
if (existing) {
|
|
128
|
+
throw new InvalidLifecycleTransitionError(proposal.proposal_id, existing.state, 'proposed');
|
|
129
|
+
}
|
|
130
|
+
const entry = {
|
|
131
|
+
entry_id: this.generateId(),
|
|
132
|
+
proposal_id: proposal.proposal_id,
|
|
133
|
+
state: 'proposed',
|
|
134
|
+
actor: proposal.proposed_by,
|
|
135
|
+
timestamp: new Date().toISOString(),
|
|
136
|
+
previous_entry_id: null,
|
|
137
|
+
payload: { kind: 'proposed', proposal, source_snapshot: sourceSnapshot },
|
|
138
|
+
};
|
|
139
|
+
await this.ledger.append(entry);
|
|
140
|
+
return entry;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* Record the evaluation result for a proposal.
|
|
144
|
+
*
|
|
145
|
+
* Transitions `proposed → evaluated` (pass) or `proposed → rejected` (fail).
|
|
146
|
+
* Rejection occurs when the evaluation did not pass.
|
|
147
|
+
*
|
|
148
|
+
* @throws {InvalidLifecycleTransitionError} if proposal is not in `proposed` state.
|
|
149
|
+
*/
|
|
150
|
+
async evaluate(proposalId, result, evaluatedBy) {
|
|
151
|
+
this.assertEnabled();
|
|
152
|
+
const current = await this.requireLatestEntry(proposalId, 'proposed');
|
|
153
|
+
const nextState = result.passed ? 'evaluated' : 'rejected';
|
|
154
|
+
this.assertValidTransition(proposalId, current.state, nextState);
|
|
155
|
+
const entry = {
|
|
156
|
+
entry_id: this.generateId(),
|
|
157
|
+
proposal_id: proposalId,
|
|
158
|
+
state: nextState,
|
|
159
|
+
actor: evaluatedBy,
|
|
160
|
+
timestamp: new Date().toISOString(),
|
|
161
|
+
previous_entry_id: current.entry_id,
|
|
162
|
+
payload: nextState === 'evaluated'
|
|
163
|
+
? { kind: 'evaluated', result }
|
|
164
|
+
: { kind: 'rejected', reason: `Evaluation failed: score ${result.score} below threshold`, at_state: 'proposed' },
|
|
165
|
+
};
|
|
166
|
+
await this.ledger.append(entry);
|
|
167
|
+
return entry;
|
|
168
|
+
}
|
|
169
|
+
/**
|
|
170
|
+
* Approve an evaluated proposal.
|
|
171
|
+
*
|
|
172
|
+
* Transitions `evaluated → approved`.
|
|
173
|
+
*
|
|
174
|
+
* Governance enforcement:
|
|
175
|
+
* - Resolves the required verification policy from the proposal's context.
|
|
176
|
+
* - Rejects if `verificationResult.verification_method` does not meet the
|
|
177
|
+
* required policy strength.
|
|
178
|
+
* - TLP:RED always requires `human_required`.
|
|
179
|
+
* - `production_direct` scope requires at minimum `third_party_audit`.
|
|
180
|
+
*
|
|
181
|
+
* @throws {InvalidLifecycleTransitionError} if proposal is not in `evaluated` state.
|
|
182
|
+
* @throws {GovernanceViolationError} if the verification policy is insufficient.
|
|
183
|
+
*/
|
|
184
|
+
async approve(proposalId, verificationResult, approvedBy) {
|
|
185
|
+
this.assertEnabled();
|
|
186
|
+
const current = await this.requireLatestEntry(proposalId, 'evaluated');
|
|
187
|
+
this.assertValidTransition(proposalId, current.state, 'approved');
|
|
188
|
+
// Extract context from the original proposed entry
|
|
189
|
+
const proposedEntry = await this.requireProposedEntry(proposalId);
|
|
190
|
+
const proposedPayload = proposedEntry.payload;
|
|
191
|
+
if (proposedPayload.kind !== 'proposed') {
|
|
192
|
+
throw new Error(`Unexpected payload kind for proposed entry: ${proposedPayload.kind}`);
|
|
193
|
+
}
|
|
194
|
+
const context = proposedPayload.proposal.context;
|
|
195
|
+
// Resolve required policy and enforce
|
|
196
|
+
const requiredPolicy = resolveRequiredPolicy(context, this.config.governance);
|
|
197
|
+
const providedPolicy = verificationResult.verification_method;
|
|
198
|
+
if (!meetsVerificationThreshold(providedPolicy, requiredPolicy)) {
|
|
199
|
+
const reason = this.buildGovernanceViolationReason(context, requiredPolicy);
|
|
200
|
+
throw new GovernanceViolationError(proposalId, providedPolicy, requiredPolicy, reason);
|
|
201
|
+
}
|
|
202
|
+
// If verification itself did not pass, reject instead
|
|
203
|
+
if (!verificationResult.verified) {
|
|
204
|
+
this.assertValidTransition(proposalId, current.state, 'rejected');
|
|
205
|
+
const rejectedEntry = {
|
|
206
|
+
entry_id: this.generateId(),
|
|
207
|
+
proposal_id: proposalId,
|
|
208
|
+
state: 'rejected',
|
|
209
|
+
actor: approvedBy,
|
|
210
|
+
timestamp: new Date().toISOString(),
|
|
211
|
+
previous_entry_id: current.entry_id,
|
|
212
|
+
payload: {
|
|
213
|
+
kind: 'rejected',
|
|
214
|
+
reason: 'Verification did not pass',
|
|
215
|
+
at_state: 'evaluated',
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
await this.ledger.append(rejectedEntry);
|
|
219
|
+
return rejectedEntry;
|
|
220
|
+
}
|
|
221
|
+
const entry = {
|
|
222
|
+
entry_id: this.generateId(),
|
|
223
|
+
proposal_id: proposalId,
|
|
224
|
+
state: 'approved',
|
|
225
|
+
actor: approvedBy,
|
|
226
|
+
timestamp: new Date().toISOString(),
|
|
227
|
+
previous_entry_id: current.entry_id,
|
|
228
|
+
payload: { kind: 'approved', verification_result: verificationResult, approved_by: approvedBy },
|
|
229
|
+
};
|
|
230
|
+
await this.ledger.append(entry);
|
|
231
|
+
return entry;
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* Apply an approved proposal, recording the resulting policy snapshot.
|
|
235
|
+
*
|
|
236
|
+
* Transitions `approved → applied`.
|
|
237
|
+
*
|
|
238
|
+
* @throws {InvalidLifecycleTransitionError} if proposal is not in `approved` state.
|
|
239
|
+
*/
|
|
240
|
+
async apply(proposalId, resultSnapshot, appliedBy) {
|
|
241
|
+
this.assertEnabled();
|
|
242
|
+
const current = await this.requireLatestEntry(proposalId, 'approved');
|
|
243
|
+
this.assertValidTransition(proposalId, current.state, 'applied');
|
|
244
|
+
const entry = {
|
|
245
|
+
entry_id: this.generateId(),
|
|
246
|
+
proposal_id: proposalId,
|
|
247
|
+
state: 'applied',
|
|
248
|
+
actor: appliedBy,
|
|
249
|
+
timestamp: new Date().toISOString(),
|
|
250
|
+
previous_entry_id: current.entry_id,
|
|
251
|
+
payload: { kind: 'applied', result_snapshot: resultSnapshot },
|
|
252
|
+
};
|
|
253
|
+
await this.ledger.append(entry);
|
|
254
|
+
return entry;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Roll back an applied proposal to a prior snapshot.
|
|
258
|
+
*
|
|
259
|
+
* Transitions `applied → rolled_back`.
|
|
260
|
+
*
|
|
261
|
+
* @throws {InvalidLifecycleTransitionError} if proposal is not in `applied` state.
|
|
262
|
+
*/
|
|
263
|
+
async rollback(proposalId, reason, restoredSnapshotId, rolledBackBy) {
|
|
264
|
+
this.assertEnabled();
|
|
265
|
+
const current = await this.requireLatestEntry(proposalId, 'applied');
|
|
266
|
+
this.assertValidTransition(proposalId, current.state, 'rolled_back');
|
|
267
|
+
const entry = {
|
|
268
|
+
entry_id: this.generateId(),
|
|
269
|
+
proposal_id: proposalId,
|
|
270
|
+
state: 'rolled_back',
|
|
271
|
+
actor: rolledBackBy,
|
|
272
|
+
timestamp: new Date().toISOString(),
|
|
273
|
+
previous_entry_id: current.entry_id,
|
|
274
|
+
payload: { kind: 'rolled_back', reason, restored_snapshot_id: restoredSnapshotId },
|
|
275
|
+
};
|
|
276
|
+
await this.ledger.append(entry);
|
|
277
|
+
return entry;
|
|
278
|
+
}
|
|
279
|
+
/**
|
|
280
|
+
* Return the current lifecycle state of a proposal, or null if unknown.
|
|
281
|
+
*/
|
|
282
|
+
async getState(proposalId) {
|
|
283
|
+
const entry = await this.ledger.getLatestEntry(proposalId);
|
|
284
|
+
return entry?.state ?? null;
|
|
285
|
+
}
|
|
286
|
+
// -------------------------------------------------------------------------
|
|
287
|
+
// Private helpers
|
|
288
|
+
// -------------------------------------------------------------------------
|
|
289
|
+
assertEnabled() {
|
|
290
|
+
if (!this.config.enabled) {
|
|
291
|
+
throw new RuntimeDisabledError();
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
assertSchemaCompatible(snapshot) {
|
|
295
|
+
if (!isSchemaCompatible(this.config.policy_schema_version, snapshot.schema_version)) {
|
|
296
|
+
throw new SchemaIncompatibleError(snapshot.snapshot_id, formatSchemaVersion(snapshot.schema_version), formatSchemaVersion(this.config.policy_schema_version));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
assertValidTransition(proposalId, from, to) {
|
|
300
|
+
const valid = VALID_LIFECYCLE_TRANSITIONS.some(([f, t]) => f === from && t === to);
|
|
301
|
+
if (!valid) {
|
|
302
|
+
throw new InvalidLifecycleTransitionError(proposalId, from, to);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
async requireLatestEntry(proposalId, expectedState) {
|
|
306
|
+
const entry = await this.ledger.getLatestEntry(proposalId);
|
|
307
|
+
if (!entry) {
|
|
308
|
+
throw new Error(`No ledger entry found for proposal ${proposalId}`);
|
|
309
|
+
}
|
|
310
|
+
if (entry.state !== expectedState) {
|
|
311
|
+
throw new InvalidLifecycleTransitionError(proposalId, entry.state, expectedState);
|
|
312
|
+
}
|
|
313
|
+
return entry;
|
|
314
|
+
}
|
|
315
|
+
async requireProposedEntry(proposalId) {
|
|
316
|
+
const entries = await this.ledger.getEntriesForProposal(proposalId);
|
|
317
|
+
const proposed = entries.find((e) => e.payload.kind === 'proposed');
|
|
318
|
+
if (!proposed) {
|
|
319
|
+
throw new Error(`No proposed entry found for proposal ${proposalId}`);
|
|
320
|
+
}
|
|
321
|
+
return proposed;
|
|
322
|
+
}
|
|
323
|
+
buildGovernanceViolationReason(context, requiredPolicy) {
|
|
324
|
+
if (context.tlp_classification === 'RED') {
|
|
325
|
+
return `TLP:RED context requires human_required verification`;
|
|
326
|
+
}
|
|
327
|
+
if (context.scope === 'production_direct') {
|
|
328
|
+
return `production_direct scope requires at least third_party_audit`;
|
|
329
|
+
}
|
|
330
|
+
return `context requires ${requiredPolicy}`;
|
|
331
|
+
}
|
|
332
|
+
/**
|
|
333
|
+
* Assert governance config invariants at construction time.
|
|
334
|
+
* Prevents misconfiguration that would weaken production safety gates.
|
|
335
|
+
*/
|
|
336
|
+
assertGovernanceInvariants(config) {
|
|
337
|
+
const gov = config.governance;
|
|
338
|
+
if (VERIFICATION_POLICY_STRENGTH[gov.production_direct_min_policy] <
|
|
339
|
+
VERIFICATION_POLICY_STRENGTH['third_party_audit']) {
|
|
340
|
+
throw new Error(`GovernanceConfig.production_direct_min_policy must be at least "third_party_audit" — got "${gov.production_direct_min_policy}"`);
|
|
341
|
+
}
|
|
342
|
+
if (gov.tlp_red_policy !== 'human_required') {
|
|
343
|
+
throw new Error(`GovernanceConfig.tlp_red_policy must be "human_required" — got "${gov.tlp_red_policy}"`);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
// ---------------------------------------------------------------------------
|
|
348
|
+
// In-memory ledger (for testing and shadow mode)
|
|
349
|
+
// ---------------------------------------------------------------------------
|
|
350
|
+
/**
|
|
351
|
+
* Simple in-memory ImprovementLedger.
|
|
352
|
+
* Used in tests and non-production shadow mode.
|
|
353
|
+
* Not suitable for production (no persistence, no durability guarantees).
|
|
354
|
+
*/
|
|
355
|
+
export class InMemoryImprovementLedger {
|
|
356
|
+
entries = new Map();
|
|
357
|
+
async append(entry) {
|
|
358
|
+
const existing = this.entries.get(entry.proposal_id) ?? [];
|
|
359
|
+
// Idempotent: skip if entry_id already present
|
|
360
|
+
if (existing.some((e) => e.entry_id === entry.entry_id))
|
|
361
|
+
return;
|
|
362
|
+
this.entries.set(entry.proposal_id, [...existing, entry]);
|
|
363
|
+
}
|
|
364
|
+
async getEntriesForProposal(proposalId) {
|
|
365
|
+
return this.entries.get(proposalId) ?? [];
|
|
366
|
+
}
|
|
367
|
+
async getLatestEntry(proposalId) {
|
|
368
|
+
const entries = this.entries.get(proposalId) ?? [];
|
|
369
|
+
return entries[entries.length - 1] ?? null;
|
|
370
|
+
}
|
|
371
|
+
/** Test helper: clear all entries. */
|
|
372
|
+
clear() {
|
|
373
|
+
this.entries.clear();
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
// ---------------------------------------------------------------------------
|
|
377
|
+
// Factory
|
|
378
|
+
// ---------------------------------------------------------------------------
|
|
379
|
+
/**
|
|
380
|
+
* Create a MetacognitiveImprovementRuntime with the default governance config.
|
|
381
|
+
*/
|
|
382
|
+
export function createMetacognitiveRuntime(options = {}) {
|
|
383
|
+
const config = {
|
|
384
|
+
enabled: options.enabled ?? false,
|
|
385
|
+
policy_schema_version: { major: 1, minor: 0, patch: 0 },
|
|
386
|
+
governance: DEFAULT_GOVERNANCE_CONFIG,
|
|
387
|
+
};
|
|
388
|
+
const ledger = options.ledger ?? new InMemoryImprovementLedger();
|
|
389
|
+
return new MetacognitiveImprovementRuntime(config, ledger, options.generateId);
|
|
390
|
+
}
|
|
391
|
+
//# sourceMappingURL=runtime.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runtime.js","sourceRoot":"","sources":["../../../packages/ai/metacognition/runtime.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;GAmBG;AAUH,OAAO,EACL,2BAA2B,EAC3B,yBAAyB,EACzB,4BAA4B,EAC5B,kBAAkB,EAClB,0BAA0B,EAC1B,qBAAqB,EACrB,mBAAmB,GACpB,MAAM,YAAY,CAAC;AAwCpB,8EAA8E;AAC9E,iBAAiB;AACjB,8EAA8E;AAE9E,gEAAgE;AAChE,MAAM,OAAO,+BAAgC,SAAQ,KAAK;IAEtC;IACA;IACA;IAHlB,YACkB,WAAmB,EACnB,IAA+B,EAC/B,EAA6B;QAE7C,KAAK,CACH,6CAA6C,WAAW,KAAK,IAAI,MAAM,EAAE,EAAE,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OAAO,EAAE,OAAO,CAAC,OAAO,IAAI,KAAK;QACjC,qBAAqB,EAAE,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE;QACvD,UAAU,EAAE,yBAAyB;KACtC,CAAC;IACF,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,yBAAyB,EAAE,CAAC;IACjE,OAAO,IAAI,+BAA+B,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,CAAC,UAAU,CAAC,CAAC;AACjF,CAAC"}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Metacognitive Improvement — Structured Telemetry
|
|
3
|
+
* TLP:AMBER - Internal Use Only
|
|
4
|
+
*
|
|
5
|
+
* Emits structured telemetry events for the metacognitive improvement lifecycle.
|
|
6
|
+
* Tracks proposal throughput, approval ratio, and rollback rate.
|
|
7
|
+
*
|
|
8
|
+
* The telemetry system is intentionally thin and side-effect-free:
|
|
9
|
+
* - Events are emitted to registered sinks (console, remote, in-memory).
|
|
10
|
+
* - Sinks are async and non-blocking; errors are caught and ignored.
|
|
11
|
+
* - The default sink writes structured JSON to stdout (compatible with log aggregators).
|
|
12
|
+
*
|
|
13
|
+
* @module ai/metacognition/telemetry
|
|
14
|
+
*/
|
|
15
|
+
import type { ImprovementLifecycleState } from './types.js';
|
|
16
|
+
/** All metacognitive lifecycle event types. */
|
|
17
|
+
export type MetacogTelemetryEventType = 'metacog.proposal.submitted' | 'metacog.proposal.evaluated' | 'metacog.proposal.approved' | 'metacog.proposal.rejected' | 'metacog.proposal.applied' | 'metacog.proposal.rolled_back' | 'metacog.transfer.evaluated';
|
|
18
|
+
/** Base fields present on every metacognitive telemetry event. */
|
|
19
|
+
export interface MetacogTelemetryEventBase {
|
|
20
|
+
event: MetacogTelemetryEventType;
|
|
21
|
+
/** ISO timestamp when the event was emitted. */
|
|
22
|
+
timestamp: string;
|
|
23
|
+
proposal_id: string;
|
|
24
|
+
/** Actor that triggered the event (agent id or human reviewer id). */
|
|
25
|
+
actor: string;
|
|
26
|
+
domain: string;
|
|
27
|
+
tlp_classification: string;
|
|
28
|
+
scope: string;
|
|
29
|
+
trace_id?: string;
|
|
30
|
+
session_id?: string;
|
|
31
|
+
}
|
|
32
|
+
/** Emitted when a proposal is submitted to the runtime. */
|
|
33
|
+
export interface ProposalSubmittedEvent extends MetacogTelemetryEventBase {
|
|
34
|
+
event: 'metacog.proposal.submitted';
|
|
35
|
+
source_snapshot_id: string;
|
|
36
|
+
}
|
|
37
|
+
/** Emitted when a proposal finishes evaluation (pass or fail). */
|
|
38
|
+
export interface ProposalEvaluatedEvent extends MetacogTelemetryEventBase {
|
|
39
|
+
event: 'metacog.proposal.evaluated';
|
|
40
|
+
passed: boolean;
|
|
41
|
+
score: number;
|
|
42
|
+
regression_detected: boolean;
|
|
43
|
+
}
|
|
44
|
+
/** Emitted when a proposal is approved. */
|
|
45
|
+
export interface ProposalApprovedEvent extends MetacogTelemetryEventBase {
|
|
46
|
+
event: 'metacog.proposal.approved';
|
|
47
|
+
verification_method: string;
|
|
48
|
+
}
|
|
49
|
+
/** Emitted when a proposal is rejected (at any lifecycle stage). */
|
|
50
|
+
export interface ProposalRejectedEvent extends MetacogTelemetryEventBase {
|
|
51
|
+
event: 'metacog.proposal.rejected';
|
|
52
|
+
rejected_at_state: ImprovementLifecycleState;
|
|
53
|
+
reason: string;
|
|
54
|
+
}
|
|
55
|
+
/** Emitted when a proposal is applied. */
|
|
56
|
+
export interface ProposalAppliedEvent extends MetacogTelemetryEventBase {
|
|
57
|
+
event: 'metacog.proposal.applied';
|
|
58
|
+
result_snapshot_id: string;
|
|
59
|
+
}
|
|
60
|
+
/** Emitted when a proposal is rolled back. */
|
|
61
|
+
export interface ProposalRolledBackEvent extends MetacogTelemetryEventBase {
|
|
62
|
+
event: 'metacog.proposal.rolled_back';
|
|
63
|
+
reason: string;
|
|
64
|
+
restored_snapshot_id: string;
|
|
65
|
+
}
|
|
66
|
+
/** Emitted when a transfer evaluation completes. */
|
|
67
|
+
export interface TransferEvaluatedEvent extends MetacogTelemetryEventBase {
|
|
68
|
+
event: 'metacog.transfer.evaluated';
|
|
69
|
+
source_domain_id: string;
|
|
70
|
+
target_domain_ids: string[];
|
|
71
|
+
transfer_score: number;
|
|
72
|
+
promotable: boolean;
|
|
73
|
+
}
|
|
74
|
+
/** Union of all metacognitive telemetry events. */
|
|
75
|
+
export type MetacogTelemetryEvent = ProposalSubmittedEvent | ProposalEvaluatedEvent | ProposalApprovedEvent | ProposalRejectedEvent | ProposalAppliedEvent | ProposalRolledBackEvent | TransferEvaluatedEvent;
|
|
76
|
+
/** Receives emitted telemetry events. Must not throw. */
|
|
77
|
+
export type TelemetrySink = (event: MetacogTelemetryEvent) => void | Promise<void>;
|
|
78
|
+
/**
|
|
79
|
+
* Running metrics for a metacognitive improvement session or time window.
|
|
80
|
+
* Provides throughput, approval ratio, and rollback rate.
|
|
81
|
+
*/
|
|
82
|
+
export interface MetacogMetrics {
|
|
83
|
+
/** Total proposals submitted. */
|
|
84
|
+
proposals_submitted: number;
|
|
85
|
+
/** Proposals that passed evaluation. */
|
|
86
|
+
proposals_evaluated_pass: number;
|
|
87
|
+
/** Proposals that failed evaluation or were rejected. */
|
|
88
|
+
proposals_evaluated_fail: number;
|
|
89
|
+
/** Proposals approved (verification passed). */
|
|
90
|
+
proposals_approved: number;
|
|
91
|
+
/** Proposals applied to production. */
|
|
92
|
+
proposals_applied: number;
|
|
93
|
+
/** Proposals rolled back after apply. */
|
|
94
|
+
proposals_rolled_back: number;
|
|
95
|
+
/** Approval ratio: approved / submitted (0–1, or null if none submitted). */
|
|
96
|
+
approval_ratio: number | null;
|
|
97
|
+
/** Rollback rate: rolled_back / applied (0–1, or null if none applied). */
|
|
98
|
+
rollback_rate: number | null;
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Emits structured telemetry events and aggregates running metrics.
|
|
102
|
+
*
|
|
103
|
+
* Usage:
|
|
104
|
+
* ```typescript
|
|
105
|
+
* const emitter = new MetacogTelemetryEmitter([consoleSink]);
|
|
106
|
+
* emitter.proposalSubmitted({ proposal_id, actor, domain, ... });
|
|
107
|
+
* const metrics = emitter.getMetrics();
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export declare class MetacogTelemetryEmitter {
|
|
111
|
+
private readonly sinks;
|
|
112
|
+
private counts;
|
|
113
|
+
constructor(sinks?: TelemetrySink[]);
|
|
114
|
+
proposalSubmitted(fields: Omit<ProposalSubmittedEvent, 'event' | 'timestamp'>): void;
|
|
115
|
+
proposalEvaluated(fields: Omit<ProposalEvaluatedEvent, 'event' | 'timestamp'>): void;
|
|
116
|
+
proposalApproved(fields: Omit<ProposalApprovedEvent, 'event' | 'timestamp'>): void;
|
|
117
|
+
proposalRejected(fields: Omit<ProposalRejectedEvent, 'event' | 'timestamp'>): void;
|
|
118
|
+
proposalApplied(fields: Omit<ProposalAppliedEvent, 'event' | 'timestamp'>): void;
|
|
119
|
+
proposalRolledBack(fields: Omit<ProposalRolledBackEvent, 'event' | 'timestamp'>): void;
|
|
120
|
+
transferEvaluated(fields: Omit<TransferEvaluatedEvent, 'event' | 'timestamp'>): void;
|
|
121
|
+
/**
|
|
122
|
+
* Return computed metrics from all events observed since construction.
|
|
123
|
+
*/
|
|
124
|
+
getMetrics(): MetacogMetrics;
|
|
125
|
+
/** Reset all counters (useful for time-windowed metrics). */
|
|
126
|
+
resetMetrics(): void;
|
|
127
|
+
private emit;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Default sink: writes structured JSON to stdout.
|
|
131
|
+
* Compatible with log aggregators that parse JSON lines.
|
|
132
|
+
*/
|
|
133
|
+
export declare const defaultConsoleSink: TelemetrySink;
|
|
134
|
+
/**
|
|
135
|
+
* In-memory sink: collects events for test assertions.
|
|
136
|
+
*/
|
|
137
|
+
export declare class InMemoryTelemetrySink {
|
|
138
|
+
readonly events: MetacogTelemetryEvent[];
|
|
139
|
+
readonly sink: TelemetrySink;
|
|
140
|
+
/** Filter events by type. */
|
|
141
|
+
byType<T extends MetacogTelemetryEvent>(type: T['event']): T[];
|
|
142
|
+
clear(): void;
|
|
143
|
+
}
|
|
144
|
+
//# sourceMappingURL=telemetry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"telemetry.d.ts","sourceRoot":"","sources":["../../../packages/ai/metacognition/telemetry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAM5D,+CAA+C;AAC/C,MAAM,MAAM,yBAAyB,GACjC,4BAA4B,GAC5B,4BAA4B,GAC5B,2BAA2B,GAC3B,2BAA2B,GAC3B,0BAA0B,GAC1B,8BAA8B,GAC9B,4BAA4B,CAAC;AAEjC,kEAAkE;AAClE,MAAM,WAAW,yBAAyB;IACxC,KAAK,EAAE,yBAAyB,CAAC;IACjC,gDAAgD;IAChD,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,CAAC;IACpB,sEAAsE;IACtE,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,kBAAkB,EAAE,MAAM,CAAC;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED,2DAA2D;AAC3D,MAAM,WAAW,sBAAuB,SAAQ,yBAAyB;IACvE,KAAK,EAAE,4BAA4B,CAAC;IACpC,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED,kEAAkE;AAClE,MAAM,WAAW,sBAAuB,SAAQ,yBAAyB;IACvE,KAAK,EAAE,4BAA4B,CAAC;IACpC,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,mBAAmB,EAAE,OAAO,CAAC;CAC9B;AAED,2CAA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