create-principles-disciple 1.153.2 → 1.153.4

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 (105) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/worker/workspace-worker.js +5 -1
  3. package/codex-adapter/package.json +1 -1
  4. package/console/dist/server/index.js +8 -1
  5. package/console/dist/server/models/ApprovalsGroupedConsoleModel.d.ts +9 -1
  6. package/console/dist/server/models/ApprovalsGroupedConsoleModel.js +19 -1
  7. package/console/dist/server/models/IntentPageModel.d.ts +37 -1
  8. package/console/dist/server/models/IntentPageModel.js +53 -1
  9. package/console/dist/server/routes/update-history.d.ts +32 -0
  10. package/console/dist/server/routes/update-history.js +215 -1
  11. package/console/dist/web/assets/app.css +106 -0
  12. package/console/dist/web/assets/app.js +118 -32
  13. package/console/dist/web/assets/intent-reflection.webp +3 -0
  14. package/core/dist/runtime/config/index.d.ts +1 -1
  15. package/core/dist/runtime/config/index.d.ts.map +1 -1
  16. package/core/dist/runtime/config/index.js +1 -1
  17. package/core/dist/runtime/config/index.js.map +1 -1
  18. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  19. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +4 -1
  20. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  21. package/core/dist/runtime/index.d.ts +3 -3
  22. package/core/dist/runtime/index.d.ts.map +1 -1
  23. package/core/dist/runtime/index.js +2 -2
  24. package/core/dist/runtime/index.js.map +1 -1
  25. package/core/dist/runtime/intent/intent-browser.d.ts +2 -2
  26. package/core/dist/runtime/intent/intent-browser.d.ts.map +1 -1
  27. package/core/dist/runtime/intent/intent-browser.js +5 -1
  28. package/core/dist/runtime/intent/intent-browser.js.map +1 -1
  29. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  30. package/core/dist/runtime/pain-signal-bridge.js +58 -11
  31. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  32. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  33. package/core/dist/runtime/pain-signal-runtime-factory.js +11 -2
  34. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  35. package/core/package.json +1 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +12 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/installer.d.ts +24 -0
  40. package/dist/installer.d.ts.map +1 -1
  41. package/dist/installer.js +59 -5
  42. package/dist/installer.js.map +1 -1
  43. package/dist/installers/codex-host-installer.d.ts +7 -0
  44. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  45. package/dist/installers/codex-host-installer.js +62 -14
  46. package/dist/installers/codex-host-installer.js.map +1 -1
  47. package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
  48. package/dist/installers/workbuddy-host-installer.js +44 -8
  49. package/dist/installers/workbuddy-host-installer.js.map +1 -1
  50. package/dist/prompts.d.ts +6 -0
  51. package/dist/prompts.d.ts.map +1 -1
  52. package/dist/prompts.js +17 -7
  53. package/dist/prompts.js.map +1 -1
  54. package/dist/utils/env.d.ts +19 -2
  55. package/dist/utils/env.d.ts.map +1 -1
  56. package/dist/utils/env.js +55 -14
  57. package/dist/utils/env.js.map +1 -1
  58. package/dist/utils/host-workspace-ownership.d.ts +25 -0
  59. package/dist/utils/host-workspace-ownership.d.ts.map +1 -0
  60. package/dist/utils/host-workspace-ownership.js +69 -0
  61. package/dist/utils/host-workspace-ownership.js.map +1 -0
  62. package/host-runtime/dist/diagnostician-auto-run.js +6 -0
  63. package/host-runtime/dist/governance-signal-admission.js +7 -0
  64. package/host-runtime/dist/index.d.ts +1 -0
  65. package/host-runtime/dist/index.js +4 -0
  66. package/host-runtime/dist/intent-doc-reader.d.ts +70 -0
  67. package/host-runtime/dist/intent-doc-reader.js +292 -0
  68. package/host-runtime/package.json +1 -1
  69. package/install-layout/dist/index.d.ts +24 -1
  70. package/install-layout/dist/index.js +58 -1
  71. package/install-layout/dist/mcp-binding-contract.d.ts +27 -0
  72. package/install-layout/dist/mcp-binding-contract.js +62 -0
  73. package/install-layout/package.json +1 -1
  74. package/package.json +3 -3
  75. package/pd-cli/dist/commands/diagnose.d.ts.map +1 -1
  76. package/pd-cli/dist/commands/diagnose.js +7 -1
  77. package/pd-cli/dist/commands/diagnose.js.map +1 -1
  78. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  79. package/pd-cli/dist/commands/health-mcp.js +20 -2
  80. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  81. package/pd-cli/dist/commands/mcp-probe.d.ts +11 -0
  82. package/pd-cli/dist/commands/mcp-probe.d.ts.map +1 -1
  83. package/pd-cli/dist/commands/mcp-probe.js +24 -2
  84. package/pd-cli/dist/commands/mcp-probe.js.map +1 -1
  85. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  86. package/pd-cli/dist/commands/pain-record.js +6 -0
  87. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  88. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  89. package/pd-cli/dist/commands/pain-retry.js +8 -1
  90. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  91. package/pd-cli/package.json +1 -1
  92. package/plugin/dist/bundle.js +473 -473
  93. package/plugin/dist/openclaw.plugin.json +1 -1
  94. package/plugin/mcp/launcher.cjs +132 -5
  95. package/plugin/openclaw.plugin.json +1 -1
  96. package/plugin/package.json +1 -1
  97. package/release-manager/dist/installer.js +59 -5
  98. package/release-manager/dist/installers/codex-host-installer.js +62 -14
  99. package/release-manager/dist/installers/workbuddy-host-installer.js +44 -8
  100. package/release-manager/dist/utils/env.js +55 -14
  101. package/release-manager/dist/utils/host-workspace-ownership.js +69 -0
  102. package/release-manager/package.json +1 -1
  103. package/workbuddy-adapter/dist/worker/workspace-worker.js +5 -1
  104. package/workbuddy-adapter/package.json +1 -1
  105. package/workbuddy-adapter/plugin/mcp/launcher.cjs +132 -5
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "productVersion": "2.8.8",
4
- "sourceCommit": "7b5fd027304c61350b9bd443551ab40a017e6139"
4
+ "sourceCommit": "adbcfd33f4765fffee9de71055826edb8ed128a6"
5
5
  }
@@ -28,7 +28,7 @@
28
28
  import fs from 'node:fs';
29
29
  import path from 'node:path';
30
30
  import { computeFeatureFlagsFromConfig, createRuntimeStateHandle, createPainSignalBridge, isRetryWaitBackoffElapsed, pickDiagnosticianCandidate, PrincipleTreeLedgerAdapter, resolveDiagnosticianCapability, } from '@principles/core/runtime';
31
- import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
31
+ import { createWorkspaceBehaviorEvidencePort, createCodexArtificerTrustedFactsPort, loadPdConfigForPlugin, loadFeatureFlagFromConfig, reconcileGovernanceContinuation, runInternalizationConsumerCycle, runStage2CorrectionCycle, createSignalClassifierForWorkspace, createHostIntentDocReader, saveHostToolDeclaration, HOST_TOOL_DECLARATION_VERSION, } from '@principles/host-runtime';
32
32
  import { catchUpCodexIngestion } from '../ingestion/catch-up.js';
33
33
  import { CODEX_TOOL_SEMANTIC_MAPPINGS, CODEX_TOOL_SEMANTICS } from '../tool-semantics.js';
34
34
  const WORKER_OWNER = 'companion-worker';
@@ -230,6 +230,10 @@ export async function runCodexWorkspaceWorkerCycle(options) {
230
230
  owner: WORKER_OWNER,
231
231
  effectiveConfig: config.effective,
232
232
  getEnvVar: (name) => process.env[name],
233
+ // PRI-1233 / SPEC §9.2: this worker is where Stage A actually runs
234
+ // for governance-admitted Codex pains — the neutral host reader
235
+ // must ride along (flag-off = zero filesystem access inside it).
236
+ intentDocReader: createHostIntentDocReader({ workspaceDir, effectiveConfig: config.effective }),
233
237
  });
234
238
  const executed = await bridge.executePendingDiagnosis({ taskId: candidate.taskId });
235
239
  // PRI-917 v0.3.3 review fix (P2-2): forward the parked-candidate
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@principles/codex-adapter",
3
- "version": "0.12.0",
3
+ "version": "0.12.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",
@@ -38,7 +38,7 @@ import { handleIntentDecisionsRoute, disposeIntentDecisionModels } from './route
38
38
  import { handleOnboardingRoute, disposeOnboardingModels } from './routes/onboarding.js';
39
39
  import { createWorkspacesRoutes } from './routes/workspaces.js';
40
40
  import { handleUpdateRoute } from './routes/update.js';
41
- import { handleUpdateHistoryRoute, reconcileUpdateHistoryFromJournals } from './routes/update-history.js';
41
+ import { handleUpdateHistoryRoute, handleUpdateHistoryPruneRoute, reconcileUpdateHistoryFromJournals } from './routes/update-history.js';
42
42
  import { handleUpdateTransactionRoute } from './routes/update-transaction.js';
43
43
  import { handleConfigRoute } from './routes/config.js';
44
44
  import { sendJson, sendNotFound, sendError } from './utils/response.js';
@@ -474,6 +474,13 @@ export function handleRequest(services) {
474
474
  asyncHandler(() => handleWorkspacesRoute(req, res, subPath))(req, res);
475
475
  return;
476
476
  }
477
+ // POST /api/update/history/prune — Owner history cleanup (keep newest N).
478
+ // Exact match BEFORE the /api/update/history branch and the update
479
+ // catch-all; keep arrives as ?keep=<int>, default 5.
480
+ if (routePath === '/api/update/history/prune') {
481
+ asyncHandler(() => handleUpdateHistoryPruneRoute(req, res, services.workspaceDir))(req, res);
482
+ return;
483
+ }
477
484
  // GET /api/update/history (MUST be before update catch-all)
478
485
  if (routePath === '/api/update/history') {
479
486
  asyncHandler(() => handleUpdateHistoryRoute(req, res, services.workspaceDir, ''))(req, res);
@@ -8,7 +8,15 @@ export type ApprovalApproveBlockCode = 'identity_unresolved' | 'artifact_unavail
8
8
  * `SqliteApprovalStore.approve()` runs, so the card can never promise an
9
9
  * approval the write path refuses.
10
10
  */
11
- | 'strategic_conflict_unconfirmed';
11
+ | 'strategic_conflict_unconfirmed'
12
+ /**
13
+ * PRI-1238: the gate's specific refusal codes for boundary conflicts
14
+ * (non-negotiables / stop-escalation → `owner_boundary_conflict`) and
15
+ * core-principle conflicts (`core_principle_conflict`). Surfaced from the
16
+ * strategic view's own blockCode so the Owner copy names the real fence;
17
+ * neither can be lifted by a confirm_drift decision.
18
+ */
19
+ | 'owner_boundary_conflict' | 'core_principle_conflict';
12
20
  export interface ApprovalApproveBlock {
13
21
  code: ApprovalApproveBlockCode;
14
22
  /** Machine-readable server reason (technical details; not the card copy). */
@@ -410,9 +410,27 @@ export class ApprovalsGroupedConsoleModel {
410
410
  // artifact; a sibling pending record must never inherit it.
411
411
  const recordStrategic = artifactStrategicMap.get(approval.artifactId);
412
412
  const strategicView = approval.status === 'pending' ? recordStrategic : undefined;
413
+ // PRI-1238 (CodeRabbit PR #2684 review): gate.code is ALWAYS the
414
+ // generic 'strategic_conflict_unconfirmed' — the gate names the
415
+ // specific class only inside its REASON text. The specific Owner copy
416
+ // is therefore projected here from the view's OWN conflicts list,
417
+ // mirroring the gate's `isExemptableConflict` rule
418
+ // (strategic-conflict-gate.ts:72-75). This is presentation ONLY: the
419
+ // gate owns whether the approval is blocked and what clears it; this
420
+ // projection only selects the i18n copy, and the C6 browser suite
421
+ // pins it against the real server fence.
422
+ const specificCode = (() => {
423
+ const confirmed = (strategicView?.conflicts ?? []).filter((c) => c.status === 'confirmed');
424
+ if (confirmed.some((c) => c.against === 'core_principle'))
425
+ return 'core_principle_conflict';
426
+ if (confirmed.some((c) => c.against === 'owner_intent'
427
+ && (c.ref === 'non_negotiables' || c.ref === 'stop_escalation')))
428
+ return 'owner_boundary_conflict';
429
+ return undefined;
430
+ })();
413
431
  const strategicBlock = strategicView !== undefined && !strategicView.resolved
414
432
  ? {
415
- code: 'strategic_conflict_unconfirmed',
433
+ code: specificCode ?? 'strategic_conflict_unconfirmed',
416
434
  reason: strategicView.reason ?? 'no_effective_resolution',
417
435
  nextAction: strategicView.nextAction ?? 'resolve the confirmed strategic conflict for this contract, then approve again',
418
436
  }
@@ -1,8 +1,36 @@
1
- import { type IntentDocWarning, type IntentDocVersion, type IntentLang } from '@principles/core/runtime';
1
+ import { type IntentDocWarning, type IntentDocVersion, type IntentLang, type IntentSectionState } from '@principles/core/runtime';
2
+ /**
3
+ * SPEC-PD-INTENT-UNIFICATION-001 §12.2 — content readiness of the INTENT doc.
4
+ *
5
+ * Derived EXCLUSIVELY from Core's shared classification
6
+ * (analyzeIntentDocSections → deriveIntentDocState); the console never
7
+ * re-implements template detection.
8
+ */
9
+ export type IntentContentReadiness = 'template_only' | 'incomplete' | 'configured';
10
+ /** Per-section classification (SPEC §11.4) — Core's states, projected as-is. */
11
+ export type IntentSectionStateDto = Record<string, IntentSectionState>;
2
12
  export interface IntentPageResult {
3
13
  ok: boolean;
4
14
  found: boolean;
5
15
  flagEnabled: boolean;
16
+ /**
17
+ * Content readiness of the document. For every NOT-readable summary
18
+ * (flag off / not found / oversized / read error) this is `template_only`
19
+ * with `usableSectionCount: 0` — the honest "nothing usable" answer. The
20
+ * Disabled / Missing / Error UI states are derived from flagEnabled /
21
+ * found / ok / reason, NOT from this enum (SPEC §12.2).
22
+ */
23
+ contentReadiness: IntentContentReadiness;
24
+ /** How many of the 5 sections carry Owner-authored content (0–5). */
25
+ usableSectionCount: number;
26
+ /** Always 5 — the fixed section contract of INTENT.md. */
27
+ totalSectionCount: number;
28
+ /**
29
+ * Per-section states (all 5 keys, Core's authored|placeholder|missing),
30
+ * present when ok=true. Missing/placeholder sections are NEVER presented
31
+ * as configured content.
32
+ */
33
+ sectionStates?: IntentSectionStateDto;
6
34
  warnings: IntentDocWarning[];
7
35
  path?: string;
8
36
  contentHash?: string;
@@ -25,6 +53,14 @@ export interface IntentSaveResult {
25
53
  contentHash?: string;
26
54
  lastEditedAt?: string;
27
55
  warnings?: IntentDocWarning[];
56
+ /**
57
+ * SPEC §12.1: the save response carries the SAME content-status projection
58
+ * as the summary, computed from the just-saved content (PRI-1234).
59
+ */
60
+ contentReadiness?: IntentContentReadiness;
61
+ usableSectionCount?: number;
62
+ totalSectionCount?: number;
63
+ sectionStates?: IntentSectionStateDto;
28
64
  reason?: string;
29
65
  nextAction?: string;
30
66
  }
@@ -1,9 +1,17 @@
1
1
  import * as fs from 'node:fs';
2
2
  import * as path from 'node:path';
3
- import { INTENT_MAX_BYTES, getIntentFilename, createIntentTemplate, parseIntentDocSections, computeIntentContentHash, validateIntentDocSections, SqliteConnection, SqliteIntentDocVersionStore, } from '@principles/core/runtime';
3
+ import { INTENT_MAX_BYTES, getIntentFilename, createIntentTemplate, parseIntentDocSections, analyzeIntentDocSections, deriveIntentDocState, computeIntentContentHash, validateIntentDocSections, SqliteConnection, SqliteIntentDocVersionStore, } from '@principles/core/runtime';
4
4
  import { resolveStateDbPath } from '@principles/core/runtime/storage-paths';
5
5
  import { errorMessage } from '../utils/response.js';
6
6
  const INTENT_DIR = '.principles';
7
+ /** The five fixed INTENT.md section keys, in document order. */
8
+ const INTENT_SECTION_KEYS = [
9
+ 'why',
10
+ 'desiredOutcome',
11
+ 'nonNegotiables',
12
+ 'stopEscalation',
13
+ 'currentStrategicFocus',
14
+ ];
7
15
  function stateDbExists(workspaceDir) {
8
16
  return fs.existsSync(resolveStateDbPath(workspaceDir));
9
17
  }
@@ -90,6 +98,9 @@ export class IntentPageModel {
90
98
  ok: false,
91
99
  found: false,
92
100
  flagEnabled: false,
101
+ contentReadiness: 'template_only',
102
+ usableSectionCount: 0,
103
+ totalSectionCount: INTENT_SECTION_KEYS.length,
93
104
  warnings: [],
94
105
  reason: 'flag_disabled',
95
106
  nextAction: `Enable the intent_engineering feature flag in .pd/config.yaml to read ${getIntentFilename(lang)}.`,
@@ -110,6 +121,9 @@ export class IntentPageModel {
110
121
  ok: false,
111
122
  found: false,
112
123
  flagEnabled: true,
124
+ contentReadiness: 'template_only',
125
+ usableSectionCount: 0,
126
+ totalSectionCount: INTENT_SECTION_KEYS.length,
113
127
  warnings: [],
114
128
  reason: 'not_found',
115
129
  nextAction: `Create .principles/${getIntentFilename(lang)} using "pd intent init".`,
@@ -120,6 +134,9 @@ export class IntentPageModel {
120
134
  ok: false,
121
135
  found: true,
122
136
  flagEnabled: true,
137
+ contentReadiness: 'template_only',
138
+ usableSectionCount: 0,
139
+ totalSectionCount: INTENT_SECTION_KEYS.length,
123
140
  warnings: [],
124
141
  reason: 'oversized',
125
142
  nextAction: `${getIntentFilename(lang)} exceeds ${INTENT_MAX_BYTES} bytes (${read.oversized} bytes). Reduce content.`,
@@ -145,10 +162,27 @@ export class IntentPageModel {
145
162
  if (sections.currentStrategicFocus !== undefined) {
146
163
  sectionRecord.currentStrategicFocus = sections.currentStrategicFocus;
147
164
  }
165
+ // PRI-1234 / SPEC §12.2 + §7: content readiness comes from Core's
166
+ // shared deterministic classification — the console NEVER re-implements
167
+ // template detection. A template question is never Owner intent.
168
+ const analyses = analyzeIntentDocSections(sections, lang);
169
+ const docState = deriveIntentDocState(analyses);
170
+ const contentReadiness = docState === 'configured' ? 'configured'
171
+ : docState === 'partially_configured' ? 'incomplete'
172
+ : 'template_only';
173
+ const usableSectionCount = analyses.filter((a) => a.state === 'authored').length;
174
+ const sectionStates = {};
175
+ for (const analysis of analyses) {
176
+ sectionStates[analysis.key] = analysis.state;
177
+ }
148
178
  return {
149
179
  ok: true,
150
180
  found: true,
151
181
  flagEnabled: true,
182
+ contentReadiness,
183
+ usableSectionCount,
184
+ totalSectionCount: INTENT_SECTION_KEYS.length,
185
+ sectionStates,
152
186
  warnings,
153
187
  path: filePath,
154
188
  contentHash,
@@ -162,6 +196,9 @@ export class IntentPageModel {
162
196
  ok: false,
163
197
  found: false,
164
198
  flagEnabled: true,
199
+ contentReadiness: 'template_only',
200
+ usableSectionCount: 0,
201
+ totalSectionCount: INTENT_SECTION_KEYS.length,
165
202
  warnings: [],
166
203
  reason: 'read_error',
167
204
  nextAction: `Check filesystem permissions for .principles/${getIntentFilename(lang)}.`,
@@ -310,6 +347,17 @@ export class IntentPageModel {
310
347
  const warnings = validateIntentDocSections(sections);
311
348
  const contentHash = computeIntentContentHash(content);
312
349
  const stat = fs.statSync(filePath);
350
+ // PRI-1234 / SPEC §12.1: project the SAME readiness fields as the
351
+ // summary onto the save response (single Core classification source).
352
+ const analyses = analyzeIntentDocSections(sections, lang);
353
+ const docState = deriveIntentDocState(analyses);
354
+ const contentReadiness = docState === 'configured' ? 'configured'
355
+ : docState === 'partially_configured' ? 'incomplete'
356
+ : 'template_only';
357
+ const sectionStates = {};
358
+ for (const analysis of analyses) {
359
+ sectionStates[analysis.key] = analysis.state;
360
+ }
313
361
  recordVersion({ workspaceDir: this.workspaceDir, lang, content, reason: 'save' });
314
362
  return {
315
363
  ok: true,
@@ -318,6 +366,10 @@ export class IntentPageModel {
318
366
  contentHash,
319
367
  lastEditedAt: stat.mtime.toISOString(),
320
368
  warnings,
369
+ contentReadiness,
370
+ usableSectionCount: analyses.filter((a) => a.state === 'authored').length,
371
+ totalSectionCount: INTENT_SECTION_KEYS.length,
372
+ sectionStates,
321
373
  };
322
374
  }
323
375
  catch (err) {
@@ -49,4 +49,36 @@ export declare function appendUpdateHistory(workspaceDir: string, entry: Omit<Up
49
49
  */
50
50
  export declare function reconcileUpdateHistoryFromJournals(workspaceDir: string, pdHome: string): void;
51
51
  export declare function handleUpdateHistoryRoute(req: IncomingMessage, res: ServerResponse, workspaceDir: string, _subPath: string): Promise<void>;
52
+ interface UpdateHistoryPruneResult {
53
+ /** Entries actually removed by this call (0 when the file was already within budget). */
54
+ removed: number;
55
+ /** Entries left in the history file after the prune. */
56
+ remaining: number;
57
+ /** Rolling pre-rewrite backup; absent when there was no file to back up. */
58
+ backupPath?: string;
59
+ /** transactionIds recorded into the prune ledger by this call. */
60
+ prunedTransactionIds: string[];
61
+ }
62
+ /**
63
+ * Owner-facing cleanup of the history read model: keep the newest `keep`
64
+ * entries by fact time, remove the rest. The removed rows' transactionIds are
65
+ * recorded in the prune ledger so `reconcileUpdateHistoryFromJournals` does
66
+ * not resurrect them from the durable journals on the next startup. The
67
+ * journals themselves (~/.pd/transactions, installer-owned) are never touched.
68
+ *
69
+ * Window closure: the 50-entry cap silently evicts old rows while their
70
+ * journals survive, so a bare "removed rows" ledger would let restart re-derive
71
+ * rows OLDER than the ones the Owner deleted — the cleaned list would grow
72
+ * back. "Keep the newest 5" therefore covers every fact older than the kept
73
+ * window: any ReleaseManager-domain journal whose first fact time precedes the
74
+ * oldest kept row is ledgered too (pdHome read-only; absent/unreadable home
75
+ * degrades to file-row-only cleanup with a console.warn, rc-9).
76
+ *
77
+ * Bounded mutation per docs/process/DATA_CLEANUP_GUIDELINES.md: the file is
78
+ * backed up before the first rewrite (single rolling .bak-prune, no
79
+ * accumulation), and the response carries the row accounting (removed /
80
+ * remaining) instead of a bare ok.
81
+ */
82
+ export declare function pruneUpdateHistory(workspaceDir: string, keep: number, pdHome?: string): UpdateHistoryPruneResult;
83
+ export declare function handleUpdateHistoryPruneRoute(req: IncomingMessage, res: ServerResponse, workspaceDir: string): Promise<void>;
52
84
  export {};
@@ -1,7 +1,8 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
3
  import { isReleaseManagerTransactionId } from 'create-principles-disciple/update-console';
4
- import { sendSuccess, sendMethodNotAllowed } from '../utils/response.js';
4
+ import { sendSuccess, sendError, sendMethodNotAllowed } from '../utils/response.js';
5
+ import { getPdHome } from '../utils/pd-home.js';
5
6
  /** Historical authority values remain readable; only ReleaseManager writes new attempts. */
6
7
  export const UPDATE_HISTORY_AUTHORITIES = ['release-manager', 'legacy-console-updater'];
7
8
  export const UPDATE_HISTORY_KINDS = [
@@ -112,6 +113,39 @@ export function appendUpdateHistory(workspaceDir, entry) {
112
113
  }
113
114
  fs.writeFileSync(historyPath, JSON.stringify(history, null, 2));
114
115
  }
116
+ // ── Prune ledger (Owner deletion intent) ────────────────────────────────────
117
+ /** Default retention for an Owner cleanup: the newest 5 entries stay. */
118
+ const UPDATE_HISTORY_PRUNE_KEEP_DEFAULT = 5;
119
+ const UPDATE_HISTORY_PRUNE_KEEP_MAX = 50;
120
+ const PRUNED_LEDGER_FILENAME = 'update-history-pruned.json';
121
+ function getPrunedLedgerPath(workspaceDir) {
122
+ return path.join(workspaceDir, '.pd', PRUNED_LEDGER_FILENAME);
123
+ }
124
+ /**
125
+ * Load the prune ledger — transactionIds the Owner explicitly removed and
126
+ * must NOT be re-derived from `~/.pd/transactions` journals. Corrupt or
127
+ * partially malformed ledgers degrade to their valid prefix (console.warn,
128
+ * never throw): a broken ledger must not make reconcile resurrect rows or
129
+ * break the history read path.
130
+ */
131
+ function loadPrunedTransactionIds(ledgerPath) {
132
+ // Read-first (no exists-check): same file-system-race reasoning as the
133
+ // backup copy below — ENOENT simply means no ledger exists yet.
134
+ try {
135
+ const parsed = JSON.parse(fs.readFileSync(ledgerPath, 'utf-8'));
136
+ if (!Array.isArray(parsed)) {
137
+ console.warn(`[update-history] Prune ledger is not an array (${ledgerPath}); ignoring it`);
138
+ return [];
139
+ }
140
+ return parsed.flatMap((value) => (typeof value === 'string' && value.length > 0 ? [value] : []));
141
+ }
142
+ catch (err) {
143
+ if (err.code === 'ENOENT')
144
+ return [];
145
+ console.warn(`[update-history] Failed to read prune ledger (${ledgerPath}):`, err instanceof Error ? err.message : err);
146
+ return [];
147
+ }
148
+ }
115
149
  /**
116
150
  * PRI-853 (ADR-0024 D-7, SPEC §12.1): reconcile the Owner-facing history from
117
151
  * the transaction journal. With apply running in the detached bootstrap
@@ -138,6 +172,11 @@ export function reconcileUpdateHistoryFromJournals(workspaceDir, pdHome) {
138
172
  if (!fs.existsSync(transactionsDir))
139
173
  return;
140
174
  const historyPath = getHistoryPath(workspaceDir);
175
+ // Rows the Owner pruned deliberately stay pruned: the ledger records that
176
+ // deletion intent, otherwise reconcile would re-derive those rows from the
177
+ // still-present journals on every startup — the read model must honor the
178
+ // Owner's cleanup instead of silently resurrecting it.
179
+ const prunedTransactionIds = new Set(loadPrunedTransactionIds(getPrunedLedgerPath(workspaceDir)));
141
180
  const loaded = loadHistory(historyPath);
142
181
  // A row WITHOUT a transactionId has no domain evidence either way — realtime
143
182
  // and legacy records stay untouched. A transactionId OUTSIDE the update
@@ -162,6 +201,8 @@ export function reconcileUpdateHistoryFromJournals(workspaceDir, pdHome) {
162
201
  continue;
163
202
  if (journaledIds.has(transactionId))
164
203
  continue;
204
+ if (prunedTransactionIds.has(transactionId))
205
+ continue;
165
206
  let lastState = null;
166
207
  let productVersion = null;
167
208
  let fromVersion = null;
@@ -233,3 +274,176 @@ export async function handleUpdateHistoryRoute(req, res, workspaceDir, _subPath)
233
274
  const history = loadHistory(historyPath);
234
275
  sendSuccess(res, history);
235
276
  }
277
+ // ── Owner history cleanup (POST /api/update/history/prune) ──────────────────
278
+ /**
279
+ * Fact time of a journal = the first `at` on its lines (PRI-926: the planned
280
+ * line carries the transaction's moment). Unreadable/undated journals return
281
+ * null and are never covered by a cleanup window — a fact we cannot date is a
282
+ * fact we cannot claim the Owner wanted gone.
283
+ */
284
+ function journalFactTimeMs(journalPath) {
285
+ try {
286
+ const raw = fs.readFileSync(journalPath, 'utf-8');
287
+ for (const line of raw.split('\n')) {
288
+ if (line.trim().length === 0)
289
+ continue;
290
+ const parsed = JSON.parse(line);
291
+ if (typeof parsed.at === 'string' && parsed.at.length > 0) {
292
+ const ms = Date.parse(parsed.at);
293
+ return Number.isNaN(ms) ? null : ms;
294
+ }
295
+ }
296
+ }
297
+ catch {
298
+ return null;
299
+ }
300
+ return null;
301
+ }
302
+ function collectJournalIdsOlderThan(pdHome, oldestKeptMs, alreadyPruned) {
303
+ const transactionsDir = path.join(pdHome, 'transactions');
304
+ // Read-first (no exists-check): ENOENT means no transactions dir yet —
305
+ // nothing older to cover; other read errors degrade to an empty result
306
+ // (logged) so the cleanup never fails because of the window enrichment.
307
+ try {
308
+ const covered = [];
309
+ for (const entry of fs.readdirSync(transactionsDir)) {
310
+ if (!entry.endsWith('.jsonl'))
311
+ continue;
312
+ const transactionId = entry.slice(0, -'.jsonl'.length);
313
+ if (alreadyPruned.has(transactionId))
314
+ continue;
315
+ if (!isReleaseManagerTransactionId(transactionId))
316
+ continue;
317
+ const factMs = journalFactTimeMs(path.join(transactionsDir, entry));
318
+ if (factMs !== null && factMs < oldestKeptMs)
319
+ covered.push(transactionId);
320
+ }
321
+ return covered;
322
+ }
323
+ catch (err) {
324
+ console.warn('[update-history] Cleanup window journal scan failed; ledger covers file rows only:', err instanceof Error ? err.message : err);
325
+ return [];
326
+ }
327
+ }
328
+ /**
329
+ * Owner-facing cleanup of the history read model: keep the newest `keep`
330
+ * entries by fact time, remove the rest. The removed rows' transactionIds are
331
+ * recorded in the prune ledger so `reconcileUpdateHistoryFromJournals` does
332
+ * not resurrect them from the durable journals on the next startup. The
333
+ * journals themselves (~/.pd/transactions, installer-owned) are never touched.
334
+ *
335
+ * Window closure: the 50-entry cap silently evicts old rows while their
336
+ * journals survive, so a bare "removed rows" ledger would let restart re-derive
337
+ * rows OLDER than the ones the Owner deleted — the cleaned list would grow
338
+ * back. "Keep the newest 5" therefore covers every fact older than the kept
339
+ * window: any ReleaseManager-domain journal whose first fact time precedes the
340
+ * oldest kept row is ledgered too (pdHome read-only; absent/unreadable home
341
+ * degrades to file-row-only cleanup with a console.warn, rc-9).
342
+ *
343
+ * Bounded mutation per docs/process/DATA_CLEANUP_GUIDELINES.md: the file is
344
+ * backed up before the first rewrite (single rolling .bak-prune, no
345
+ * accumulation), and the response carries the row accounting (removed /
346
+ * remaining) instead of a bare ok.
347
+ */
348
+ export function pruneUpdateHistory(workspaceDir, keep, pdHome) {
349
+ const historyPath = getHistoryPath(workspaceDir);
350
+ const history = loadHistory(historyPath);
351
+ if (history.length <= keep) {
352
+ return { removed: 0, remaining: history.length, prunedTransactionIds: [] };
353
+ }
354
+ // Newest-first by fact time; Array#sort is stable, so equal instants keep
355
+ // file order. Nothing has been written yet — from here on the mutations are
356
+ // committed (backup → rewrite → ledger append).
357
+ const sortedDesc = [...history].sort((a, b) => factTimeMs(b.timestamp) - factTimeMs(a.timestamp));
358
+ const kept = sortedDesc.slice(0, keep);
359
+ const removedEntries = sortedDesc.slice(keep);
360
+ let backupPath;
361
+ // Copy-first (no exists-check): an existsSync→copyFileSync gap is a file
362
+ // system race (CodeQL js/file-system-race); a missing source surfaces as
363
+ // ENOENT here, which simply means there was nothing to back up.
364
+ try {
365
+ backupPath = `${historyPath}.bak-prune`;
366
+ fs.copyFileSync(historyPath, backupPath);
367
+ }
368
+ catch (err) {
369
+ if (err.code !== 'ENOENT')
370
+ throw err;
371
+ backupPath = undefined;
372
+ }
373
+ const prunedTransactionIds = Array.from(new Set(removedEntries.flatMap((entry) => (entry.transactionId ? [entry.transactionId] : []))));
374
+ // Journals older than the kept window join the ledger so a restart cannot
375
+ // re-derive the cleanup away. Unparseable kept stamps sort at 0 — the window
376
+ // floor then proves nothing and no journal is covered (honest fallback: the
377
+ // deletion boundary is unprovable, so we must not claim coverage). That
378
+ // corner self-converges: when a later prune removes the re-derived rows,
379
+ // their own transactionIds enter the ledger through the explicit-removal
380
+ // path — the same holds for a journal tied to the oldest kept instant
381
+ // (strict `<`), because a removed tied row in the file is recorded directly.
382
+ const oldestKeptMs = Math.min(...kept.map((entry) => factTimeMs(entry.timestamp)));
383
+ if (pdHome !== undefined && oldestKeptMs > 0) {
384
+ prunedTransactionIds.push(...collectJournalIdsOlderThan(pdHome, oldestKeptMs, new Set(prunedTransactionIds)));
385
+ }
386
+ const prunedIds = Array.from(new Set(prunedTransactionIds));
387
+ // Ledger BEFORE the history rewrite: if the ledger write fails nothing has
388
+ // been deleted yet (clean failure); if the history rewrite fails after a
389
+ // successful ledger write, the rows stay visible and a retried prune is
390
+ // idempotent — never "deleted but unledgered", which would resurrect.
391
+ if (prunedIds.length > 0) {
392
+ const ledgerPath = getPrunedLedgerPath(workspaceDir);
393
+ const merged = Array.from(new Set([...loadPrunedTransactionIds(ledgerPath), ...prunedIds]));
394
+ fs.writeFileSync(ledgerPath, JSON.stringify(merged, null, 2));
395
+ }
396
+ // The file's canonical order stays ascending (oldest first) — readers and
397
+ // reconcile rely on it; the UI sorts for display.
398
+ const remainingAsc = [...kept].sort((a, b) => factTimeMs(a.timestamp) - factTimeMs(b.timestamp));
399
+ fs.writeFileSync(historyPath, JSON.stringify(remainingAsc, null, 2));
400
+ return {
401
+ removed: removedEntries.length,
402
+ remaining: remainingAsc.length,
403
+ ...(backupPath !== undefined ? { backupPath } : {}),
404
+ prunedTransactionIds: prunedIds,
405
+ };
406
+ }
407
+ /**
408
+ * `keep` arrives as the only mutation argument. Untrusted runtime input
409
+ * (rc-1/rc-2): absent → documented default; present but not an integer in
410
+ * [1, 50] → structured refusal, never a silent clamp (rc-3).
411
+ */
412
+ function parsePruneKeep(url) {
413
+ const raw = url !== undefined && url.includes('?') ? new URLSearchParams(url.slice(url.indexOf('?') + 1)).get('keep') : null;
414
+ if (raw === null)
415
+ return { ok: true, keep: UPDATE_HISTORY_PRUNE_KEEP_DEFAULT };
416
+ const parsed = Number(raw);
417
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > UPDATE_HISTORY_PRUNE_KEEP_MAX) {
418
+ return {
419
+ ok: false,
420
+ reason: 'invalid_keep',
421
+ nextAction: `keep must be an integer between 1 and ${UPDATE_HISTORY_PRUNE_KEEP_MAX} (e.g. POST /api/update/history/prune?keep=5)`,
422
+ };
423
+ }
424
+ return { ok: true, keep: parsed };
425
+ }
426
+ export async function handleUpdateHistoryPruneRoute(req, res, workspaceDir) {
427
+ if (req.method !== 'POST') {
428
+ sendMethodNotAllowed(res);
429
+ return;
430
+ }
431
+ // Validate BEFORE any side effect — a refused request must not touch the
432
+ // history file, the backup, or the ledger (EP-02/ERR-183 preflight rule).
433
+ const keep = parsePruneKeep(req.url);
434
+ if (!keep.ok) {
435
+ sendError(res, 400, keep.reason, keep.reason, { nextAction: keep.nextAction });
436
+ return;
437
+ }
438
+ // The cleanup window covers journals too; an unresolvable pdHome degrades
439
+ // the cleanup to its file rows (logged) rather than failing the mutation.
440
+ let pdHome;
441
+ try {
442
+ ({ pdHome } = getPdHome());
443
+ }
444
+ catch (err) {
445
+ console.warn('[update-history] pdHome unresolvable; cleanup window covers file rows only:', err instanceof Error ? err.message : err);
446
+ }
447
+ const result = pruneUpdateHistory(workspaceDir, keep.keep, pdHome);
448
+ sendSuccess(res, result);
449
+ }