@principles/host-runtime 4.6.0 → 4.7.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.
@@ -103,38 +103,44 @@ export async function runPendingDiagnosticianOnce(options) {
103
103
  }
104
104
  const stateDir = path.join(options.workspaceDir, '.state');
105
105
  try {
106
- const bridge = await createPainSignalBridge({
107
- workspaceDir: options.workspaceDir,
108
- stateDir,
109
- ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
110
- owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
111
- effectiveConfig: config.effective,
112
- getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
113
- // PRI-1233 / SPEC §9.2: the L3 consumer executes admitted tasks, so it
114
- // is where Stage A actually runs for governance-admitted pains — the
115
- // neutral host reader must ride along or admission would never capture
116
- // a snapshot on this path. Flag-off keeps zero filesystem access.
117
- intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
118
- // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
119
- // like every other diagnosis entry.
120
- trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir) }),
121
- // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
122
- sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir),
123
- // SPEC §9.6: lazy probe — a flag revoked between candidate pick and
124
- // execution still stops the run at the bridge boundary.
125
- isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(options.workspaceDir),
126
- });
127
- const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
128
- if (executed.status === 'failed') {
129
- return {
130
- served: false,
131
- taskId: candidate.taskId,
132
- reason: 'execution_failed',
133
- ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
134
- nextAction: 'Inspect the workspace runtime profile; the task keeps its pending/retry state for the next tick or Console (L2).',
135
- };
106
+ let releaseBridge;
107
+ try {
108
+ const bridge = await createPainSignalBridge({
109
+ workspaceDir: options.workspaceDir,
110
+ stateDir,
111
+ ledgerAdapter: new PrincipleTreeLedgerAdapter({ stateDir }),
112
+ owner: options.owner ?? DIAGNOSTICIAN_AUTO_RUN_OWNER,
113
+ effectiveConfig: config.effective,
114
+ getEnvVar: options.getEnvVar ?? ((name) => process.env[name]),
115
+ // PRI-1233 / SPEC §9.2: the L3 consumer executes admitted tasks, so it
116
+ // is where Stage A actually runs for governance-admitted pains — the
117
+ // neutral host reader must ride along or admission would never capture
118
+ // a snapshot on this path. Flag-off keeps zero filesystem access.
119
+ intentDocReader: createHostIntentDocReader({ workspaceDir: options.workspaceDir, effectiveConfig: config.effective }),
120
+ // PRI-1265: the auto-run path sees the bound session's ORIGINAL turns
121
+ // like every other diagnosis entry.
122
+ trajectoryTurnReader: createGovernanceTrajectoryTurnReader({ workspaceDir: options.workspaceDir, sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir) }),
123
+ // PRI-1283 R2: latest-consent gate consulted per assembly / model call.
124
+ sourceMaterialAuthorization: createConsentLedgerSourceMaterialAuthorization(options.workspaceDir),
125
+ // SPEC §9.6: lazy probe — a flag revoked between candidate pick and
126
+ // execution still stops the run at the bridge boundary.
127
+ isAutoPainSubmissionAuthorized: () => isAutomaticPainSubmissionAuthorized(options.workspaceDir),
128
+ }, (release) => { releaseBridge = release; });
129
+ const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
130
+ if (executed.status === 'failed') {
131
+ return {
132
+ served: false,
133
+ taskId: candidate.taskId,
134
+ reason: 'execution_failed',
135
+ ...(executed.message !== undefined ? { message: executed.message.slice(0, 200) } : {}),
136
+ nextAction: 'Inspect the workspace runtime profile; the task keeps its pending/retry state for the next tick or Console (L2).',
137
+ };
138
+ }
139
+ return { served: true, taskId: candidate.taskId };
140
+ }
141
+ finally {
142
+ await releaseBridge?.();
136
143
  }
137
- return { served: true, taskId: candidate.taskId };
138
144
  }
139
145
  catch (error) {
140
146
  // A missing/!invalid runtime profile must not throw out of the timer that
@@ -318,6 +318,44 @@ export type ListGovernanceObservationsResult = {
318
318
  observations: readonly GovernanceObservationRecord[];
319
319
  } | Degradation;
320
320
  export declare function listGovernanceObservations(input: ListGovernanceObservationsInput): ListGovernanceObservationsResult;
321
+ /** A retained conversational row for an exact (host, rollout, turn). */
322
+ export interface GovernanceConversationTextRow {
323
+ readonly id: number;
324
+ readonly kind: 'user_turn' | 'assistant_turn';
325
+ readonly logicalKey: string;
326
+ readonly visibleText: string;
327
+ readonly observedAt: string;
328
+ }
329
+ export interface ListGovernanceConversationTextsInput {
330
+ readonly workspaceDir: string;
331
+ readonly hostKind: GovernanceObservationInput['hostKind'];
332
+ readonly rolloutIdentity: string;
333
+ readonly hostTurnId: string;
334
+ /**
335
+ * The turn's LAST N readable conversational rows (a long turn whose final
336
+ * answer sits behind dozens of tool/reasoning observations must still
337
+ * surface it — the generic list's `ORDER BY id LIMIT` window would cut it).
338
+ */
339
+ readonly limit?: number;
340
+ readonly databaseFactory?: ObservationDatabaseFactory;
341
+ }
342
+ export type ListGovernanceConversationTextsResult = {
343
+ readonly ok: true;
344
+ readonly rows: readonly GovernanceConversationTextRow[];
345
+ } | {
346
+ readonly ok: false;
347
+ readonly reason: string;
348
+ readonly nextAction: string;
349
+ };
350
+ /**
351
+ * The ONE selection rule for an exact target turn's readable text, shared by
352
+ * the worker's evidence backfill, the diagnosis-time exact-turn reader and
353
+ * the submit path's opportunistic enrichment (devin BUG_0002): filter
354
+ * host/session/turn + conversational kind + retained readable text INSIDE
355
+ * the SQL, then take the LAST N by id (reversed back to capture order) —
356
+ * never a generic early window over all observation kinds.
357
+ */
358
+ export declare function listGovernanceConversationTextsForHostTurn(input: ListGovernanceConversationTextsInput): ListGovernanceConversationTextsResult;
321
359
  export declare function promoteGovernanceEvidence(input: PromoteGovernanceEvidenceInput): PromoteGovernanceEvidenceResult;
322
360
  export interface QuarantineGovernanceObservationArgs {
323
361
  readonly workspaceDir: string;
@@ -952,6 +952,47 @@ class PromotionMissingError extends Error {
952
952
  this.name = 'PromotionMissingError';
953
953
  }
954
954
  }
955
+ /**
956
+ * The ONE selection rule for an exact target turn's readable text, shared by
957
+ * the worker's evidence backfill, the diagnosis-time exact-turn reader and
958
+ * the submit path's opportunistic enrichment (devin BUG_0002): filter
959
+ * host/session/turn + conversational kind + retained readable text INSIDE
960
+ * the SQL, then take the LAST N by id (reversed back to capture order) —
961
+ * never a generic early window over all observation kinds.
962
+ */
963
+ export function listGovernanceConversationTextsForHostTurn(input) {
964
+ const opened = openStore(input.workspaceDir, input.databaseFactory);
965
+ if (!('db' in opened))
966
+ return opened;
967
+ const { db, close } = opened;
968
+ try {
969
+ const limit = Math.min(Math.max(input.limit ?? 12, 1), 64);
970
+ const rows = db.prepare([
971
+ 'SELECT id, kind, logical_key, visible_text, observed_at FROM governance_observations',
972
+ 'WHERE host_kind = ? AND rollout_identity = ? AND host_turn_id = ?',
973
+ "AND kind IN ('user_turn','assistant_turn')",
974
+ "AND completeness = 'complete'",
975
+ "AND retention_class IN ('operational','promoted')",
976
+ "AND visible_text IS NOT NULL AND TRIM(visible_text) <> ''",
977
+ 'ORDER BY id DESC LIMIT ?',
978
+ ].join(' ')).all(input.hostKind, input.rolloutIdentity, input.hostTurnId, limit);
979
+ const mapped = rows.map((row) => {
980
+ const kind = rowField(row, 'kind');
981
+ return {
982
+ id: Number(rowField(row, 'id')),
983
+ kind: kind === 'assistant_turn' ? 'assistant_turn' : 'user_turn',
984
+ logicalKey: String(rowField(row, 'logical_key')),
985
+ visibleText: String(rowField(row, 'visible_text')),
986
+ observedAt: String(rowField(row, 'observed_at')),
987
+ };
988
+ });
989
+ mapped.reverse();
990
+ return { ok: true, rows: mapped };
991
+ }
992
+ finally {
993
+ close();
994
+ }
995
+ }
955
996
  export function promoteGovernanceEvidence(input) {
956
997
  const opened = openStore(input.workspaceDir, input.databaseFactory);
957
998
  if (!('db' in opened))
@@ -1,5 +1,5 @@
1
1
  import { denyAllSourceMaterialAuthorization, } from '@principles/core/runtime';
2
- import { listGovernanceObservations, listGovernanceTurnTexts } from './governance-observation-store.js';
2
+ import { listGovernanceConversationTextsForHostTurn, listGovernanceTurnTexts } from './governance-observation-store.js';
3
3
  /** Bound on turns per list call — the assembler bounds the window again. */
4
4
  const MAX_TURNS_PER_SESSION = 200;
5
5
  /** The governance-observation hosts whose turns this reader can serve. */
@@ -74,45 +74,38 @@ export function createGovernanceTrajectoryTurnReader(args) {
74
74
  || !port.isHostSourceMaterialAuthorized(authorizedHostKind).authorized) {
75
75
  return { userTurns: [], assistantTurns: [] };
76
76
  }
77
- const result = listGovernanceObservations({
77
+ // PRI-1273 (devin BUG_0002): the shared exact-turn selection rule —
78
+ // conversational kind + retained readable text filtered INSIDE the SQL
79
+ // and the turn's LAST rows kept, so a final answer sitting behind
80
+ // dozens of tool/reasoning observations still enters the window (the
81
+ // old generic `ORDER BY id LIMIT 64` window cut it).
82
+ const result = listGovernanceConversationTextsForHostTurn({
78
83
  workspaceDir: args.workspaceDir,
79
- rolloutIdentity: sessionId,
80
84
  hostKind: authorizedHostKind,
85
+ rolloutIdentity: sessionId,
81
86
  hostTurnId,
82
- limit: 64,
87
+ limit: 32,
83
88
  });
84
89
  if (!result.ok)
85
90
  return { userTurns: [], assistantTurns: [] };
86
- const retainedText = (row) => (row.retentionClass === 'operational' || row.retentionClass === 'promoted')
87
- && typeof row.visibleText === 'string'
88
- && row.visibleText.trim() !== ''
89
- ? row.visibleText
90
- : null;
91
- const userRows = result.observations.filter((row) => row.kind === 'user_turn');
92
91
  return {
93
- userTurns: userRows.flatMap((row, index) => {
94
- const text = retainedText(row);
95
- return text === null ? [] : [{
96
- id: row.id,
97
- turnIndex: row.sourceOrdinal !== null && row.sourceOrdinal >= 0 ? row.sourceOrdinal : index,
98
- rawExcerpt: text,
99
- correctionDetected: false,
100
- correctionCue: null,
101
- createdAt: row.observedAt,
102
- }];
103
- }),
104
- assistantTurns: result.observations.filter((row) => row.kind === 'assistant_turn').flatMap((row) => {
105
- const text = retainedText(row);
106
- return text === null ? [] : [{
107
- id: row.id,
108
- sessionId,
109
- runId: '',
110
- provider: '',
111
- model: '',
112
- sanitizedText: text,
113
- createdAt: row.observedAt,
114
- }];
115
- }),
92
+ userTurns: result.rows.flatMap((row, index) => row.kind === 'user_turn' ? [{
93
+ id: row.id,
94
+ turnIndex: index,
95
+ rawExcerpt: row.visibleText,
96
+ correctionDetected: false,
97
+ correctionCue: null,
98
+ createdAt: row.observedAt,
99
+ }] : []),
100
+ assistantTurns: result.rows.flatMap((row) => row.kind === 'assistant_turn' ? [{
101
+ id: row.id,
102
+ sessionId,
103
+ runId: '',
104
+ provider: '',
105
+ model: '',
106
+ sanitizedText: row.visibleText,
107
+ createdAt: row.observedAt,
108
+ }] : []),
116
109
  };
117
110
  },
118
111
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/host-runtime",
3
- "version": "4.6.0",
3
+ "version": "4.7.0",
4
4
  "description": "Shared host-neutral orchestration for Principles Disciple MVP-Core hook paths.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -39,8 +39,8 @@
39
39
  "lint": "eslint \"src/**/*.ts\""
40
40
  },
41
41
  "dependencies": {
42
- "@principles/core": "^8.1.0",
43
- "@principles/install-layout": "^0.10.0",
42
+ "@principles/core": "^8.2.0",
43
+ "@principles/install-layout": "^0.11.0",
44
44
  "better-sqlite3": "^13.0.3",
45
45
  "js-yaml": "^5.4.3"
46
46
  },
@@ -57,5 +57,5 @@
57
57
  "url": "git+https://github.com/csuzngjh/principles.git"
58
58
  },
59
59
  "license": "Apache-2.0",
60
- "gitHead": "5e3b8d53d46dfb3884966a006be3996c1dd34428"
60
+ "gitHead": "06a20cb7842f41a6510937f92340343158164b9f"
61
61
  }