@principles/host-runtime 4.5.0 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -35,10 +35,13 @@ import fs from 'node:fs';
35
35
  import path from 'node:path';
36
36
  import { randomUUID } from 'node:crypto';
37
37
  import Database from 'better-sqlite3';
38
- import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
38
+ import { collectSync, computeFeatureFlagsFromConfig, CORRECTION_SEED_KEYWORDS, PainToPrincipleService, PrincipleTreeLedgerAdapter, RuntimeStateManager, createDiagnosticianTaskId, sanitizeString, boundCorrectionEvidenceText, fingerprintStatement, isOwnerManualCorrectionEvidence, MAX_EVIDENCE_VALUE_CHARS, evaluateStage2ConfidenceGate, evaluatePainIngress, migrateLegacyGfiSchema, STAGE2_MAX_ATTEMPTS, PENDING_CANDIDATE_TTL_MS, } from '@principles/core/runtime';
39
39
  import { deriveProductionCorrectionPainIdentity, hasProductionPainSchema, } from './production-pain-evidence.js';
40
40
  import { promoteGovernanceEvidence, ensureGovernanceSchema } from './governance-observation-store.js';
41
+ import { readSourceMaterialAuthorization } from './source-material-authorization.js';
42
+ import { readConversationIngestionConsent } from './conversation-ingestion/consent.js';
41
43
  import { loadPdConfigForPlugin } from './pd-config.js';
44
+ import { isAutomaticPainSubmissionAuthorized } from './auto-pain-authorization.js';
42
45
  import { createHostIntentDocReader } from './intent-doc-reader.js';
43
46
  import { resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
44
47
  // ─── Shared detector constants (one truth for both hosts) ───────────────────
@@ -427,9 +430,15 @@ function tryConsumeRateLimit({ db, rootSessionId, ruleVersion, now }) {
427
430
  /** ONE reason builder for inline admission and the pending→admitted transition. */
428
431
  function correctionReason(candidate, matchedTerms) {
429
432
  if (candidate.explicitOwnerStatement === true) {
430
- return candidate.explicitChannel === 'codex_explicit_agent'
431
- ? 'Codex explicit owner statement (agent-assisted, no prefix)'
432
- : `${candidate.hostKind === 'workbuddy' ? 'WorkBuddy' : 'Codex'} explicit owner statement (PD记录痛苦 prefix)`;
433
+ if (candidate.explicitChannel === 'codex_explicit_agent') {
434
+ // PRI-1283 round 3: only a transcript-verified agent submission may
435
+ // carry the owner-explicit reason marker; an unverified one is
436
+ // Agent-derived and must NOT match `isOwnerExplicitStatementReason`.
437
+ return candidate.ownerVerbatimConfirmed === true
438
+ ? 'Codex explicit owner statement (agent-assisted, owner confirmed)'
439
+ : 'Codex agent-reported pain statement (owner confirmation unverified)';
440
+ }
441
+ return `${candidate.hostKind === 'workbuddy' ? 'WorkBuddy' : 'Codex'} explicit owner statement (PD记录痛苦 prefix)`;
433
442
  }
434
443
  return matchedTerms.length > 0
435
444
  ? `User correction detected: ${matchedTerms.join(', ')}`
@@ -499,7 +508,21 @@ function buildTaskSubmissionPayload(candidate, workspaceDir, details) {
499
508
  ...(candidate.explicitOwnerStatement === true
500
509
  ? { correctionEvidence: candidate.hostKind === 'workbuddy'
501
510
  ? { text: boundCorrectionEvidenceText({ text: candidate.text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }, workspaceDir).text, classification: 'owner_statement', channel: 'workbuddy_explicit_prefix' }
502
- : { text: sanitizeString(candidate.text, workspaceDir), classification: 'owner_statement', channel: candidate.explicitChannel === 'codex_explicit_agent' ? 'codex_explicit_agent' : 'codex_explicit_prefix' } }
511
+ : candidate.explicitChannel === 'codex_explicit_agent'
512
+ ? (candidate.ownerVerbatimConfirmed === true
513
+ ? (() => {
514
+ // PRI-1283 round 3: the bound confirmation fingerprint covers
515
+ // the PERSISTED (sanitized) text — the final submitted content.
516
+ const text = sanitizeString(candidate.text, workspaceDir);
517
+ return {
518
+ text,
519
+ classification: 'owner_statement',
520
+ channel: 'codex_explicit_agent',
521
+ ownerConfirmation: { kind: 'owner_verbatim_turn_match', statementFingerprint: fingerprintStatement(text) },
522
+ };
523
+ })()
524
+ : { text: sanitizeString(candidate.text, workspaceDir), channel: 'codex_explicit_agent' })
525
+ : { text: sanitizeString(candidate.text, workspaceDir), classification: 'owner_statement', channel: 'codex_explicit_prefix' } }
503
526
  : {}),
504
527
  };
505
528
  return payload;
@@ -728,6 +751,29 @@ function buildOwnerCorrectionIngressReport(facts) {
728
751
  evidence: bundle,
729
752
  };
730
753
  }
754
+ function buildAgentAssistedCorrectionIngressReport(facts) {
755
+ const [first, ...rest] = facts.evidence;
756
+ const bundle = first === undefined
757
+ ? { status: 'unavailable', reason: 'trajectory_unavailable' }
758
+ : { status: 'available', entries: [first, ...rest] };
759
+ return {
760
+ identity: { kind: 'manual_pain_id', painId: facts.painId },
761
+ painType: 'user_frustration',
762
+ source: 'user_correction',
763
+ reason: facts.reason,
764
+ score: GOVERNANCE_STRONG_PAIN_SCORE,
765
+ origin: { kind: 'agent_assisted', channel: 'codex_explicit_agent' },
766
+ correlation: {
767
+ status: 'bound',
768
+ hostKind: 'codex',
769
+ rootSessionId: facts.rootSessionId,
770
+ rolloutIdentity: facts.rolloutIdentity,
771
+ logicalObservationKey: facts.logicalObservationKey,
772
+ hostTurnId: facts.hostTurnId,
773
+ },
774
+ evidence: bundle,
775
+ };
776
+ }
731
777
  function ownerExplicitChannel(candidate) {
732
778
  if (candidate.explicitChannel !== undefined)
733
779
  return candidate.explicitChannel;
@@ -839,50 +885,46 @@ function admitCorrection({ db, candidate, workspaceDir, now, nowIso, keywordStor
839
885
  text: candidate.text,
840
886
  });
841
887
  const ingressReasonValue = correctionReason(candidate, detection?.output.matchedTerms ?? []);
842
- const ingressDecision = isExplicit
843
- ? evaluatePainIngress(buildOwnerCorrectionIngressReport({
844
- hostKind: candidate.hostKind,
845
- channel: ownerExplicitChannel(candidate),
846
- logicalObservationKey: candidate.logicalObservationKey,
847
- rolloutIdentity: candidate.rolloutIdentity,
848
- rootSessionId: candidate.rootSessionId,
849
- hostTurnId: candidate.hostTurnId,
850
- painId,
851
- reason: ingressReasonValue,
852
- // Codex has a real governance observation anchor when ingestion
853
- // persisted one; otherwise (ingestion disabled) the statement degrades
854
- // to the Owner Manual path instead of fabricating a trace. WorkBuddy
855
- // explicit intake has no transcript evidence and degrades honestly.
856
- evidence: correctionIngressEvidence({
857
- db,
858
- hostKind: candidate.hostKind,
859
- logicalObservationKey: candidate.logicalObservationKey,
860
- rolloutIdentity: candidate.rolloutIdentity,
861
- rootSessionId: candidate.rootSessionId,
862
- hostTurnId: candidate.hostTurnId,
863
- text: candidate.text,
864
- workspaceDir,
865
- }),
888
+ const ingressEvidence = correctionIngressEvidence({
889
+ db,
890
+ hostKind: candidate.hostKind,
891
+ logicalObservationKey: candidate.logicalObservationKey,
892
+ rolloutIdentity: candidate.rolloutIdentity,
893
+ rootSessionId: candidate.rootSessionId,
894
+ hostTurnId: candidate.hostTurnId,
895
+ text: candidate.text,
896
+ workspaceDir,
897
+ });
898
+ const correctionFacts = {
899
+ hostKind: candidate.hostKind,
900
+ logicalObservationKey: candidate.logicalObservationKey,
901
+ rolloutIdentity: candidate.rolloutIdentity,
902
+ rootSessionId: candidate.rootSessionId,
903
+ hostTurnId: candidate.hostTurnId,
904
+ painId,
905
+ reason: ingressReasonValue,
906
+ evidence: ingressEvidence,
907
+ };
908
+ const agentAssistedExplicit = isExplicit
909
+ && candidate.hostKind === 'codex'
910
+ && candidate.explicitChannel === 'codex_explicit_agent'
911
+ && candidate.ownerVerbatimConfirmed !== true;
912
+ const ingressDecision = agentAssistedExplicit
913
+ ? evaluatePainIngress(buildAgentAssistedCorrectionIngressReport({
914
+ logicalObservationKey: correctionFacts.logicalObservationKey,
915
+ rolloutIdentity: correctionFacts.rolloutIdentity,
916
+ rootSessionId: correctionFacts.rootSessionId,
917
+ hostTurnId: correctionFacts.hostTurnId,
918
+ painId: correctionFacts.painId,
919
+ reason: correctionFacts.reason,
920
+ evidence: correctionFacts.evidence,
866
921
  }))
867
- : evaluatePainIngress(buildCorrectionIngressReport({
868
- hostKind: candidate.hostKind,
869
- logicalObservationKey: candidate.logicalObservationKey,
870
- rolloutIdentity: candidate.rolloutIdentity,
871
- rootSessionId: candidate.rootSessionId,
872
- hostTurnId: candidate.hostTurnId,
873
- painId,
874
- reason: ingressReasonValue,
875
- evidence: correctionIngressEvidence({
876
- db,
877
- hostKind: candidate.hostKind,
878
- logicalObservationKey: candidate.logicalObservationKey,
879
- rolloutIdentity: candidate.rolloutIdentity,
880
- rootSessionId: candidate.rootSessionId,
881
- hostTurnId: candidate.hostTurnId,
882
- text: candidate.text,
883
- workspaceDir,
884
- }),
885
- }));
922
+ : isExplicit
923
+ ? evaluatePainIngress(buildOwnerCorrectionIngressReport({
924
+ ...correctionFacts,
925
+ channel: ownerExplicitChannel(candidate),
926
+ }))
927
+ : evaluatePainIngress(buildCorrectionIngressReport(correctionFacts));
886
928
  const ingressReason = ingressDecision.action === 'refuse' || ingressDecision.action === 'observation_only'
887
929
  ? ingressDecision.reasonCode
888
930
  : null;
@@ -1129,6 +1171,17 @@ function parsePendingRow(row) {
1129
1171
  * text. Rows whose claim is younger than PENDING_REVIEW_CLAIM_TTL_MS are
1130
1172
  * skipped (another worker is reviewing them); TTL-expired rows become
1131
1173
  * `abandoned(ttl_expired)` here, before any LLM work.
1174
+ *
1175
+ * PRI-1283 review round 2 (directive A4): every claim re-reads the LATEST
1176
+ * conversation-ingestion consent for the row's host. A host whose consent is
1177
+ * no longer granted never yields a claimable candidate — the pending row is
1178
+ * terminated as `abandoned('source_revoked')` right here (CAS on the exact
1179
+ * payload text; the D6 terminal field set drops trigger.text /
1180
+ * trigger.matchedTerms / hostTurnId / task_payload), so the revoked excerpt
1181
+ * can neither be claimed nor keep living in the payload. Revocation is the
1182
+ * linearization point: claims after it see the terminal row, and an
1183
+ * in-flight claim is fenced by `recordPendingCorrectionReview` /
1184
+ * `settlePendingCorrection` (both CAS on `decision='pending_llm_review'`).
1132
1185
  */
1133
1186
  export function claimPendingCorrectionCandidates(input) {
1134
1187
  const opened = openAdmissionStore(input.workspaceDir, input.databaseFactory);
@@ -1140,6 +1193,7 @@ export function claimPendingCorrectionCandidates(input) {
1140
1193
  const limit = Math.min(Math.max(input.limit ?? 2, 1), 8);
1141
1194
  const candidates = [];
1142
1195
  let expired = 0;
1196
+ let revoked = 0;
1143
1197
  try {
1144
1198
  const rows = db.prepare(`SELECT * FROM governance_signal_admissions
1145
1199
  WHERE decision = 'pending_llm_review' ORDER BY id LIMIT ?`).all(limit * 3);
@@ -1162,6 +1216,31 @@ export function claimPendingCorrectionCandidates(input) {
1162
1216
  expired += 1;
1163
1217
  continue;
1164
1218
  }
1219
+ // Directive A4: latest-consent re-validation at claim time. The row's
1220
+ // own host attribution (host_kind column) is the authority — never the
1221
+ // caller's assumption. The three ledger states mirror the R3 sweep
1222
+ // EXACTLY (one authorization judgment, directive B2):
1223
+ // - a RECORDED non-granted decision (revoked/pending/failed) is a
1224
+ // revocation: the pending row is TERMINATED here (CAS on the exact
1225
+ // payload) instead of yielding a candidate whose text would flow
1226
+ // into a model call;
1227
+ // - a MISSING record is NOT a revocation (the sweep skips it too) —
1228
+ // the lifecycle proceeds; pending rows on ledger-less workspaces
1229
+ // are historical admission-chain output, not revoked material;
1230
+ // - an UNREADABLE ledger fails closed: no claim, no termination.
1231
+ const consentRead = readConversationIngestionConsent(path.resolve(input.workspaceDir), parsed.hostKind === 'workbuddy' ? 'workbuddy' : 'codex');
1232
+ if (!consentRead.ok) {
1233
+ return { ok: false, reason: `pending_claim_consent_unreadable:${consentRead.reason}`, nextAction: `${consentRead.nextAction} — pending rows stay durable and unclaimed until the ledger is readable.` };
1234
+ }
1235
+ if (consentRead.record !== null && consentRead.record.decision !== 'granted') {
1236
+ const { changes } = db.prepare(`UPDATE governance_signal_admissions
1237
+ SET decision = 'abandoned', reason = 'source_revoked', task_payload_json = ?, updated_at = ?
1238
+ WHERE logical_observation_key = ? AND decision = 'pending_llm_review' AND task_payload_json = ?`)
1239
+ .run(pendingTerminalPayload({ decision: 'abandoned', reason: 'source_revoked', attempts: parsed.payload.review.attempts, confidence: null, nowIso }), nowIso, key, parsed.payloadText);
1240
+ if (changes === 1)
1241
+ revoked += 1;
1242
+ continue;
1243
+ }
1165
1244
  const ageMs = Date.parse(parsed.createdAt);
1166
1245
  if (!Number.isFinite(ageMs) || now.getTime() - ageMs >= PENDING_CANDIDATE_TTL_MS) {
1167
1246
  db.prepare(`UPDATE governance_signal_admissions
@@ -1204,7 +1283,7 @@ export function claimPendingCorrectionCandidates(input) {
1204
1283
  createdAt: parsed.createdAt,
1205
1284
  });
1206
1285
  }
1207
- return { ok: true, candidates, expired };
1286
+ return { ok: true, candidates, expired, revoked };
1208
1287
  }
1209
1288
  catch (error) {
1210
1289
  const detail = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);
@@ -1214,6 +1293,52 @@ export function claimPendingCorrectionCandidates(input) {
1214
1293
  close();
1215
1294
  }
1216
1295
  }
1296
+ /**
1297
+ * PRI-1283 review round 2 (directive A5): the LAST authorization gate before
1298
+ * `classifier(candidate.text, …)` starts a model request. Verifies, in one
1299
+ * fresh read, that (a) the row is STILL `pending_llm_review`, (b) this
1300
+ * worker's fencing token still owns the claim, and (c) the row's host still
1301
+ * has granted consent. This is the revocation linearization boundary for NEW
1302
+ * model requests: after a revocation completes (ledger decision or sweep
1303
+ * termination), no fresh classifier call may start on the old source's text.
1304
+ * A request already in flight cannot be recalled — its RESULT is fenced
1305
+ * instead by `recordPendingCorrectionReview` (decision + claimToken CAS).
1306
+ */
1307
+ export function verifyPendingClaimForClassification(input) {
1308
+ const opened = openAdmissionStore(input.workspaceDir, input.databaseFactory);
1309
+ if (!('db' in opened))
1310
+ return opened;
1311
+ const { db, close } = opened;
1312
+ try {
1313
+ const row = pendingReviewMarkerRow(db, input.logicalObservationKey);
1314
+ if (row === null || rowField(row, 'decision') !== 'pending_llm_review') {
1315
+ return { ok: true, allowed: false, reason: 'not_pending' };
1316
+ }
1317
+ const parsed = parsePendingRow(row);
1318
+ if (parsed === null)
1319
+ return { ok: true, allowed: false, reason: 'payload_invalid' };
1320
+ const currentClaimToken = parsed.payload.review.claimToken;
1321
+ if (currentClaimToken === undefined || currentClaimToken !== input.claimToken) {
1322
+ return { ok: true, allowed: false, reason: 'claim_not_owned' };
1323
+ }
1324
+ // Same three-state ledger semantics as the claim path and the R3 sweep
1325
+ // (one authorization judgment): a RECORDED non-granted decision blocks
1326
+ // the model request; a MISSING record is not a revocation (the claim
1327
+ // path let it through, and so must the pre-classifier gate); an
1328
+ // UNREADABLE ledger fails closed.
1329
+ const consentRead = readConversationIngestionConsent(path.resolve(input.workspaceDir), parsed.hostKind === 'workbuddy' ? 'workbuddy' : 'codex');
1330
+ if (!consentRead.ok) {
1331
+ return { ok: false, reason: `pending_claim_consent_unreadable:${consentRead.reason}`, nextAction: consentRead.nextAction };
1332
+ }
1333
+ if (consentRead.record !== null && consentRead.record.decision !== 'granted') {
1334
+ return { ok: true, allowed: false, reason: consentRead.record.decision === 'revoked' ? 'source_revoked' : 'consent_not_granted' };
1335
+ }
1336
+ return { ok: true, allowed: true };
1337
+ }
1338
+ finally {
1339
+ close();
1340
+ }
1341
+ }
1217
1342
  /**
1218
1343
  * Release THIS worker's claim when no classification started (budget exhausted
1219
1344
  * or classifier unavailable), so the next cycle can re-claim immediately.
@@ -1669,16 +1794,38 @@ function isGovernanceTaskPayload(value) {
1669
1794
  // such submissions (the statement itself satisfies the empty-input-evidence
1670
1795
  // admission condition).
1671
1796
  const correctionEvidence = own(value, 'correctionEvidence');
1797
+ const correctionChannel = isRecord(correctionEvidence) ? own(correctionEvidence, 'channel') : undefined;
1798
+ const correctionText = isRecord(correctionEvidence) ? own(correctionEvidence, 'text') : undefined;
1672
1799
  const hasOwnerStatement = isRecord(correctionEvidence)
1673
1800
  && own(correctionEvidence, 'classification') === 'owner_statement'
1674
- && ((own(correctionEvidence, 'channel') === 'codex_explicit_prefix' || own(correctionEvidence, 'channel') === 'codex_explicit_agent') && hostKind === 'codex'
1675
- || own(correctionEvidence, 'channel') === 'workbuddy_explicit_prefix' && hostKind === 'workbuddy')
1676
- && typeof own(correctionEvidence, 'text') === 'string'
1677
- && own(correctionEvidence, 'text').length > 0;
1678
- if (correctionEvidence !== undefined && !hasOwnerStatement)
1801
+ && typeof correctionText === 'string' && correctionText.length > 0
1802
+ && (
1803
+ // Direct Owner channels: the channel itself is the credible record.
1804
+ (correctionChannel === 'codex_explicit_prefix' && hostKind === 'codex')
1805
+ || (correctionChannel === 'workbuddy_explicit_prefix' && hostKind === 'workbuddy')
1806
+ // Agent-assisted: owner_manual ONLY with a bound Owner confirmation
1807
+ // record — kind + fingerprint re-verified against the persisted text
1808
+ // (PRI-1283 round 3; a bare payload claim is never sufficient).
1809
+ || (correctionChannel === 'codex_explicit_agent' && hostKind === 'codex'
1810
+ && isOwnerManualCorrectionEvidence(correctionEvidence)));
1811
+ // Agent-derived covers BOTH the current shape (no classification) and the
1812
+ // legacy pre-round-3 shape (`classification:'owner_statement'` written
1813
+ // without a bound confirmation). Those rows are Agent-derived under the
1814
+ // ruling — still valid payloads for task recovery — while a row that
1815
+ // CARRIES an ownerConfirmation the shared judgment cannot verify is a
1816
+ // forged-claim shape and stays rejected.
1817
+ const isAgentDerivedStatement = isRecord(correctionEvidence)
1818
+ && correctionChannel === 'codex_explicit_agent' && hostKind === 'codex'
1819
+ && typeof correctionText === 'string' && correctionText.length > 0
1820
+ && own(correctionEvidence, 'ownerConfirmation') === undefined
1821
+ && !isOwnerManualCorrectionEvidence(correctionEvidence);
1822
+ if (correctionEvidence !== undefined && !hasOwnerStatement && !isAgentDerivedStatement)
1679
1823
  return false;
1680
1824
  const evidence = own(value, 'evidence');
1681
- if (!Array.isArray(evidence) || (evidence.length === 0 && !hasOwnerStatement) || evidence.length > 8)
1825
+ // An explicit submission — owner-confirmed OR agent-derived (CR-02) — is a
1826
+ // first-class input basis, so the evidence array may legitimately be empty
1827
+ // (e.g. conversation-ingestion off → no persisted observation to bind).
1828
+ if (!Array.isArray(evidence) || (evidence.length === 0 && !hasOwnerStatement && !isAgentDerivedStatement) || evidence.length > 8)
1682
1829
  return false;
1683
1830
  for (const entry of evidence) {
1684
1831
  if (!isRecord(entry))
@@ -1698,6 +1845,22 @@ function isGovernanceTaskPayload(value) {
1698
1845
  }
1699
1846
  return true;
1700
1847
  }
1848
+ /**
1849
+ * PRI-1283 round 5 (review): the correction evidence a recovery re-persists
1850
+ * must carry the SAME classification judgment the validator applied — never
1851
+ * the marker's stale label. A legacy pre-round-3 agent-relayed row may still
1852
+ * claim `classification:'owner_statement'` without a bound confirmation; the
1853
+ * shared ruling treats it as Agent-derived, and the current writer shape
1854
+ * carries no classification for agent-derived text. Persisting the stale
1855
+ * claim would let Recall re-serve a false `owner_statement` classification.
1856
+ */
1857
+ function recoveryCorrectionEvidence(persisted, sessionId) {
1858
+ const next = { ...persisted, sessionId };
1859
+ if (!isOwnerManualCorrectionEvidence(next)) {
1860
+ delete next.classification;
1861
+ }
1862
+ return next;
1863
+ }
1701
1864
  /**
1702
1865
  * Ensure exactly one pending Diagnostician task exists for an admitted
1703
1866
  * canonical pain (SPEC §13). Idempotent across hook retries, reconciliation,
@@ -1739,6 +1902,61 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1739
1902
  if (!isGovernanceTaskPayload(payloadParsed)) {
1740
1903
  return { ok: false, reason: 'admission_task_payload_invalid', nextAction: 're-admit the signal or run reconciliation after repairing the workspace state' };
1741
1904
  }
1905
+ const hasExistingTaskLink = typeof existingTaskId === 'string' && existingTaskId.length > 0;
1906
+ const markerHostKind = payloadParsed.hostKind;
1907
+ const { correctionEvidence } = payloadParsed;
1908
+ const ownerManual = isOwnerManualCorrectionEvidence(correctionEvidence);
1909
+ const agentAssistedExplicit = isRecord(correctionEvidence)
1910
+ && correctionEvidence.channel === 'codex_explicit_agent'
1911
+ && !ownerManual;
1912
+ const sourceAuthorization = markerHostKind === 'codex' || markerHostKind === 'workbuddy'
1913
+ ? readSourceMaterialAuthorization({ workspaceDir, hostKind: markerHostKind })
1914
+ : undefined;
1915
+ // Every blocked authorization state (including a missing ledger) forbids
1916
+ // historical observation reads. A missing ledger is not a revocation, so
1917
+ // it is handled by the ingress evidence gate below rather than the sweep
1918
+ // remediation branch.
1919
+ const sourceMaterialReadable = sourceAuthorization === undefined
1920
+ || sourceAuthorization.status !== 'blocked';
1921
+ // A linked task remains idempotently reportable after revocation, but the
1922
+ // marker must not trigger a historical observation read on that path.
1923
+ if (hasExistingTaskLink && !sourceMaterialReadable) {
1924
+ return { ok: true, taskId: existingTaskId, created: false, duplicate: true, linkRepaired: false };
1925
+ }
1926
+ // After revocation, repair a crash-after-create task link without reading
1927
+ // the historical observation. An agent-assisted explicit statement is
1928
+ // still Agent-derived: even a missing ledger cannot authorize re-persisting
1929
+ // it into a NEW task. A direct Owner channel remains independently allowed.
1930
+ if (!ownerManual && sourceAuthorization?.status === 'blocked'
1931
+ && (sourceAuthorization.reason !== 'consent_missing' || agentAssistedExplicit)) {
1932
+ const taskId = createDiagnosticianTaskId(input.canonicalPainId);
1933
+ const stateManager = new RuntimeStateManager({ workspaceDir });
1934
+ try {
1935
+ await stateManager.initialize();
1936
+ const existing = await stateManager.getTask(taskId);
1937
+ if (existing !== null) {
1938
+ db.prepare('UPDATE governance_signal_admissions SET diagnostician_task_id = ?, updated_at = ? WHERE logical_observation_key = ?')
1939
+ .run(taskId, new Date().toISOString(), input.logicalObservationKey);
1940
+ return { ok: true, taskId, created: false, duplicate: true, linkRepaired: true };
1941
+ }
1942
+ }
1943
+ finally {
1944
+ await stateManager.close().catch(() => undefined);
1945
+ }
1946
+ return {
1947
+ ok: false,
1948
+ reason: sourceAuthorization.reason === 'consent_missing'
1949
+ ? 'pain_ingress_agent_assisted_consent_required'
1950
+ : 'source_authorization_revoked',
1951
+ nextAction: sourceAuthorization.reason === 'consent_missing'
1952
+ ? 'The Codex agent-assisted wording is Agent-derived; record a Codex conversation-ingestion consent grant before creating a diagnostic task, or use the direct Owner explicit prefix for Owner-authored words.'
1953
+ : sourceAuthorization.reason === 'consent_unreadable'
1954
+ ? 'repair the consent ledger first (<workspace>/.state/conversation-ingestion-consent.json is unreadable); the sweep refuses to run until the authority is readable'
1955
+ : sourceAuthorization.reason === 'consent_revoked'
1956
+ ? `purge persisted copies first: pd consent sweep-revoked --workspace "${workspaceDir}" --apply (host: ${markerHostKind})`
1957
+ : `resolve the pending or failed conversation-ingestion consent decision for ${markerHostKind} in "${workspaceDir}" before retrying; a revocation sweep is only appropriate after the ledger records a revocation`,
1958
+ };
1959
+ }
1742
1960
  // SPEC v0.3.1 §1.2: provenance is DERIVED from the marker's ingress facts,
1743
1961
  // never hardcoded. The marker is host-context-bound by construction, and
1744
1962
  // its payload carries the evidence entries that make this a `submit`.
@@ -1747,7 +1965,6 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1747
1965
  const hostTurnId = payloadParsed.hostKind === 'codex'
1748
1966
  ? (markerKey.split('|')[2] ?? markerKey)
1749
1967
  : (markerKey.lastIndexOf('|') > 0 ? markerKey.slice(0, markerKey.lastIndexOf('|')) : markerKey);
1750
- const markerHostKind = payloadParsed.hostKind;
1751
1968
  // P1 review round 3: never trust the payload's evidence list — re-derive it
1752
1969
  // from trajectory.db with the full lineage tuple. A marker that references a
1753
1970
  // non-existent observation (or a WorkBuddy automatic correction) evaluates
@@ -1757,16 +1974,18 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1757
1974
  // run for it. Only corrections are gated on a real observation.
1758
1975
  const isCorrectionPayload = payloadParsed.painType !== 'tool_failure';
1759
1976
  const ingressEvidence = isCorrectionPayload && (markerHostKind === 'codex' || markerHostKind === 'workbuddy')
1760
- ? correctionIngressEvidence({
1761
- db,
1762
- hostKind: markerHostKind,
1763
- logicalObservationKey: markerKey,
1764
- rolloutIdentity: typeof rolloutIdentity === 'string' ? rolloutIdentity : '',
1765
- rootSessionId: payloadParsed.sessionId,
1766
- hostTurnId,
1767
- text: payloadParsed.reason,
1768
- workspaceDir,
1769
- })
1977
+ ? (sourceMaterialReadable
1978
+ ? correctionIngressEvidence({
1979
+ db,
1980
+ hostKind: markerHostKind,
1981
+ logicalObservationKey: markerKey,
1982
+ rolloutIdentity: typeof rolloutIdentity === 'string' ? rolloutIdentity : '',
1983
+ rootSessionId: payloadParsed.sessionId,
1984
+ hostTurnId,
1985
+ text: payloadParsed.reason,
1986
+ workspaceDir,
1987
+ })
1988
+ : [])
1770
1989
  : payloadParsed.evidence.map((entry) => ({
1771
1990
  kind: 'behavior_trace',
1772
1991
  sourceRef: entry.sourceRef,
@@ -1779,31 +1998,32 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1779
1998
  // source. An explicit Owner statement is owner_manual (manual_pain_id,
1780
1999
  // correctionEvidence channel); everything else is the automatic hook.
1781
2000
  const ownerChannel = payloadParsed.correctionEvidence?.channel;
1782
- const ingressDecision = ownerChannel !== undefined
2001
+ const ingressFacts = {
2002
+ hostKind: markerHostKind,
2003
+ logicalObservationKey: markerKey,
2004
+ rolloutIdentity: typeof rolloutIdentity === 'string' ? rolloutIdentity : '',
2005
+ rootSessionId: payloadParsed.sessionId,
2006
+ hostTurnId,
2007
+ painId: input.canonicalPainId,
2008
+ reason: payloadParsed.reason,
2009
+ evidence: ingressEvidence,
2010
+ };
2011
+ const ingressDecision = ownerManual && ownerChannel !== undefined
1783
2012
  ? evaluatePainIngress(buildOwnerCorrectionIngressReport({
1784
- hostKind: markerHostKind,
2013
+ ...ingressFacts,
1785
2014
  channel: ownerChannel,
1786
- logicalObservationKey: markerKey,
1787
- rolloutIdentity: typeof rolloutIdentity === 'string' ? rolloutIdentity : '',
1788
- rootSessionId: payloadParsed.sessionId,
1789
- hostTurnId,
1790
- painId: input.canonicalPainId,
1791
- reason: payloadParsed.reason,
1792
- // CR-02: never fabricate transcript evidence for an Owner statement;
1793
- // an empty list is the honest basis and bound explicit reports
1794
- // legitimately degrade.
1795
- evidence: ingressEvidence,
1796
2015
  }))
1797
- : evaluatePainIngress(buildCorrectionIngressReport({
1798
- hostKind: markerHostKind,
1799
- logicalObservationKey: markerKey,
1800
- rolloutIdentity: typeof rolloutIdentity === 'string' ? rolloutIdentity : '',
1801
- rootSessionId: payloadParsed.sessionId,
1802
- hostTurnId,
1803
- painId: input.canonicalPainId,
1804
- reason: payloadParsed.reason,
1805
- evidence: ingressEvidence,
1806
- }));
2016
+ : agentAssistedExplicit && markerHostKind === 'codex'
2017
+ ? evaluatePainIngress(buildAgentAssistedCorrectionIngressReport({
2018
+ logicalObservationKey: ingressFacts.logicalObservationKey,
2019
+ rolloutIdentity: ingressFacts.rolloutIdentity,
2020
+ rootSessionId: ingressFacts.rootSessionId,
2021
+ hostTurnId: ingressFacts.hostTurnId,
2022
+ painId: ingressFacts.painId,
2023
+ reason: ingressFacts.reason,
2024
+ evidence: ingressFacts.evidence,
2025
+ }))
2026
+ : evaluatePainIngress(buildCorrectionIngressReport(ingressFacts));
1807
2027
  if (ingressDecision.action === 'refuse' || ingressDecision.action === 'observation_only') {
1808
2028
  // Fail closed: an inconsistent/evidence-less admitted marker must not
1809
2029
  // silently become a task (and must never be relabelled automatic_hook).
@@ -1823,9 +2043,9 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1823
2043
  // the historical provenance rather than inventing an ingress report.
1824
2044
  provenance = 'host_context_bound';
1825
2045
  }
1826
- // Recovery path: a task link already exists. The ingress decision above
1827
- // still ran, so an inconsistent admitted marker fails closed instead of
1828
- // being reported as a healthy duplicate.
2046
+ // Preserve the existing fail-closed validation for linked tasks while
2047
+ // consent is readable. The revoked path above returns without transcript
2048
+ // access because the already-linked task is durable.
1829
2049
  if (typeof existingTaskId === 'string' && existingTaskId.length > 0) {
1830
2050
  return {
1831
2051
  ok: true,
@@ -1836,6 +2056,18 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1836
2056
  ...(ingressWarning !== undefined ? { ingressWarning } : {}),
1837
2057
  };
1838
2058
  }
2059
+ // B-class authorization (Pain Ingress SPEC §9.6): a governance marker
2060
+ // whose ingress facts classify as automatic_hook still requires the
2061
+ // Workspace's own automatic_pain_submission opt-in. An already-linked
2062
+ // task is untouched (recovery branch above); a NEW diagnosis task is
2063
+ // never created for an unauthorized automatic signal.
2064
+ if (provenance === 'automatic_hook' && !isAutomaticPainSubmissionAuthorized(workspaceDir)) {
2065
+ return {
2066
+ ok: false,
2067
+ reason: 'auto_pain_unauthorized',
2068
+ nextAction: 'Enable features.automatic_pain_submission in this workspace .pd/config.yaml to admit automatic Pain submissions.',
2069
+ };
2070
+ }
1839
2071
  const taskId = createDiagnosticianTaskId(input.canonicalPainId);
1840
2072
  // Cross-store crash recovery (SPEC §13): a task may already exist from a
1841
2073
  // crashed prior attempt (crash-after-create, before the link write).
@@ -1847,6 +2079,35 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1847
2079
  await stateManager.initialize();
1848
2080
  let existing = await stateManager.getTask(taskId);
1849
2081
  if (existing === null) {
2082
+ // PRI-1283 round 4 (SEC finding): after the host's ingestion consent
2083
+ // left granted, recovering this marker must not re-persist governed
2084
+ // conversation material into a NEW diagnostic task — the copy would
2085
+ // outlive the pending sweep. An owner-manual statement is exempt (an
2086
+ // explicit submission is not conversation ingestion). The check runs
2087
+ // only on the create path: a task already persisted before the
2088
+ // crash still gets its link repaired above/below.
2089
+ if ((markerHostKind === 'codex' || markerHostKind === 'workbuddy')
2090
+ && !ownerManual) {
2091
+ // A MISSING ledger is not a revocation (the sweep treats it the
2092
+ // same); refuse only on a recorded non-granted decision or an
2093
+ // unreadable one.
2094
+ const authz = readSourceMaterialAuthorization({ workspaceDir, hostKind: markerHostKind });
2095
+ if (authz.status === 'blocked'
2096
+ && authz.reason !== 'consent_missing') {
2097
+ return {
2098
+ ok: false,
2099
+ reason: 'source_authorization_revoked',
2100
+ // An unreadable ledger cannot be swept (the sweep refuses to
2101
+ // purge against an unreadable authority) — point at the ledger
2102
+ // repair FIRST instead of a command that cannot run.
2103
+ nextAction: authz.reason === 'consent_unreadable'
2104
+ ? `repair the consent ledger first (<workspace>/.state/conversation-ingestion-consent.json is unreadable); the sweep refuses to run until the authority is readable`
2105
+ : authz.reason === 'consent_revoked'
2106
+ ? `purge persisted copies first: pd consent sweep-revoked --workspace "${workspaceDir}" --apply (host: ${markerHostKind})`
2107
+ : `resolve the pending or failed conversation-ingestion consent decision for ${markerHostKind} in "${workspaceDir}" before retrying; a revocation sweep is only appropriate after the ledger records a revocation`,
2108
+ };
2109
+ }
2110
+ }
1850
2111
  const stateDir = path.join(workspaceDir, '.state');
1851
2112
  const config = loadPdConfigForPlugin(workspaceDir);
1852
2113
  if (!config.ok) {
@@ -1866,6 +2127,9 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1866
2127
  // marker, canonical pain id, task id and idempotency semantics above
1867
2128
  // are untouched; a reader failure degrades inside Stage A only.
1868
2129
  intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
2130
+ // SPEC §9.6: lazy probe — revocation between this admission check
2131
+ // and the async persist still refuses the submission.
2132
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(workspaceDir),
1869
2133
  });
1870
2134
  const result = await service.recordPain({
1871
2135
  painId: input.canonicalPainId,
@@ -1883,7 +2147,9 @@ export async function ensureGovernanceDiagnosticianTask(input) {
1883
2147
  // CR-02: replay the explicit Owner statement verbatim (classified,
1884
2148
  // channel-disclosed) so re-created tasks keep the same input basis.
1885
2149
  ...(payloadParsed.correctionEvidence !== undefined
1886
- ? { correctionEvidence: { ...payloadParsed.correctionEvidence, sessionId: payloadParsed.sessionId } }
2150
+ ? {
2151
+ correctionEvidence: recoveryCorrectionEvidence(payloadParsed.correctionEvidence, payloadParsed.sessionId),
2152
+ }
1887
2153
  : {}),
1888
2154
  recordObservability: true,
1889
2155
  });
@@ -1970,9 +2236,15 @@ export async function ensureGovernanceContinuation(input) {
1970
2236
  // continuation cannot begin diagnosis before the eligible evidence window
1971
2237
  // has been promoted. A promotion failure is retained as a degradation,
1972
2238
  // but never prevents the task from being durably ensured.
1973
- const codexConsent = typeof input.codexConversationIngestionEnabled === 'boolean'
2239
+ // PRI-1283 R2: the caller-supplied flag is necessary but NOT sufficient —
2240
+ // the consent LEDGER is re-read here so a revocation recorded against a
2241
+ // still-enabled flag cannot keep promoting old observations (the flag is
2242
+ // runtime authority for ingestion; the ledger is the governance record).
2243
+ const codexFlagConsent = typeof input.codexConversationIngestionEnabled === 'boolean'
1974
2244
  ? input.codexConversationIngestionEnabled
1975
2245
  : input.conversationIngestionEnabled === true;
2246
+ const codexLedgerConsent = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'codex' });
2247
+ const codexConsent = codexFlagConsent && codexLedgerConsent.status === 'authorized';
1976
2248
  const promoted = codexConsent
1977
2249
  ? promoteAdmittedGovernanceEvidence({
1978
2250
  workspaceDir,
@@ -2012,9 +2284,14 @@ export async function reconcileGovernanceContinuation(input) {
2012
2284
  const workspaceDir = path.resolve(input.workspaceDir);
2013
2285
  // Accept the pre-rename field too: an older caller paired with this runtime
2014
2286
  // must not silently lose Codex evidence promotion (P2 review).
2015
- const codexConsent = typeof input.codexConversationIngestionEnabled === 'boolean'
2287
+ // PRI-1283 R2: the flag input is ANDed with a LIVE consent-ledger read —
2288
+ // reconciliation must stop promoting observations the moment the ledger
2289
+ // records a revocation, even if the runtime flag lags behind.
2290
+ const codexFlagConsent = typeof input.codexConversationIngestionEnabled === 'boolean'
2016
2291
  ? input.codexConversationIngestionEnabled
2017
2292
  : input.conversationIngestionEnabled === true;
2293
+ const codexLedgerConsent = readSourceMaterialAuthorization({ workspaceDir, hostKind: 'codex' });
2294
+ const codexConsent = codexFlagConsent && codexLedgerConsent.status === 'authorized';
2018
2295
  const opened = openAdmissionStore(input.workspaceDir, input.databaseFactory);
2019
2296
  if (!('db' in opened)) {
2020
2297
  return { ok: false, reason: opened.reason, nextAction: opened.nextAction, tasksEnsured: 0, linksRepaired: 0, pendingTails: 0, completedTails: 0, staleTails: 0, degradations: [opened.reason] };