create-principles-disciple 1.150.1 → 1.150.2
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/_release/product-identity.json +1 -1
- package/codex-adapter/dist/ingestion/ingestion.d.ts +9 -7
- package/codex-adapter/dist/ingestion/ingestion.js +68 -144
- package/codex-adapter/dist/ingestion/transcript-decoder.d.ts +35 -44
- package/codex-adapter/dist/ingestion/transcript-decoder.js +23 -84
- package/codex-adapter/dist/ingestion/transcript-source.d.ts +29 -0
- package/codex-adapter/dist/ingestion/transcript-source.js +65 -0
- package/codex-adapter/dist/pd-hook.d.ts +5 -0
- package/codex-adapter/dist/pd-hook.js +8 -1
- package/console/dist/server/routes/examiner-eligibility.d.ts +73 -0
- package/console/dist/server/routes/examiner-eligibility.js +326 -0
- package/console/dist/server/routes/examiner.js +66 -8
- package/console/dist/web/assets/app.css +40 -0
- package/console/dist/web/assets/app.js +30 -30
- package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
- package/core/dist/runtime/config/pd-config-effective.js +5 -2
- package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
- package/core/package.json +1 -1
- package/dist/installers/codex-host-installer.d.ts.map +1 -1
- package/dist/installers/codex-host-installer.js +20 -0
- package/dist/installers/codex-host-installer.js.map +1 -1
- package/host-runtime/dist/adaptive-priority-provider.d.ts +7 -0
- package/host-runtime/dist/adaptive-priority-provider.js +34 -2
- package/host-runtime/dist/adaptive-skip-decision.d.ts +61 -0
- package/host-runtime/dist/adaptive-skip-decision.js +114 -0
- package/host-runtime/dist/codex-ingestion-consent.d.ts +32 -95
- package/host-runtime/dist/codex-ingestion-consent.js +33 -205
- package/host-runtime/dist/conversation-ingestion/consent.d.ts +124 -0
- package/host-runtime/dist/conversation-ingestion/consent.js +531 -0
- package/host-runtime/dist/conversation-ingestion/index.d.ts +12 -0
- package/host-runtime/dist/conversation-ingestion/index.js +12 -0
- package/host-runtime/dist/conversation-ingestion/pipeline.d.ts +101 -0
- package/host-runtime/dist/conversation-ingestion/pipeline.js +162 -0
- package/host-runtime/dist/conversation-ingestion/source.d.ts +172 -0
- package/host-runtime/dist/conversation-ingestion/source.js +111 -0
- package/host-runtime/dist/conversation-ingestion/text-policy.d.ts +51 -0
- package/host-runtime/dist/conversation-ingestion/text-policy.js +68 -0
- package/host-runtime/dist/governance-observation-store.d.ts +9 -7
- package/host-runtime/dist/governance-observation-store.js +20 -4
- package/host-runtime/dist/index.d.ts +1 -0
- package/host-runtime/dist/index.js +6 -0
- package/host-runtime/package.json +1 -1
- package/package.json +2 -2
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +213 -213
- package/release-manager/dist/installers/codex-host-installer.js +20 -0
- package/release-manager/package.json +1 -1
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation-ingestion consent ledger v3 (PRI-1171; SPEC v0.2 §8.1).
|
|
3
|
+
*
|
|
4
|
+
* Host-neutral successor of the Codex-only consent store: ONE file per
|
|
5
|
+
* workspace, keyed by host kind, at
|
|
6
|
+
* `<workspace>/.state/conversation-ingestion-consent.json`.
|
|
7
|
+
*
|
|
8
|
+
* Authority model (P4, unchanged from v2): the FEATURE FLAGS stay the runtime
|
|
9
|
+
* authority for whether ingestion runs; this ledger is the GOVERNANCE RECORD
|
|
10
|
+
* that the conversation-ingestion flags may only be enabled THROUGH the
|
|
11
|
+
* disclosed consent flow (or an explicit Owner directive). The unified
|
|
12
|
+
* ingestion pipeline additionally consults the recorded decision as its
|
|
13
|
+
* consent gate (SPEC §8.2: host AND ingestion-flag AND consent=granted).
|
|
14
|
+
*
|
|
15
|
+
* v2 → v3 migration (one-way, audit-preserving): when no v3 file exists but a
|
|
16
|
+
* legacy `<workspace>/.pd/codex-ingestion-consent.json` (schema v2) does, the
|
|
17
|
+
* first read migrates it — the v3 file is written FIRST (atomic), then the
|
|
18
|
+
* legacy file is RENAMED with a `.superseded` suffix (never deleted). A crash
|
|
19
|
+
* between the two steps is safe: v3 existing means the legacy file is ignored;
|
|
20
|
+
* no v3 means the migration simply retries. Health and the pipeline read ONLY
|
|
21
|
+
* v3 (single authority — no dual-file ambiguity).
|
|
22
|
+
*
|
|
23
|
+
* Records carry `disclosureVersion`: consent binds to the disclosure text it
|
|
24
|
+
* was granted against. The full-text tier additionally requires the record's
|
|
25
|
+
* disclosureVersion to be at least the current disclosure (see
|
|
26
|
+
* conversation-ingestion/text-policy.ts); an old bounded-era grant stays
|
|
27
|
+
* bounded until a new-disclosure record exists.
|
|
28
|
+
*
|
|
29
|
+
* `decidedVia: 'owner_directive'` records an Owner decision made outside the
|
|
30
|
+
* setup flows (e.g. SPEC approval), with `evidenceRef` pointing at the
|
|
31
|
+
* decision record.
|
|
32
|
+
*
|
|
33
|
+
* Patterns mirror the v2 store: missing file is the normal never-asked case;
|
|
34
|
+
* malformed files fail loud (rc-3/rc-9) because silently treating them as
|
|
35
|
+
* "never asked" could re-enable against a recorded Owner decision; writes are
|
|
36
|
+
* atomic (temp + rename); unknown/malformed fields are rejected via guards,
|
|
37
|
+
* never `as` (rc-1/rc-2/rc-5). This file is consent control state — it never
|
|
38
|
+
* contains captured conversation text.
|
|
39
|
+
*/
|
|
40
|
+
import fs from 'node:fs';
|
|
41
|
+
import path from 'node:path';
|
|
42
|
+
export const CONVERSATION_INGESTION_CONSENT_FILENAME = 'conversation-ingestion-consent.json';
|
|
43
|
+
export const CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION = '3';
|
|
44
|
+
/** Suffix applied to the superseded v2 file (kept on disk for audit; never read again). */
|
|
45
|
+
export const CONVERSATION_INGESTION_CONSENT_SUPERSEDED_SUFFIX = '.superseded';
|
|
46
|
+
/** Legacy v2 authority location (Codex-only era); migrated on first read. */
|
|
47
|
+
export const LEGACY_CODEX_CONSENT_FILENAME = 'codex-ingestion-consent.json';
|
|
48
|
+
export const LEGACY_CODEX_CONSENT_SCHEMA_VERSION = '2';
|
|
49
|
+
export function getConversationIngestionConsentPath(workspaceDir) {
|
|
50
|
+
return path.join(path.resolve(workspaceDir), '.state', CONVERSATION_INGESTION_CONSENT_FILENAME);
|
|
51
|
+
}
|
|
52
|
+
function getLegacyCodexConsentPath(workspaceDir) {
|
|
53
|
+
return path.join(path.resolve(workspaceDir), '.pd', LEGACY_CODEX_CONSENT_FILENAME);
|
|
54
|
+
}
|
|
55
|
+
function isDecision(value) {
|
|
56
|
+
return value === 'granted' || value === 'pending' || value === 'revoked' || value === 'failed';
|
|
57
|
+
}
|
|
58
|
+
function isDecidedVia(value) {
|
|
59
|
+
return value === 'pd_codex_setup' || value === 'codex_plugin_setup' || value === 'owner_directive';
|
|
60
|
+
}
|
|
61
|
+
function isHostKind(value) {
|
|
62
|
+
return value === 'codex' || value === 'workbuddy' || value === 'openclaw';
|
|
63
|
+
}
|
|
64
|
+
function isNonShortString(value, max) {
|
|
65
|
+
return typeof value === 'string' && value.length > 0 && value.length <= max;
|
|
66
|
+
}
|
|
67
|
+
function isIsoTimestamp(value) {
|
|
68
|
+
return isNonShortString(value, 40) && !Number.isNaN(Date.parse(value));
|
|
69
|
+
}
|
|
70
|
+
const RECORD_ALLOWED_KEYS = ['decision', 'disclosureVersion', 'decidedAt', 'decidedVia', 'failureReason', 'evidenceRef', 'schemaVersion'];
|
|
71
|
+
const HOST_KINDS = ['codex', 'workbuddy', 'openclaw'];
|
|
72
|
+
/**
|
|
73
|
+
* Validate ONE host slot against the v3 record contract. Guards, never `as`
|
|
74
|
+
* (rc-1/rc-2); the post-validation reconstruction re-invokes the guards so the
|
|
75
|
+
* type system only sees narrowed fields.
|
|
76
|
+
*/
|
|
77
|
+
function validateRecord(hostKind, value) {
|
|
78
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
|
79
|
+
return { record: null, errors: [`hosts.${hostKind} must be an object`] };
|
|
80
|
+
}
|
|
81
|
+
const obj = value;
|
|
82
|
+
const errors = [];
|
|
83
|
+
for (const key of Object.keys(obj)) {
|
|
84
|
+
if (!RECORD_ALLOWED_KEYS.includes(key))
|
|
85
|
+
errors.push(`hosts.${hostKind} has unknown field '${key}'`);
|
|
86
|
+
}
|
|
87
|
+
if (!isDecision(obj.decision))
|
|
88
|
+
errors.push(`hosts.${hostKind}.decision must be pending|granted|revoked|failed`);
|
|
89
|
+
if (!isNonShortString(obj.disclosureVersion, 40))
|
|
90
|
+
errors.push(`hosts.${hostKind}.disclosureVersion must be a short non-empty string`);
|
|
91
|
+
if (!isIsoTimestamp(obj.decidedAt))
|
|
92
|
+
errors.push(`hosts.${hostKind}.decidedAt must be a parseable ISO-8601 string`);
|
|
93
|
+
if (!isDecidedVia(obj.decidedVia))
|
|
94
|
+
errors.push(`hosts.${hostKind}.decidedVia must be pd_codex_setup|codex_plugin_setup|owner_directive`);
|
|
95
|
+
if (obj.failureReason !== undefined && !isNonShortString(obj.failureReason, 200)) {
|
|
96
|
+
errors.push(`hosts.${hostKind}.failureReason must be a non-empty string (≤200 chars) when present`);
|
|
97
|
+
}
|
|
98
|
+
if (obj.evidenceRef !== undefined && !isNonShortString(obj.evidenceRef, 200)) {
|
|
99
|
+
errors.push(`hosts.${hostKind}.evidenceRef must be a non-empty string (≤200 chars) when present`);
|
|
100
|
+
}
|
|
101
|
+
// NOTE: decision=failed without failureReason is NOT rejected at the read
|
|
102
|
+
// boundary (forward-compat with the v2 posture) — the write side enforces it.
|
|
103
|
+
if (obj.schemaVersion !== CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION) {
|
|
104
|
+
errors.push(`hosts.${hostKind}.schemaVersion must be '${CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION}'`);
|
|
105
|
+
}
|
|
106
|
+
if (errors.length > 0)
|
|
107
|
+
return { record: null, errors };
|
|
108
|
+
return {
|
|
109
|
+
record: {
|
|
110
|
+
decision: isDecision(obj.decision) ? obj.decision : 'failed',
|
|
111
|
+
disclosureVersion: isNonShortString(obj.disclosureVersion, 40) ? obj.disclosureVersion : '',
|
|
112
|
+
decidedAt: isIsoTimestamp(obj.decidedAt) ? obj.decidedAt : '',
|
|
113
|
+
decidedVia: isDecidedVia(obj.decidedVia) ? obj.decidedVia : 'pd_codex_setup',
|
|
114
|
+
...(isNonShortString(obj.failureReason, 200) && obj.failureReason !== undefined ? { failureReason: obj.failureReason } : {}),
|
|
115
|
+
...(isNonShortString(obj.evidenceRef, 200) && obj.evidenceRef !== undefined ? { evidenceRef: obj.evidenceRef } : {}),
|
|
116
|
+
schemaVersion: CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION,
|
|
117
|
+
},
|
|
118
|
+
errors: [],
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
function parseLedgerFile(raw) {
|
|
122
|
+
let parsed;
|
|
123
|
+
try {
|
|
124
|
+
parsed = JSON.parse(raw);
|
|
125
|
+
}
|
|
126
|
+
catch {
|
|
127
|
+
return { ledger: null, errors: ['malformed json'] };
|
|
128
|
+
}
|
|
129
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
130
|
+
return { ledger: null, errors: ['file must be a JSON object'] };
|
|
131
|
+
}
|
|
132
|
+
const obj = parsed;
|
|
133
|
+
const errors = [];
|
|
134
|
+
for (const key of Object.keys(obj)) {
|
|
135
|
+
if (key !== 'schemaVersion' && key !== 'hosts')
|
|
136
|
+
errors.push(`unknown field '${key}'`);
|
|
137
|
+
}
|
|
138
|
+
if (obj.schemaVersion !== CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION) {
|
|
139
|
+
errors.push(`schemaVersion must be '${CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION}'`);
|
|
140
|
+
}
|
|
141
|
+
const hosts = {};
|
|
142
|
+
if (typeof obj.hosts !== 'object' || obj.hosts === null || Array.isArray(obj.hosts)) {
|
|
143
|
+
errors.push('hosts must be an object keyed by host kind');
|
|
144
|
+
}
|
|
145
|
+
else {
|
|
146
|
+
const hostsObj = obj.hosts;
|
|
147
|
+
for (const key of Object.keys(hostsObj)) {
|
|
148
|
+
if (!isHostKind(key)) {
|
|
149
|
+
errors.push(`hosts has unknown host kind '${key}'`);
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const validated = validateRecord(key, hostsObj[key]);
|
|
153
|
+
if (validated.record === null)
|
|
154
|
+
errors.push(...validated.errors);
|
|
155
|
+
else
|
|
156
|
+
hosts[key] = validated.record;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
if (errors.length > 0)
|
|
160
|
+
return { ledger: null, errors };
|
|
161
|
+
return { ledger: { hosts }, errors: [] };
|
|
162
|
+
}
|
|
163
|
+
function unreadable(reason, filePath) {
|
|
164
|
+
return {
|
|
165
|
+
ok: false,
|
|
166
|
+
reason: `conversation_ingestion_consent_unreadable: ${reason.slice(0, 120)}`,
|
|
167
|
+
nextAction: `Fix or delete ${filePath} (delete = consent returns to not_present; the ingestion flags themselves are unchanged)`,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
function malformed(errors, filePath) {
|
|
171
|
+
return {
|
|
172
|
+
ok: false,
|
|
173
|
+
reason: `conversation_ingestion_consent_malformed: ${errors.join('; ').slice(0, 400)}`,
|
|
174
|
+
nextAction: `Fix or delete ${filePath} (delete = consent returns to not_present; the ingestion flags themselves are unchanged)`,
|
|
175
|
+
};
|
|
176
|
+
}
|
|
177
|
+
function writeLedgerAtomically(filePath, ledger) {
|
|
178
|
+
const dir = path.dirname(filePath);
|
|
179
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
180
|
+
const body = `${JSON.stringify({ schemaVersion: CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION, hosts: ledger.hosts }, null, 2)}\n`;
|
|
181
|
+
try {
|
|
182
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
183
|
+
fs.writeFileSync(tmpPath, body, { encoding: 'utf8', mode: 0o600 });
|
|
184
|
+
fs.renameSync(tmpPath, filePath);
|
|
185
|
+
return { ok: true };
|
|
186
|
+
}
|
|
187
|
+
catch (error) {
|
|
188
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
189
|
+
try {
|
|
190
|
+
fs.rmSync(tmpPath, { force: true });
|
|
191
|
+
}
|
|
192
|
+
catch {
|
|
193
|
+
// best-effort cleanup; the write failure below is the loud signal
|
|
194
|
+
}
|
|
195
|
+
return {
|
|
196
|
+
ok: false,
|
|
197
|
+
reason: `conversation_ingestion_consent_write_failed: ${message.slice(0, 200)}`,
|
|
198
|
+
nextAction: `Check permissions on ${dir}`,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* Parse the legacy Codex v2 record (strict — the same posture as the v2 store:
|
|
204
|
+
* garbage is never silently treated as "never asked").
|
|
205
|
+
*/
|
|
206
|
+
function parseLegacyCodexRecord(raw, filePath) {
|
|
207
|
+
let parsed;
|
|
208
|
+
try {
|
|
209
|
+
parsed = JSON.parse(raw);
|
|
210
|
+
}
|
|
211
|
+
catch {
|
|
212
|
+
return { record: null, read: { ok: false, reason: 'legacy_codex_consent_malformed_json', nextAction: `Fix or delete the legacy file ${filePath}; it blocks the v3 migration until readable.` } };
|
|
213
|
+
}
|
|
214
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
|
215
|
+
return { record: null, read: { ok: false, reason: 'legacy_codex_consent_malformed_shape', nextAction: `Fix or delete the legacy file ${filePath}; it blocks the v3 migration until readable.` } };
|
|
216
|
+
}
|
|
217
|
+
const obj = parsed;
|
|
218
|
+
const allowed = ['decision', 'disclosureVersion', 'decidedAt', 'decidedVia', 'failureReason', 'schemaVersion'];
|
|
219
|
+
const errors = [];
|
|
220
|
+
for (const key of Object.keys(obj)) {
|
|
221
|
+
if (!allowed.includes(key))
|
|
222
|
+
errors.push(`unknown field '${key}'`);
|
|
223
|
+
}
|
|
224
|
+
if (!isDecision(obj.decision))
|
|
225
|
+
errors.push('decision must be pending|granted|revoked|failed');
|
|
226
|
+
if (!isNonShortString(obj.disclosureVersion, 40))
|
|
227
|
+
errors.push('disclosureVersion must be a short non-empty string');
|
|
228
|
+
if (!isIsoTimestamp(obj.decidedAt))
|
|
229
|
+
errors.push('decidedAt must be a parseable ISO-8601 string');
|
|
230
|
+
if (!isDecidedVia(obj.decidedVia))
|
|
231
|
+
errors.push('decidedVia must be pd_codex_setup|codex_plugin_setup|owner_directive');
|
|
232
|
+
if (obj.failureReason !== undefined && !isNonShortString(obj.failureReason, 200))
|
|
233
|
+
errors.push('failureReason must be a non-empty string (≤200 chars) when present');
|
|
234
|
+
if (obj.schemaVersion !== LEGACY_CODEX_CONSENT_SCHEMA_VERSION)
|
|
235
|
+
errors.push(`schemaVersion must be '${LEGACY_CODEX_CONSENT_SCHEMA_VERSION}'`);
|
|
236
|
+
if (errors.length > 0) {
|
|
237
|
+
return { record: null, read: { ok: false, reason: `legacy_codex_consent_malformed: ${errors.join('; ').slice(0, 400)}`, nextAction: `Fix or delete the legacy file ${filePath}; it blocks the v3 migration until readable.` } };
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
record: {
|
|
241
|
+
decision: isDecision(obj.decision) ? obj.decision : 'failed',
|
|
242
|
+
disclosureVersion: isNonShortString(obj.disclosureVersion, 40) ? obj.disclosureVersion : '',
|
|
243
|
+
decidedAt: isIsoTimestamp(obj.decidedAt) ? obj.decidedAt : '',
|
|
244
|
+
decidedVia: isDecidedVia(obj.decidedVia) ? obj.decidedVia : 'pd_codex_setup',
|
|
245
|
+
...(isNonShortString(obj.failureReason, 200) && obj.failureReason !== undefined ? { failureReason: obj.failureReason } : {}),
|
|
246
|
+
schemaVersion: CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION,
|
|
247
|
+
},
|
|
248
|
+
read: null,
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Create the v3 ledger ONLY when it does not exist yet (exclusive create).
|
|
253
|
+
* Content lands via a uniquely-named temp file + atomic hard link, so a
|
|
254
|
+
* concurrent creator can never observe a half-written ledger and this writer
|
|
255
|
+
* can never clobber one: `EEXIST` on the link means someone else created the
|
|
256
|
+
* authority first (possibly carrying a NEWER decision — e.g. a revoke), which
|
|
257
|
+
* must be adopted, not overwritten.
|
|
258
|
+
*/
|
|
259
|
+
function createLedgerIfAbsent(filePath, hosts) {
|
|
260
|
+
const dir = path.dirname(filePath);
|
|
261
|
+
const tmpPath = `${filePath}.tmp-${process.pid}-${Date.now()}`;
|
|
262
|
+
const body = `${JSON.stringify({ schemaVersion: CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION, hosts }, null, 2)}\n`;
|
|
263
|
+
try {
|
|
264
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
265
|
+
fs.writeFileSync(tmpPath, body, { encoding: 'utf8', mode: 0o600 });
|
|
266
|
+
try {
|
|
267
|
+
fs.linkSync(tmpPath, filePath); // atomic create-or-EEXIST
|
|
268
|
+
return { ok: true, created: true };
|
|
269
|
+
}
|
|
270
|
+
catch (linkError) {
|
|
271
|
+
const codeValue = typeof linkError === 'object' && linkError !== null && Object.hasOwn(linkError, 'code')
|
|
272
|
+
? linkError.code
|
|
273
|
+
: undefined;
|
|
274
|
+
if (codeValue === 'EEXIST')
|
|
275
|
+
return { ok: true, created: false };
|
|
276
|
+
throw linkError;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
catch (error) {
|
|
280
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
281
|
+
return {
|
|
282
|
+
ok: false,
|
|
283
|
+
reason: `conversation_ingestion_consent_write_failed: ${message.slice(0, 200)}`,
|
|
284
|
+
nextAction: `Check permissions on ${dir}`,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
try {
|
|
289
|
+
fs.rmSync(tmpPath, { force: true });
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
// best-effort temp cleanup; never masks the primary outcome
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
/** Read and validate the existing v3 ledger directly (no recursion back into migration). */
|
|
297
|
+
function adoptExistingLedger(v3Path) {
|
|
298
|
+
let raw;
|
|
299
|
+
try {
|
|
300
|
+
raw = fs.readFileSync(v3Path, 'utf8');
|
|
301
|
+
}
|
|
302
|
+
catch (error) {
|
|
303
|
+
const codeValue = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
|
|
304
|
+
? error.code
|
|
305
|
+
: undefined;
|
|
306
|
+
const code = typeof codeValue === 'string' ? codeValue : String(error);
|
|
307
|
+
return unreadable(code, v3Path);
|
|
308
|
+
}
|
|
309
|
+
const { ledger, errors } = parseLedgerFile(raw);
|
|
310
|
+
if (ledger === null)
|
|
311
|
+
return malformed(errors, v3Path);
|
|
312
|
+
const codexRecord = ledger.hosts.codex ?? null;
|
|
313
|
+
return { ok: true, existed: codexRecord !== null, record: codexRecord };
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Migrate a legacy v2 Codex consent file to the v3 ledger: create v3 only if
|
|
317
|
+
* absent (a concurrent writer's newer decisions win), then rename the legacy
|
|
318
|
+
* file with the superseded suffix. Returns the authoritative record, or a
|
|
319
|
+
* loud failure — never a silent "never asked".
|
|
320
|
+
*/
|
|
321
|
+
function migrateLegacyCodexConsent(workspaceDir) {
|
|
322
|
+
const legacyPath = getLegacyCodexConsentPath(workspaceDir);
|
|
323
|
+
let raw;
|
|
324
|
+
try {
|
|
325
|
+
raw = fs.readFileSync(legacyPath, 'utf8');
|
|
326
|
+
}
|
|
327
|
+
catch (error) {
|
|
328
|
+
const codeValue = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
|
|
329
|
+
? error.code
|
|
330
|
+
: undefined;
|
|
331
|
+
if (codeValue === 'ENOENT')
|
|
332
|
+
return { ok: true, existed: false, record: null };
|
|
333
|
+
const code = typeof codeValue === 'string' ? codeValue : String(error);
|
|
334
|
+
return unreadable(`legacy read ${code}`, legacyPath);
|
|
335
|
+
}
|
|
336
|
+
const { record, read } = parseLegacyCodexRecord(raw, legacyPath);
|
|
337
|
+
if (read !== null)
|
|
338
|
+
return read;
|
|
339
|
+
if (record === null) {
|
|
340
|
+
// Unreachable in practice (parse either returns a record or a read
|
|
341
|
+
// failure); fail loud rather than assert (rc-2 posture).
|
|
342
|
+
return { ok: false, reason: 'legacy_codex_consent_invalid', nextAction: `Fix or delete the legacy file ${legacyPath}; it blocks the v3 migration until readable.` };
|
|
343
|
+
}
|
|
344
|
+
const v3Path = getConversationIngestionConsentPath(workspaceDir);
|
|
345
|
+
const created = createLedgerIfAbsent(v3Path, { codex: record });
|
|
346
|
+
if (!created.ok)
|
|
347
|
+
return { ok: false, reason: created.reason, nextAction: created.nextAction };
|
|
348
|
+
try {
|
|
349
|
+
fs.renameSync(legacyPath, `${legacyPath}${CONVERSATION_INGESTION_CONSENT_SUPERSEDED_SUFFIX}`);
|
|
350
|
+
}
|
|
351
|
+
catch (error) {
|
|
352
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
353
|
+
if (created.created) {
|
|
354
|
+
// v3 is already authoritative on disk; the un-renamed legacy file is
|
|
355
|
+
// inert (reads consult v3 first) but surface the residue loudly (rc-9).
|
|
356
|
+
return {
|
|
357
|
+
ok: true,
|
|
358
|
+
existed: true,
|
|
359
|
+
record,
|
|
360
|
+
migratedFromLegacy: true,
|
|
361
|
+
warnings: [`legacy_consent_rename_failed: ${message.slice(0, 120)}`],
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
// Someone else created v3 AND we could not supersede the legacy file —
|
|
365
|
+
// inert residue; the existing v3 is adopted below (warning surfaces it).
|
|
366
|
+
const adopted = adoptExistingLedger(v3Path);
|
|
367
|
+
if (!adopted.ok)
|
|
368
|
+
return adopted;
|
|
369
|
+
return { ...adopted, migratedFromLegacy: true, warnings: [...(adopted.warnings ?? []), `legacy_consent_rename_failed: ${message.slice(0, 120)}`] };
|
|
370
|
+
}
|
|
371
|
+
if (created.created) {
|
|
372
|
+
return { ok: true, existed: true, record, migratedFromLegacy: true };
|
|
373
|
+
}
|
|
374
|
+
// v3 already existed (concurrent writer completed the migration or landed a
|
|
375
|
+
// NEWER decision): adopt the existing authority — never overwrite it.
|
|
376
|
+
const adopted = adoptExistingLedger(v3Path);
|
|
377
|
+
if (!adopted.ok)
|
|
378
|
+
return adopted;
|
|
379
|
+
return { ...adopted, migratedFromLegacy: true };
|
|
380
|
+
}
|
|
381
|
+
/**
|
|
382
|
+
* Read one host's consent record from the v3 ledger (the ONLY authority).
|
|
383
|
+
* A missing v3 file with an existing legacy v2 Codex file triggers the one-way
|
|
384
|
+
* migration. ENOENT on both is the normal never-asked case.
|
|
385
|
+
*/
|
|
386
|
+
export function readConversationIngestionConsent(workspaceDir, hostKind) {
|
|
387
|
+
const filePath = getConversationIngestionConsentPath(workspaceDir);
|
|
388
|
+
let raw;
|
|
389
|
+
try {
|
|
390
|
+
raw = fs.readFileSync(filePath, 'utf8');
|
|
391
|
+
}
|
|
392
|
+
catch (error) {
|
|
393
|
+
const codeValue = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
|
|
394
|
+
? error.code
|
|
395
|
+
: undefined;
|
|
396
|
+
if (codeValue === 'ENOENT') {
|
|
397
|
+
if (hostKind === 'codex')
|
|
398
|
+
return migrateLegacyCodexConsent(workspaceDir);
|
|
399
|
+
return { ok: true, existed: false, record: null };
|
|
400
|
+
}
|
|
401
|
+
const code = typeof codeValue === 'string' ? codeValue : String(error);
|
|
402
|
+
return unreadable(code, filePath);
|
|
403
|
+
}
|
|
404
|
+
const { ledger, errors } = parseLedgerFile(raw);
|
|
405
|
+
if (ledger === null)
|
|
406
|
+
return malformed(errors, filePath);
|
|
407
|
+
const record = ledger.hosts[hostKind] ?? null;
|
|
408
|
+
return { ok: true, existed: record !== null, record };
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* Record an explicit consent decision for one host (the setup flow presents
|
|
412
|
+
* the frozen disclosure before calling this; an owner_directive record cites
|
|
413
|
+
* its evidenceRef). Other hosts' slots are preserved; the flags themselves are
|
|
414
|
+
* intentionally untouched.
|
|
415
|
+
*/
|
|
416
|
+
export function recordConversationIngestionConsent(workspaceDir, hostKind, input) {
|
|
417
|
+
const errors = [];
|
|
418
|
+
if (input.decidedAt !== undefined && !isIsoTimestamp(input.decidedAt))
|
|
419
|
+
errors.push('decidedAt must be a parseable ISO-8601 string when provided');
|
|
420
|
+
if (input.decision === 'failed' && (input.failureReason === undefined || input.failureReason.trim().length === 0)) {
|
|
421
|
+
errors.push('decision=failed requires a non-empty failureReason');
|
|
422
|
+
}
|
|
423
|
+
if (input.failureReason !== undefined && input.decision !== 'failed' && input.failureReason.trim().length === 0) {
|
|
424
|
+
errors.push('failureReason must be non-empty when provided');
|
|
425
|
+
}
|
|
426
|
+
if (input.evidenceRef !== undefined && !isNonShortString(input.evidenceRef, 200))
|
|
427
|
+
errors.push('evidenceRef must be a non-empty string (≤200 chars) when provided');
|
|
428
|
+
if (input.decidedVia === 'owner_directive' && input.evidenceRef === undefined) {
|
|
429
|
+
errors.push('decidedVia=owner_directive requires an evidenceRef pointing at the decision record');
|
|
430
|
+
}
|
|
431
|
+
if (errors.length > 0) {
|
|
432
|
+
return {
|
|
433
|
+
ok: false,
|
|
434
|
+
reason: 'conversation_ingestion_consent_input_invalid: ' + errors.join('; '),
|
|
435
|
+
nextAction: `Fix the recordConversationIngestionConsent arguments for host '${hostKind}' at the call site.`,
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
// disclosureVersion: explicit (new-disclosure records) — otherwise the
|
|
439
|
+
// caller-bound default must be provided; refusing empty keeps grants
|
|
440
|
+
// attributable to a concrete disclosure text.
|
|
441
|
+
if (input.disclosureVersion !== undefined && !isNonShortString(input.disclosureVersion, 40)) {
|
|
442
|
+
return {
|
|
443
|
+
ok: false,
|
|
444
|
+
reason: 'conversation_ingestion_consent_input_invalid: disclosureVersion must be a short non-empty string when provided',
|
|
445
|
+
nextAction: `Fix the recordConversationIngestionConsent arguments for host '${hostKind}' at the call site.`,
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
if (input.disclosureVersion === undefined) {
|
|
449
|
+
return {
|
|
450
|
+
ok: false,
|
|
451
|
+
reason: 'conversation_ingestion_consent_input_invalid: disclosureVersion is required (consent binds to the disclosure it was granted against)',
|
|
452
|
+
nextAction: `Pass the frozen disclosure version the decision was made against for host '${hostKind}'.`,
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
const record = {
|
|
456
|
+
decision: input.decision,
|
|
457
|
+
disclosureVersion: input.disclosureVersion,
|
|
458
|
+
decidedAt: input.decidedAt ?? new Date().toISOString(),
|
|
459
|
+
decidedVia: input.decidedVia,
|
|
460
|
+
...(input.failureReason !== undefined ? { failureReason: input.failureReason.slice(0, 200) } : {}),
|
|
461
|
+
...(input.evidenceRef !== undefined ? { evidenceRef: input.evidenceRef.slice(0, 200) } : {}),
|
|
462
|
+
schemaVersion: CONVERSATION_INGESTION_CONSENT_SCHEMA_VERSION,
|
|
463
|
+
};
|
|
464
|
+
const filePath = getConversationIngestionConsentPath(workspaceDir);
|
|
465
|
+
// Read-modify-write preserving sibling host slots; a malformed existing
|
|
466
|
+
// ledger fails loud rather than being clobbered (rc-3).
|
|
467
|
+
let hosts = {};
|
|
468
|
+
try {
|
|
469
|
+
const raw = fs.readFileSync(filePath, 'utf8');
|
|
470
|
+
const { ledger, errors: parseErrors } = parseLedgerFile(raw);
|
|
471
|
+
if (ledger === null) {
|
|
472
|
+
return {
|
|
473
|
+
ok: false,
|
|
474
|
+
reason: `conversation_ingestion_consent_malformed: ${parseErrors.join('; ').slice(0, 400)}`,
|
|
475
|
+
nextAction: `Fix or delete ${filePath} before recording a new decision (delete = consent returns to not_present).`,
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
hosts = { ...ledger.hosts };
|
|
479
|
+
}
|
|
480
|
+
catch (error) {
|
|
481
|
+
const codeValue = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
|
|
482
|
+
? error.code
|
|
483
|
+
: undefined;
|
|
484
|
+
if (codeValue !== 'ENOENT') {
|
|
485
|
+
// The caller asked to WRITE: any non-ENOENT failure on the pre-write
|
|
486
|
+
// ledger read (ENOTDIR/EACCES/…) means the authority location itself is
|
|
487
|
+
// unusable — report it with the write-failed vocabulary so the health
|
|
488
|
+
// surface and tests see one failure class on every platform (Linux
|
|
489
|
+
// surfaces ENOTDIR here where Windows reports ENOENT at the write step).
|
|
490
|
+
const code = typeof codeValue === 'string' ? codeValue : String(error);
|
|
491
|
+
return { ok: false, reason: `conversation_ingestion_consent_write_failed: ${code.slice(0, 120)}`, nextAction: `Check permissions on ${filePath}` };
|
|
492
|
+
}
|
|
493
|
+
// First ledger for this workspace — a legacy Codex file must be migrated
|
|
494
|
+
// first regardless of WHICH host is being recorded, so the new record
|
|
495
|
+
// lands in a ledger that already carries history (and the legacy file
|
|
496
|
+
// gets superseded, not orphaned). Skipping this for non-codex hosts would
|
|
497
|
+
// silently abandon a recorded Codex Owner decision (review Major).
|
|
498
|
+
const migrated = migrateLegacyCodexConsent(workspaceDir);
|
|
499
|
+
if (!migrated.ok)
|
|
500
|
+
return { ok: false, reason: migrated.reason, nextAction: migrated.nextAction };
|
|
501
|
+
if (migrated.record !== null)
|
|
502
|
+
hosts = { codex: migrated.record };
|
|
503
|
+
}
|
|
504
|
+
hosts[hostKind] = record;
|
|
505
|
+
const written = writeLedgerAtomically(filePath, { hosts });
|
|
506
|
+
if (!written.ok)
|
|
507
|
+
return { ok: false, reason: written.reason, nextAction: written.nextAction };
|
|
508
|
+
return { ok: true, record };
|
|
509
|
+
}
|
|
510
|
+
/**
|
|
511
|
+
* Combine the consent record with the ingestion flag into the health-surface
|
|
512
|
+
* state. Every flag×record combination maps to exactly one interpretable
|
|
513
|
+
* state — none of them reads as silently healthy.
|
|
514
|
+
*/
|
|
515
|
+
export function deriveConversationIngestionConsentState(record, ingestionFlagEnabled) {
|
|
516
|
+
if (record === null) {
|
|
517
|
+
return ingestionFlagEnabled ? 'flag_on_without_grant' : 'not_present';
|
|
518
|
+
}
|
|
519
|
+
switch (record.decision) {
|
|
520
|
+
case 'granted':
|
|
521
|
+
return 'granted';
|
|
522
|
+
case 'revoked':
|
|
523
|
+
return 'revoked';
|
|
524
|
+
case 'failed':
|
|
525
|
+
return 'failed';
|
|
526
|
+
case 'pending':
|
|
527
|
+
return 'pending';
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
/** Host kinds recognized by the ledger (for health surfaces). */
|
|
531
|
+
export const CONVERSATION_CONSENT_HOST_KINDS = HOST_KINDS;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation-ingestion seam — public face (PRI-1171; SPEC v0.2 §4.1).
|
|
3
|
+
*
|
|
4
|
+
* The host-neutral minimal set: source contract + shared pipeline + consent
|
|
5
|
+
* ledger v3 + text policy. Host decoders live in their own adapter packages
|
|
6
|
+
* (AGENTS §8.2); a new host implements TranscriptSourceAdapter and calls
|
|
7
|
+
* runConversationIngestion — zero changes to this package.
|
|
8
|
+
*/
|
|
9
|
+
export * from './source.js';
|
|
10
|
+
export * from './pipeline.js';
|
|
11
|
+
export * from './consent.js';
|
|
12
|
+
export * from './text-policy.js';
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation-ingestion seam — public face (PRI-1171; SPEC v0.2 §4.1).
|
|
3
|
+
*
|
|
4
|
+
* The host-neutral minimal set: source contract + shared pipeline + consent
|
|
5
|
+
* ledger v3 + text policy. Host decoders live in their own adapter packages
|
|
6
|
+
* (AGENTS §8.2); a new host implements TranscriptSourceAdapter and calls
|
|
7
|
+
* runConversationIngestion — zero changes to this package.
|
|
8
|
+
*/
|
|
9
|
+
export * from './source.js';
|
|
10
|
+
export * from './pipeline.js';
|
|
11
|
+
export * from './consent.js';
|
|
12
|
+
export * from './text-policy.js';
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation-ingestion pipeline — the single orchestration entry for
|
|
3
|
+
* unified host trajectory ingestion (PRI-1171; SPEC v0.2 §4.1).
|
|
4
|
+
*
|
|
5
|
+
* Five segments, host-neutral:
|
|
6
|
+
*
|
|
7
|
+
* gate (flag short-circuit, ZERO port calls) → consent gate → locate →
|
|
8
|
+
* bounded window read (TOCTOU-mapped) → host decode → host contract guard →
|
|
9
|
+
* pre-ingest host side-writes → sanitize-at-store ingest with checkpoint →
|
|
10
|
+
* stop-classified outcome.
|
|
11
|
+
*
|
|
12
|
+
* Ordering invariants carried over verbatim from the Codex path (behavior
|
|
13
|
+
* lock, fixtures in codex-adapter/tests/ingestion/ingestion.test.ts):
|
|
14
|
+
* - flag-off / consent-not-granted short-circuit BEFORE locate — the
|
|
15
|
+
* transcript filesystem boundary receives zero calls (SPEC §10 hard
|
|
16
|
+
* privacy invariant, proven by a port spy);
|
|
17
|
+
* - a host contract guard refusal (e.g. unsupported host version) ingests
|
|
18
|
+
* NOTHING and holds the checkpoint — the next trigger retries;
|
|
19
|
+
* - pre-ingest side-write failure (e.g. verified tool outcomes) holds the
|
|
20
|
+
* checkpoint so the delta retries instead of silently losing facts;
|
|
21
|
+
* - a stable malformed record commits the records BEFORE it, holds the
|
|
22
|
+
* checkpoint at it, and degrades loudly;
|
|
23
|
+
* - an incomplete tail commits what precedes it, parks the checkpoint at
|
|
24
|
+
* the tail start, and reports a warning (transient by design).
|
|
25
|
+
*
|
|
26
|
+
* The pipeline never learns host formats: the source adapter supplies locate
|
|
27
|
+
* + decode + rollout lineage; `degradeTexts` carries host-CLI vocabulary
|
|
28
|
+
* (quarantine commands etc.) so Operator-facing nextActions stay exact.
|
|
29
|
+
*/
|
|
30
|
+
import { type GovernanceObservationInput } from '../governance-observation-store.js';
|
|
31
|
+
import { type HookHints, type SessionRef, type TranscriptDelta, type TranscriptPort, type TranscriptSourceAdapter } from './source.js';
|
|
32
|
+
import type { ConversationIngestionConsentDecision } from './consent.js';
|
|
33
|
+
/** Verdict of a pre-ingest host side-write: failure holds the checkpoint (retry-safe). */
|
|
34
|
+
export type PreIngestVerdict = {
|
|
35
|
+
ok: true;
|
|
36
|
+
} | {
|
|
37
|
+
ok: false;
|
|
38
|
+
reason: string;
|
|
39
|
+
nextAction: string;
|
|
40
|
+
};
|
|
41
|
+
/** Neutral defaults; hosts pass their exact CLI vocabulary to keep Operator-facing text stable. */
|
|
42
|
+
export interface PipelineDegradeTexts {
|
|
43
|
+
/** nextAction for `transcript_read_failed:*`. */
|
|
44
|
+
readonly readFailedNextAction: string;
|
|
45
|
+
/** nextAction for `checkpoint_inconsistent`. */
|
|
46
|
+
readonly checkpointInconsistentNextAction: string;
|
|
47
|
+
/** nextAction for the post-commit `transcript_record_malformed` degradation. */
|
|
48
|
+
readonly malformedNextAction: string;
|
|
49
|
+
/** nextAction for `transcript_record_too_large`. */
|
|
50
|
+
readonly oversizedNextAction: string;
|
|
51
|
+
}
|
|
52
|
+
export interface RunIngestionArgs {
|
|
53
|
+
readonly workspaceDir: string;
|
|
54
|
+
readonly source: TranscriptSourceAdapter;
|
|
55
|
+
readonly session: SessionRef;
|
|
56
|
+
readonly hints: HookHints;
|
|
57
|
+
readonly env?: {
|
|
58
|
+
home?: string | undefined;
|
|
59
|
+
};
|
|
60
|
+
/** The ingestion flag verdict, resolved by the caller BEFORE any I/O (double flag gate stays host-side). */
|
|
61
|
+
readonly flags: {
|
|
62
|
+
ingestionEnabled: boolean;
|
|
63
|
+
};
|
|
64
|
+
/** The host's consent decision from the v3 ledger (see conversation-ingestion/consent.ts). */
|
|
65
|
+
readonly consent: {
|
|
66
|
+
decision: ConversationIngestionConsentDecision | 'not_present';
|
|
67
|
+
};
|
|
68
|
+
readonly now?: Date;
|
|
69
|
+
/** Injected filesystem boundary (tests spy here; production uses the node port). */
|
|
70
|
+
readonly port?: TranscriptPort;
|
|
71
|
+
readonly maxBatchBytes?: number;
|
|
72
|
+
readonly degradeTexts?: Partial<PipelineDegradeTexts>;
|
|
73
|
+
/**
|
|
74
|
+
* Host side-writes that must land BEFORE the checkpoint advances (e.g. Codex
|
|
75
|
+
* verified tool outcomes). A failure holds the checkpoint; the delta retries.
|
|
76
|
+
*/
|
|
77
|
+
readonly preIngest?: (args: {
|
|
78
|
+
workspaceDir: string;
|
|
79
|
+
delta: TranscriptDelta;
|
|
80
|
+
now: Date;
|
|
81
|
+
}) => PreIngestVerdict;
|
|
82
|
+
}
|
|
83
|
+
export type ConversationIngestionOutcome = {
|
|
84
|
+
status: 'ok';
|
|
85
|
+
inserted: number;
|
|
86
|
+
enriched: number;
|
|
87
|
+
duplicates: number;
|
|
88
|
+
warnings: readonly string[];
|
|
89
|
+
lagBytes: number;
|
|
90
|
+
/** Decoded observations (admission candidate derivation stays host-side). */
|
|
91
|
+
observations: readonly GovernanceObservationInput[];
|
|
92
|
+
/** The host session identity the checkpoint/rollout were committed under. */
|
|
93
|
+
sessionIdentity: string;
|
|
94
|
+
checkpointByteOffset: number;
|
|
95
|
+
} | {
|
|
96
|
+
status: 'degraded';
|
|
97
|
+
reason: string;
|
|
98
|
+
nextAction: string;
|
|
99
|
+
warnings: readonly string[];
|
|
100
|
+
};
|
|
101
|
+
export declare function runConversationIngestion(args: RunIngestionArgs): ConversationIngestionOutcome;
|