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.
Files changed (47) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/ingestion.d.ts +9 -7
  3. package/codex-adapter/dist/ingestion/ingestion.js +68 -144
  4. package/codex-adapter/dist/ingestion/transcript-decoder.d.ts +35 -44
  5. package/codex-adapter/dist/ingestion/transcript-decoder.js +23 -84
  6. package/codex-adapter/dist/ingestion/transcript-source.d.ts +29 -0
  7. package/codex-adapter/dist/ingestion/transcript-source.js +65 -0
  8. package/codex-adapter/dist/pd-hook.d.ts +5 -0
  9. package/codex-adapter/dist/pd-hook.js +8 -1
  10. package/console/dist/server/routes/examiner-eligibility.d.ts +73 -0
  11. package/console/dist/server/routes/examiner-eligibility.js +326 -0
  12. package/console/dist/server/routes/examiner.js +66 -8
  13. package/console/dist/web/assets/app.css +40 -0
  14. package/console/dist/web/assets/app.js +30 -30
  15. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  16. package/core/dist/runtime/config/pd-config-effective.js +5 -2
  17. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  18. package/core/package.json +1 -1
  19. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  20. package/dist/installers/codex-host-installer.js +20 -0
  21. package/dist/installers/codex-host-installer.js.map +1 -1
  22. package/host-runtime/dist/adaptive-priority-provider.d.ts +7 -0
  23. package/host-runtime/dist/adaptive-priority-provider.js +34 -2
  24. package/host-runtime/dist/adaptive-skip-decision.d.ts +61 -0
  25. package/host-runtime/dist/adaptive-skip-decision.js +114 -0
  26. package/host-runtime/dist/codex-ingestion-consent.d.ts +32 -95
  27. package/host-runtime/dist/codex-ingestion-consent.js +33 -205
  28. package/host-runtime/dist/conversation-ingestion/consent.d.ts +124 -0
  29. package/host-runtime/dist/conversation-ingestion/consent.js +531 -0
  30. package/host-runtime/dist/conversation-ingestion/index.d.ts +12 -0
  31. package/host-runtime/dist/conversation-ingestion/index.js +12 -0
  32. package/host-runtime/dist/conversation-ingestion/pipeline.d.ts +101 -0
  33. package/host-runtime/dist/conversation-ingestion/pipeline.js +162 -0
  34. package/host-runtime/dist/conversation-ingestion/source.d.ts +172 -0
  35. package/host-runtime/dist/conversation-ingestion/source.js +111 -0
  36. package/host-runtime/dist/conversation-ingestion/text-policy.d.ts +51 -0
  37. package/host-runtime/dist/conversation-ingestion/text-policy.js +68 -0
  38. package/host-runtime/dist/governance-observation-store.d.ts +9 -7
  39. package/host-runtime/dist/governance-observation-store.js +20 -4
  40. package/host-runtime/dist/index.d.ts +1 -0
  41. package/host-runtime/dist/index.js +6 -0
  42. package/host-runtime/package.json +1 -1
  43. package/package.json +2 -2
  44. package/pd-cli/package.json +1 -1
  45. package/plugin/dist/bundle.js +213 -213
  46. package/release-manager/dist/installers/codex-host-installer.js +20 -0
  47. package/release-manager/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "productVersion": "2.8.6",
4
- "sourceCommit": "8851a3be8c3bcacb732609143bfe3d2ac4ba4ea5"
4
+ "sourceCommit": "3d6e2af3cf55ad63b7bb388c005adf4b923eb383"
5
5
  }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Codex conversation ingestion orchestrator (Codex Governance Closure
3
- * Slice A; SPEC rev 2 §7/§9/§17).
3
+ * Slice A; SPEC rev 2 §7/§9/§17; PRI-1171 P1 seam migration).
4
4
  *
5
5
  * Called by pd-hook ONLY after both `host.codex` and
6
6
  * `codex_conversation_ingestion` are enabled — the flag check happens
@@ -9,18 +9,20 @@
9
9
  * hard privacy invariant, proven by a port spy test).
10
10
  *
11
11
  * Responsibilities: extract validated ingestion fields from the raw hook
12
- * payload (Codex protocol facts live in the adapter, not host-runtime),
13
- * authorize the transcript path, run bounded incremental decoding from the
14
- * durable checkpoint, apply the supported-version guard, and hand the
15
- * projected observations to the host-neutral host-runtime seam.
12
+ * payload (Codex protocol facts live in the adapter, not host-runtime), and
13
+ * run the transcript delta through the host-neutral
14
+ * `runConversationIngestion` pipeline with the Codex source adapter
15
+ * (locate/decode/version guard live in transcript-source.ts; the pipeline
16
+ * owns checkpoint, TOCTOU mapping, stop classification, and the store
17
+ * commit). Verified tool outcomes ride the pipeline's pre-ingest hook so a
18
+ * write failure still holds the checkpoint (CR-01 ordering).
16
19
  *
17
20
  * Stop (`turn_complete`) is the turn-complete ingestion trigger (G1 §2);
18
21
  * live `UserPromptSubmit`/`PostToolUse` contribute live observations that
19
22
  * the transcript replay later converges with (SPEC §10 source precedence).
20
23
  */
21
24
  import type { HostEventKind } from '@principles/core/host';
22
- import { type GovernanceSignalCandidate } from '@principles/host-runtime';
23
- import { type TranscriptPort } from './transcript-decoder.js';
25
+ import { type GovernanceSignalCandidate, type TranscriptPort } from '@principles/host-runtime';
24
26
  export interface CodexIngestionOptions {
25
27
  readonly workspaceDir: string;
26
28
  readonly env?: {
@@ -1,8 +1,8 @@
1
- import { ingestGovernanceObservations, readGovernanceCheckpoint, recordVerifiedToolOutcomes, } from '@principles/host-runtime';
1
+ import { ingestGovernanceObservations, recordVerifiedToolOutcomes, runConversationIngestion, } from '@principles/host-runtime';
2
+ import { createNodeTranscriptPort } from './transcript-decoder.js';
3
+ import { createCodexTranscriptSource } from './transcript-source.js';
2
4
  import { resolveCodexHome } from './codex-home.js';
3
5
  import { validateCodexTranscriptPath } from './transcript-path.js';
4
- import { classifyCodexVersion, CODEX_VERSION_NEXT_ACTION } from './codex-version.js';
5
- import { decodeTranscriptWindow, createNodeTranscriptPort, CODEX_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError } from './transcript-decoder.js';
6
6
  import { extractFields } from './ingestion-fields.js';
7
7
  import { buildLiveCorrectionCandidate, buildTranscriptCandidates } from './admission.js';
8
8
  let activePort = null;
@@ -72,6 +72,13 @@ function ingestLiveObservation({ fields, rolloutIdentity, workspaceDir, now }) {
72
72
  rolloutIdentity,
73
73
  };
74
74
  }
75
+ /** Exact Operator-facing degradation texts the Codex CLI vocabulary owns (quarantine commands etc.). */
76
+ const CODEX_PIPELINE_DEGRADE_TEXTS = {
77
+ readFailedNextAction: 'verify the transcript file still exists and is a regular file inside the Codex sessions root.',
78
+ checkpointInconsistentNextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale rollout records via `pd codex ingest quarantine` or re-ingest from a fresh rollout.',
79
+ malformedNextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.',
80
+ oversizedNextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.',
81
+ };
75
82
  /**
76
83
  * SPEC-CODEX-PAIN-CLOSURE-001 CR-01: project decoded CommandExecution facts
77
84
  * onto the shared verified-outcome upgrade. The transcript's model-level call
@@ -109,138 +116,62 @@ function collectVerifiedToolOutcomes(observations) {
109
116
  }
110
117
  return outcomes;
111
118
  }
112
- function ingestTranscriptDelta({ fallbackRootSessionId, canonicalPath, identity, rolloutIdentity, workspaceDir, now, port }) {
113
- const checkpoint = readGovernanceCheckpoint({ workspaceDir, hostKind: 'codex', rolloutIdentity });
114
- if (checkpoint !== null && !('byteOffset' in checkpoint) && 'ok' in checkpoint && checkpoint.ok === false) {
115
- return { status: 'degraded', reason: checkpoint.reason, nextAction: checkpoint.nextAction, warnings: [] };
116
- }
117
- const existing = checkpoint !== null && 'byteOffset' in checkpoint ? checkpoint : null;
118
- const offset = existing !== null ? existing.byteOffset : 0;
119
- let window;
120
- try {
121
- // Post-open revalidation (SPEC §9): the port must prove the opened
122
- // object still carries the identity the validator approved.
123
- window = port.read({ canonicalPath, offset, maxBytes: CODEX_INGESTION_MAX_BATCH_BYTES, expectedIdentity: identity });
124
- }
125
- catch (error) {
126
- if (error instanceof TranscriptReplacedError) {
127
- return { status: 'degraded', reason: 'transcript_replaced', nextAction: 'the transcript changed identity after validation (replacement or symlink swap); refusing to read — the next Stop revalidates the current file.', warnings: [] };
128
- }
129
- const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
130
- return { status: 'degraded', reason: `transcript_read_failed:${detail}`, nextAction: 'verify the transcript file still exists and is a regular file inside the Codex sessions root.', warnings: [] };
131
- }
132
- if (offset > window.fileSize) {
133
- // The file shrank below the committed cursor: replaced or truncated —
134
- // never guess; hold the checkpoint and degrade explicitly.
135
- return { status: 'degraded', reason: 'checkpoint_inconsistent', nextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale rollout records via `pd codex ingest quarantine` or re-ingest from a fresh rollout.', warnings: [] };
136
- }
137
- const byteBoundReached = offset + window.bytes.length < window.fileSize;
138
- const decoded = decodeTranscriptWindow({
139
- bytes: window.bytes,
140
- fileOffset: offset,
141
- byteBoundReached,
142
- rolloutIdentity,
143
- fallbackRootSessionId: existing !== null ? existing.rootSessionId : fallbackRootSessionId,
144
- nowIso: now.toISOString(),
145
- });
146
- // Supported-version guard (SPEC §9): the version signal lives in the
147
- // transcript session_meta (or the committed checkpoint after the first
148
- // batch). Anything below the verified floor or above the verified ceiling
149
- // degrades explicitly — never guess record fields of an unknown contract.
150
- const cliVersion = decoded.rolloutMeta.cliVersion ?? existing?.cliVersion ?? null;
151
- const version = classifyCodexVersion(cliVersion);
152
- if (version.status !== 'supported') {
153
- return {
154
- status: 'degraded',
155
- reason: `${version.reason}:${cliVersion ?? 'unknown'}`,
156
- nextAction: CODEX_VERSION_NEXT_ACTION,
157
- warnings: decoded.warnings,
158
- };
159
- }
160
- const degradations = [];
161
- if (decoded.stop.kind === 'malformed') {
162
- degradations.push({ reason: 'transcript_record_malformed', ...(decoded.stop.ordinal !== null ? { ordinal: decoded.stop.ordinal } : {}), nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.' });
163
- }
164
- else if (decoded.stop.kind === 'oversized_record') {
165
- degradations.push({ reason: 'transcript_record_too_large', nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.' });
166
- }
167
- const rootSessionId = decoded.rolloutMeta.rootSessionId ?? existing?.rootSessionId ?? fallbackRootSessionId;
168
- // CR-01: upgrade text-only live observations with the host-verified exit
169
- // codes BEFORE the checkpoint advances, so a write failure holds the delta
170
- // and the next Stop retries instead of silently losing the verified facts.
171
- const verifiedOutcomes = collectVerifiedToolOutcomes(decoded.observations);
172
- if (verifiedOutcomes.length > 0) {
173
- // SPEC-RULECODE-HOST-PROMOTION-001 R2: stamp the producing host on the
174
- // inserted rows so attribution-aware readers can prove provenance.
175
- const verified = recordVerifiedToolOutcomes({ workspaceDir, sessionId: rootSessionId, outcomes: verifiedOutcomes, hostKind: 'codex' });
176
- const failed = verified.find((result) => result.status === 'unavailable');
177
- if (failed !== undefined) {
178
- const reason = failed.reason === 'trajectory_db_not_found' ? 'verified_outcome_db_unavailable' : `verified_outcome_write_failed:${failed.reason.split(':', 2)[1] ?? ''}`;
179
- return { status: 'degraded', reason, nextAction: 'inspect the workspace trajectory database; the transcript checkpoint was NOT advanced, the next Stop retries this delta.', warnings: decoded.warnings };
180
- }
181
- }
182
- const result = ingestGovernanceObservations({
119
+ /**
120
+ * CR-01 rides the pipeline's pre-ingest hook: upgrade text-only live
121
+ * observations with the host-verified exit codes BEFORE the checkpoint
122
+ * advances, so a write failure holds the delta and the next Stop retries
123
+ * instead of silently losing the verified facts.
124
+ */
125
+ function codexVerifiedOutcomesPreIngest({ workspaceDir, delta, now: _now }) {
126
+ const verifiedOutcomes = collectVerifiedToolOutcomes(delta.observations);
127
+ if (verifiedOutcomes.length === 0)
128
+ return { ok: true };
129
+ // SPEC-RULECODE-HOST-PROMOTION-001 R2: stamp the producing host on the
130
+ // inserted rows so attribution-aware readers can prove provenance.
131
+ const rootSessionId = delta.rollout.rootSessionId ?? '';
132
+ const verified = recordVerifiedToolOutcomes({ workspaceDir, sessionId: rootSessionId, outcomes: verifiedOutcomes, hostKind: 'codex' });
133
+ const failed = verified.find((result) => result.status === 'unavailable');
134
+ if (failed !== undefined) {
135
+ const reason = failed.reason === 'trajectory_db_not_found' ? 'verified_outcome_db_unavailable' : `verified_outcome_write_failed:${failed.reason.split(':', 2)[1] ?? ''}`;
136
+ return { ok: false, reason, nextAction: 'inspect the workspace trajectory database; the transcript checkpoint was NOT advanced, the next Stop retries this delta.' };
137
+ }
138
+ return { ok: true };
139
+ }
140
+ function ingestTranscriptDelta({ fallbackRootSessionId, transcriptPath, workspaceDir, env, now, port }) {
141
+ const outcome = runConversationIngestion({
183
142
  workspaceDir,
184
- rollout: {
185
- hostKind: 'codex',
186
- rolloutIdentity,
187
- rootSessionId,
188
- ...(decoded.rolloutMeta.parentRolloutIdentity !== null ? { parentRolloutIdentity: decoded.rolloutMeta.parentRolloutIdentity } : {}),
189
- ...(decoded.rolloutMeta.agentIdentity !== null ? { agentIdentity: decoded.rolloutMeta.agentIdentity } : {}),
190
- ...(decoded.rolloutMeta.agentDepth !== null ? { agentDepth: decoded.rolloutMeta.agentDepth } : {}),
191
- },
192
- observations: decoded.observations,
193
- checkpoint: {
194
- hostKind: 'codex',
195
- rolloutIdentity,
196
- byteOffset: decoded.nextByteOffset,
197
- lastOrdinal: decoded.lastOrdinal >= 0 ? decoded.lastOrdinal : existing?.lastOrdinal ?? 0,
198
- cliVersion: cliVersion ?? undefined,
199
- rootSessionId,
200
- incompleteTail: decoded.stop.kind === 'incomplete_tail',
201
- },
202
- ...(degradations.length > 0 ? { degradations } : {}),
203
- ...(decoded.compactionTimestamp !== null ? { compactionTimestamp: decoded.compactionTimestamp } : {}),
204
- ...(decoded.rollbackTurns.length > 0 ? { rollbackTurns: decoded.rollbackTurns } : {}),
143
+ source: createCodexTranscriptSource({ env, fallbackRootSessionId, now }),
144
+ session: { sessionId: fallbackRootSessionId },
145
+ hints: { transcriptPath },
146
+ // PRI-1171 P1 phasing: the double FLAG gate (host.codex ∧
147
+ // codex_conversation_ingestion) is checked by pd-hook / catch-up BEFORE
148
+ // this module is entered, and the consent LEDGER remains the governance
149
+ // record the setup flow enforces (v2 authority model — the runtime gate
150
+ // reads only the flags). The pipeline's consent gate therefore receives
151
+ // the setup-flow invariant 'granted' until the P3 full-text batch wires
152
+ // the real v3 record + disclosureVersion tier.
153
+ flags: { ingestionEnabled: true },
154
+ consent: { decision: 'granted' },
205
155
  now,
156
+ port,
157
+ degradeTexts: CODEX_PIPELINE_DEGRADE_TEXTS,
158
+ preIngest: codexVerifiedOutcomesPreIngest,
206
159
  });
207
- const warnings = [...decoded.warnings, ...result.warnings];
208
- if (!result.ok) {
209
- return { status: 'degraded', reason: result.reason ?? 'governance_write_failed', nextAction: result.nextAction ?? 'inspect the workspace trajectory database.', warnings };
210
- }
211
- if (decoded.stop.kind === 'incomplete_tail') {
212
- warnings.push('transcript_incomplete_tail');
213
- }
214
- if (decoded.stop.kind === 'malformed') {
215
- // The store already committed the records before the malformed line and
216
- // held the checkpoint at it; surface the stable failure loudly (SPEC §14.2).
217
- return {
218
- status: 'degraded',
219
- reason: 'transcript_record_malformed',
220
- nextAction: 'the record is stable-invalid; quarantine this record via `pd codex ingest quarantine` (dry-run default). Later records remain as lag.',
221
- warnings,
222
- };
223
- }
224
- if (decoded.stop.kind === 'oversized_record') {
225
- return {
226
- status: 'degraded',
227
- reason: 'transcript_record_too_large',
228
- nextAction: 'a single transcript record exceeds the bounded-read window; inspect the rollout file.',
229
- warnings,
230
- };
160
+ if (outcome.status === 'degraded') {
161
+ return outcome;
231
162
  }
232
163
  return {
233
164
  status: 'ok',
234
- inserted: result.inserted,
235
- enriched: result.enriched,
236
- duplicates: result.duplicates,
237
- warnings,
238
- lagBytes: Math.max(0, window.fileSize - decoded.nextByteOffset),
165
+ inserted: outcome.inserted,
166
+ enriched: outcome.enriched,
167
+ duplicates: outcome.duplicates,
168
+ warnings: outcome.warnings,
169
+ lagBytes: outcome.lagBytes,
239
170
  // Slice B: transcript-only user turns / tool calls that were never seen
240
171
  // live get their admission evaluation here (SPEC §10/§12) — already
241
172
  // admitted logical keys no-op on the marker.
242
- admissionCandidates: buildTranscriptCandidates(decoded.observations),
243
- rolloutIdentity,
173
+ admissionCandidates: buildTranscriptCandidates(outcome.observations),
174
+ rolloutIdentity: outcome.sessionIdentity,
244
175
  };
245
176
  }
246
177
  export function ingestCodexConversation(rawPayload, kind, options) {
@@ -252,21 +183,22 @@ export function ingestCodexConversation(rawPayload, kind, options) {
252
183
  // SPEC §9: never scan for another file; keep a neutral degraded result.
253
184
  return { status: 'degraded', reason: 'transcript_unavailable', nextAction: 'Codex supplied no transcript for this event; nothing is read or fabricated.', warnings: [] };
254
185
  }
255
- const home = resolveCodexHome(options.env);
256
- if (!home.ok)
257
- return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
258
- const validated = validateCodexTranscriptPath(fields.transcriptPath, home.home);
259
- if (!validated.ok)
260
- return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
261
186
  const now = options.now ?? new Date();
262
187
  if (kind === 'before_prompt_build' || kind === 'after_tool_call') {
188
+ // Live observations key on the rollout identity derived from the SAME
189
+ // validated transcript reference the Stop replay later converges with
190
+ // (SPEC §10) — validate here exactly as before the seam migration.
191
+ const home = resolveCodexHome(options.env);
192
+ if (!home.ok)
193
+ return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
194
+ const validated = validateCodexTranscriptPath(fields.transcriptPath, home.home);
195
+ if (!validated.ok)
196
+ return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
263
197
  return ingestLiveObservation({ fields, rolloutIdentity: validated.rolloutIdentity, workspaceDir: options.workspaceDir, now });
264
198
  }
265
199
  return ingestTranscriptDelta({
266
200
  fallbackRootSessionId: fields.sessionId,
267
- canonicalPath: validated.canonicalPath,
268
- identity: validated.identity,
269
- rolloutIdentity: validated.rolloutIdentity,
201
+ transcriptPath: fields.transcriptPath,
270
202
  workspaceDir: options.workspaceDir,
271
203
  env: options.env ?? {},
272
204
  now,
@@ -282,17 +214,9 @@ export function ingestCodexConversation(rawPayload, kind, options) {
282
214
  * previously-authenticated rollouts (checkpoints), never discovered sessions.
283
215
  */
284
216
  export function ingestCodexTranscriptFromPath(args) {
285
- const home = resolveCodexHome(args.env);
286
- if (!home.ok)
287
- return { status: 'degraded', reason: home.reason, nextAction: home.nextAction, warnings: [] };
288
- const validated = validateCodexTranscriptPath(args.transcriptPath, home.home);
289
- if (!validated.ok)
290
- return { status: 'degraded', reason: validated.reason, nextAction: validated.nextAction, warnings: [] };
291
217
  return ingestTranscriptDelta({
292
218
  fallbackRootSessionId: args.fallbackRootSessionId,
293
- canonicalPath: validated.canonicalPath,
294
- identity: validated.identity,
295
- rolloutIdentity: validated.rolloutIdentity,
219
+ transcriptPath: args.transcriptPath,
296
220
  workspaceDir: args.workspaceDir,
297
221
  env: args.env ?? {},
298
222
  now: args.now ?? new Date(),
@@ -1,47 +1,38 @@
1
- import type { GovernanceObservationInput } from '@principles/host-runtime';
2
- export declare const CODEX_INGESTION_MAX_BATCH_BYTES: number;
3
- export declare const CODEX_INGESTION_MAX_BATCH_RECORDS = 256;
4
- export interface TranscriptReadResult {
5
- /** Raw bytes read from [offset, offset+maxBytes) — never a decoded string, so multi-byte UTF-8 never corrupts offset math. */
6
- readonly bytes: Buffer;
7
- readonly fileSize: number;
8
- }
9
- /** Identity the validator captured pre-open; the port must re-prove it post-open (SPEC §9 TOCTOU). */
10
- export interface TranscriptExpectedIdentity {
11
- readonly dev: number;
12
- readonly ino: number;
13
- readonly size: number;
14
- readonly mtimeMs: number;
15
- }
16
- /** Arguments for one bounded transcript window read. */
17
- export interface TranscriptReadRequest {
18
- readonly canonicalPath: string;
19
- readonly offset: number;
20
- readonly maxBytes: number;
21
- /** Pre-open identity from the validator; the port re-proves it post-open. */
22
- readonly expectedIdentity?: TranscriptExpectedIdentity;
23
- }
24
- /** Filesystem boundary for the transcript read — injectable so tests can spy. */
25
- export interface TranscriptPort {
26
- read(request: TranscriptReadRequest): TranscriptReadResult;
27
- }
28
- /** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
29
- export declare class TranscriptReplacedError extends Error {
30
- constructor();
31
- }
32
- export declare function createNodeTranscriptPort(): TranscriptPort;
33
- export type TranscriptDecodeStop = {
34
- kind: 'eof';
35
- } | {
36
- kind: 'incomplete_tail';
37
- } | {
38
- kind: 'malformed';
39
- ordinal: number | null;
40
- } | {
41
- kind: 'byte_bound';
42
- } | {
43
- kind: 'oversized_record';
44
- };
1
+ /**
2
+ * Codex rollout transcript incremental decoder (Codex Governance Closure
3
+ * Slice A; SPEC rev 2 §9, G1 probe report §6).
4
+ *
5
+ * Decodes a bounded byte window from the durable checkpoint offset and
6
+ * projects ONLY governance-relevant visible facts (SPEC §12 privacy
7
+ * boundary): genuine visible user messages (`content_item_kinds[0] ===
8
+ * "user.text"` — host-injected context arrives as user-role records with
9
+ * other kinds), visible assistant commentary/final messages, and tool
10
+ * execution facts anchored on the `event_msg item_completed
11
+ * CommandExecution` record whose `item.id` IS the hook `tool_use_id` id
12
+ * space (the G1-verified bridge; the model-level `call_id` is a different
13
+ * space). Hidden reasoning, system/developer prompts, world_state,
14
+ * host-injected context, and unknown record bodies are identified by shape
15
+ * and dropped before persistence — never projected, logged, or emitted.
16
+ *
17
+ * Failure classes are distinct (SPEC §14): an incomplete final line (no
18
+ * trailing newline at EOF) is a transient append/flush boundary — the
19
+ * checkpoint does not advance past it and the next ingestion retries; a
20
+ * complete line that fails JSON parsing or envelope validation is a stable
21
+ * malformed record — decoding stops at it without advancing, with a
22
+ * structured reason. Unknown-but-well-formed record types are skipped with
23
+ * a bounded warning and DO advance.
24
+ *
25
+ * PRI-1171 P1: the host-neutral skeleton (TranscriptPort with post-open
26
+ * identity revalidation, batch bounds, stop taxonomy, and the
27
+ * newline-window/incomplete-tail plan) moved to
28
+ * host-runtime/conversation-ingestion/source.ts; this module keeps ONLY the
29
+ * Codex-specific record projection and re-exports the moved names for one
30
+ * version cycle. Behavior is byte-identical (locked by the existing
31
+ * ingestion fixtures).
32
+ */
33
+ import { type GovernanceObservationInput, type TranscriptDecodeStop } from '@principles/host-runtime';
34
+ export { CONVERSATION_INGESTION_MAX_BATCH_BYTES as CODEX_INGESTION_MAX_BATCH_BYTES, CONVERSATION_INGESTION_MAX_BATCH_RECORDS as CODEX_INGESTION_MAX_BATCH_RECORDS, TranscriptReplacedError, createNodeTranscriptPort, } from '@principles/host-runtime';
35
+ export type { TranscriptReadResult, TranscriptExpectedIdentity, TranscriptReadRequest, TranscriptPort, TranscriptDecodeStop, } from '@principles/host-runtime';
45
36
  export interface DecodedDelta {
46
37
  readonly observations: readonly GovernanceObservationInput[];
47
38
  readonly rolloutMeta: {
@@ -21,69 +21,18 @@
21
21
  * malformed record — decoding stops at it without advancing, with a
22
22
  * structured reason. Unknown-but-well-formed record types are skipped with
23
23
  * a bounded warning and DO advance.
24
+ *
25
+ * PRI-1171 P1: the host-neutral skeleton (TranscriptPort with post-open
26
+ * identity revalidation, batch bounds, stop taxonomy, and the
27
+ * newline-window/incomplete-tail plan) moved to
28
+ * host-runtime/conversation-ingestion/source.ts; this module keeps ONLY the
29
+ * Codex-specific record projection and re-exports the moved names for one
30
+ * version cycle. Behavior is byte-identical (locked by the existing
31
+ * ingestion fixtures).
24
32
  */
25
- import fs from 'node:fs';
26
- export const CODEX_INGESTION_MAX_BATCH_BYTES = 1024 * 1024;
27
- export const CODEX_INGESTION_MAX_BATCH_RECORDS = 256;
28
- /** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
29
- export class TranscriptReplacedError extends Error {
30
- constructor() {
31
- super('transcript_replaced_after_validation');
32
- this.name = 'TranscriptReplacedError';
33
- }
34
- }
35
- function identityMatches(opened, expected) {
36
- // Size+mtime fingerprint must ALWAYS hold. When the platform reports a
37
- // Number-safe inode on both sides, the inode must match too (it is what
38
- // catches delete+recreate replacements whose inode got reused on Linux CI
39
- // with a same-ms write; a same-size same-ms recreate remains outside the
40
- // threat model for an append-only host-owned file). On platforms whose
41
- // ino exceeds Number.MAX_SAFE_INTEGER (Windows file IDs), the inode is not
42
- // reliably comparable and the fingerprint alone decides. A false refusal
43
- // is the safe direction: the hook degrades observably and the next Stop
44
- // revalidates and retries.
45
- if (opened.size !== expected.size || opened.mtimeMs !== expected.mtimeMs)
46
- return false;
47
- const comparableIno = expected.ino !== 0 && expected.dev !== 0
48
- && opened.ino !== 0 && Number.isSafeInteger(expected.ino) && Number.isSafeInteger(opened.ino);
49
- if (comparableIno)
50
- return opened.ino === expected.ino && opened.dev === expected.dev;
51
- return true;
52
- }
53
- export function createNodeTranscriptPort() {
54
- return {
55
- read({ canonicalPath, offset, maxBytes, expectedIdentity }) {
56
- const fd = fs.openSync(canonicalPath, 'r');
57
- try {
58
- // Post-open revalidation (G1 §7 / SPEC §9): fstat the OPEN OBJECT —
59
- // not the path — and re-prove it is the regular file the validator
60
- // approved, still at the expected identity. A path swapped between
61
- // validation and open (replacement/symlink TOCTOU) is refused before
62
- // a single byte is read.
63
- const stats = fs.fstatSync(fd);
64
- if (!stats.isFile())
65
- throw new Error('transcript_is_not_regular_file');
66
- if (expectedIdentity !== undefined && !identityMatches(stats, expectedIdentity)) {
67
- throw new TranscriptReplacedError();
68
- }
69
- const length = Math.max(0, Math.min(maxBytes, stats.size - offset));
70
- if (length === 0)
71
- return { bytes: Buffer.alloc(0), fileSize: stats.size };
72
- const buffer = Buffer.alloc(length);
73
- const bytesRead = fs.readSync(fd, buffer, 0, length, offset);
74
- // Post-read byte bound re-verification (EP-08): never trust the
75
- // pre-read stat for the enforced cap.
76
- const actual = bytesRead < 0 ? 0 : bytesRead;
77
- if (actual > maxBytes)
78
- throw new Error('transcript_read_exceeded_bound');
79
- return { bytes: buffer.subarray(0, actual), fileSize: stats.size };
80
- }
81
- finally {
82
- fs.closeSync(fd);
83
- }
84
- },
85
- };
86
- }
33
+ import { CONVERSATION_INGESTION_MAX_BATCH_RECORDS, planJsonlWindow, } from '@principles/host-runtime';
34
+ // Compat re-exports (one version cycle): the seam owns the skeleton now.
35
+ export { CONVERSATION_INGESTION_MAX_BATCH_BYTES as CODEX_INGESTION_MAX_BATCH_BYTES, CONVERSATION_INGESTION_MAX_BATCH_RECORDS as CODEX_INGESTION_MAX_BATCH_RECORDS, TranscriptReplacedError, createNodeTranscriptPort, } from '@principles/host-runtime';
87
36
  function isRecord(value) {
88
37
  return typeof value === 'object' && value !== null && !Array.isArray(value);
89
38
  }
@@ -426,26 +375,16 @@ export function decodeTranscriptWindow(input) {
426
375
  if (bytes.length === 0) {
427
376
  return { ...finish(context, input.fileOffset, -1), stop: { kind: 'eof' } };
428
377
  }
429
- // UTF-8 multi-byte sequences never contain 0x0A, so splitting the byte
430
- // window at newline bytes is safe and keeps the checkpoint byte-exact.
431
- const lastNewline = bytes.lastIndexOf(0x0a);
432
- const completeEnd = lastNewline + 1; // exclusive byte end of the newline-terminated region
433
- const tailBytes = bytes.subarray(completeEnd); // bytes after the final newline (no terminator)
434
- let cursor = input.fileOffset;
378
+ // PRI-1171: the newline-window split (complete lines + unterminated tail)
379
+ // comes from the seam's planJsonlWindow — the same byte-exact
380
+ // incomplete-tail semantics every host inherits.
381
+ const plan = planJsonlWindow(bytes, input.fileOffset);
435
382
  let lastOrdinal = -1;
436
383
  let recordsConsumed = 0;
437
- let lineStart = 0;
438
- while (lineStart < completeEnd) {
439
- const lineEnd = bytes.indexOf(0x0a, lineStart);
440
- if (lineEnd === -1 || lineEnd >= completeEnd)
441
- break;
442
- const lineBytes = bytes.subarray(lineStart, lineEnd);
443
- const recordByteStart = cursor;
444
- cursor = input.fileOffset + lineEnd + 1;
445
- lineStart = lineEnd + 1;
384
+ for (const { bytes: lineBytes, recordByteStart } of plan.lines) {
446
385
  if (lineBytes.length === 0 || lineBytes.toString('utf8').trim().length === 0)
447
386
  continue;
448
- if (recordsConsumed >= CODEX_INGESTION_MAX_BATCH_RECORDS) {
387
+ if (recordsConsumed >= CONVERSATION_INGESTION_MAX_BATCH_RECORDS) {
449
388
  return { ...finish(context, recordByteStart, lastOrdinal), stop: { kind: 'byte_bound' } };
450
389
  }
451
390
  const line = decodeLine(lineBytes);
@@ -459,27 +398,27 @@ export function decodeTranscriptWindow(input) {
459
398
  lastOrdinal = line.ordinal;
460
399
  projectRecord(context, { type: line.type, payload: line.payload ?? {}, ordinal: line.ordinal, recordByteStart, timestamp: line.timestamp });
461
400
  }
462
- if (tailBytes.length > 0) {
463
- const tailStart = cursor; // byte offset where the unterminated tail begins
401
+ if (plan.tail !== null) {
402
+ const tailStart = plan.tail.startOffset; // byte offset where the unterminated tail begins
464
403
  if (input.byteBoundReached) {
465
404
  // The window ended mid-line because of the byte bound — the line is not
466
405
  // known-incomplete; leave it wholly unread and report bounded lag.
467
- if (lastNewline === -1) {
406
+ if (plan.lines.length === 0) {
468
407
  return { ...finish(context, input.fileOffset, lastOrdinal), stop: { kind: 'oversized_record' } };
469
408
  }
470
409
  return { ...finish(context, tailStart, lastOrdinal), stop: { kind: 'byte_bound' } };
471
410
  }
472
- const line = decodeLine(tailBytes);
411
+ const line = decodeLine(plan.tail.bytes);
473
412
  if (line.record !== null && line.type !== null) {
474
413
  // A parseable final line without a trailing newline is a complete
475
414
  // record; consume it and advance the checkpoint to EOF.
476
415
  lastOrdinal = line.ordinal;
477
416
  projectRecord(context, { type: line.type, payload: line.payload ?? {}, ordinal: line.ordinal, recordByteStart: tailStart, timestamp: line.timestamp });
478
- return { ...finish(context, tailStart + tailBytes.length, lastOrdinal), stop: { kind: 'eof' } };
417
+ return { ...finish(context, tailStart + plan.tail.bytes.length, lastOrdinal), stop: { kind: 'eof' } };
479
418
  }
480
419
  // Incomplete final line: transient append/flush boundary — do not
481
420
  // advance past the previous record; the next ingestion retries (SPEC §14.1).
482
421
  return { ...finish(context, tailStart, lastOrdinal), stop: { kind: 'incomplete_tail' } };
483
422
  }
484
- return { ...finish(context, cursor, lastOrdinal), stop: input.byteBoundReached ? { kind: 'byte_bound' } : { kind: 'eof' } };
423
+ return { ...finish(context, plan.completeEndOffset, lastOrdinal), stop: input.byteBoundReached ? { kind: 'byte_bound' } : { kind: 'eof' } };
485
424
  }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Codex transcript source adapter for the host-neutral conversation-ingestion
3
+ * seam (PRI-1171 P1; SPEC v0.2 §4.1/§4.4).
4
+ *
5
+ * Everything Codex-specific about LOCATING and DECODING a rollout lives here:
6
+ * - locate: Codex home resolution + `validateCodexTranscriptPath`
7
+ * containment and pre-open identity capture (SPEC §9 — never scan for
8
+ * another file);
9
+ * - decodeWindow: the rollout record projection (transcript-decoder.ts)
10
+ * plus the supported-version guard, expressed as the seam's data-shaped
11
+ * `guard` verdict so the pipeline can refuse a delta without ingesting
12
+ * or advancing the checkpoint;
13
+ * - rollout lineage (root session / parent / agent / depth / cliVersion)
14
+ * resolved with the committed checkpoint as fallback, exactly as the
15
+ * pre-seam orchestrator did (behavior lock).
16
+ *
17
+ * The seam (host-runtime/conversation-ingestion) stays format-agnostic; this
18
+ * is the per-host thin half of "one decoder per host".
19
+ */
20
+ import type { TranscriptSourceAdapter } from '@principles/host-runtime';
21
+ export interface CodexTranscriptSourceContext {
22
+ readonly env: {
23
+ CODEX_HOME?: string | undefined;
24
+ };
25
+ /** Hook-payload session id — the last-ditch root-session fallback (G1 §4). */
26
+ readonly fallbackRootSessionId: string;
27
+ readonly now: Date;
28
+ }
29
+ export declare function createCodexTranscriptSource(context: CodexTranscriptSourceContext): TranscriptSourceAdapter;