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
@@ -0,0 +1,162 @@
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 { ingestGovernanceObservations, readGovernanceCheckpoint, } from '../governance-observation-store.js';
31
+ import { CONVERSATION_INGESTION_MAX_BATCH_BYTES, TranscriptReplacedError, createNodeTranscriptPort, } from './source.js';
32
+ export function runConversationIngestion(args) {
33
+ const texts = {
34
+ readFailedNextAction: 'verify the transcript file still exists and is a regular file inside the host sessions root.',
35
+ checkpointInconsistentNextAction: 'the transcript is shorter than the committed checkpoint; quarantine the stale records or re-ingest from a fresh session.',
36
+ malformedNextAction: 'the record is stable-invalid; quarantine this record. Later records remain as lag.',
37
+ oversizedNextAction: 'a single transcript record exceeds the bounded-read window; inspect the transcript file.',
38
+ ...args.degradeTexts,
39
+ };
40
+ const degraded = (reason, nextAction, warnings) => ({ status: 'degraded', reason, nextAction, warnings });
41
+ // 1. Flag short-circuit — before locate, before ANY port call (SPEC §10).
42
+ if (!args.flags.ingestionEnabled) {
43
+ return degraded('ingestion_disabled', 'enable the conversation-ingestion flag for this host in the workspace .pd/config.yaml to ingest transcripts.', []);
44
+ }
45
+ // 2. Consent gate (SPEC §8.2: host flag AND ingestion flag AND consent=granted).
46
+ if (args.consent.decision !== 'granted') {
47
+ return degraded(`consent_not_granted:${args.consent.decision}`, 'record a granted consent decision for this host (setup flow or Owner directive) before transcript ingestion runs.', []);
48
+ }
49
+ const now = args.now ?? new Date();
50
+ const port = args.port ?? createNodeTranscriptPort();
51
+ // 3. Locate (deterministic, host rules).
52
+ const locator = args.source.locate(args.session, args.hints, args.env ?? {});
53
+ if (locator.status === 'degraded') {
54
+ return degraded(locator.reason, locator.nextAction, []);
55
+ }
56
+ // 4. Durable checkpoint (per host_kind + session identity).
57
+ const checkpoint = readGovernanceCheckpoint({ workspaceDir: args.workspaceDir, hostKind: args.source.hostKind, rolloutIdentity: locator.sessionIdentity });
58
+ if (checkpoint !== null && !('byteOffset' in checkpoint) && 'ok' in checkpoint && checkpoint.ok === false) {
59
+ return degraded(checkpoint.reason, checkpoint.nextAction, []);
60
+ }
61
+ const existing = checkpoint !== null && 'byteOffset' in checkpoint ? checkpoint : null;
62
+ const offset = existing !== null ? existing.byteOffset : 0;
63
+ // 5. One bounded window read; TOCTOU/replacement maps to structured refusals.
64
+ let windowBytes;
65
+ let fileSize;
66
+ try {
67
+ const window = port.read({
68
+ canonicalPath: locator.filePath,
69
+ offset,
70
+ maxBytes: args.maxBatchBytes ?? CONVERSATION_INGESTION_MAX_BATCH_BYTES,
71
+ expectedIdentity: locator.expectedIdentity,
72
+ });
73
+ ({ bytes: windowBytes, fileSize } = window);
74
+ }
75
+ catch (error) {
76
+ if (error instanceof TranscriptReplacedError) {
77
+ return degraded('transcript_replaced', 'the transcript changed identity after validation (replacement or symlink swap); refusing to read — the next Stop revalidates the current file.', []);
78
+ }
79
+ const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
80
+ return degraded(`transcript_read_failed:${detail}`, texts.readFailedNextAction, []);
81
+ }
82
+ if (offset > fileSize) {
83
+ // The file shrank below the committed cursor: replaced or truncated —
84
+ // never guess; hold the checkpoint and degrade explicitly.
85
+ return degraded('checkpoint_inconsistent', texts.checkpointInconsistentNextAction, []);
86
+ }
87
+ // 6. Host decode (pure).
88
+ const byteBoundReached = offset + windowBytes.length < fileSize;
89
+ const delta = args.source.decodeWindow(locator, { bytes: windowBytes, fileOffset: offset, byteBoundReached, fileSize }, existing);
90
+ // 7. Host contract guard — refuse the WHOLE delta, hold the checkpoint.
91
+ if (delta.guard !== null) {
92
+ return degraded(delta.guard.reason, delta.guard.nextAction, delta.warnings);
93
+ }
94
+ // 8. Stop-classified store degradations (recorded on the checkpoint row).
95
+ const degradations = [];
96
+ if (delta.stop.kind === 'malformed') {
97
+ degradations.push({ reason: 'transcript_record_malformed', ...(delta.stop.ordinal !== null ? { ordinal: delta.stop.ordinal } : {}), nextAction: texts.malformedNextAction });
98
+ }
99
+ else if (delta.stop.kind === 'oversized_record') {
100
+ degradations.push({ reason: 'transcript_record_too_large', nextAction: texts.oversizedNextAction });
101
+ }
102
+ const rootSessionId = delta.rollout.rootSessionId ?? existing?.rootSessionId ?? args.session.sessionId;
103
+ // 9. Pre-ingest host side-writes — failure holds the checkpoint (retry-safe).
104
+ if (args.preIngest !== undefined) {
105
+ const verdict = args.preIngest({ workspaceDir: args.workspaceDir, delta, now });
106
+ if (verdict !== null && !verdict.ok) {
107
+ return degraded(verdict.reason, verdict.nextAction, delta.warnings);
108
+ }
109
+ }
110
+ // 10. Sanitize-at-store ingest with the durable checkpoint.
111
+ const result = ingestGovernanceObservations({
112
+ workspaceDir: args.workspaceDir,
113
+ rollout: {
114
+ hostKind: args.source.hostKind,
115
+ rolloutIdentity: locator.sessionIdentity,
116
+ rootSessionId,
117
+ ...(delta.rollout.parentRolloutIdentity !== undefined ? { parentRolloutIdentity: delta.rollout.parentRolloutIdentity } : {}),
118
+ ...(delta.rollout.agentIdentity !== undefined ? { agentIdentity: delta.rollout.agentIdentity } : {}),
119
+ ...(delta.rollout.agentDepth !== undefined ? { agentDepth: delta.rollout.agentDepth } : {}),
120
+ },
121
+ observations: delta.observations,
122
+ checkpoint: {
123
+ hostKind: args.source.hostKind,
124
+ rolloutIdentity: locator.sessionIdentity,
125
+ byteOffset: delta.nextByteOffset,
126
+ lastOrdinal: delta.lastOrdinal >= 0 ? delta.lastOrdinal : existing?.lastOrdinal ?? 0,
127
+ ...(delta.rollout.cliVersion !== undefined ? { cliVersion: delta.rollout.cliVersion } : {}),
128
+ rootSessionId,
129
+ incompleteTail: delta.stop.kind === 'incomplete_tail',
130
+ },
131
+ ...(degradations.length > 0 ? { degradations } : {}),
132
+ ...(delta.compactionTimestamp !== null ? { compactionTimestamp: delta.compactionTimestamp } : {}),
133
+ ...(delta.rollbackTurns.length > 0 ? { rollbackTurns: delta.rollbackTurns } : {}),
134
+ now,
135
+ });
136
+ const warnings = [...delta.warnings, ...result.warnings];
137
+ if (!result.ok) {
138
+ return degraded(result.reason ?? 'governance_write_failed', result.nextAction ?? 'inspect the workspace trajectory database.', warnings);
139
+ }
140
+ if (delta.stop.kind === 'incomplete_tail') {
141
+ warnings.push('transcript_incomplete_tail');
142
+ }
143
+ if (delta.stop.kind === 'malformed') {
144
+ // The store already committed the records before the malformed line and
145
+ // held the checkpoint at it; surface the stable failure loudly.
146
+ return degraded('transcript_record_malformed', texts.malformedNextAction, warnings);
147
+ }
148
+ if (delta.stop.kind === 'oversized_record') {
149
+ return degraded('transcript_record_too_large', texts.oversizedNextAction, warnings);
150
+ }
151
+ return {
152
+ status: 'ok',
153
+ inserted: result.inserted,
154
+ enriched: result.enriched,
155
+ duplicates: result.duplicates,
156
+ warnings,
157
+ lagBytes: Math.max(0, fileSize - delta.nextByteOffset),
158
+ observations: delta.observations,
159
+ sessionIdentity: locator.sessionIdentity,
160
+ checkpointByteOffset: delta.nextByteOffset,
161
+ };
162
+ }
@@ -0,0 +1,172 @@
1
+ import type { GovernanceCheckpointRecord, GovernanceObservationHostKind, GovernanceObservationInput } from '../governance-observation-store.js';
2
+ /** Bounded single-window read: 1 MiB per invocation (hosts loop from checkpoints). */
3
+ export declare const CONVERSATION_INGESTION_MAX_BATCH_BYTES: number;
4
+ /** Bounded records per window before the decode reports a byte-bound stop. */
5
+ export declare const CONVERSATION_INGESTION_MAX_BATCH_RECORDS = 256;
6
+ export interface TranscriptReadResult {
7
+ /** Raw bytes read from [offset, offset+maxBytes) — never a decoded string, so multi-byte UTF-8 never corrupts offset math. */
8
+ readonly bytes: Buffer;
9
+ readonly fileSize: number;
10
+ }
11
+ /** Identity the validator captured pre-open; the port must re-prove it post-open (TOCTOU). */
12
+ export interface TranscriptExpectedIdentity {
13
+ readonly dev: number;
14
+ readonly ino: number;
15
+ readonly size: number;
16
+ readonly mtimeMs: number;
17
+ }
18
+ /** Arguments for one bounded transcript window read. */
19
+ export interface TranscriptReadRequest {
20
+ readonly canonicalPath: string;
21
+ readonly offset: number;
22
+ readonly maxBytes: number;
23
+ /** Pre-open identity from the validator; the port re-proves it post-open. */
24
+ readonly expectedIdentity?: TranscriptExpectedIdentity;
25
+ }
26
+ /** Filesystem boundary for the transcript read — injectable so tests can spy. */
27
+ export interface TranscriptPort {
28
+ read(request: TranscriptReadRequest): TranscriptReadResult;
29
+ }
30
+ /** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
31
+ export declare class TranscriptReplacedError extends Error {
32
+ constructor();
33
+ }
34
+ export declare function createNodeTranscriptPort(): TranscriptPort;
35
+ /**
36
+ * Why a decode stopped. Semantics moved verbatim from the Codex decoder (SPEC
37
+ * rev 2 §14): `incomplete_tail` is transient (retry), `malformed` is stable
38
+ * (stop at the record, never advance past it), `byte_bound`/`oversized_record`
39
+ * report bounded lag, `eof` is a clean end.
40
+ */
41
+ export type TranscriptDecodeStop = {
42
+ kind: 'eof';
43
+ } | {
44
+ kind: 'incomplete_tail';
45
+ } | {
46
+ kind: 'malformed';
47
+ ordinal: number | null;
48
+ } | {
49
+ kind: 'byte_bound';
50
+ } | {
51
+ kind: 'oversized_record';
52
+ };
53
+ export type SeamHostKind = GovernanceObservationHostKind;
54
+ /** The host session being ingested (identity the host's own hooks carry). */
55
+ export interface SessionRef {
56
+ readonly sessionId: string;
57
+ readonly cwd?: string;
58
+ }
59
+ /**
60
+ * Hook-payload hints pointing at the durable transcript. Field names differ
61
+ * by channel: UserPromptSubmit/SessionStart/SessionEnd carry
62
+ * `transcript_path`; Stop carries `agent_transcript_path` (capability-matrix
63
+ * Table A). Hosts read whichever their protocol provides.
64
+ */
65
+ export interface HookHints {
66
+ readonly transcriptPath?: string;
67
+ readonly agentTranscriptPath?: string;
68
+ readonly generationId?: string;
69
+ }
70
+ export type TranscriptLocator = {
71
+ status: 'ok';
72
+ /** Canonical, containment-authorized transcript file path. */
73
+ filePath: string;
74
+ /** Pre-open identity the port will re-prove (TOCTOU). */
75
+ expectedIdentity: TranscriptExpectedIdentity;
76
+ /** The host's durable session identity (Codex rollout uuid / WorkBuddy sessionId) — checkpoint + ingest key. */
77
+ sessionIdentity: string;
78
+ } | {
79
+ status: 'degraded';
80
+ reason: string;
81
+ nextAction: string;
82
+ };
83
+ /** Rollout/session lineage carried alongside a decoded delta (host-filled). */
84
+ export interface TranscriptRolloutContext {
85
+ readonly rootSessionId?: string;
86
+ readonly cliVersion?: string;
87
+ readonly parentRolloutIdentity?: string;
88
+ readonly agentIdentity?: string;
89
+ readonly agentDepth?: number;
90
+ }
91
+ /**
92
+ * Host contract guard verdict: when non-null, the delta is REFUSED — nothing
93
+ * is ingested, the checkpoint does not advance (e.g. Codex supported-version
94
+ * guard: never guess the record contract of an unverified host version).
95
+ */
96
+ export interface TranscriptDecodeGuard {
97
+ readonly reason: string;
98
+ readonly nextAction: string;
99
+ }
100
+ /** Neutral result of decoding one bounded transcript window. */
101
+ export interface TranscriptDelta {
102
+ readonly observations: readonly GovernanceObservationInput[];
103
+ readonly rollout: TranscriptRolloutContext;
104
+ readonly guard: TranscriptDecodeGuard | null;
105
+ /** Compaction marker timestamp (Codex); hosts without the concept pass null. NEVER passed as a store tombstone speculatively. */
106
+ readonly compactionTimestamp: string | null;
107
+ readonly rollbackTurns: readonly number[];
108
+ readonly stop: TranscriptDecodeStop;
109
+ /** Checkpoint byte offset to commit: start of the first unconsumed byte. */
110
+ readonly nextByteOffset: number;
111
+ /** Highest ordinal consumed (for the checkpoint's last_ordinal); -1 when none. */
112
+ readonly lastOrdinal: number;
113
+ readonly warnings: readonly string[];
114
+ /** Transcript file size at read time (lag computation + shrink detection). */
115
+ readonly fileSize: number;
116
+ }
117
+ /** One bounded window handed to a host decoder. */
118
+ export interface TranscriptWindow {
119
+ readonly bytes: Buffer;
120
+ readonly fileOffset: number;
121
+ /** True when bytes did not reach EOF — the window was cut by the bounded read. */
122
+ readonly byteBoundReached: boolean;
123
+ readonly fileSize: number;
124
+ }
125
+ /**
126
+ * The per-host adapter: deterministic locate + pure incremental decode.
127
+ * Implementations live in the HOST's adapter package; this seam defines the
128
+ * contract and the shared pipeline that drives it.
129
+ */
130
+ export interface TranscriptSourceAdapter {
131
+ readonly hostKind: SeamHostKind;
132
+ /**
133
+ * Deterministic transcript location: hook hints first, then the host's own
134
+ * exact-path derivation. NEVER directory-scan for a "latest" file.
135
+ */
136
+ locate(session: SessionRef, hints: HookHints, env: {
137
+ home?: string;
138
+ }): TranscriptLocator;
139
+ /**
140
+ * Decode one bounded window into observations — PURE: no filesystem access,
141
+ * no store writes; all FS goes through the port in the pipeline. Must
142
+ * inherit the incomplete-tail semantics via planJsonlWindow.
143
+ */
144
+ decodeWindow(locator: TranscriptLocator & {
145
+ status: 'ok';
146
+ }, window: TranscriptWindow, checkpoint: GovernanceCheckpointRecord | null): TranscriptDelta;
147
+ }
148
+ /** One newline-terminated raw line with its absolute byte start. */
149
+ export interface JsonlLineSlice {
150
+ readonly bytes: Buffer;
151
+ readonly recordByteStart: number;
152
+ }
153
+ export interface JsonlWindowPlan {
154
+ /** Newline-terminated lines in source order (empty lines included; hosts skip them). */
155
+ readonly lines: readonly JsonlLineSlice[];
156
+ /** Absolute offset just past the final newline (= next offset when no tail is consumable). */
157
+ readonly completeEndOffset: number;
158
+ /** Unterminated bytes after the final newline (EOF flush boundary or byte-bound cut), with their absolute start. */
159
+ readonly tail: {
160
+ readonly bytes: Buffer;
161
+ readonly startOffset: number;
162
+ } | null;
163
+ }
164
+ /**
165
+ * Split a bounded read window at newline bytes. UTF-8 multi-byte sequences
166
+ * never contain 0x0A, so byte-level splitting is safe and keeps checkpoint
167
+ * math byte-exact. Hosts classify the tail: a parseable final line at EOF is
168
+ * a complete record (consume + advance to EOF); an unparseable one is an
169
+ * incomplete tail (hold the checkpoint); under a byte bound the tail is
170
+ * simply lag (or `oversized_record` when the whole window had no newline).
171
+ */
172
+ export declare function planJsonlWindow(bytes: Buffer, fileOffset: number): JsonlWindowPlan;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Conversation-ingestion seam — host-neutral transcript source contract
3
+ * (PRI-1171 unified host trajectory ingestion; SPEC v0.2 §4.1).
4
+ *
5
+ * This is the ONE interface a new host implements to join unified trajectory
6
+ * ingestion: a transcript source adapter (deterministic locate + pure
7
+ * incremental decode) plus the shared pipeline in pipeline.ts. Host-specific
8
+ * decoding stays in the host's own adapter package (AGENTS §8.2) — this seam
9
+ * deliberately knows nothing about rollout/session/jsonl formats beyond the
10
+ * byte-window contract below.
11
+ *
12
+ * Moved here from codex-adapter/src/ingestion/transcript-decoder.ts (P1
13
+ * migration, behavior-locked by the existing Codex fixtures):
14
+ * - the injectable filesystem boundary (TranscriptPort) with post-open
15
+ * identity revalidation (TOCTOU refusal);
16
+ * - the bounded batch constants;
17
+ * - the newline-window plan (complete lines + unterminated tail) that
18
+ * carries the incomplete-tail semantics: a final line without a trailing
19
+ * newline at EOF is a transient append/flush boundary — it is NOT consumed
20
+ * and the checkpoint does not advance past it.
21
+ */
22
+ import fs from 'node:fs';
23
+ /** Bounded single-window read: 1 MiB per invocation (hosts loop from checkpoints). */
24
+ export const CONVERSATION_INGESTION_MAX_BATCH_BYTES = 1024 * 1024;
25
+ /** Bounded records per window before the decode reports a byte-bound stop. */
26
+ export const CONVERSATION_INGESTION_MAX_BATCH_RECORDS = 256;
27
+ /** Thrown by the port when the opened object is not the validated one (replacement/TOCTOU). */
28
+ export class TranscriptReplacedError extends Error {
29
+ constructor() {
30
+ super('transcript_replaced_after_validation');
31
+ this.name = 'TranscriptReplacedError';
32
+ }
33
+ }
34
+ function identityMatches(opened, expected) {
35
+ // Size+mtime fingerprint must ALWAYS hold. When the platform reports a
36
+ // Number-safe inode on both sides, the inode must match too (it is what
37
+ // catches delete+recreate replacements whose inode got reused on Linux CI
38
+ // with a same-ms write; a same-size same-ms recreate remains outside the
39
+ // threat model for an append-only host-owned file). On platforms whose
40
+ // ino exceeds Number.MAX_SAFE_INTEGER (Windows file IDs), the inode is not
41
+ // reliably comparable and the fingerprint alone decides. A false refusal
42
+ // is the safe direction: the hook degrades observably and the next Stop
43
+ // revalidates and retries.
44
+ if (opened.size !== expected.size || opened.mtimeMs !== expected.mtimeMs)
45
+ return false;
46
+ const comparableIno = expected.ino !== 0 && expected.dev !== 0
47
+ && opened.ino !== 0 && Number.isSafeInteger(expected.ino) && Number.isSafeInteger(opened.ino);
48
+ if (comparableIno)
49
+ return opened.ino === expected.ino && opened.dev === expected.dev;
50
+ return true;
51
+ }
52
+ export function createNodeTranscriptPort() {
53
+ return {
54
+ read({ canonicalPath, offset, maxBytes, expectedIdentity }) {
55
+ const fd = fs.openSync(canonicalPath, 'r');
56
+ try {
57
+ // Post-open revalidation: fstat the OPEN OBJECT — not the path — and
58
+ // re-prove it is the regular file the validator approved, still at the
59
+ // expected identity. A path swapped between validation and open
60
+ // (replacement/symlink TOCTOU) is refused before a single byte is read.
61
+ const stats = fs.fstatSync(fd);
62
+ if (!stats.isFile())
63
+ throw new Error('transcript_is_not_regular_file');
64
+ if (expectedIdentity !== undefined && !identityMatches(stats, expectedIdentity)) {
65
+ throw new TranscriptReplacedError();
66
+ }
67
+ const length = Math.max(0, Math.min(maxBytes, stats.size - offset));
68
+ if (length === 0)
69
+ return { bytes: Buffer.alloc(0), fileSize: stats.size };
70
+ const buffer = Buffer.alloc(length);
71
+ const bytesRead = fs.readSync(fd, buffer, 0, length, offset);
72
+ // Post-read byte bound re-verification (EP-08): never trust the
73
+ // pre-read stat for the enforced cap.
74
+ const actual = bytesRead < 0 ? 0 : bytesRead;
75
+ if (actual > maxBytes)
76
+ throw new Error('transcript_read_exceeded_bound');
77
+ return { bytes: buffer.subarray(0, actual), fileSize: stats.size };
78
+ }
79
+ finally {
80
+ fs.closeSync(fd);
81
+ }
82
+ },
83
+ };
84
+ }
85
+ /**
86
+ * Split a bounded read window at newline bytes. UTF-8 multi-byte sequences
87
+ * never contain 0x0A, so byte-level splitting is safe and keeps checkpoint
88
+ * math byte-exact. Hosts classify the tail: a parseable final line at EOF is
89
+ * a complete record (consume + advance to EOF); an unparseable one is an
90
+ * incomplete tail (hold the checkpoint); under a byte bound the tail is
91
+ * simply lag (or `oversized_record` when the whole window had no newline).
92
+ */
93
+ export function planJsonlWindow(bytes, fileOffset) {
94
+ const lastNewline = bytes.lastIndexOf(0x0a);
95
+ const completeEnd = lastNewline + 1; // exclusive byte end of the newline-terminated region
96
+ const lines = [];
97
+ let lineStart = 0;
98
+ while (lineStart < completeEnd) {
99
+ const lineEnd = bytes.indexOf(0x0a, lineStart);
100
+ if (lineEnd === -1 || lineEnd >= completeEnd)
101
+ break;
102
+ lines.push({ bytes: bytes.subarray(lineStart, lineEnd), recordByteStart: fileOffset + lineStart });
103
+ lineStart = lineEnd + 1;
104
+ }
105
+ const tailBytes = completeEnd < bytes.length ? bytes.subarray(completeEnd) : null;
106
+ return {
107
+ lines,
108
+ completeEndOffset: fileOffset + completeEnd,
109
+ tail: tailBytes !== null && tailBytes.length > 0 ? { bytes: tailBytes, startOffset: fileOffset + completeEnd } : null,
110
+ };
111
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Consent-tiered text policy for conversation ingestion (PRI-1171; SPEC v0.2
3
+ * §4.2 / §8.1).
4
+ *
5
+ * The stored `visible_text` bound follows the CONSENT TIER, not a global
6
+ * constant:
7
+ *
8
+ * bounded — the pre-unification behavior and the default: 200 chars + the
9
+ * 15-char `___TRUNCATED___` suffix applied by the core evidence
10
+ * sanitizer (the longest stored value today is 215).
11
+ * full — reachable ONLY when the recorded consent is `granted` AND its
12
+ * `disclosureVersion` is at least the CURRENT disclosure version
13
+ * (an old bounded-era grant never silently widens). Hard cap
14
+ * 20,000 chars against malformed giant records; the observed
15
+ * truncation rate is reported at acceptance time.
16
+ *
17
+ * P1 ships this resolver with the seam; the sanitizer-side application of the
18
+ * full bound (core `sanitizeString` maxChars parameter) lands with the P3
19
+ * depth-alignment batch, so in P1 every tier resolves through the unchanged
20
+ * bounded storage path.
21
+ */
22
+ export type TextPolicy = {
23
+ tier: 'bounded';
24
+ maxChars: 200;
25
+ } | {
26
+ tier: 'full';
27
+ maxChars: 20_000;
28
+ };
29
+ export declare const TEXT_POLICY_BOUNDED_MAX_CHARS = 200;
30
+ export declare const TEXT_POLICY_FULL_MAX_CHARS = 20000;
31
+ /**
32
+ * Order two disclosure version identifiers. Identifiers in the wild mix
33
+ * alphabetic prefixes with numeric runs INSIDE one segment ('g2a-2026-08-28',
34
+ * 'b2', 'b10'), so both a plain lexicographic compare ('b10' < 'b2') and a
35
+ * separator-only split get numeric orderings wrong. This tokenizes each
36
+ * identifier into digit and non-digit runs, comparing digit runs numerically
37
+ * and the rest lexicographically — a stable total order for the version
38
+ * families PD actually issues. A missing trailing token orders below a
39
+ * present one ('b2' < 'b2.1').
40
+ */
41
+ export declare function compareDisclosureVersions(a: string, b: string): number;
42
+ /**
43
+ * Resolve the text tier for one host's consent record. `requiredDisclosureVersion`
44
+ * is the disclosure the caller's CURRENT flow presents (the version whose text
45
+ * the Owner actually saw); a record granted against an older disclosure stays
46
+ * bounded until a new-disclosure record exists.
47
+ */
48
+ export declare function resolveTextPolicy(consent: {
49
+ decision: string;
50
+ disclosureVersion: string | null;
51
+ }, requiredDisclosureVersion: string): TextPolicy;
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Consent-tiered text policy for conversation ingestion (PRI-1171; SPEC v0.2
3
+ * §4.2 / §8.1).
4
+ *
5
+ * The stored `visible_text` bound follows the CONSENT TIER, not a global
6
+ * constant:
7
+ *
8
+ * bounded — the pre-unification behavior and the default: 200 chars + the
9
+ * 15-char `___TRUNCATED___` suffix applied by the core evidence
10
+ * sanitizer (the longest stored value today is 215).
11
+ * full — reachable ONLY when the recorded consent is `granted` AND its
12
+ * `disclosureVersion` is at least the CURRENT disclosure version
13
+ * (an old bounded-era grant never silently widens). Hard cap
14
+ * 20,000 chars against malformed giant records; the observed
15
+ * truncation rate is reported at acceptance time.
16
+ *
17
+ * P1 ships this resolver with the seam; the sanitizer-side application of the
18
+ * full bound (core `sanitizeString` maxChars parameter) lands with the P3
19
+ * depth-alignment batch, so in P1 every tier resolves through the unchanged
20
+ * bounded storage path.
21
+ */
22
+ export const TEXT_POLICY_BOUNDED_MAX_CHARS = 200;
23
+ export const TEXT_POLICY_FULL_MAX_CHARS = 20_000;
24
+ /**
25
+ * Order two disclosure version identifiers. Identifiers in the wild mix
26
+ * alphabetic prefixes with numeric runs INSIDE one segment ('g2a-2026-08-28',
27
+ * 'b2', 'b10'), so both a plain lexicographic compare ('b10' < 'b2') and a
28
+ * separator-only split get numeric orderings wrong. This tokenizes each
29
+ * identifier into digit and non-digit runs, comparing digit runs numerically
30
+ * and the rest lexicographically — a stable total order for the version
31
+ * families PD actually issues. A missing trailing token orders below a
32
+ * present one ('b2' < 'b2.1').
33
+ */
34
+ export function compareDisclosureVersions(a, b) {
35
+ const tokensA = a.match(/\d+|\D+/g) ?? [];
36
+ const tokensB = b.match(/\d+|\D+/g) ?? [];
37
+ const length = Math.max(tokensA.length, tokensB.length);
38
+ for (let index = 0; index < length; index += 1) {
39
+ const ta = tokensA[index] ?? '';
40
+ const tb = tokensB[index] ?? '';
41
+ const aIsNumeric = ta.length > 0 && /^\d+$/.test(ta);
42
+ const bIsNumeric = tb.length > 0 && /^\d+$/.test(tb);
43
+ if (aIsNumeric && bIsNumeric) {
44
+ const na = Number(ta);
45
+ const nb = Number(tb);
46
+ if (na !== nb)
47
+ return na < nb ? -1 : 1;
48
+ }
49
+ else if (ta !== tb) {
50
+ return ta < tb ? -1 : 1;
51
+ }
52
+ }
53
+ return 0;
54
+ }
55
+ /**
56
+ * Resolve the text tier for one host's consent record. `requiredDisclosureVersion`
57
+ * is the disclosure the caller's CURRENT flow presents (the version whose text
58
+ * the Owner actually saw); a record granted against an older disclosure stays
59
+ * bounded until a new-disclosure record exists.
60
+ */
61
+ export function resolveTextPolicy(consent, requiredDisclosureVersion) {
62
+ if (consent.decision === 'granted'
63
+ && consent.disclosureVersion !== null
64
+ && compareDisclosureVersions(consent.disclosureVersion, requiredDisclosureVersion) >= 0) {
65
+ return { tier: 'full', maxChars: TEXT_POLICY_FULL_MAX_CHARS };
66
+ }
67
+ return { tier: 'bounded', maxChars: TEXT_POLICY_BOUNDED_MAX_CHARS };
68
+ }
@@ -3,13 +3,15 @@ export declare const GOVERNANCE_RETENTION_MAX_TURNS = 32;
3
3
  export declare const GOVERNANCE_RETENTION_MAX_AGE_MS: number;
4
4
  export declare const GOVERNANCE_PROMOTION_PRECEDING_TURNS = 12;
5
5
  export declare const GOVERNANCE_PENDING_TAIL_STALE_MS: number;
6
+ /** Host taxonomy for governance observations (schema v4; PRI-1171 unification). */
7
+ export type GovernanceObservationHostKind = 'codex' | 'workbuddy' | 'openclaw';
6
8
  export type GovernanceObservationKind = 'user_turn' | 'assistant_turn' | 'tool_call';
7
9
  export type GovernanceObservationSource = 'live_hook' | 'transcript';
8
10
  export type GovernanceObservationCompleteness = 'complete' | 'partial';
9
11
  /** `quarantined` (Slice D §15): audited, permanently-invalid row; bodies dropped, metadata kept. */
10
12
  export type GovernanceRetentionClass = 'operational' | 'promoted' | 'expired' | 'rolled_back' | 'quarantined';
11
13
  export interface GovernanceObservationInput {
12
- readonly hostKind: 'codex';
14
+ readonly hostKind: GovernanceObservationHostKind;
13
15
  readonly rolloutIdentity: string;
14
16
  readonly rootSessionId: string;
15
17
  readonly parentRolloutIdentity?: string;
@@ -45,7 +47,7 @@ export interface GovernanceObservationInput {
45
47
  readonly observedAt: string;
46
48
  }
47
49
  export interface GovernanceCheckpointInput {
48
- readonly hostKind: 'codex';
50
+ readonly hostKind: GovernanceObservationHostKind;
49
51
  readonly rolloutIdentity: string;
50
52
  readonly byteOffset: number;
51
53
  readonly lastOrdinal: number;
@@ -104,7 +106,7 @@ export interface GovernanceObservationRecord {
104
106
  }
105
107
  export interface PromoteGovernanceEvidenceInput {
106
108
  readonly workspaceDir: string;
107
- readonly hostKind: 'codex';
109
+ readonly hostKind: GovernanceObservationHostKind;
108
110
  readonly rolloutIdentity: string;
109
111
  readonly triggerLogicalKey: string;
110
112
  /** Caller-provided pain reference. Slice A never mints a pain identity (SPEC §18). */
@@ -136,7 +138,7 @@ type Degradation = {
136
138
  nextAction: string;
137
139
  };
138
140
  export interface GovernanceRolloutDescriptor {
139
- readonly hostKind: 'codex';
141
+ readonly hostKind: GovernanceObservationHostKind;
140
142
  readonly rolloutIdentity: string;
141
143
  readonly rootSessionId: string;
142
144
  readonly parentRolloutIdentity?: string;
@@ -159,14 +161,14 @@ export interface IngestGovernanceObservationsInput {
159
161
  export declare function ingestGovernanceObservations(input: IngestGovernanceObservationsInput): IngestGovernanceObservationsResult;
160
162
  export interface ReadGovernanceCheckpointArgs {
161
163
  readonly workspaceDir: string;
162
- readonly hostKind: 'codex';
164
+ readonly hostKind: GovernanceObservationHostKind;
163
165
  readonly rolloutIdentity: string;
164
166
  readonly databaseFactory?: ObservationDatabaseFactory;
165
167
  }
166
168
  export declare function readGovernanceCheckpoint(args: ReadGovernanceCheckpointArgs): GovernanceCheckpointRecord | null | Degradation;
167
169
  export interface ListGovernanceCheckpointsArgs {
168
170
  readonly workspaceDir: string;
169
- readonly hostKind: 'codex';
171
+ readonly hostKind: GovernanceObservationHostKind;
170
172
  readonly databaseFactory?: ObservationDatabaseFactory;
171
173
  }
172
174
  export type ListGovernanceCheckpointsResult = {
@@ -196,7 +198,7 @@ export declare function listGovernanceObservations(input: ListGovernanceObservat
196
198
  export declare function promoteGovernanceEvidence(input: PromoteGovernanceEvidenceInput): PromoteGovernanceEvidenceResult;
197
199
  export interface QuarantineGovernanceObservationArgs {
198
200
  readonly workspaceDir: string;
199
- readonly hostKind: 'codex';
201
+ readonly hostKind: GovernanceObservationHostKind;
200
202
  readonly rolloutIdentity: string;
201
203
  /** governance_observations.id — `pd codex ingest quarantine --record <id>`. */
202
204
  readonly recordId: number;