harness-everything 1.0.1 → 1.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.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHANGELOG.md +14 -0
- package/ci/mechanism-394-ledger-match.test.js +219 -0
- package/ci/mechanism-496-claude-capture.test.js +342 -0
- package/ci/mechanism-496-codex-capture.test.js +508 -0
- package/ci/mechanism-496-local-error-cli-edges.test.js +234 -0
- package/ci/mechanism-496-local-error-cli.test.js +517 -0
- package/ci/mechanism-496-local-error-store.test.js +731 -0
- package/ci/mechanism-496-opencode-capture.test.js +483 -0
- package/ci/mechanism-496-review-fixes.test.js +278 -0
- package/hooks/scripts/codex-ledger-lesson.js +103 -27
- package/hooks/scripts/ledger-lesson.js +94 -23
- package/hooks/scripts/lib/ledger-match.js +39 -3
- package/hooks/scripts/lib/local-error-source.js +127 -0
- package/hooks/scripts/lib/local-errors.js +597 -0
- package/hooks/scripts/lib/observations.js +1 -1
- package/opencode-plugin/index.mjs +86 -1
- package/opencode-plugin/plugin.json +1 -1
- package/package.json +2 -1
- package/plugins/harness-everything/.antigravity-plugin/plugin.json +1 -1
- package/plugins/harness-everything/.codex-plugin/plugin.json +1 -1
- package/plugins/harness-everything/hooks/scripts/codex-ledger-lesson.js +103 -27
- package/plugins/harness-everything/hooks/scripts/ledger-lesson.js +94 -23
- package/plugins/harness-everything/hooks/scripts/lib/ledger-match.js +39 -3
- package/plugins/harness-everything/hooks/scripts/lib/local-error-source.js +127 -0
- package/plugins/harness-everything/hooks/scripts/lib/local-errors.js +597 -0
- package/plugins/harness-everything/hooks/scripts/lib/observations.js +1 -1
- package/plugins/harness-everything/plugin.json +1 -1
- package/sbom.cdx.json +7 -7
- package/scripts/errors-local.js +357 -0
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// Local error store (#496 D1): bounded, redacted local storage for tool-failure
|
|
3
|
+
// occurrences and provisional local lessons alongside System One observations.
|
|
4
|
+
// Shares observations.storeRoot(), .index.lock, and atomic JSON writes, while
|
|
5
|
+
// keeping records in errors-index.json (separate from observations-index.json
|
|
6
|
+
// and System One training exports).
|
|
7
|
+
|
|
8
|
+
const crypto = require('node:crypto');
|
|
9
|
+
const path = require('node:path');
|
|
10
|
+
const observations = require('./observations');
|
|
11
|
+
const { resolveWorkspaceIdentity } = require('./harness-state');
|
|
12
|
+
const { validateMatch } = require('./ledger-match');
|
|
13
|
+
|
|
14
|
+
const SCHEMA_VERSION = 1;
|
|
15
|
+
const INDEX_FILE = 'errors-index.json';
|
|
16
|
+
const INDEX_KIND = 'local-error-store';
|
|
17
|
+
const DESTINATIONS = Object.freeze(['harness', 'project', 'unknown']);
|
|
18
|
+
const COMMAND_CLASSES = Object.freeze(['git', 'gh', 'test', 'build', 'package', 'shell']);
|
|
19
|
+
const HOSTS = Object.freeze(['claude', 'codex', 'opencode', 'unknown']);
|
|
20
|
+
const IDENTIFIER_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
21
|
+
const RECORD_ID_PATTERN = /^E-\d{4,}$/;
|
|
22
|
+
const RESERVED_E_PREFIX = /^E-/i;
|
|
23
|
+
const WORKSPACE_CONTEXT_KEYS = Object.freeze([
|
|
24
|
+
'workspace_root', 'workspaceRoot', 'project_root', 'projectRoot',
|
|
25
|
+
'working_directory', 'workingDirectory', 'cwd', 'root',
|
|
26
|
+
]);
|
|
27
|
+
const WORKSPACE_ENV_KEYS = Object.freeze([
|
|
28
|
+
'HARNESS_WORKSPACE_ROOT', 'CLAUDE_PROJECT_DIR', 'CODEX_PROJECT_DIR',
|
|
29
|
+
]);
|
|
30
|
+
const SECRET_QUERY_KEY_PATTERN = /(?:token|secret|password|passwd|api[_-]?key|apikey|auth|sig(?:nature)?|credential|bearer|jwt|private[_-]?key|(?:^|[_-])(?:key|pwd|sid|cred|session|cookie)(?:$|[_-]))/i;
|
|
31
|
+
const SECRET_FRAGMENT_PARAM_PATTERN = /(?:^|[&#])[^=]*(?:token|secret|password|passwd|api[_-]?key|apikey|auth|sig(?:nature)?)=/i;
|
|
32
|
+
|
|
33
|
+
const LIMITS = Object.freeze({
|
|
34
|
+
maxExcerptBytes: 2048,
|
|
35
|
+
maxLessonChars: 4096,
|
|
36
|
+
maxCueChars: 4096,
|
|
37
|
+
maxMatchedLedgerIds: 16,
|
|
38
|
+
maxRecordsPerWorkspace: 200,
|
|
39
|
+
maxTotalRecords: 1000,
|
|
40
|
+
maxIndexBytes: 2 * 1024 * 1024,
|
|
41
|
+
defaultLockTimeoutMs: 50,
|
|
42
|
+
retentionMs: observations.RETENTION_MS,
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
function isObject(value) {
|
|
46
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function validIdentifier(value) {
|
|
50
|
+
return typeof value === 'string' && IDENTIFIER_PATTERN.test(value);
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function escapeRegExp(value) {
|
|
54
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function redactErrorText(text, env = process.env) {
|
|
58
|
+
let out = observations.redact(text);
|
|
59
|
+
for (const key of ['HOME', 'USERPROFILE']) {
|
|
60
|
+
const home = env && typeof env[key] === 'string' ? env[key] : '';
|
|
61
|
+
if (home && home.length > 1) {
|
|
62
|
+
out = out.replace(new RegExp(escapeRegExp(home), 'g'), '<home>');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
// Omit suspected credentials and token-like strings.
|
|
66
|
+
out = out.replace(/(https?:\/\/)([^:@/\s]+):([^@/\s]+)@/gi, '$1<redacted>@');
|
|
67
|
+
out = out.replace(/(\b(?:proxy-)?authorization[ \t]*:[ \t]*)(?:basic|bearer)\b[ \t]+[^\r\n]*/gi, '$1<redacted>');
|
|
68
|
+
out = out.replace(/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}\b/gi, '$1<redacted>');
|
|
69
|
+
out = out.replace(/\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, '<redacted>');
|
|
70
|
+
out = out.replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, '<redacted>');
|
|
71
|
+
out = out.replace(/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/g, '<redacted>');
|
|
72
|
+
out = out.replace(/\b(?:sk|pk|rk|ak|pat|tok)[_-][A-Za-z0-9_-]{16,}\b/gi, '<redacted>');
|
|
73
|
+
out = out.replace(
|
|
74
|
+
/(\b[A-Za-z0-9_]*(?:token|secret|password|passwd|api[_-]?key|auth(?:orization)?)[A-Za-z0-9_]*\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s"'<>|;,]+)/gi,
|
|
75
|
+
'$1<redacted>'
|
|
76
|
+
);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function normalizeCommandClass(input) {
|
|
81
|
+
if (isObject(input)) {
|
|
82
|
+
if (typeof input.commandClass === 'string' && COMMAND_CLASSES.includes(input.commandClass)) {
|
|
83
|
+
return input.commandClass;
|
|
84
|
+
}
|
|
85
|
+
if (input.command !== undefined && input.command !== null) {
|
|
86
|
+
return observations.classifyCommand(input.command);
|
|
87
|
+
}
|
|
88
|
+
return 'shell';
|
|
89
|
+
}
|
|
90
|
+
if (typeof input === 'string' && COMMAND_CLASSES.includes(input)) return input;
|
|
91
|
+
return observations.classifyCommand(input);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function detectDiagnosticFamilies(redactedOutput) {
|
|
95
|
+
const families = new Set();
|
|
96
|
+
const text = String(redactedOutput || '');
|
|
97
|
+
|
|
98
|
+
// Commitlint diagnostic lines: `✖ <message> [<rule-id>]`
|
|
99
|
+
const commitlintRules = new Set();
|
|
100
|
+
for (const line of text.split(/\r?\n/)) {
|
|
101
|
+
const found = line.match(/^\s*✖\s+[^[]+\[([a-z0-9][a-z0-9_-]{0,40})\]\s*$/);
|
|
102
|
+
if (found) commitlintRules.add(found[1]);
|
|
103
|
+
}
|
|
104
|
+
for (const rule of [...commitlintRules].sort()) {
|
|
105
|
+
families.add(`commitlint-${rule}`);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
// Git non-fast-forward rejection.
|
|
109
|
+
if (/\[rejected\][^\n]*non-fast-forward/i.test(text) ||
|
|
110
|
+
(/failed to push some refs/i.test(text) && /non-fast-forward/i.test(text))) {
|
|
111
|
+
families.add('git-non-fast-forward');
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// npm ERR! / npm error code failure.
|
|
115
|
+
if (/^\s*npm (?:ERR!|error\b)/m.test(text)) {
|
|
116
|
+
families.add('npm-err');
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// EPERM / operation not permitted.
|
|
120
|
+
if (/\bEPERM\b/.test(text) || /operation not permitted/i.test(text)) {
|
|
121
|
+
families.add('eperm');
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return [...families].sort();
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function normalizeFallbackText(redactedOutput) {
|
|
128
|
+
return String(redactedOutput || '')
|
|
129
|
+
.toLowerCase()
|
|
130
|
+
.replace(/\b\d{4}-\d{2}-\d{2}[t ]\d{2}[:_]\d{2}[:_]\d{2}(?:[._]\d+)?z?\b/g, '<ts>')
|
|
131
|
+
.replace(/[a-z]:\\[^\s"'<>|]+/g, '<path>')
|
|
132
|
+
.replace(/(?:\/[a-z0-9._-]+){2,}/g, '<path>')
|
|
133
|
+
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/g, '<uuid>')
|
|
134
|
+
.replace(/\b[0-9a-f]{7,64}\b/g, '<hex>')
|
|
135
|
+
.replace(/:\d+:\d+\b/g, ':<loc>')
|
|
136
|
+
.replace(/\b\d+\b/g, '<n>')
|
|
137
|
+
.replace(/\s+/g, ' ')
|
|
138
|
+
.trim();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function normalizeSignature(input, options = {}) {
|
|
142
|
+
const env = options.env || process.env;
|
|
143
|
+
const cmdClass = normalizeCommandClass(input);
|
|
144
|
+
const rawOutput = isObject(input) ? (input.output ?? input.outputExcerpt ?? '') : String(input || '');
|
|
145
|
+
// Redact BEFORE signature derivation so volatile secrets/paths/emails never affect signatures.
|
|
146
|
+
const redacted = redactErrorText(rawOutput, env);
|
|
147
|
+
const families = detectDiagnosticFamilies(redacted);
|
|
148
|
+
|
|
149
|
+
let suffix;
|
|
150
|
+
if (families.length === 1) {
|
|
151
|
+
suffix = families[0];
|
|
152
|
+
} else if (families.length > 1) {
|
|
153
|
+
// Order-independent composite for ambiguous multi-family output (E-0027).
|
|
154
|
+
suffix = `multi-${observations.sha(families.join(','), 8)}`;
|
|
155
|
+
} else {
|
|
156
|
+
const normalized = normalizeFallbackText(redacted);
|
|
157
|
+
suffix = normalized ? `generic-${observations.sha(normalized, 12)}` : 'unknown';
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const candidate = `v1-${cmdClass}-${suffix}`;
|
|
161
|
+
if (candidate.length <= 64 && validIdentifier(candidate)) return candidate;
|
|
162
|
+
return `v1-${cmdClass}-${observations.sha(candidate, 12)}`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function opaqueKey(value) {
|
|
166
|
+
if (typeof value !== 'string' || !value.trim()) return null;
|
|
167
|
+
return observations.sha(value.trim(), 24);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function extractWorkspacePath(input, depth = 0) {
|
|
171
|
+
if (typeof input === 'string' && input.trim()) return input.trim();
|
|
172
|
+
if (!isObject(input) || depth > 2) return null;
|
|
173
|
+
for (const key of WORKSPACE_CONTEXT_KEYS) {
|
|
174
|
+
const value = input[key];
|
|
175
|
+
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
176
|
+
if (isObject(value)) {
|
|
177
|
+
const nested = extractWorkspacePath(value, depth + 1);
|
|
178
|
+
if (nested) return nested;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
for (const key of ['workspace', 'project', 'host', 'context']) {
|
|
182
|
+
if (isObject(input[key])) {
|
|
183
|
+
const nested = extractWorkspacePath(input[key], depth + 1);
|
|
184
|
+
if (nested) return nested;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return null;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function extractBoundEnvRoot(env) {
|
|
191
|
+
if (!isObject(env)) return null;
|
|
192
|
+
for (const key of WORKSPACE_ENV_KEYS) {
|
|
193
|
+
if (typeof env[key] === 'string' && env[key].trim()) return env[key].trim();
|
|
194
|
+
}
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function isBoundedWorkspaceKey(value) {
|
|
199
|
+
return typeof value === 'string' && Boolean(value.trim()) && value.length <= 256 && !/[\0\r\n]/.test(value);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function resolveCanonicalWorkspaceKey(input, options = {}) {
|
|
203
|
+
const env = options.env || process.env;
|
|
204
|
+
const boundPath = extractWorkspacePath(input) || extractBoundEnvRoot(env);
|
|
205
|
+
if (!boundPath) return null;
|
|
206
|
+
const identity = resolveWorkspaceIdentity({ workspaceRoot: boundPath });
|
|
207
|
+
if (!identity || !identity.workspaceRoot || !identity.workspaceKey || identity.workspaceKey === 'unbound-workspace') {
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
return identity.workspaceKey;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function resolveWriterWorkspaceKey(input, options = {}) {
|
|
214
|
+
const hasSuppliedKey = isObject(input) && input.workspaceKey !== undefined && input.workspaceKey !== null && input.workspaceKey !== '';
|
|
215
|
+
const canonicalKey = resolveCanonicalWorkspaceKey(input, options);
|
|
216
|
+
if (!canonicalKey) {
|
|
217
|
+
throw new Error('invalid workspaceKey: resolvable workspace context required');
|
|
218
|
+
}
|
|
219
|
+
if (hasSuppliedKey) {
|
|
220
|
+
if (!isBoundedWorkspaceKey(input.workspaceKey) || input.workspaceKey.trim() !== canonicalKey) {
|
|
221
|
+
throw new Error('invalid workspaceKey: supplied key disagrees with canonical workspace identity');
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
return canonicalKey;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function resolveWorkspaceKey(input, options = {}) {
|
|
228
|
+
return resolveWriterWorkspaceKey(input, options);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function normalizeHost(value) {
|
|
232
|
+
const host = String(value || 'unknown').trim().toLowerCase();
|
|
233
|
+
return HOSTS.includes(host) ? host : 'unknown';
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function normalizeDestination(value, strict = false) {
|
|
237
|
+
if (value === undefined || value === null || value === '') return 'unknown';
|
|
238
|
+
if (typeof value === 'string' && DESTINATIONS.includes(value)) return value;
|
|
239
|
+
if (strict) throw new Error(`invalid destination: ${value}`);
|
|
240
|
+
return 'unknown';
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function normalizeMatchedLedgerIds(ids) {
|
|
244
|
+
if (!Array.isArray(ids)) return [];
|
|
245
|
+
const out = [];
|
|
246
|
+
const seen = new Set();
|
|
247
|
+
for (const item of ids) {
|
|
248
|
+
if (typeof item !== 'string') continue;
|
|
249
|
+
const trimmed = item.trim();
|
|
250
|
+
if (!trimmed || seen.has(trimmed)) continue;
|
|
251
|
+
if (!RECORD_ID_PATTERN.test(trimmed) && !validIdentifier(trimmed)) continue;
|
|
252
|
+
seen.add(trimmed);
|
|
253
|
+
out.push(trimmed);
|
|
254
|
+
if (out.length >= LIMITS.maxMatchedLedgerIds) break;
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function makeProvisionalId(parts) {
|
|
260
|
+
return `p-${observations.sha(JSON.stringify(parts), 20)}`;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function validateProvisionalId(id) {
|
|
264
|
+
if (!validIdentifier(id) || RESERVED_E_PREFIX.test(id)) {
|
|
265
|
+
throw new Error('invalid provisionalId: must be a lowercase matcher identifier outside E- namespace');
|
|
266
|
+
}
|
|
267
|
+
return id;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function hasTokenShapedValue(value) {
|
|
271
|
+
if (typeof value !== 'string' || !value) return false;
|
|
272
|
+
if (/^(?:Bearer|Basic|Token)\s+\S{8,}/i.test(value)) return true;
|
|
273
|
+
if (/\b(?:gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/.test(value)) return true;
|
|
274
|
+
if (/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/.test(value)) return true;
|
|
275
|
+
if (/\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b/.test(value)) return true;
|
|
276
|
+
if (/\b(?:sk|pk|rk|ak|pat|tok|xox[baprs])[_-][A-Za-z0-9_-]{16,}\b/i.test(value)) return true;
|
|
277
|
+
if (/^[0-9a-f]{32,}$/i.test(value)) return true;
|
|
278
|
+
if (value.length >= 24 && /^[A-Za-z0-9._~+/=-]+$/.test(value) &&
|
|
279
|
+
/[A-Za-z]/.test(value) && /\d/.test(value) && (/[A-Z]/.test(value) || /[+/=]/.test(value))) {
|
|
280
|
+
return true;
|
|
281
|
+
}
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
function validateIssueUrl(url) {
|
|
286
|
+
if (url === undefined || url === null || url === '') return null;
|
|
287
|
+
if (typeof url !== 'string' || url.length > 512 || /[\s\0]/.test(url)) {
|
|
288
|
+
throw new Error('invalid issueUrl');
|
|
289
|
+
}
|
|
290
|
+
let parsed;
|
|
291
|
+
try { parsed = new URL(url); } catch (_) { throw new Error('invalid issueUrl'); }
|
|
292
|
+
if (parsed.protocol !== 'https:') throw new Error('invalid issueUrl: https required');
|
|
293
|
+
if (parsed.username !== '' || parsed.password !== '' || /^https:\/\/[^/?#]*@/i.test(url)) {
|
|
294
|
+
throw new Error('invalid issueUrl: userinfo not allowed');
|
|
295
|
+
}
|
|
296
|
+
for (const [key, value] of parsed.searchParams.entries()) {
|
|
297
|
+
if (SECRET_QUERY_KEY_PATTERN.test(key) || hasTokenShapedValue(value)) {
|
|
298
|
+
throw new Error('invalid issueUrl: credential query parameter not allowed');
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
if (parsed.hash) {
|
|
302
|
+
const hashBody = parsed.hash.slice(1);
|
|
303
|
+
if (hasTokenShapedValue(hashBody) || SECRET_FRAGMENT_PARAM_PATTERN.test(hashBody)) {
|
|
304
|
+
throw new Error('invalid issueUrl: credential fragment not allowed');
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return parsed.toString();
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function validatePromotionId(promotionId) {
|
|
311
|
+
if (promotionId === undefined || promotionId === null || promotionId === '') return null;
|
|
312
|
+
if (typeof promotionId !== 'string' || !RECORD_ID_PATTERN.test(promotionId)) {
|
|
313
|
+
throw new Error('invalid promotionId');
|
|
314
|
+
}
|
|
315
|
+
return promotionId;
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
function effectiveLimits(overrides) {
|
|
319
|
+
if (!isObject(overrides)) return LIMITS;
|
|
320
|
+
const pick = (key, fallback) => (Number.isFinite(overrides[key]) && overrides[key] > 0 ? overrides[key] : fallback);
|
|
321
|
+
return {
|
|
322
|
+
maxExcerptBytes: pick('maxExcerptBytes', LIMITS.maxExcerptBytes),
|
|
323
|
+
maxLessonChars: pick('maxLessonChars', LIMITS.maxLessonChars),
|
|
324
|
+
maxCueChars: pick('maxCueChars', LIMITS.maxCueChars),
|
|
325
|
+
maxMatchedLedgerIds: pick('maxMatchedLedgerIds', LIMITS.maxMatchedLedgerIds),
|
|
326
|
+
maxRecordsPerWorkspace: pick('maxRecordsPerWorkspace', LIMITS.maxRecordsPerWorkspace),
|
|
327
|
+
maxTotalRecords: pick('maxTotalRecords', LIMITS.maxTotalRecords),
|
|
328
|
+
maxIndexBytes: pick('maxIndexBytes', LIMITS.maxIndexBytes),
|
|
329
|
+
defaultLockTimeoutMs: pick('defaultLockTimeoutMs', LIMITS.defaultLockTimeoutMs),
|
|
330
|
+
retentionMs: pick('retentionMs', LIMITS.retentionMs),
|
|
331
|
+
};
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function evictOne(records, predicate) {
|
|
335
|
+
// Prefer evicting oldest occurrence before evicting any provisional lesson.
|
|
336
|
+
const occIdx = records.findIndex(r => r.kind === 'occurrence' && predicate(r));
|
|
337
|
+
if (occIdx !== -1) { records.splice(occIdx, 1); return true; }
|
|
338
|
+
const anyIdx = records.findIndex(predicate);
|
|
339
|
+
if (anyIdx !== -1) { records.splice(anyIdx, 1); return true; }
|
|
340
|
+
return false;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function withinRetention(record, now, retentionMs) {
|
|
344
|
+
const ts = Date.parse(record && record.createdAt || '');
|
|
345
|
+
return !Number.isFinite(ts) || ts > now - retentionMs;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function enforceBounds(index, workspaceKey, limits, now) {
|
|
349
|
+
index.records = index.records.filter(r => withinRetention(r, now, limits.retentionMs));
|
|
350
|
+
|
|
351
|
+
// Per-workspace cap.
|
|
352
|
+
const inWorkspace = () => index.records.filter(r => r.workspaceKey === workspaceKey).length;
|
|
353
|
+
while (inWorkspace() > limits.maxRecordsPerWorkspace) {
|
|
354
|
+
if (!evictOne(index.records, r => r.workspaceKey === workspaceKey)) break;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Global record cap.
|
|
358
|
+
while (index.records.length > limits.maxTotalRecords) {
|
|
359
|
+
if (!evictOne(index.records, () => true)) break;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// Total index byte cap.
|
|
363
|
+
while (index.records.length > 1 && Buffer.byteLength(JSON.stringify(index), 'utf8') > limits.maxIndexBytes) {
|
|
364
|
+
if (!evictOne(index.records, () => true)) break;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
function getStorePath(options = {}) {
|
|
369
|
+
const root = options.root || observations.storeRoot(options.env || process.env);
|
|
370
|
+
return { root, file: path.join(root, INDEX_FILE) };
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function loadIndex(file) {
|
|
374
|
+
const raw = observations.readJson(file, null);
|
|
375
|
+
if (raw && raw.schemaVersion === SCHEMA_VERSION && raw.kind === INDEX_KIND && Array.isArray(raw.records)) {
|
|
376
|
+
return raw;
|
|
377
|
+
}
|
|
378
|
+
return { schemaVersion: SCHEMA_VERSION, kind: INDEX_KIND, records: [] };
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
function appendOccurrence(input, options = {}) {
|
|
382
|
+
try {
|
|
383
|
+
if (!isObject(input)) return { status: 'invalid', record: null };
|
|
384
|
+
const env = options.env || process.env;
|
|
385
|
+
const limits = effectiveLimits(options.limits);
|
|
386
|
+
const { root, file } = getStorePath({ root: options.root, env });
|
|
387
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
388
|
+
const createdAt = typeof input.createdAt === 'string' && Number.isFinite(Date.parse(input.createdAt))
|
|
389
|
+
? input.createdAt : new Date(now).toISOString();
|
|
390
|
+
|
|
391
|
+
let workspaceKey;
|
|
392
|
+
try {
|
|
393
|
+
workspaceKey = resolveWriterWorkspaceKey(input, { env });
|
|
394
|
+
} catch (error) {
|
|
395
|
+
return { status: 'invalid', record: null, error: error && error.message ? error.message : String(error) };
|
|
396
|
+
}
|
|
397
|
+
const host = normalizeHost(input.host);
|
|
398
|
+
const sessionKey = opaqueKey(input.sessionKey);
|
|
399
|
+
const toolUseId = opaqueKey(input.toolUseId);
|
|
400
|
+
const commandClass = normalizeCommandClass(input);
|
|
401
|
+
const rawOutput = input.output ?? input.outputExcerpt ?? '';
|
|
402
|
+
const redactedOutput = redactErrorText(rawOutput, env);
|
|
403
|
+
const outputExcerpt = observations.tailBytes(redactedOutput, limits.maxExcerptBytes);
|
|
404
|
+
const signature = typeof input.signature === 'string' && validIdentifier(input.signature)
|
|
405
|
+
? input.signature
|
|
406
|
+
: normalizeSignature({ commandClass, output: redactedOutput }, { env });
|
|
407
|
+
const exitCode = Number.isInteger(input.exitCode) ? input.exitCode : null;
|
|
408
|
+
const matchedLedgerIds = normalizeMatchedLedgerIds(input.matchedLedgerIds);
|
|
409
|
+
const destination = normalizeDestination(input.destination, false);
|
|
410
|
+
|
|
411
|
+
const hasIdempotencyKey = Boolean(sessionKey && toolUseId);
|
|
412
|
+
const provisionalId = hasIdempotencyKey
|
|
413
|
+
? makeProvisionalId(['occurrence', workspaceKey, host, sessionKey, toolUseId])
|
|
414
|
+
: makeProvisionalId(['occurrence', workspaceKey, host, signature, createdAt, crypto.randomBytes(8).toString('hex')]);
|
|
415
|
+
|
|
416
|
+
const record = {
|
|
417
|
+
schemaVersion: SCHEMA_VERSION,
|
|
418
|
+
kind: 'occurrence',
|
|
419
|
+
provisionalId,
|
|
420
|
+
workspaceKey,
|
|
421
|
+
destination,
|
|
422
|
+
createdAt,
|
|
423
|
+
signature,
|
|
424
|
+
source: 'tool-failure',
|
|
425
|
+
host,
|
|
426
|
+
sessionKey,
|
|
427
|
+
toolUseId,
|
|
428
|
+
commandClass,
|
|
429
|
+
exitCode,
|
|
430
|
+
outputExcerpt,
|
|
431
|
+
matchedLedgerIds,
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
const lockTimeoutMs = Number.isFinite(options.lockTimeoutMs) && options.lockTimeoutMs >= 0
|
|
435
|
+
? options.lockTimeoutMs : limits.defaultLockTimeoutMs;
|
|
436
|
+
|
|
437
|
+
let outcome = null;
|
|
438
|
+
let saved = record;
|
|
439
|
+
const locked = observations.withLock(root, () => {
|
|
440
|
+
const index = loadIndex(file);
|
|
441
|
+
if (hasIdempotencyKey) {
|
|
442
|
+
const existing = index.records.find(r =>
|
|
443
|
+
r.kind === 'occurrence' &&
|
|
444
|
+
r.host === host &&
|
|
445
|
+
r.workspaceKey === workspaceKey &&
|
|
446
|
+
r.sessionKey === sessionKey &&
|
|
447
|
+
r.toolUseId === toolUseId
|
|
448
|
+
);
|
|
449
|
+
if (existing) {
|
|
450
|
+
outcome = 'duplicate';
|
|
451
|
+
saved = existing;
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
index.records.push(record);
|
|
456
|
+
enforceBounds(index, workspaceKey, limits, now);
|
|
457
|
+
observations.writeJsonAtomic(file, index);
|
|
458
|
+
outcome = 'appended';
|
|
459
|
+
}, { timeoutMs: lockTimeoutMs });
|
|
460
|
+
|
|
461
|
+
if (!locked) return { status: 'lock-timeout', record: null };
|
|
462
|
+
return { status: outcome || 'appended', record: saved };
|
|
463
|
+
} catch (error) {
|
|
464
|
+
return { status: 'error', record: null, error: error && error.message ? error.message : String(error) };
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function addProvisionalLesson(input, options = {}) {
|
|
469
|
+
if (!isObject(input)) throw new Error('invalid provisional lesson input');
|
|
470
|
+
const env = options.env || process.env;
|
|
471
|
+
const limits = effectiveLimits(options.limits);
|
|
472
|
+
const { root, file } = getStorePath({ root: options.root, env });
|
|
473
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
474
|
+
const createdAt = typeof input.createdAt === 'string' && Number.isFinite(Date.parse(input.createdAt))
|
|
475
|
+
? input.createdAt : new Date(now).toISOString();
|
|
476
|
+
|
|
477
|
+
const workspaceKey = resolveWriterWorkspaceKey(input, { env });
|
|
478
|
+
const destination = normalizeDestination(input.destination, true);
|
|
479
|
+
if (!validIdentifier(input.signature)) throw new Error('invalid signature');
|
|
480
|
+
const match = validateMatch(input.match);
|
|
481
|
+
|
|
482
|
+
if (typeof input.lesson !== 'string' || !input.lesson.trim()) throw new Error('invalid lesson');
|
|
483
|
+
const lesson = redactErrorText(input.lesson.trim(), env).slice(0, limits.maxLessonChars);
|
|
484
|
+
if (!lesson.trim()) throw new Error('invalid lesson');
|
|
485
|
+
|
|
486
|
+
let cue;
|
|
487
|
+
if (input.cue !== undefined && input.cue !== null) {
|
|
488
|
+
if (typeof input.cue !== 'string') throw new Error('invalid cue');
|
|
489
|
+
cue = redactErrorText(input.cue.trim(), env).slice(0, limits.maxCueChars);
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
const issueUrl = validateIssueUrl(input.issueUrl);
|
|
493
|
+
const promotionId = validatePromotionId(input.promotionId);
|
|
494
|
+
|
|
495
|
+
const provisionalId = input.provisionalId !== undefined && input.provisionalId !== null
|
|
496
|
+
? validateProvisionalId(input.provisionalId)
|
|
497
|
+
: makeProvisionalId(['provisional-lesson', workspaceKey, input.signature, match, lesson]);
|
|
498
|
+
|
|
499
|
+
const record = {
|
|
500
|
+
schemaVersion: SCHEMA_VERSION,
|
|
501
|
+
kind: 'provisional-lesson',
|
|
502
|
+
provisionalId,
|
|
503
|
+
workspaceKey,
|
|
504
|
+
destination,
|
|
505
|
+
createdAt,
|
|
506
|
+
signature: input.signature,
|
|
507
|
+
match,
|
|
508
|
+
lesson,
|
|
509
|
+
...(cue !== undefined ? { cue } : {}),
|
|
510
|
+
issueUrl,
|
|
511
|
+
promotionId,
|
|
512
|
+
};
|
|
513
|
+
|
|
514
|
+
const lockTimeoutMs = Number.isFinite(options.lockTimeoutMs) && options.lockTimeoutMs >= 0
|
|
515
|
+
? options.lockTimeoutMs : limits.defaultLockTimeoutMs;
|
|
516
|
+
|
|
517
|
+
let outcome = null;
|
|
518
|
+
let saved = record;
|
|
519
|
+
const locked = observations.withLock(root, () => {
|
|
520
|
+
const index = loadIndex(file);
|
|
521
|
+
const existing = index.records.find(r =>
|
|
522
|
+
r.kind === 'provisional-lesson' &&
|
|
523
|
+
r.workspaceKey === workspaceKey &&
|
|
524
|
+
r.provisionalId === provisionalId
|
|
525
|
+
);
|
|
526
|
+
if (existing) {
|
|
527
|
+
outcome = 'duplicate';
|
|
528
|
+
saved = existing;
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
index.records.push(record);
|
|
532
|
+
enforceBounds(index, workspaceKey, limits, now);
|
|
533
|
+
observations.writeJsonAtomic(file, index);
|
|
534
|
+
outcome = 'appended';
|
|
535
|
+
}, { timeoutMs: lockTimeoutMs });
|
|
536
|
+
|
|
537
|
+
if (!locked) return { status: 'lock-timeout', record: null };
|
|
538
|
+
return { status: outcome || 'appended', record: saved };
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
function listRecords(options = {}) {
|
|
542
|
+
try {
|
|
543
|
+
const env = options.env || process.env;
|
|
544
|
+
const limits = effectiveLimits(options.limits);
|
|
545
|
+
const now = Number.isFinite(options.now) ? options.now : Date.now();
|
|
546
|
+
const { file } = getStorePath({ root: options.root, env });
|
|
547
|
+
const index = loadIndex(file);
|
|
548
|
+
let targetWorkspace = null;
|
|
549
|
+
const hasWorkspaceContext = Boolean(extractWorkspacePath(options));
|
|
550
|
+
const hasSuppliedKey = options.workspaceKey !== undefined && options.workspaceKey !== null && options.workspaceKey !== '';
|
|
551
|
+
if (hasWorkspaceContext) {
|
|
552
|
+
const canonicalKey = resolveCanonicalWorkspaceKey(options, { env });
|
|
553
|
+
if (!canonicalKey) return [];
|
|
554
|
+
if (hasSuppliedKey) {
|
|
555
|
+
if (!isBoundedWorkspaceKey(options.workspaceKey) || options.workspaceKey.trim() !== canonicalKey) {
|
|
556
|
+
return [];
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
targetWorkspace = canonicalKey;
|
|
560
|
+
} else if (hasSuppliedKey) {
|
|
561
|
+
if (!isBoundedWorkspaceKey(options.workspaceKey)) return [];
|
|
562
|
+
targetWorkspace = options.workspaceKey.trim();
|
|
563
|
+
}
|
|
564
|
+
let records = index.records.filter(record => {
|
|
565
|
+
if (!isObject(record)) return false;
|
|
566
|
+
if (!withinRetention(record, now, limits.retentionMs)) return false;
|
|
567
|
+
if (targetWorkspace && record.workspaceKey !== targetWorkspace) return false;
|
|
568
|
+
if (options.kind && record.kind !== options.kind) return false;
|
|
569
|
+
if (options.destination && record.destination !== options.destination) return false;
|
|
570
|
+
if (options.signature && record.signature !== options.signature) return false;
|
|
571
|
+
return true;
|
|
572
|
+
});
|
|
573
|
+
if (Number.isInteger(options.limit) && options.limit >= 0) {
|
|
574
|
+
records = records.slice(-options.limit);
|
|
575
|
+
}
|
|
576
|
+
return records.map(r => JSON.parse(JSON.stringify(r)));
|
|
577
|
+
} catch (_) {
|
|
578
|
+
return [];
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
module.exports = {
|
|
583
|
+
SCHEMA_VERSION,
|
|
584
|
+
INDEX_FILE,
|
|
585
|
+
INDEX_KIND,
|
|
586
|
+
DESTINATIONS,
|
|
587
|
+
COMMAND_CLASSES,
|
|
588
|
+
LIMITS,
|
|
589
|
+
getStorePath,
|
|
590
|
+
resolveWorkspaceKey,
|
|
591
|
+
redactErrorText,
|
|
592
|
+
normalizeSignature,
|
|
593
|
+
validateMatch,
|
|
594
|
+
appendOccurrence,
|
|
595
|
+
addProvisionalLesson,
|
|
596
|
+
listRecords,
|
|
597
|
+
};
|
|
@@ -693,6 +693,6 @@ function handle(payload, env = process.env) {
|
|
|
693
693
|
|
|
694
694
|
module.exports = {
|
|
695
695
|
INTENTS, TIERS, STRATEGIES, RETENTION_MS, PREVIOUS_BYTES, enabled, storeRoot, redact, validLabel, parseLabelLine, stripLabels, tailBytes, sha, normalizeSystemOne, classifyCommand, labelTier, contradictions,
|
|
696
|
-
normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
|
|
696
|
+
normalizeTerms, transcriptMessage, recordTool, emptyBehavior, mergeBehavior, toolFailed, handle, readJson, writeJsonAtomic, withLock, appendRecord, appendRecordDetailed, observationTurnMatch, findObservationTurnMatch, markSessionBackfillBehaviorUnobserved,
|
|
697
697
|
expired, recordText, sweep,
|
|
698
698
|
};
|