create-principles-disciple 1.151.0 → 1.152.1

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 (177) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/tool-semantics.d.ts +11 -1
  3. package/codex-adapter/dist/tool-semantics.js +11 -1
  4. package/codex-adapter/package.json +1 -1
  5. package/console/dist/server/index.js +5 -0
  6. package/console/dist/server/models/EvidenceChainConsoleModel.js +1 -2
  7. package/console/dist/server/models/GovernanceConsoleModel.js +56 -68
  8. package/console/dist/server/models/RuleCandidateBindingConsoleModel.js +31 -31
  9. package/console/dist/server/routes/failed-tasks.js +84 -1
  10. package/console/dist/server/routes/update.js +45 -30
  11. package/console/dist/server/update-timeout.js +15 -1
  12. package/console/dist/shared/rule-candidate-binding-contract.d.ts +4 -1
  13. package/console/dist/web/assets/app.js +26 -26
  14. package/core/dist/runtime/activation/ledger-identity.d.ts.map +1 -1
  15. package/core/dist/runtime/activation/ledger-identity.js +5 -0
  16. package/core/dist/runtime/activation/ledger-identity.js.map +1 -1
  17. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts +6 -0
  18. package/core/dist/runtime/activation/prompt-activation-reader-contract.d.ts.map +1 -1
  19. package/core/dist/runtime/activation/prompt-activation-reader-contract.js +105 -7
  20. package/core/dist/runtime/activation/prompt-activation-reader-contract.js.map +1 -1
  21. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.d.ts.map +1 -1
  22. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.js +10 -1
  23. package/core/dist/runtime/adapter/principle-tree-ledger-adapter.js.map +1 -1
  24. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  25. package/core/dist/runtime/candidate-audit.js +6 -3
  26. package/core/dist/runtime/candidate-audit.js.map +1 -1
  27. package/core/dist/runtime/golden-trace.d.ts.map +1 -1
  28. package/core/dist/runtime/golden-trace.js +30 -24
  29. package/core/dist/runtime/golden-trace.js.map +1 -1
  30. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.d.ts.map +1 -1
  31. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.js +4 -4
  32. package/core/dist/runtime/internalization/refiner-sandbox-wrapper.js.map +1 -1
  33. package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts +13 -0
  34. package/core/dist/runtime/internalization/rollout-reviewer-runner.d.ts.map +1 -1
  35. package/core/dist/runtime/internalization/rollout-reviewer-runner.js +28 -4
  36. package/core/dist/runtime/internalization/rollout-reviewer-runner.js.map +1 -1
  37. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +21 -1
  38. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  39. package/core/dist/runtime/internalization/rule-host-input-builder.js +13 -0
  40. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  41. package/core/dist/runtime/internalization/scribe-runner.d.ts.map +1 -1
  42. package/core/dist/runtime/internalization/scribe-runner.js +25 -3
  43. package/core/dist/runtime/internalization/scribe-runner.js.map +1 -1
  44. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts +1 -0
  45. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  46. package/core/dist/runtime/internalization-chain-integrity-read-model.js +8 -5
  47. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  48. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  49. package/core/dist/runtime/pruning-read-model.js +7 -5
  50. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  51. package/core/dist/runtime/schema-conformance-read-model.d.ts +1 -0
  52. package/core/dist/runtime/schema-conformance-read-model.d.ts.map +1 -1
  53. package/core/dist/runtime/schema-conformance-read-model.js +8 -5
  54. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  55. package/core/dist/runtime/signal-collector/types.d.ts +6 -0
  56. package/core/dist/runtime/signal-collector/types.d.ts.map +1 -1
  57. package/core/dist/runtime/signal-collector/types.js.map +1 -1
  58. package/core/dist/runtime/types/rule-candidate-binding.d.ts +1 -1
  59. package/core/dist/runtime/types/rule-candidate-binding.d.ts.map +1 -1
  60. package/core/dist/trajectory-store.d.ts +17 -1
  61. package/core/dist/trajectory-store.d.ts.map +1 -1
  62. package/core/dist/trajectory-store.js +32 -10
  63. package/core/dist/trajectory-store.js.map +1 -1
  64. package/core/package.json +1 -1
  65. package/dist/index.js +34 -0
  66. package/dist/index.js.map +1 -1
  67. package/dist/installer.d.ts +53 -0
  68. package/dist/installer.d.ts.map +1 -1
  69. package/dist/installer.js +106 -1
  70. package/dist/installer.js.map +1 -1
  71. package/dist/installers/index.d.ts +31 -0
  72. package/dist/installers/index.d.ts.map +1 -1
  73. package/dist/installers/index.js +76 -3
  74. package/dist/installers/index.js.map +1 -1
  75. package/dist/installers/legacy-workbuddy-skill.d.ts +46 -14
  76. package/dist/installers/legacy-workbuddy-skill.d.ts.map +1 -1
  77. package/dist/installers/legacy-workbuddy-skill.js +162 -29
  78. package/dist/installers/legacy-workbuddy-skill.js.map +1 -1
  79. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  80. package/dist/installers/workbuddy-host-installer.js +7 -6
  81. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  82. package/dist/update/release-manager.d.ts +1 -1
  83. package/dist/update/release-manager.d.ts.map +1 -1
  84. package/dist/update/release-manager.js +45 -2
  85. package/dist/update/release-manager.js.map +1 -1
  86. package/host-runtime/dist/active-principle-prompt.js +3 -2
  87. package/host-runtime/dist/governance-observation-store.js +2 -2
  88. package/host-runtime/dist/governance-signal-admission.js +14 -1
  89. package/host-runtime/dist/host-liveness-contract.js +2 -2
  90. package/host-runtime/dist/product-telemetry/milestone-readers.js +3 -2
  91. package/host-runtime/dist/production-pain-evidence.js +3 -2
  92. package/host-runtime/dist/production-rulehost-gate.d.ts +20 -0
  93. package/host-runtime/dist/production-rulehost-gate.js +110 -35
  94. package/host-runtime/dist/prompt-activation-deliverability.d.ts +2 -0
  95. package/host-runtime/dist/prompt-activation-deliverability.js +5 -3
  96. package/host-runtime/dist/prompt-injection-status.js +3 -2
  97. package/host-runtime/dist/workspace-behavior-evidence.js +4 -3
  98. package/host-runtime/package.json +5 -1
  99. package/install-layout/dist/mcp-binding-contract.js +5 -0
  100. package/install-layout/package.json +1 -1
  101. package/package.json +3 -3
  102. package/pd-cli/dist/commands/candidate.d.ts.map +1 -1
  103. package/pd-cli/dist/commands/candidate.js +2 -1
  104. package/pd-cli/dist/commands/candidate.js.map +1 -1
  105. package/pd-cli/dist/commands/console.d.ts.map +1 -1
  106. package/pd-cli/dist/commands/console.js +8 -0
  107. package/pd-cli/dist/commands/console.js.map +1 -1
  108. package/pd-cli/dist/commands/demo-story-a.d.ts.map +1 -1
  109. package/pd-cli/dist/commands/demo-story-a.js +2 -1
  110. package/pd-cli/dist/commands/demo-story-a.js.map +1 -1
  111. package/pd-cli/dist/commands/health-mcp.d.ts +21 -0
  112. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  113. package/pd-cli/dist/commands/health-mcp.js +19 -1
  114. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  115. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  116. package/pd-cli/dist/commands/health.js +12 -4
  117. package/pd-cli/dist/commands/health.js.map +1 -1
  118. package/pd-cli/dist/commands/legacy-cleanup.d.ts.map +1 -1
  119. package/pd-cli/dist/commands/legacy-cleanup.js +2 -1
  120. package/pd-cli/dist/commands/legacy-cleanup.js.map +1 -1
  121. package/pd-cli/dist/commands/pain-list.d.ts.map +1 -1
  122. package/pd-cli/dist/commands/pain-list.js +2 -1
  123. package/pd-cli/dist/commands/pain-list.js.map +1 -1
  124. package/pd-cli/dist/commands/principles-stats.d.ts.map +1 -1
  125. package/pd-cli/dist/commands/principles-stats.js +2 -1
  126. package/pd-cli/dist/commands/principles-stats.js.map +1 -1
  127. package/pd-cli/dist/commands/quality-scorecard.d.ts.map +1 -1
  128. package/pd-cli/dist/commands/quality-scorecard.js +2 -1
  129. package/pd-cli/dist/commands/quality-scorecard.js.map +1 -1
  130. package/pd-cli/dist/commands/runtime-init.d.ts.map +1 -1
  131. package/pd-cli/dist/commands/runtime-init.js +5 -4
  132. package/pd-cli/dist/commands/runtime-init.js.map +1 -1
  133. package/pd-cli/dist/commands/runtime-internalization-evidence.d.ts.map +1 -1
  134. package/pd-cli/dist/commands/runtime-internalization-evidence.js +2 -1
  135. package/pd-cli/dist/commands/runtime-internalization-evidence.js.map +1 -1
  136. package/pd-cli/dist/commands/runtime-recovery-failed-task.d.ts.map +1 -1
  137. package/pd-cli/dist/commands/runtime-recovery-failed-task.js +2 -1
  138. package/pd-cli/dist/commands/runtime-recovery-failed-task.js.map +1 -1
  139. package/pd-cli/dist/legacy/session-history-import.js +2 -2
  140. package/pd-cli/dist/legacy/session-history-import.js.map +1 -1
  141. package/pd-cli/dist/services/console-launcher.d.ts +15 -0
  142. package/pd-cli/dist/services/console-launcher.d.ts.map +1 -1
  143. package/pd-cli/dist/services/console-launcher.js +7 -1
  144. package/pd-cli/dist/services/console-launcher.js.map +1 -1
  145. package/pd-cli/package.json +1 -1
  146. package/pd-mcp-server/dist/index.js +33 -2
  147. package/pd-mcp-server/dist/server.d.ts +7 -3
  148. package/pd-mcp-server/dist/server.js +6 -1
  149. package/pd-mcp-server/dist/submit-assembly.d.ts +24 -0
  150. package/pd-mcp-server/dist/submit-assembly.js +61 -0
  151. package/pd-mcp-server/dist/version.d.ts +1 -1
  152. package/pd-mcp-server/dist/version.js +1 -1
  153. package/pd-mcp-server/package.json +2 -1
  154. package/plugin/dist/bundle.js +451 -473
  155. package/plugin/dist/constants/tool-semantics.d.ts +13 -0
  156. package/plugin/dist/core/correction-anchor.d.ts +40 -0
  157. package/plugin/dist/core/experiment-workspace-guard.d.ts +10 -0
  158. package/plugin/dist/core/mcp-binding.d.ts +3 -1
  159. package/plugin/dist/core/signal-collector-host.d.ts +19 -1
  160. package/plugin/dist/core/workspace-context.d.ts +0 -4
  161. package/plugin/dist/hooks/gate.d.ts +0 -5
  162. package/plugin/dist/openclaw.plugin.json +1 -1
  163. package/plugin/dist/rulehost-evidence.js +4 -4
  164. package/plugin/mcp/launcher.cjs +85 -0
  165. package/plugin/openclaw.plugin.json +1 -1
  166. package/plugin/package.json +1 -1
  167. package/release-manager/dist/installer.js +106 -1
  168. package/release-manager/dist/installers/index.js +76 -3
  169. package/release-manager/dist/installers/legacy-workbuddy-skill.js +162 -29
  170. package/release-manager/dist/installers/workbuddy-host-installer.js +7 -6
  171. package/release-manager/dist/update/release-manager.js +45 -2
  172. package/release-manager/package.json +1 -1
  173. package/workbuddy-adapter/dist/tool-semantics.d.ts +11 -0
  174. package/workbuddy-adapter/dist/tool-semantics.js +11 -0
  175. package/workbuddy-adapter/package.json +1 -1
  176. package/workbuddy-adapter/plugin/mcp/launcher.cjs +85 -0
  177. package/plugin/dist/core/rule-host.d.ts +0 -203
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "productVersion": "2.8.6",
4
- "sourceCommit": "d70d277260da6f9ef2fcbecb622501cea504a12c"
4
+ "sourceCommit": "80b43dd1b98d261b580215cff8b815594606178c"
5
5
  }
@@ -8,7 +8,7 @@
8
8
  * never fire on a real Codex event.
9
9
  *
10
10
  * EVIDENCE BOUND: this declaration contains only names with in-repo
11
- * evidence — the shipped hook matcher `Bash|apply_patch`
11
+ * evidence — the shipped hook matcher `Bash|apply_patch|pd_submit_pain`
12
12
  * (plugins/principles-disciple/hooks/hooks.json:5, locked by
13
13
  * packages/codex-adapter/tests/codex-plugin-bundle.test.ts:183 and used as
14
14
  * the installed-hook fixture in
@@ -17,6 +17,16 @@
17
17
  * Codex tool surface is tracked as PRI-657 — a wrong guess would be worse
18
18
  * than a gap (the reliability check rejects undeclared names, forcing
19
19
  * correct names).
20
+ *
21
+ * OG-4 DELIBERATE OMISSION (2026-11-13): the PreToolUse matcher now also
22
+ * routes `pd_submit_pain` (the shared MCP write tool) so the hook OBSERVES the
23
+ * call, but the name is intentionally NOT declared here. `CanonicalKind` is a
24
+ * file-mutation axis: `write` feeds `computeBehaviorFacts.writeCount` and
25
+ * disables the `'other' ⇒ facts incomplete` conservative guard. Declaring a
26
+ * ledger write as a file write would fabricate file-level facts, and the
27
+ * payload carries no target path. Until the enum grows a non-file mutation
28
+ * kind (or host-sampled events justify a mapping), it resolves to `'other'`,
29
+ * which the provider treats as an incomplete semantic view.
20
30
  */
21
31
  import { type ToolSemanticMappingV1, type ToolSemanticRegistry } from '@principles/core/runtime';
22
32
  export declare const CODEX_TOOL_SEMANTIC_MAPPINGS: readonly ToolSemanticMappingV1[];
@@ -8,7 +8,7 @@
8
8
  * never fire on a real Codex event.
9
9
  *
10
10
  * EVIDENCE BOUND: this declaration contains only names with in-repo
11
- * evidence — the shipped hook matcher `Bash|apply_patch`
11
+ * evidence — the shipped hook matcher `Bash|apply_patch|pd_submit_pain`
12
12
  * (plugins/principles-disciple/hooks/hooks.json:5, locked by
13
13
  * packages/codex-adapter/tests/codex-plugin-bundle.test.ts:183 and used as
14
14
  * the installed-hook fixture in
@@ -17,6 +17,16 @@
17
17
  * Codex tool surface is tracked as PRI-657 — a wrong guess would be worse
18
18
  * than a gap (the reliability check rejects undeclared names, forcing
19
19
  * correct names).
20
+ *
21
+ * OG-4 DELIBERATE OMISSION (2026-11-13): the PreToolUse matcher now also
22
+ * routes `pd_submit_pain` (the shared MCP write tool) so the hook OBSERVES the
23
+ * call, but the name is intentionally NOT declared here. `CanonicalKind` is a
24
+ * file-mutation axis: `write` feeds `computeBehaviorFacts.writeCount` and
25
+ * disables the `'other' ⇒ facts incomplete` conservative guard. Declaring a
26
+ * ledger write as a file write would fabricate file-level facts, and the
27
+ * payload carries no target path. Until the enum grows a non-file mutation
28
+ * kind (or host-sampled events justify a mapping), it resolves to `'other'`,
29
+ * which the provider treats as an incomplete semantic view.
20
30
  */
21
31
  import { buildToolSemanticRegistry } from '@principles/core/runtime';
22
32
  export const CODEX_TOOL_SEMANTIC_MAPPINGS = Object.freeze([
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.10.0",
3
+ "version": "0.10.1",
4
4
  "description": "Codex CLI host adapter for Principles Disciple — implements HostAdapter interface for OpenAI Codex CLI's stdin/stdout JSON hook model (ADR-0020).",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -213,6 +213,11 @@ const UPDATE_APPLY_FULL_TIMEOUT_MS = resolveApplyFullTimeoutMs();
213
213
  // host). Measured on a CN network against GitHub Pages: normally ~1.2s, but a
214
214
  // single slow DNS/TLS leg pushes it past 12s, which the old 10s default turned
215
215
  // into a 504 "Request timeout" on every page load (observed ~1 run in 5).
216
+ // PRI-1101: 30s was outlived at least once by a healthy check, and the late
217
+ // success was then dropped. The replacement 120s is an empirical budget that
218
+ // covers observed slow runs (~12.5s), NOT a bound on the inner operation: tuf-js
219
+ // allows 3 x 100s per request across >=4 sequential requests (~1200s worst
220
+ // case), so a check above 120s can still be cut off. See update-timeout.ts.
216
221
  // Same knob pattern as apply-full: PD_UPDATE_CHECK_TIMEOUT_MS (ms) overrides.
217
222
  const UPDATE_CHECK_TIMEOUT_MS = resolveCheckTimeoutMs();
218
223
  /**
@@ -32,7 +32,6 @@ import { openTrajectoryDbReadonly } from '@principles/core/trajectory-store';
32
32
  import { resolveStateDbPath, resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
33
33
  import * as fs from 'node:fs';
34
34
  import * as path from 'node:path';
35
- import Database from 'better-sqlite3';
36
35
  import { errorMessage } from '../utils/response.js';
37
36
  /**
38
37
  * P1-2: restore the assistant turn text for verbatim display.
@@ -183,7 +182,7 @@ export class EvidenceChainConsoleModel {
183
182
  if (fs.existsSync(trajectoryDbPath)) {
184
183
  let trajDb = null;
185
184
  try {
186
- trajDb = new Database(trajectoryDbPath, { readonly: true });
185
+ trajDb = openTrajectoryDbReadonly(this.workspaceDir);
187
186
  try {
188
187
  painEvents = trajDb.prepare('SELECT id, session_id, source, score, reason, severity, origin, confidence, text, created_at, canonical_pain_id, runtime_task_id, host_kind FROM pain_events ORDER BY created_at DESC LIMIT 100').all();
189
188
  }
@@ -1,5 +1,6 @@
1
1
  import { SqliteConnection, SqliteApprovalQueueStore, SqlitePIArtifactStore, ApprovalQueue, } from '@principles/core/runtime';
2
- import { resolveStateDbPath, resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
2
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
3
+ import { openTrajectoryDbReadonly, TrajectoryDbUnavailableError } from '@principles/core/trajectory-store';
3
4
  import * as fs from 'node:fs';
4
5
  import * as path from 'node:path';
5
6
  import { errorMessage } from '../utils/response.js';
@@ -43,6 +44,13 @@ function isMissingTableError(err) {
43
44
  return false;
44
45
  return err.message.includes('no such table');
45
46
  }
47
+ /** Machine-readable cause for a trajectory.db read failure (never a fabricated 0). */
48
+ function trajectoryDbFailureDetail(err) {
49
+ if (err instanceof TrajectoryDbUnavailableError) {
50
+ return err.table ? `${err.code}: ${err.table}` : err.code;
51
+ }
52
+ return errorMessage(err);
53
+ }
46
54
  function isRecord(value) {
47
55
  return typeof value === 'object' && value !== null && !Array.isArray(value);
48
56
  }
@@ -292,82 +300,62 @@ export class GovernanceConsoleModel {
292
300
  stateReason = 'No governance chain activity recorded yet.';
293
301
  nextAction = 'PD will surface principle candidates here once behavior deviations are captured and reviewable artifacts are generated.';
294
302
  }
295
- // PRI-380: Query trajectory.db for behavior evidence count
296
- let evidenceInProgressCount = 0;
297
- const trajectoryDbPath = resolveTrajectoryDbPath(this.workspaceDir);
298
- if (fs.existsSync(trajectoryDbPath)) {
303
+ // PRI-380: Query trajectory.db for behavior evidence count.
304
+ //
305
+ // PRI-1207: a missing/unreadable trajectory.db means "cannot determine",
306
+ // not "zero". The count stays undefined and a degraded signal is pushed,
307
+ // so the console never renders a silent 0 over an absent data source.
308
+ let evidenceInProgressCount;
309
+ try {
310
+ const trajDb = openTrajectoryDbReadonly(this.workspaceDir);
299
311
  try {
300
- const Database = (await import('better-sqlite3')).default;
301
- const trajDb = new Database(trajectoryDbPath, { readonly: true });
302
- try {
303
- const rows = trajDb.prepare('SELECT COUNT(*) as c FROM pain_events').all();
304
- if (Array.isArray(rows) && rows.length > 0) {
305
- const [row] = rows;
306
- if (isRecord(row) && Object.hasOwn(row, 'c') && typeof row.c === 'number') {
307
- evidenceInProgressCount = row.c;
308
- }
312
+ const rows = trajDb.prepare('SELECT COUNT(*) as c FROM pain_events').all();
313
+ if (Array.isArray(rows) && rows.length > 0) {
314
+ const [row] = rows;
315
+ if (isRecord(row) && Object.hasOwn(row, 'c') && typeof row.c === 'number') {
316
+ evidenceInProgressCount = row.c;
309
317
  }
310
318
  }
311
- catch (err) {
312
- if (!isMissingTableError(err))
313
- throw err;
314
- degradedSignals.push({
315
- reasonCode: 'trajectory_db_unavailable',
316
- nextActionCode: 'check_trajectory_db',
317
- reason: 'Behavior evidence source (trajectory.db) is unavailable — evidence count may be inaccurate.',
318
- nextAction: 'Check trajectory.db file integrity in .state directory.',
319
- source: 'source_unavailable',
320
- });
321
- }
322
- finally {
323
- trajDb.close();
324
- }
325
319
  }
326
- catch (err) {
327
- degradedSignals.push({
328
- reasonCode: 'trajectory_db_unavailable',
329
- nextActionCode: 'check_trajectory_db',
330
- reason: 'Behavior evidence source (trajectory.db) is unavailable — evidence count may be inaccurate.',
331
- nextAction: 'Check trajectory.db file integrity in .state directory.',
332
- source: 'source_unavailable',
333
- });
334
- if (!(err instanceof Error))
335
- throw err;
320
+ finally {
321
+ trajDb.close();
336
322
  }
337
323
  }
338
- // Wave 4: Query gate_blocks for today's auto-block count
339
- let gateBlocksToday = 0;
340
- if (fs.existsSync(trajectoryDbPath)) {
324
+ catch (err) {
325
+ degradedSignals.push({
326
+ reasonCode: 'trajectory_db_unavailable',
327
+ nextActionCode: 'check_trajectory_db',
328
+ reason: `Behavior evidence source (trajectory.db) is unavailable — evidence count is unknown, not zero (${trajectoryDbFailureDetail(err)}).`,
329
+ nextAction: 'Check trajectory.db file integrity in .state directory.',
330
+ source: 'source_unavailable',
331
+ });
332
+ }
333
+ // Wave 4: Query gate_blocks for today's auto-block count.
334
+ // Same contract as above: unreadable source => unknown, never 0.
335
+ let gateBlocksToday;
336
+ try {
337
+ const trajDb = openTrajectoryDbReadonly(this.workspaceDir);
341
338
  try {
342
- const Database = (await import('better-sqlite3')).default;
343
- const trajDb = new Database(trajectoryDbPath, { readonly: true });
344
- try {
345
- const todayStart = new Date();
346
- todayStart.setHours(0, 0, 0, 0);
347
- const row = trajDb.prepare('SELECT COUNT(*) as c FROM gate_blocks WHERE created_at >= ?').get(todayStart.toISOString());
348
- if (isRecord(row) && Object.hasOwn(row, 'c') && typeof row.c === 'number') {
349
- gateBlocksToday = row.c;
350
- }
351
- }
352
- catch (err) {
353
- if (!isMissingTableError(err))
354
- throw err;
355
- }
356
- finally {
357
- trajDb.close();
339
+ const todayStart = new Date();
340
+ todayStart.setHours(0, 0, 0, 0);
341
+ const row = trajDb.prepare('SELECT COUNT(*) as c FROM gate_blocks WHERE created_at >= ?').get(todayStart.toISOString());
342
+ if (isRecord(row) && Object.hasOwn(row, 'c') && typeof row.c === 'number') {
343
+ gateBlocksToday = row.c;
358
344
  }
359
345
  }
360
- catch (err) {
361
- degradedSignals.push({
362
- reasonCode: 'trajectory_db_unavailable',
363
- nextActionCode: 'check_trajectory_db',
364
- reason: 'gate_blocks source is unavailable — gate block count may be inaccurate.',
365
- nextAction: 'Check trajectory.db file integrity in .state directory.',
366
- source: 'source_unavailable',
367
- });
368
- console.warn('GovernanceConsoleModel: failed to read gate_blocks:', err);
346
+ finally {
347
+ trajDb.close();
369
348
  }
370
349
  }
350
+ catch (err) {
351
+ degradedSignals.push({
352
+ reasonCode: 'trajectory_db_unavailable',
353
+ nextActionCode: 'check_trajectory_db',
354
+ reason: `gate_blocks source is unavailable — gate block count is unknown, not zero (${trajectoryDbFailureDetail(err)}).`,
355
+ nextAction: 'Check trajectory.db file integrity in .state directory.',
356
+ source: 'source_unavailable',
357
+ });
358
+ }
371
359
  const response = {
372
360
  pendingReviewCount,
373
361
  behaviorDeviationCount,
@@ -385,13 +373,13 @@ export class GovernanceConsoleModel {
385
373
  if (degradedSignals.length > 0) {
386
374
  response.degradedSignals = degradedSignals;
387
375
  }
388
- if (evidenceInProgressCount > 0) {
376
+ if (evidenceInProgressCount !== undefined && evidenceInProgressCount > 0) {
389
377
  response.evidenceInProgressCount = evidenceInProgressCount;
390
378
  }
391
379
  if (pendingHumanReviewCount > 0) {
392
380
  response.pendingHumanReviewCount = pendingHumanReviewCount;
393
381
  }
394
- if (gateBlocksToday > 0) {
382
+ if (gateBlocksToday !== undefined && gateBlocksToday > 0) {
395
383
  response.gateBlocksToday = gateBlocksToday;
396
384
  }
397
385
  return response;
@@ -1,8 +1,8 @@
1
1
  import path from 'node:path';
2
2
  import { existsSync } from 'node:fs';
3
- import Database from 'better-sqlite3';
4
3
  import { createRuntimeStateHandle, PrincipleTreeLedgerAdapter, reviseRuleBindingOnce, resolveRuleBindingRevisionTarget, reviseRuleSourceOnce, previewRuleSourceCorrection, hydratePITaskRecord, candidateIdFromDreamerSeed, } from '@principles/core/runtime';
5
- import { resolveStateDbPath, resolveTrajectoryDbPath } from '@principles/core/runtime/storage-paths';
4
+ import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
5
+ import { openTrajectoryDbReadonly } from '@principles/core/trajectory-store';
6
6
  import { readLedgerFileState } from '@principles/core/principle-tree-ledger';
7
7
  import { ActivationsConsoleModel } from './ActivationsConsoleModel.js';
8
8
  function record(value) {
@@ -145,33 +145,36 @@ export class RuleCandidateBindingConsoleModel {
145
145
  const distinct = [...new Set(painIds.filter(id => id !== ''))];
146
146
  if (distinct.length === 0)
147
147
  return { sources: result, degraded: null };
148
- const dbPath = resolveTrajectoryDbPath(this.workspaceDir);
149
- if (!existsSync(dbPath))
150
- return { sources: result, degraded: null };
151
- let db = null;
152
148
  try {
153
- db = new Database(dbPath, { readonly: true });
154
- const placeholders = distinct.map(() => '?').join(',');
155
- const rows = db.prepare(`SELECT canonical_pain_id AS painId, source, text, created_at AS createdAt
156
- FROM pain_events WHERE canonical_pain_id IN (${placeholders})`).all(...distinct);
157
- // Multiple events may share a canonical id; keep the newest (same policy
158
- // as the pain list ordering — newest first).
159
- for (const row of rows) {
160
- if (!record(row))
161
- continue;
162
- const painId = typeof row.painId === 'string' ? row.painId : '';
163
- if (painId === '')
164
- continue;
165
- const existing = result.get(painId);
166
- const createdAt = typeof row.createdAt === 'string' ? row.createdAt : null;
167
- if (existing && existing.createdAt && createdAt && existing.createdAt >= createdAt)
168
- continue;
169
- result.set(painId, {
170
- painId,
171
- text: typeof row.text === 'string' && row.text.trim() !== '' ? row.text : null,
172
- source: typeof row.source === 'string' ? row.source : 'unknown',
173
- createdAt,
174
- });
149
+ // A missing/unreadable trajectory.db is "cannot read", never "nothing
150
+ // recorded" — the degraded flag below is the only honest answer.
151
+ const db = openTrajectoryDbReadonly(this.workspaceDir);
152
+ try {
153
+ const placeholders = distinct.map(() => '?').join(',');
154
+ const rows = db.prepare(`SELECT canonical_pain_id AS painId, source, text, created_at AS createdAt
155
+ FROM pain_events WHERE canonical_pain_id IN (${placeholders})`).all(...distinct);
156
+ // Multiple events may share a canonical id; keep the newest (same policy
157
+ // as the pain list ordering — newest first).
158
+ for (const row of rows) {
159
+ if (!record(row))
160
+ continue;
161
+ const painId = typeof row.painId === 'string' ? row.painId : '';
162
+ if (painId === '')
163
+ continue;
164
+ const existing = result.get(painId);
165
+ const createdAt = typeof row.createdAt === 'string' ? row.createdAt : null;
166
+ if (existing && existing.createdAt && createdAt && existing.createdAt >= createdAt)
167
+ continue;
168
+ result.set(painId, {
169
+ painId,
170
+ text: typeof row.text === 'string' && row.text.trim() !== '' ? row.text : null,
171
+ source: typeof row.source === 'string' ? row.source : 'unknown',
172
+ createdAt,
173
+ });
174
+ }
175
+ }
176
+ finally {
177
+ db.close();
175
178
  }
176
179
  }
177
180
  catch {
@@ -179,9 +182,6 @@ export class RuleCandidateBindingConsoleModel {
179
182
  // turns missing lookups into 记录暂不可读 (rc-9 observable degradation).
180
183
  return { sources: new Map(), degraded: 'trajectory_unreadable' };
181
184
  }
182
- finally {
183
- db?.close();
184
- }
185
185
  return { sources: result, degraded: null };
186
186
  }
187
187
  /** Identity stays with the ledger adapter (the identity authority); the
@@ -379,6 +379,58 @@ function optionalString(obj, key) {
379
379
  const value = obj[key];
380
380
  return typeof value === 'string' ? value : null;
381
381
  }
382
+ /** `detail` may itself be a JSON document; expose its useful fields without inventing them. */
383
+ function detailFields(detail) {
384
+ if (detail === null)
385
+ return { missingFields: [], nextAction: null };
386
+ try {
387
+ const parsed = JSON.parse(detail);
388
+ if (!isRecord(parsed))
389
+ return { missingFields: [], nextAction: null };
390
+ return {
391
+ missingFields: toStringArray(parsed.missingFields),
392
+ nextAction: optionalString(parsed, 'nextAction'),
393
+ };
394
+ }
395
+ catch {
396
+ return { missingFields: [], nextAction: null };
397
+ }
398
+ }
399
+ function projectHumanReview(value) {
400
+ const record = asRecord(value);
401
+ if (!record)
402
+ return null;
403
+ const detail = optionalString(record, 'detail');
404
+ const { missingFields, nextAction } = detailFields(detail);
405
+ return {
406
+ reasonCode: optionalString(record, 'reasonCode'),
407
+ detail,
408
+ missingFields,
409
+ nextAction,
410
+ sourceRunId: optionalString(record, 'sourceRunId'),
411
+ sourceArtifactId: optionalString(record, 'sourceArtifactId'),
412
+ createdAt: optionalString(record, 'createdAt'),
413
+ };
414
+ }
415
+ function projectIdentityPreflight(value) {
416
+ const record = asRecord(value);
417
+ if (!record)
418
+ return null;
419
+ const generatedRaw = Object.hasOwn(record, 'generated') ? record.generated : null;
420
+ return {
421
+ status: optionalString(record, 'status'),
422
+ reasonCode: optionalString(record, 'reasonCode') ?? optionalString(record, 'reason'),
423
+ detail: optionalString(record, 'detail') ?? optionalString(record, 'message'),
424
+ nextAction: optionalString(record, 'nextAction'),
425
+ stage: optionalString(record, 'stage'),
426
+ generated: typeof generatedRaw === 'boolean' ? generatedRaw : null,
427
+ };
428
+ }
429
+ function evidenceLine(label, value) {
430
+ if (value === null || value.trim() === '')
431
+ return [];
432
+ return [`${label}: ${value.length > 500 ? `${value.slice(0, 500)}…` : value}`];
433
+ }
382
434
  function projectionFromFailure(failed) {
383
435
  const { attemptCount } = failed;
384
436
  const { maxAttempts } = failed;
@@ -421,17 +473,48 @@ function projectFailureDiagnostics(diagnosticJson) {
421
473
  : outputFailure
422
474
  ? toStringArray(outputFailure.validatorErrors)
423
475
  : [];
476
+ const piMetadata = Object.hasOwn(envelope, 'pi_metadata') ? asRecord(envelope.pi_metadata) : null;
477
+ const humanReview = piMetadata ? projectHumanReview(piMetadata.humanReviewContext) : null;
478
+ const identityPreflight = Object.hasOwn(envelope, 'identityPreflight')
479
+ ? projectIdentityPreflight(envelope.identityPreflight)
480
+ : null;
481
+ const evidenceSummary = [
482
+ ...evidenceLine('humanReview.reasonCode', humanReview?.reasonCode ?? null),
483
+ ...evidenceLine('humanReview.detail', humanReview?.detail ?? null),
484
+ ...evidenceLine('humanReview.missingFields', humanReview && humanReview.missingFields.length > 0 ? humanReview.missingFields.join(', ') : null),
485
+ ...evidenceLine('identityPreflight', identityPreflight
486
+ ? JSON.stringify({
487
+ status: identityPreflight.status,
488
+ reasonCode: identityPreflight.reasonCode,
489
+ detail: identityPreflight.detail,
490
+ stage: identityPreflight.stage,
491
+ generated: identityPreflight.generated,
492
+ })
493
+ : null),
494
+ ...evidenceLine('terminal_failure', terminal ? JSON.stringify(terminal) : null),
495
+ ...evidenceLine('validator_error', effectiveValidatorErrors[effectiveValidatorErrors.length - 1] ?? null),
496
+ ...evidenceLine('failed_stage', failedStage ? JSON.stringify({
497
+ stageTaskId: failedStage.stageTaskId,
498
+ stageTaskKind: failedStage.stageTaskKind,
499
+ errorCategory: failedStage.errorCategory,
500
+ }) : null),
501
+ ].slice(0, 8);
424
502
  const projection = {
425
503
  terminalReason: terminal ? optionalString(terminal, 'reason') : null,
426
504
  terminalErrorCategory: terminal ? optionalString(terminal, 'errorCategory') : null,
427
505
  validatorErrors: effectiveValidatorErrors,
428
506
  failedStage: failedStage ? projectionFromFailure(failedStage) : null,
507
+ humanReview,
508
+ identityPreflight,
509
+ evidenceSummary,
429
510
  };
430
511
  // Nothing to say: behave as if the server never sent the block.
431
512
  if (projection.terminalReason === null
432
513
  && projection.terminalErrorCategory === null
433
514
  && projection.validatorErrors.length === 0
434
- && projection.failedStage === null) {
515
+ && projection.failedStage === null
516
+ && projection.humanReview === null
517
+ && projection.identityPreflight === null) {
435
518
  return null;
436
519
  }
437
520
  return projection;
@@ -15,37 +15,52 @@ function appendGovernedUpdateHistory(workspaceDir, entry) {
15
15
  console.error(`[update] ReleaseManager attempt completed WITHOUT an update-history record: ${errorMessage(error)}`);
16
16
  }
17
17
  }
18
+ // PRI-1101: the request budget is empirical (server/update-timeout.ts), so a
19
+ // stuck refresh can spend the full 120s before the wrapper answers. Emit one
20
+ // signal while the check is still working, so the wait is explainable instead
21
+ // of a silent hang. Diagnostic only — it never changes the response.
22
+ const CHECK_SLOW_SIGNAL_MS = 30_000;
18
23
  async function checkUpdate(authority, res) {
19
- const check = await authority.manager.check(authority.installStatus?.channel ?? 'stable');
20
- // PRI-833: derive the active identity from the SAME installStatus snapshot
21
- // the readiness gate used — no second inspect, no second identity read.
22
- const { installStatus } = authority;
23
- const activeIdentity = installStatus !== null
24
- && typeof installStatus.productVersion === 'string' && installStatus.productVersion.length > 0
25
- && typeof installStatus.releaseId === 'string' && installStatus.releaseId.length > 0
26
- && typeof installStatus.generation === 'number' && Number.isSafeInteger(installStatus.generation)
27
- ? { productVersion: installStatus.productVersion, releaseId: installStatus.releaseId, generation: installStatus.generation }
28
- : undefined;
29
- // The product version (signed active release) and the plugin package version
30
- // are independent version planes (RELEASE_PROCESS.md, "The three version
31
- // planes"): the installer ships the plugin payload while the product version
32
- // advances on its own cadence. Comparing them is a false alarm on every
33
- // healthy installation, so this check reports only the active-release identity.
34
- // PRI-848 (SPEC §12.1): one explicit state per check. A policy refusal is
35
- // `update_blocked` — the candidate EXISTS but a specific problem must be
36
- // resolved — never "up to date".
37
- const { decision } = check;
38
- const state = !decision.allowed
39
- ? 'update_blocked'
40
- : decision.direction === 'reinstall' ? 'up_to_date' : 'update_available';
41
- sendSuccess(res, {
42
- state,
43
- hasUpdate: decision.allowed && decision.direction !== 'reinstall',
44
- currentVersion: installStatus?.productVersion ?? 'unknown',
45
- latestVersion: check.candidate?.productVersion ?? '',
46
- ...(activeIdentity !== undefined ? { versionSource: 'active-release' } : {}),
47
- ...(!decision.allowed ? { reason: decision.reason, message: decision.message } : {}),
48
- });
24
+ const slowSignal = setTimeout(() => {
25
+ console.warn(`[update] /check still running after ${CHECK_SLOW_SIGNAL_MS}ms — signed metadata refresh in progress`);
26
+ }, CHECK_SLOW_SIGNAL_MS);
27
+ // Do not keep the process alive for a diagnostic timer.
28
+ slowSignal.unref();
29
+ try {
30
+ const check = await authority.manager.check(authority.installStatus?.channel ?? 'stable');
31
+ // PRI-833: derive the active identity from the SAME installStatus snapshot
32
+ // the readiness gate used — no second inspect, no second identity read.
33
+ const { installStatus } = authority;
34
+ const activeIdentity = installStatus !== null
35
+ && typeof installStatus.productVersion === 'string' && installStatus.productVersion.length > 0
36
+ && typeof installStatus.releaseId === 'string' && installStatus.releaseId.length > 0
37
+ && typeof installStatus.generation === 'number' && Number.isSafeInteger(installStatus.generation)
38
+ ? { productVersion: installStatus.productVersion, releaseId: installStatus.releaseId, generation: installStatus.generation }
39
+ : undefined;
40
+ // The product version (signed active release) and the plugin package version
41
+ // are independent version planes (RELEASE_PROCESS.md, "The three version
42
+ // planes"): the installer ships the plugin payload while the product version
43
+ // advances on its own cadence. Comparing them is a false alarm on every
44
+ // healthy installation, so this check reports only the active-release identity.
45
+ // PRI-848 (SPEC §12.1): one explicit state per check. A policy refusal is
46
+ // `update_blocked` — the candidate EXISTS but a specific problem must be
47
+ // resolved — never "up to date".
48
+ const { decision } = check;
49
+ const state = !decision.allowed
50
+ ? 'update_blocked'
51
+ : decision.direction === 'reinstall' ? 'up_to_date' : 'update_available';
52
+ sendSuccess(res, {
53
+ state,
54
+ hasUpdate: decision.allowed && decision.direction !== 'reinstall',
55
+ currentVersion: installStatus?.productVersion ?? 'unknown',
56
+ latestVersion: check.candidate?.productVersion ?? '',
57
+ ...(activeIdentity !== undefined ? { versionSource: 'active-release' } : {}),
58
+ ...(!decision.allowed ? { reason: decision.reason, message: decision.message } : {}),
59
+ });
60
+ }
61
+ finally {
62
+ clearTimeout(slowSignal);
63
+ }
49
64
  }
50
65
  /**
51
66
  * PRI-850 (SPEC v0.3 §6.1, ADR-0024 §6): apply is carried by the deployed
@@ -1,5 +1,19 @@
1
1
  const UPDATE_APPLY_FULL_DEFAULT_TIMEOUT_MS = 180000;
2
- const UPDATE_CHECK_DEFAULT_TIMEOUT_MS = 30000;
2
+ // PRI-1101: this is an EMPIRICAL budget, not a proven bound on the inner work.
3
+ // The check refreshes signed metadata through tuf-js, whose defaults are
4
+ // `fetchTimeout: 100_000` PER ATTEMPT and `fetchRetry: 2`. @gar/promise-retry
5
+ // reads that as "two retries after the first attempt", so ONE metadata request
6
+ // can take 3 x 100s. `Updater.refresh()` then issues at least four sequential
7
+ // requests (root, timestamp, snapshot, targets) before the channel document and
8
+ // the release metadata, so the derivable worst case is on the order of 1200s.
9
+ //
10
+ // 120s covers the observed slow examples (~12.5s on a CN network; the 30s
11
+ // budget this replaces was outlived at least once) with a wide margin, while
12
+ // staying far below that worst case. A check exceeding 120s is therefore STILL
13
+ // reported as a timeout even when it later succeeds: that is an accepted
14
+ // residual, not coverage. The 30s "still running" log in routes/update.ts makes
15
+ // the wait observable.
16
+ const UPDATE_CHECK_DEFAULT_TIMEOUT_MS = 120000;
3
17
  // Node clamps delays above this limit to 1ms instead of honoring the timeout.
4
18
  const MAX_TIMEOUT_MS = 2_147_483_647;
5
19
  function resolveTimeoutMs(envKey, defaultMs) {
@@ -3,7 +3,10 @@
3
3
  * trajectory.db pain_events, the principle ledger, the internalization chain).
4
4
  * No new persisted state; the Ledger remains the only binding authority. */
5
5
  /** Which owner feedback produced the candidate. Text is null when the pain
6
- * record is gone — the UI must show 未记录, never fabricate a quote. */
6
+ * record is gone — the UI must show 未记录, never fabricate a quote.
7
+ * `source: 'unreadable'` means the trajectory store could not be read at all
8
+ * (missing or corrupt), so the UI must show 记录暂不可读 instead of claiming
9
+ * the pain was never recorded. */
7
10
  export interface RuleBindingPainSourceView {
8
11
  painId: string;
9
12
  text: string | null;