@jini-ai/db 0.7.3-next.1 → 0.7.3-next.3

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 (89) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +46 -1
  3. package/dist/core/ports.d.ts +2 -2
  4. package/dist/core/ports.js +2 -2
  5. package/dist/data-modules/data-module.d.ts +2 -46
  6. package/dist/data-modules/plugin-identity.d.ts +2 -11
  7. package/dist/data-modules/snapshot.d.ts +5 -3
  8. package/dist/data-modules/snapshot.js +5 -3
  9. package/dist/events/change-set-repo.sql.d.ts +18 -5
  10. package/dist/events/change-set-repo.sql.js +25 -8
  11. package/dist/events/index.d.ts +1 -1
  12. package/dist/events/outbox-repo.sql.d.ts +26 -1
  13. package/dist/events/outbox-repo.sql.js +36 -2
  14. package/dist/events/repo.rows.d.ts +22 -4
  15. package/dist/events/repo.rows.js +32 -4
  16. package/dist/kernel/idle-turn.d.ts +62 -0
  17. package/dist/kernel/idle-turn.js +32 -0
  18. package/dist/kernel/index.d.ts +1 -0
  19. package/dist/kernel/index.js +1 -0
  20. package/dist/kernel/kernel-core.js +28 -0
  21. package/dist/kernel/schema-scope.js +2 -0
  22. package/dist/kernel/sqlite/driver.js +2 -0
  23. package/dist/kernel/turn-lock.d.ts +2 -0
  24. package/dist/kernel/turn-lock.js +7 -0
  25. package/dist/pglite/copy-source.d.ts +45 -0
  26. package/dist/pglite/copy-source.js +36 -0
  27. package/dist/pglite/index.d.ts +1 -0
  28. package/dist/pglite/index.js +1 -0
  29. package/dist/react/recovery/Recovery.d.ts +205 -0
  30. package/dist/react/recovery/Recovery.js +141 -0
  31. package/dist/react/recovery/Recovery.restore-steps.d.ts +10 -0
  32. package/dist/react/recovery/Recovery.restore-steps.js +71 -0
  33. package/dist/recovery/agent-tools.d.ts +33 -0
  34. package/dist/recovery/agent-tools.js +166 -0
  35. package/dist/recovery/drift.d.ts +47 -0
  36. package/dist/recovery/drift.js +51 -0
  37. package/dist/recovery/journal-kernel.d.ts +80 -0
  38. package/dist/recovery/journal-kernel.js +40 -0
  39. package/dist/recovery/journal-repo.sql.d.ts +154 -0
  40. package/dist/recovery/journal-repo.sql.js +303 -0
  41. package/dist/recovery/journal-schema.d.ts +37 -0
  42. package/dist/recovery/journal-schema.js +110 -0
  43. package/dist/recovery/migrate-forward-hooks.d.ts +2 -1
  44. package/dist/recovery/migrate-forward-hooks.js +3 -3
  45. package/dist/recovery/operation-lock.d.ts +2 -17
  46. package/dist/recovery/reconcile-interrupted-migration.d.ts +2 -5
  47. package/dist/recovery/reconcile-interrupted-migration.js +0 -30
  48. package/dist/recovery/restore-hooks.d.ts +4 -0
  49. package/dist/recovery/restore-hooks.js +1 -1
  50. package/dist/recovery/tool-registrations.d.ts +175 -0
  51. package/dist/recovery/tool-registrations.js +295 -0
  52. package/dist/site/repo.memory.d.ts +149 -0
  53. package/dist/site/repo.memory.js +162 -0
  54. package/dist/site/tool-registrations.d.ts +130 -0
  55. package/dist/site/tool-registrations.js +185 -0
  56. package/dist/sqlite/backup-policy.d.ts +14 -0
  57. package/dist/sqlite/backup-policy.js +47 -3
  58. package/dist/sqlite/compaction-steps.d.ts +43 -0
  59. package/dist/sqlite/compaction-steps.js +73 -0
  60. package/dist/sqlite/compaction.d.ts +63 -0
  61. package/dist/sqlite/compaction.js +263 -0
  62. package/dist/sqlite/index.d.ts +2 -1
  63. package/dist/sqlite/index.js +2 -1
  64. package/dist/tools/index.d.ts +2 -0
  65. package/dist/tools/index.js +2 -0
  66. package/dist/tools/plan-store.d.ts +1 -1
  67. package/dist/tools/plan-store.js +10 -6
  68. package/dist/tools/site-db-messages.d.ts +10 -0
  69. package/dist/tools/site-db-messages.js +23 -0
  70. package/dist/tools/site-transfer-messages.d.ts +9 -0
  71. package/dist/tools/site-transfer-messages.js +20 -0
  72. package/dist/transfer/confirmation-ui.d.ts +19 -0
  73. package/dist/transfer/confirmation-ui.js +39 -0
  74. package/dist/transfer/copy-engine.js +11 -11
  75. package/dist/transfer/destination-store.d.ts +69 -0
  76. package/dist/transfer/destination-store.js +75 -0
  77. package/dist/transfer/index.d.ts +2 -0
  78. package/dist/transfer/index.js +2 -0
  79. package/dist/transfer/internal-ddl.d.ts +6 -2
  80. package/dist/transfer/internal-ddl.js +15 -15
  81. package/dist/transfer/postgres-ddl.js +2 -2
  82. package/dist/transfer/schema-catalog.d.ts +148 -0
  83. package/dist/transfer/schema-catalog.js +141 -0
  84. package/dist/transfer/sqlite-backup.d.ts +27 -0
  85. package/dist/transfer/sqlite-backup.js +31 -0
  86. package/dist/transfer/table-catalog.js +1 -0
  87. package/dist/watermark/kernel.d.ts +64 -0
  88. package/dist/watermark/kernel.js +45 -0
  89. package/package.json +105 -10
@@ -0,0 +1,71 @@
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { agentHandle } from "@jini-ai/core/agent-handles";
3
+ import { formatTimestamp } from "@jini-ai/core/text";
4
+ /** This stylesheet's discard-count row classes (`.recovery-loss-qty` carries the numeral's weight). */
5
+ const RECOVERY_LOSS_CLASSES = { row: "recovery-loss-row", quantity: "recovery-loss-qty", category: "recovery-loss-what" };
6
+ /** Step 2 — the discarded-write-window disclosure (design-spec.md §4.3): the load-bearing,
7
+ * blocking centerpiece of this screen. Renders only categories the server response actually
8
+ * contains (never a placeholder row for an uncovered category), and renders `"unknown"` distinctly
9
+ * from `0` (INV-05 — a `0` implies verified-zero-loss, `"unknown"` means the baseline could not be
10
+ * computed at all; these must never be conflated). */
11
+ function DisclosurePanel(props) {
12
+ const { locale, copy: { t, sinceDiscardMessage, discardCountLine, categoryLabel, baselineUnavailableMessage } } = props;
13
+ const categories = Object.entries(props.disclosure.counts);
14
+ return (_jsxs("div", { className: "recovery-disclosure-panel", children: [_jsxs("div", { className: "recovery-loss-manifest", children: [_jsx("p", { className: "recovery-loss-lede", children: sinceDiscardMessage({ locale: locale, createdAt: props.point.createdAt }) }), _jsx("ul", { className: "recovery-loss-list", children: categories.map(([category, count]) => (_jsx("li", { children: discardCountLine({ locale: locale, count: count, categoryLabelText: categoryLabel({ category: category, locale: locale }), classNames: RECOVERY_LOSS_CLASSES }) }, category))) }), _jsx("p", { className: "recovery-loss-caveat", children: t({ locale: locale, key: "This covers watermark-stamped write paths only (posts/pages and plugin-table writes today) and is NOT a complete count of everything written since this restore point — change-sets, taxonomy writes, Collections entries, and sessions are not yet counted here." }) })] }), !props.disclosure.watermarkBaselineAvailable ? (_jsx("p", { className: "save-error recovery-baseline-alarm", role: "alert", children: baselineUnavailableMessage({ locale: locale }) })) : null, _jsxs("label", { id: "recovery-ack-label", className: "recovery-ack-gate", children: [_jsx("input", { type: "checkbox", checked: props.acknowledged, onChange: (e) => props.onAcknowledgeChange(e.target.checked), ...agentHandle({ handle: "recovery-disclosure-acknowledge" }, {
15
+ role: "field",
16
+ label: "Acknowledge the discarded-write-window disclosure",
17
+ }) }), t({ locale: locale, key: "I understand this count is partial, not exhaustive, and accept the loss window described above." })] })] }));
18
+ }
19
+ /** The disclosure section (top of `RestoreFlow`): the discarded-write-window error, its loading
20
+ * placeholder, or the panel itself, in that priority order. Split out because — along with
21
+ * `RestoreCeremonySteps` below — this is one of the two independent "wide branch set" halves of
22
+ * the original `RestoreFlow`: this half decides what to show about data loss, the other half
23
+ * decides what to show about ceremony progress, and neither needs the other's branches in scope. */
24
+ function RestoreDisclosureStatus(props) {
25
+ const { locale, point, disclosure, error, acknowledged, onAcknowledgeChange, copy, copy: { t } } = props;
26
+ if (error)
27
+ return _jsx("div", { className: "notice error", children: error });
28
+ if (!disclosure)
29
+ return _jsx("div", { className: "notice", children: t({ locale: locale, key: "Computing the discarded-write-window disclosure…" }) });
30
+ return _jsx(DisclosurePanel, { locale: locale, point: point, disclosure: disclosure, acknowledged: acknowledged, onAcknowledgeChange: onAcknowledgeChange, copy: copy });
31
+ }
32
+ /** Step 3a (design-spec.md §4.3) — acknowledge-gated entry into the ceremony. Its own component
33
+ * (rather than inline in `RestoreCeremonySteps`) because the busy-label ternary and the
34
+ * not-yet-acknowledged `title` ternary would otherwise nest two levels deep inside that
35
+ * function's own `step === "idle"` branch — exactly the nesting SonarJS's cognitive-complexity
36
+ * rule penalises beyond what the cyclomatic count shows. */
37
+ function RestoreIdleStep(props) {
38
+ const { locale, acknowledged, busy, onStart, copy: { t } } = props;
39
+ return (_jsx("div", { className: "recovery-ceremony-step", children: _jsx("button", { type: "button", className: "btn-primary", disabled: !acknowledged || busy, "aria-describedby": "recovery-ack-label", title: !acknowledged ? t({ locale: locale, key: "Acknowledge the disclosure above to continue." }) : undefined, onClick: onStart, ...agentHandle({ handle: "recovery-restore-start" }, { role: "button", label: "Continue to confirm the restore" }), children: busy ? t({ locale: locale, key: "Planning…" }) : t({ locale: locale, key: "Continue to confirm" }) }) }));
40
+ }
41
+ /** Step 3b (SPEC-019 C-301) — plan issued, not yet confirmed. */
42
+ function RestorePlannedStep(props) {
43
+ const { locale, planId, busy, onConfirm, copy: { t, restorePlanReadyMessage } } = props;
44
+ return (_jsxs("div", { className: "recovery-ceremony-step", children: [_jsx("p", { children: restorePlanReadyMessage({ locale: locale, planId: planId }) }), _jsx("button", { type: "button", className: "btn-secondary", onClick: onConfirm, disabled: busy, ...agentHandle({ handle: "recovery-restore-confirm" }, { role: "button", label: "Confirm the planned restore, issuing a one-time execution token" }), children: busy ? t({ locale: locale, key: "Confirming…" }) : t({ locale: locale, key: "Confirm restore" }) })] }));
45
+ }
46
+ /** Step 3c (SPEC-019 C-302) — confirmed, execution token in hand, not yet executed. */
47
+ function RestoreConfirmedStep(props) {
48
+ const { locale, busy, onExecute, copy: { t } } = props;
49
+ return (_jsxs("div", { className: "recovery-ceremony-step", children: [_jsx("p", { children: t({ locale: locale, key: "Confirmed. Executing performs the restore — this cannot be undone." }) }), _jsx("button", { type: "button", className: "btn-danger", onClick: onExecute, disabled: busy, ...agentHandle({ handle: "recovery-restore-execute" }, { role: "button", label: "Execute the confirmed restore now — cannot be undone" }), children: busy ? t({ locale: locale, key: "Restoring…" }) : t({ locale: locale, key: "Execute restore" }) })] }));
50
+ }
51
+ /** Step 3d (SPEC-019 C-303) — the ceremony's terminal state. `restartRequired` (2026-07-16,
52
+ * `DbOpsPort.restoreFromArtifact`) surfaces the "already-running process still holds the
53
+ * pre-restore file handle" caveat described in this file's header, rather than silently implying
54
+ * a live hot-swap happened. */
55
+ function RestoreDoneStep(props) {
56
+ const { locale, restoreRunId, state, restartRequired, ServerLabel, copy: { t, restoreDoneMessage } } = props;
57
+ return (_jsxs("div", { className: "recovery-ceremony-step", children: [_jsx("p", { role: "status", children: restoreDoneMessage({ locale: locale, restoreRunId: restoreRunId, stateNode: _jsx("span", { className: `status status-${state}`, children: _jsx(ServerLabel, { value: state }) }) }) }), restartRequired ? (_jsx("p", { className: "save-error", role: "alert", children: t({ locale: locale, key: "The database file was replaced — this server process is still serving the pre-restore data from its open connection. Restart the server now to pick up the restored data." }) })) : null] }));
58
+ }
59
+ /** The four-stage ceremony switch (idle → planned → confirmed → done) plus its own error slot.
60
+ * Exactly one of the four step components below renders at a time, keyed off `step` — this
61
+ * function owns that selection so `RestoreFlow` itself doesn't have to. */
62
+ function RestoreCeremonySteps(props) {
63
+ const { locale, ceremonyError, step, busy, acknowledged, plan, confirmationToken, result, onStart, onConfirm, onExecute, copy, ServerLabel } = props;
64
+ return (_jsxs(_Fragment, { children: [ceremonyError ? _jsx("div", { className: "notice error", children: ceremonyError }) : null, step === "idle" ? _jsx(RestoreIdleStep, { locale: locale, acknowledged: acknowledged, busy: busy, onStart: onStart, copy: copy }) : null, step === "planned" && plan ? _jsx(RestorePlannedStep, { locale: locale, planId: plan.planId, busy: busy, onConfirm: onConfirm, copy: copy }) : null, step === "confirmed" && confirmationToken ? _jsx(RestoreConfirmedStep, { locale: locale, busy: busy, onExecute: onExecute, copy: copy }) : null, step === "done" && result ? (_jsx(RestoreDoneStep, { locale: locale, restoreRunId: result.restoreRunId, state: result.state, restartRequired: result.restartRequired, copy: copy, ServerLabel: ServerLabel })) : null] }));
65
+ }
66
+ export function RestoreFlowBody({ point, onBack, controller, copy, ServerLabel, viewerTimeZone: VIEWER_TIME_ZONE }) {
67
+ const { costClassLabel } = copy;
68
+ const { disclosure, error, acknowledged, setAcknowledged, step, busy, ceremonyError, plan, confirmationToken, result, startPlan, doConfirm, doExecute, t, locale, } = controller;
69
+ return (_jsxs("div", { className: "recovery-restore-docket", children: [_jsx("button", { type: "button", className: "btn-ghost recovery-back-link", onClick: onBack, ...agentHandle({ handle: "recovery-back-to-list" }, { role: "button", label: "Back to the restore points list" }), children: t("← Restore points") }), _jsxs("div", { className: "card recovery-restore-card", children: [_jsxs("div", { className: "recovery-ceremony-summary", children: [_jsxs("div", { className: "recovery-restore-title-row", children: [_jsxs("h2", { className: "recovery-restore-title", children: [t("Restore to"), " ", formatTimestamp({ iso: point.createdAt }, { viewerTimeZone: VIEWER_TIME_ZONE })] }), _jsx("span", { className: "visually-hidden", children: t("Cost class") }), _jsx("span", { className: `status status-${point.costClass}`, children: costClassLabel({ costClass: point.costClass, locale: locale }) })] }), _jsxs("p", { className: "recovery-restore-meta", children: [_jsxs("span", { children: [_jsx("span", { className: "recovery-meta-key", children: t("Trigger") }), _jsx("span", { className: "recovery-meta-value", children: point.trigger })] }), _jsxs("span", { children: [_jsx("span", { className: "recovery-meta-key", children: t("Kind") }), _jsx("span", { className: "recovery-meta-value", children: point.kind })] })] })] }), _jsx(RestoreDisclosureStatus, { copy: copy, locale: locale, point: point, disclosure: disclosure, error: error, acknowledged: acknowledged, onAcknowledgeChange: setAcknowledged }), _jsx(RestoreCeremonySteps, { copy: copy, ServerLabel: ServerLabel, locale: locale, ceremonyError: ceremonyError, step: step, busy: busy, acknowledged: acknowledged, plan: plan, confirmationToken: confirmationToken, result: result, onStart: startPlan, onConfirm: doConfirm, onExecute: doExecute })] })] }));
70
+ }
71
+ //# sourceMappingURL=Recovery.restore-steps.js.map
@@ -0,0 +1,33 @@
1
+ import type { AgentToolDefinition as SharedAgentToolDefinition } from "@jini-ai/core";
2
+ export type AgentToolSideEffect = "none" | "mutates-durable-state" | "mints-token";
3
+ export type { AgentToolActorClassRule } from "@jini-ai/core";
4
+ /**
5
+ * JSON Schema for this tool's `input`, published via `ToolDescriptor.inputSchema` (the host's
6
+ * registration pass refuses to wire any tool lacking one). Optional, matching the other catalogs.
7
+ */
8
+ export type AgentToolDefinition = SharedAgentToolDefinition & {
9
+ sideEffects: AgentToolSideEffect;
10
+ };
11
+ /** Host wording bound into the recovery catalog's model-facing guidance. */
12
+ export interface RecoveryAgentToolCatalogArgs {
13
+ /** Sentences inserted into `backup_get_capabilities`: the host's repository-backup tools and its portable export path. */
14
+ readonly backupWorkflowGuidance: string;
15
+ /** The host read tool(s) that return a restore point id, named in the `restorePointId` field description. */
16
+ readonly restorePointIdSource: string;
17
+ }
18
+ /**
19
+ * Recovery's fixed agent-tool catalog: reads are freely agent-callable under `backup.read`;
20
+ * `backup_execute_restore` is the one destructive, token-gated tool
21
+ * (`confirmer-must-equal-own-delegatedBy`); `backup_create_restore_point` is an ordinary
22
+ * mutation, never wrapped in a plan/confirm/execute sequence — but see this file's header for why
23
+ * it is nonetheless left unwired from the recovery registrations.
24
+ *
25
+ * @param args.backupWorkflowGuidance - the host's repository-backup / export sentences.
26
+ * @param args.restorePointIdSource - the host read tool(s) that return restore point ids.
27
+ * @param _optional.resolveDeepLinkCitation - a host specification id cited in the deep-link tool description.
28
+ * @returns Seven definitions; ids, permissions, side effects and schemas are fixed by the engine.
29
+ */
30
+ export declare function createRecoveryAgentToolCatalog({ backupWorkflowGuidance, restorePointIdSource }: RecoveryAgentToolCatalogArgs, _optional?: {
31
+ resolveDeepLinkCitation?: string;
32
+ }): AgentToolDefinition[];
33
+ //# sourceMappingURL=agent-tools.d.ts.map
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @file Recovery's agent-tool catalog: no agent may hold a direct restore lever.
3
+ *
4
+ * Purpose:
5
+ * A static catalog. No `backup_confirm_restore`-equivalent tool ever exists — the human
6
+ * confirmation step is exactly the one act the gated-mutation gateway reserves for `kind='user'`/api_key
7
+ * principals; no description in this catalog may even claim to perform that step, so a future
8
+ * addition can't quietly reintroduce the capability by wording alone.
9
+ *
10
+ * Catalog notes:
11
+ * - `inputSchema` is part of `AgentToolDefinition` (optional, mirroring the other domain catalogs).
12
+ * - `backup_create_restore_point` is declared here but deliberately left UNWIRED by the host's
13
+ * recovery registrations. Short version: this tool id collides with the Database catalog's own
14
+ * `backup_create_restore_point` (the Database domain is that permission's "named tool"), and a
15
+ * recovery-local restore-point mint that never calls `DbOpsPort.captureRestorePoint()` would
16
+ * silently mint restore-point rows with no real snapshot artifact, reintroducing the
17
+ * "artifactRef silently dropped" defect the Database restore-points module records as fixed.
18
+ * - `recovery_get_status` and `recovery_resolve_deep_link` are read-only, zero-side-effect
19
+ * admin-UI sections (the recovery status bar and the deep-link re-resolution), added under the
20
+ * same "read-only admin-UI section is safe to wrap directly" bar the rest of this catalog uses.
21
+ *
22
+ * How it relates to the project:
23
+ * The server-side tool filter consumes this catalog to decide which tool names an agent
24
+ * session may see at all; `authorize()` and the confirmation-token gateway enforce the actual
25
+ * checks at call time — this module declares shape only, no I/O.
26
+ *
27
+ * The host supplies the wording that names its own tools and screens (the repository-backup
28
+ * workflow, its export path, and the read tools that return restore point ids); the engine never
29
+ * hard-codes a host tool name or product path.
30
+ */
31
+ const BACKUP_READ_PERMISSION = "backup.read";
32
+ /** No arguments — shared by every parameterless read tool in this catalog. */
33
+ const NO_INPUT_SCHEMA = {
34
+ type: "object",
35
+ additionalProperties: false,
36
+ required: [],
37
+ properties: {},
38
+ };
39
+ /** `recovery_resolve_deep_link`'s input — mirrors `./deep-link`'s
40
+ * `DatabaseContextEnvelope` shape field-for-field. Every id inside is untrusted and re-looked-up
41
+ * server-side on arrival; nothing in this schema grants authority, it only carries display
42
+ * continuity. */
43
+ const DEEP_LINK_ENVELOPE_SCHEMA = {
44
+ type: "object",
45
+ additionalProperties: false,
46
+ required: ["envelope"],
47
+ properties: {
48
+ envelope: {
49
+ type: "object",
50
+ additionalProperties: false,
51
+ required: ["v", "correlationId", "siteId", "ledgerEventId", "restorePointId", "drift", "intent", "issuedAt"],
52
+ properties: {
53
+ v: { type: "integer", description: "Envelope schema version." },
54
+ correlationId: { type: "string", description: "The incident/correlation id minted when this deep-link's chain began." },
55
+ siteId: { type: "string", description: "The site/workspace id the envelope was minted for. Re-verified server-side, never trusted as-is." },
56
+ ledgerEventId: { type: ["string", "null"], description: "The database ledger row id this envelope points at, or null." },
57
+ restorePointId: {
58
+ type: ["string", "null"],
59
+ description: "The restore point id this envelope points at, or null. Re-looked-up server-side; a stale or forged id resolves to found:false rather than being trusted.",
60
+ },
61
+ drift: { type: "string", description: "The drift status carried for display continuity only; never trusted as authoritative." },
62
+ intent: { type: "string", description: "The carried intent (e.g. 'view'), for display continuity only." },
63
+ issuedAt: { type: "string", description: "ISO-8601 timestamp the envelope was minted at." },
64
+ },
65
+ },
66
+ },
67
+ };
68
+ /** `backup_plan_restore`'s and `backup_execute_restore`'s shared input, naming the host tool that returns ids. */
69
+ function planRestoreInputSchema({ restorePointIdSource }) {
70
+ return {
71
+ type: "object",
72
+ additionalProperties: false,
73
+ required: ["restorePointId"],
74
+ properties: {
75
+ restorePointId: { type: "string", minLength: 1, description: `A restore point id, as returned by ${restorePointIdSource}.` },
76
+ },
77
+ };
78
+ }
79
+ /** The restore flow: list, capabilities, plan, and the one destructive execute tool. */
80
+ function restoreFlowTools({ backupWorkflowGuidance, planRestoreSchema }) {
81
+ return [
82
+ {
83
+ name: "backup_list_restore_points",
84
+ description: "Lists restore points for the current site, newest first, with their capture trigger and cost class.",
85
+ sideEffects: "none",
86
+ authorization: { permission: BACKUP_READ_PERMISSION },
87
+ inputSchema: NO_INPUT_SCHEMA,
88
+ },
89
+ {
90
+ name: "backup_get_capabilities",
91
+ description: `Reports this site's restore-point cost class and mechanism kind. ${backupWorkflowGuidance} Rendered static output commits are a separate publishing workflow.`,
92
+ sideEffects: "none",
93
+ authorization: { permission: BACKUP_READ_PERMISSION },
94
+ inputSchema: NO_INPUT_SCHEMA,
95
+ },
96
+ {
97
+ name: "backup_plan_restore",
98
+ description: "Previews what restoring to a given restore point would change, including the discarded-write-window disclosure.",
99
+ sideEffects: "none",
100
+ authorization: { permission: BACKUP_READ_PERMISSION },
101
+ inputSchema: planRestoreSchema,
102
+ },
103
+ {
104
+ // Asks the human in chat first (2026-09-24): wired with `humanConfirmedToolHandler`, which
105
+ // shows a confirm dialog and, only on the human's own click, confirms as that human and
106
+ // executes as the agent acting for them. The model never sees or supplies a token.
107
+ name: "backup_execute_restore",
108
+ description: "Replaces this site's current data with a restore point. Shows the user a confirm dialog first and only runs if they confirm. " +
109
+ "No restore point is taken first, so it can't be undone. Call backup_plan_restore first to see what would be lost.",
110
+ sideEffects: "mutates-durable-state",
111
+ authorization: { permission: "backup.restore" },
112
+ actorClassRule: "confirmer-must-equal-own-delegatedBy",
113
+ inputSchema: planRestoreSchema,
114
+ },
115
+ ];
116
+ }
117
+ /** The restore-point mint plus the two read-only admin-UI sections (status bar, deep-link resolution). */
118
+ function restoreAdminTools({ citation }) {
119
+ return [
120
+ {
121
+ // Catalog entry deliberately left UNWIRED — see this file's header and the host's recovery
122
+ // registrations for the full reasoning: an id collision with the Database catalog's own
123
+ // `backup_create_restore_point`, whose wiring is the canonical one.
124
+ name: "backup_create_restore_point",
125
+ description: "Mints a new restore point independent of any migration, subject to the site's cost-acknowledgment rule.",
126
+ sideEffects: "mutates-durable-state",
127
+ authorization: { permission: "backup.create" },
128
+ },
129
+ {
130
+ // Read-only "Recovery status bar + degraded banner" admin-UI section.
131
+ name: "recovery_get_status",
132
+ description: "Reports this site's current restore-point cost class plus the single highest-precedence degraded-state banner (migration interrupted, pending migration, an operation already in flight, cost class unavailable, or watermark baseline unavailable), if any.",
133
+ sideEffects: "none",
134
+ authorization: { permission: BACKUP_READ_PERMISSION },
135
+ inputSchema: NO_INPUT_SCHEMA,
136
+ },
137
+ {
138
+ // Read-only re-resolution of a deep-link envelope. Never trusts the envelope's own carried
139
+ // values; every id is re-looked-up server-side.
140
+ name: "recovery_resolve_deep_link",
141
+ description: `Re-resolves a Database-Timeline deep-link envelope server-side${citation}: looks up the envelope's restorePointId against the current restore-points list rather than trusting the envelope's own carried value. A stale or forged id resolves to found:false.`,
142
+ sideEffects: "none",
143
+ authorization: { permission: BACKUP_READ_PERMISSION },
144
+ inputSchema: DEEP_LINK_ENVELOPE_SCHEMA,
145
+ },
146
+ ];
147
+ }
148
+ /**
149
+ * Recovery's fixed agent-tool catalog: reads are freely agent-callable under `backup.read`;
150
+ * `backup_execute_restore` is the one destructive, token-gated tool
151
+ * (`confirmer-must-equal-own-delegatedBy`); `backup_create_restore_point` is an ordinary
152
+ * mutation, never wrapped in a plan/confirm/execute sequence — but see this file's header for why
153
+ * it is nonetheless left unwired from the recovery registrations.
154
+ *
155
+ * @param args.backupWorkflowGuidance - the host's repository-backup / export sentences.
156
+ * @param args.restorePointIdSource - the host read tool(s) that return restore point ids.
157
+ * @param _optional.resolveDeepLinkCitation - a host specification id cited in the deep-link tool description.
158
+ * @returns Seven definitions; ids, permissions, side effects and schemas are fixed by the engine.
159
+ */
160
+ export function createRecoveryAgentToolCatalog({ backupWorkflowGuidance, restorePointIdSource }, _optional = {}) {
161
+ // A host that cites its own specification ids passes one; the engine carries none.
162
+ const citation = _optional.resolveDeepLinkCitation === undefined ? "" : ` (${_optional.resolveDeepLinkCitation})`;
163
+ const planRestoreSchema = planRestoreInputSchema({ restorePointIdSource });
164
+ return [...restoreFlowTools({ backupWorkflowGuidance, planRestoreSchema }), ...restoreAdminTools({ citation })];
165
+ }
166
+ //# sourceMappingURL=agent-tools.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * @file SPEC-017 C-102 / CIC U-002 / REQ-03 / AC-03 — drift classification between a site's
3
+ * persisted schema snapshot and the runtime's current schema.
4
+ *
5
+ * Purpose:
6
+ * Compares `.site-meta.json {schemaVersion, schemaTag}` against `__drizzle_migrations`'s current
7
+ * tag (ADR-041 §3). Feeds the Timeline's drift banner and the preflight gate that refuses
8
+ * forward-migrate when the site has diverged onto a different migration lineage.
9
+ *
10
+ * How it relates to the project:
11
+ * Pure classification only — no I/O. Callers (the migrate-forward plan step, boot-time
12
+ * SERVE_SITE policy) read the two `SchemaSnapshot`s from their own adapters and pass them in.
13
+ *
14
+ * Architectural role:
15
+ * RELOCATED FROM `features/database/drift.ts` (2026-08-17, architecture SCC cut — see the
16
+ * database-cycle-investigation report). `db/sqlite/database-introspection-adapter.sqlite.ts` was
17
+ * the only VALUE importer of this file outside `features/database` itself, and that one edge
18
+ * (`db -> features/database`) was what closed a cycle once `features/database` got its own
19
+ * `registerToolContributor` edge back into `assistant` (see `features/database/tool-registrations.ts`'s
20
+ * `contributeDatabaseTools()`). Moving this pure, dependency-free module into `db/` — where its one
21
+ * real value-importing caller already lives — removes that edge entirely rather than narrowing it.
22
+ * `features/database/adapter.sqlite.ts` (the port-owning file) still imports `DriftStatus`/
23
+ * `SchemaSnapshot` from here, but only as `import type`, which is erased from the runtime-only graph
24
+ * `check:architecture` gates on. Depends on nothing outside this module.
25
+ *
26
+ * Moved again (w4-db lane): out of the host's `platform/db/drift.ts` into `@jini-ai/db/recovery/drift`,
27
+ * beside the recovery modules that consume the classification. Still pure and dependency-free.
28
+ */
29
+ import type { DriftStatus, SchemaSnapshot } from "@jini-ai/core/contracts/site/database-introspection";
30
+ export type { DriftStatus, SchemaSnapshot } from "@jini-ai/core/contracts/site/database-introspection";
31
+ /**
32
+ * Classifies drift between a site's persisted schema snapshot and the runtime's current schema.
33
+ *
34
+ * CIC U-002-B1/ORD1 (binding): tag-identity comparison is evaluated first and is unconditionally
35
+ * decisive — a tag mismatch is always `"diverged"`, regardless of the version-index relationship.
36
+ * Version-index comparison is used only to disambiguate `"ahead"` vs `"behind"` once the tags
37
+ * already match. This ordering exists because a naive version-index-first shortcut would
38
+ * misclassify an equal-index, different-lineage pair as `"in-sync"`.
39
+ *
40
+ * @complexity O(1).
41
+ * @overallScore 100
42
+ */
43
+ export declare function getDriftStatus(required: {
44
+ siteMeta: SchemaSnapshot;
45
+ runtime: SchemaSnapshot;
46
+ }, _optional?: Record<string, never>): DriftStatus;
47
+ //# sourceMappingURL=drift.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * @file SPEC-017 C-102 / CIC U-002 / REQ-03 / AC-03 — drift classification between a site's
3
+ * persisted schema snapshot and the runtime's current schema.
4
+ *
5
+ * Purpose:
6
+ * Compares `.site-meta.json {schemaVersion, schemaTag}` against `__drizzle_migrations`'s current
7
+ * tag (ADR-041 §3). Feeds the Timeline's drift banner and the preflight gate that refuses
8
+ * forward-migrate when the site has diverged onto a different migration lineage.
9
+ *
10
+ * How it relates to the project:
11
+ * Pure classification only — no I/O. Callers (the migrate-forward plan step, boot-time
12
+ * SERVE_SITE policy) read the two `SchemaSnapshot`s from their own adapters and pass them in.
13
+ *
14
+ * Architectural role:
15
+ * RELOCATED FROM `features/database/drift.ts` (2026-08-17, architecture SCC cut — see the
16
+ * database-cycle-investigation report). `db/sqlite/database-introspection-adapter.sqlite.ts` was
17
+ * the only VALUE importer of this file outside `features/database` itself, and that one edge
18
+ * (`db -> features/database`) was what closed a cycle once `features/database` got its own
19
+ * `registerToolContributor` edge back into `assistant` (see `features/database/tool-registrations.ts`'s
20
+ * `contributeDatabaseTools()`). Moving this pure, dependency-free module into `db/` — where its one
21
+ * real value-importing caller already lives — removes that edge entirely rather than narrowing it.
22
+ * `features/database/adapter.sqlite.ts` (the port-owning file) still imports `DriftStatus`/
23
+ * `SchemaSnapshot` from here, but only as `import type`, which is erased from the runtime-only graph
24
+ * `check:architecture` gates on. Depends on nothing outside this module.
25
+ *
26
+ * Moved again (w4-db lane): out of the host's `platform/db/drift.ts` into `@jini-ai/db/recovery/drift`,
27
+ * beside the recovery modules that consume the classification. Still pure and dependency-free.
28
+ */
29
+ /**
30
+ * Classifies drift between a site's persisted schema snapshot and the runtime's current schema.
31
+ *
32
+ * CIC U-002-B1/ORD1 (binding): tag-identity comparison is evaluated first and is unconditionally
33
+ * decisive — a tag mismatch is always `"diverged"`, regardless of the version-index relationship.
34
+ * Version-index comparison is used only to disambiguate `"ahead"` vs `"behind"` once the tags
35
+ * already match. This ordering exists because a naive version-index-first shortcut would
36
+ * misclassify an equal-index, different-lineage pair as `"in-sync"`.
37
+ *
38
+ * @complexity O(1).
39
+ * @overallScore 100
40
+ */
41
+ export function getDriftStatus(required, _optional = {}) {
42
+ const { siteMeta, runtime } = required;
43
+ if (siteMeta.tag !== runtime.tag) {
44
+ return "diverged";
45
+ }
46
+ if (siteMeta.version === runtime.version) {
47
+ return "in-sync";
48
+ }
49
+ return siteMeta.version > runtime.version ? "ahead" : "behind";
50
+ }
51
+ //# sourceMappingURL=drift.js.map
@@ -0,0 +1,80 @@
1
+ import type { Generated } from "kysely";
2
+ import type { KyselyKernel } from "../kernel/port.js";
3
+ /**
4
+ * @file The sidecar database journal (`ops/database-journal.db`; the host opens it on its SQLite driver)
5
+ * as a storage kernel: `StorageKernel<JournalDatabase>`. The journal twin of the host's chat kernel.
6
+ *
7
+ * The journal is per-site ops metadata (restore points, migration runs, the boot ledger) and stays
8
+ * a local SQLite file whatever database the site's content lives in — so its tables are typed here
9
+ * by hand, snake_case, exactly as `journal-schema.ts` creates them. Type aliases,
10
+ * not interfaces: Kysely's table typing needs them (see `packages/cms/src/comments/sql/repo.rows.ts`).
11
+ */
12
+ export type DatabaseLedgerTable = {
13
+ id: string;
14
+ site_id: string;
15
+ kind: string;
16
+ correlation_id: string | null;
17
+ restore_point_id: string | null;
18
+ schema_before_version: number | null;
19
+ schema_before_tag: string | null;
20
+ schema_after_version: number | null;
21
+ schema_after_tag: string | null;
22
+ drift_status: string | null;
23
+ outcome: string;
24
+ detail_json: string | null;
25
+ actor_workspace_id: string | null;
26
+ actor_id: string | null;
27
+ delegated_by_workspace_id: string | null;
28
+ delegated_by_id: string | null;
29
+ created_at: string;
30
+ };
31
+ export type MigrationRunsTable = {
32
+ id: string;
33
+ site_id: string;
34
+ dialect: string;
35
+ status: string;
36
+ revision_seq_at_quiesce: number | null;
37
+ quiesce_integrity: string | null;
38
+ /** 0/1 (SQLite has no boolean). */
39
+ blue_touched: Generated<number>;
40
+ correlation_id: string | null;
41
+ restore_point_id: string | null;
42
+ actor_workspace_id: string | null;
43
+ actor_id: string | null;
44
+ delegated_by_workspace_id: string | null;
45
+ delegated_by_id: string | null;
46
+ created_at: string;
47
+ updated_at: string;
48
+ };
49
+ export type RestorePointsTable = {
50
+ id: string;
51
+ site_id: string;
52
+ trigger: string;
53
+ cost_class: string;
54
+ kind: string;
55
+ artifact_ref: string;
56
+ watermark_at_capture: number | null;
57
+ captured_schema_version: number | null;
58
+ captured_schema_tag: string | null;
59
+ size_bytes: number | null;
60
+ idempotency_key: string | null;
61
+ actor_workspace_id: string | null;
62
+ actor_id: string | null;
63
+ created_at: string;
64
+ };
65
+ export type JournalDatabase = {
66
+ database_ledger: DatabaseLedgerTable;
67
+ migration_runs: MigrationRunsTable;
68
+ restore_points: RestorePointsTable;
69
+ };
70
+ export type JournalKernel = KyselyKernel<JournalDatabase>;
71
+ /**
72
+ * `kernel` with every database call held until `ready` settles (and failing with its error if it
73
+ * rejects), and `ready` reported as the kernel's own: the {@link StorageKernel.ready} contract, for a
74
+ * kernel whose schema is applied through the kernel itself after the connection opens.
75
+ */
76
+ export declare function gateJournalKernel({ kernel, ready }: {
77
+ kernel: JournalKernel;
78
+ ready: Promise<void>;
79
+ }, _optional?: Record<string, never>): JournalKernel;
80
+ //# sourceMappingURL=journal-kernel.d.ts.map
@@ -0,0 +1,40 @@
1
+ import { afterSettled, observed } from "@jini-ai/core/errors/idioms";
2
+ /**
3
+ * `kernel` with every database call held until `ready` settles (and failing with its error if it
4
+ * rejects), and `ready` reported as the kernel's own: the {@link StorageKernel.ready} contract, for a
5
+ * kernel whose schema is applied through the kernel itself after the connection opens.
6
+ */
7
+ export function gateJournalKernel({ kernel, ready }, _optional = {}) {
8
+ // Observed here so a failed open is not an unhandled rejection; every call below re-throws it.
9
+ observed({ promise: ready });
10
+ return {
11
+ ...kernel,
12
+ ready,
13
+ run: async (fn) => {
14
+ await ready;
15
+ return kernel.run(fn);
16
+ },
17
+ transaction: async (fn) => {
18
+ await ready;
19
+ return kernel.transaction(fn);
20
+ },
21
+ query: async (statement) => {
22
+ await ready;
23
+ return kernel.query(statement);
24
+ },
25
+ execute: async (statement) => {
26
+ await ready;
27
+ await kernel.execute(statement);
28
+ },
29
+ backupTo: async (destPath) => {
30
+ await ready;
31
+ await kernel.backupTo(destPath);
32
+ },
33
+ close: async () => {
34
+ // Readiness errors reach kernel callers; close must still release the underlying handle.
35
+ await afterSettled({ promise: ready });
36
+ await kernel.close();
37
+ },
38
+ };
39
+ }
40
+ //# sourceMappingURL=journal-kernel.js.map