@haaaiawd/second-nature 0.1.1 → 0.1.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 (202) hide show
  1. package/index.ts +64 -21
  2. package/openclaw.plugin.json +1 -1
  3. package/package.json +8 -2
  4. package/runtime/cli/action-bridge.d.ts +11 -0
  5. package/runtime/cli/action-bridge.js +27 -0
  6. package/runtime/cli/commands/credential.d.ts +2 -0
  7. package/runtime/cli/commands/credential.js +40 -0
  8. package/runtime/cli/commands/index.d.ts +12 -0
  9. package/runtime/cli/commands/index.js +138 -0
  10. package/runtime/cli/commands/policy.d.ts +12 -0
  11. package/runtime/cli/commands/policy.js +43 -0
  12. package/runtime/cli/explain/format-explanation.d.ts +10 -0
  13. package/runtime/cli/explain/format-explanation.js +10 -0
  14. package/runtime/cli/explain/resolve-subject.d.ts +2 -0
  15. package/runtime/cli/explain/resolve-subject.js +26 -0
  16. package/runtime/cli/index.d.ts +25 -0
  17. package/runtime/cli/index.js +36 -0
  18. package/runtime/cli/read-models/index.d.ts +20 -0
  19. package/runtime/cli/read-models/index.js +161 -0
  20. package/runtime/cli/read-models/types.d.ts +75 -0
  21. package/runtime/cli/read-models/types.js +1 -0
  22. package/runtime/connectors/agent-network/evomap/adapter.d.ts +23 -0
  23. package/runtime/connectors/agent-network/evomap/adapter.js +69 -0
  24. package/runtime/connectors/agent-network/evomap/index.d.ts +2 -0
  25. package/runtime/connectors/agent-network/evomap/index.js +2 -0
  26. package/runtime/connectors/agent-network/evomap/manifest.d.ts +2 -0
  27. package/runtime/connectors/agent-network/evomap/manifest.js +7 -0
  28. package/runtime/connectors/base/channel-health.d.ts +29 -0
  29. package/runtime/connectors/base/channel-health.js +23 -0
  30. package/runtime/connectors/base/contract.d.ts +81 -0
  31. package/runtime/connectors/base/contract.js +71 -0
  32. package/runtime/connectors/base/failure-taxonomy.d.ts +13 -0
  33. package/runtime/connectors/base/failure-taxonomy.js +105 -0
  34. package/runtime/connectors/base/index.d.ts +6 -0
  35. package/runtime/connectors/base/index.js +6 -0
  36. package/runtime/connectors/base/manifest.d.ts +11 -0
  37. package/runtime/connectors/base/manifest.js +36 -0
  38. package/runtime/connectors/base/policy-layer.d.ts +27 -0
  39. package/runtime/connectors/base/policy-layer.js +213 -0
  40. package/runtime/connectors/base/route-planner.d.ts +10 -0
  41. package/runtime/connectors/base/route-planner.js +98 -0
  42. package/runtime/connectors/index.d.ts +4 -0
  43. package/runtime/connectors/index.js +4 -0
  44. package/runtime/connectors/social-community/instreet/adapter.d.ts +32 -0
  45. package/runtime/connectors/social-community/instreet/adapter.js +79 -0
  46. package/runtime/connectors/social-community/instreet/index.d.ts +2 -0
  47. package/runtime/connectors/social-community/instreet/index.js +2 -0
  48. package/runtime/connectors/social-community/instreet/manifest.d.ts +2 -0
  49. package/runtime/connectors/social-community/instreet/manifest.js +7 -0
  50. package/runtime/connectors/social-community/moltbook/adapter.d.ts +15 -0
  51. package/runtime/connectors/social-community/moltbook/adapter.js +48 -0
  52. package/runtime/connectors/social-community/moltbook/index.d.ts +2 -0
  53. package/runtime/connectors/social-community/moltbook/index.js +2 -0
  54. package/runtime/connectors/social-community/moltbook/manifest.d.ts +7 -0
  55. package/runtime/connectors/social-community/moltbook/manifest.js +12 -0
  56. package/runtime/core/second-nature/guidance/apply-guidance.d.ts +10 -0
  57. package/runtime/core/second-nature/guidance/apply-guidance.js +10 -0
  58. package/runtime/core/second-nature/guidance/request-guidance.d.ts +18 -0
  59. package/runtime/core/second-nature/guidance/request-guidance.js +22 -0
  60. package/runtime/core/second-nature/index.d.ts +14 -0
  61. package/runtime/core/second-nature/index.js +14 -0
  62. package/runtime/core/second-nature/orchestrator/effect-dispatcher.d.ts +100 -0
  63. package/runtime/core/second-nature/orchestrator/effect-dispatcher.js +139 -0
  64. package/runtime/core/second-nature/orchestrator/guard-layer.d.ts +2 -0
  65. package/runtime/core/second-nature/orchestrator/guard-layer.js +54 -0
  66. package/runtime/core/second-nature/orchestrator/intent-planner.d.ts +3 -0
  67. package/runtime/core/second-nature/orchestrator/intent-planner.js +92 -0
  68. package/runtime/core/second-nature/orchestrator/lease-manager.d.ts +14 -0
  69. package/runtime/core/second-nature/orchestrator/lease-manager.js +58 -0
  70. package/runtime/core/second-nature/orchestrator/resume-from-checkpoint.d.ts +32 -0
  71. package/runtime/core/second-nature/orchestrator/resume-from-checkpoint.js +23 -0
  72. package/runtime/core/second-nature/outreach/build-message.d.ts +16 -0
  73. package/runtime/core/second-nature/outreach/build-message.js +27 -0
  74. package/runtime/core/second-nature/outreach/evaluate-outreach.d.ts +13 -0
  75. package/runtime/core/second-nature/outreach/evaluate-outreach.js +41 -0
  76. package/runtime/core/second-nature/quiet/quiet-pipeline.d.ts +34 -0
  77. package/runtime/core/second-nature/quiet/quiet-pipeline.js +35 -0
  78. package/runtime/core/second-nature/reflection/run-narrative-reflection.d.ts +39 -0
  79. package/runtime/core/second-nature/reflection/run-narrative-reflection.js +29 -0
  80. package/runtime/core/second-nature/rhythm/rhythm-policy.d.ts +18 -0
  81. package/runtime/core/second-nature/rhythm/rhythm-policy.js +24 -0
  82. package/runtime/core/second-nature/rhythm/select-window.d.ts +3 -0
  83. package/runtime/core/second-nature/rhythm/select-window.js +50 -0
  84. package/runtime/core/second-nature/runtime/lifecycle-service.d.ts +26 -0
  85. package/runtime/core/second-nature/runtime/lifecycle-service.js +38 -0
  86. package/runtime/core/second-nature/runtime/service-entry.d.ts +36 -0
  87. package/runtime/core/second-nature/runtime/service-entry.js +44 -0
  88. package/runtime/core/second-nature/types.d.ts +37 -0
  89. package/runtime/core/second-nature/types.js +1 -0
  90. package/runtime/guidance/contracts.d.ts +48 -0
  91. package/runtime/guidance/contracts.js +54 -0
  92. package/runtime/guidance/fallback.d.ts +2 -0
  93. package/runtime/guidance/fallback.js +17 -0
  94. package/runtime/guidance/guidance-assembler.d.ts +5 -0
  95. package/runtime/guidance/guidance-assembler.js +62 -0
  96. package/runtime/guidance/index.d.ts +8 -0
  97. package/runtime/guidance/index.js +8 -0
  98. package/runtime/guidance/output-guard.d.ts +10 -0
  99. package/runtime/guidance/output-guard.js +29 -0
  100. package/runtime/guidance/persona-selection.d.ts +11 -0
  101. package/runtime/guidance/persona-selection.js +90 -0
  102. package/runtime/guidance/review-workflow.d.ts +15 -0
  103. package/runtime/guidance/review-workflow.js +60 -0
  104. package/runtime/guidance/template-registry.d.ts +3 -0
  105. package/runtime/guidance/template-registry.js +45 -0
  106. package/runtime/guidance/types.d.ts +72 -0
  107. package/runtime/guidance/types.js +1 -0
  108. package/runtime/observability/db/index.d.ts +10 -0
  109. package/runtime/observability/db/index.js +17 -0
  110. package/runtime/observability/db/schema/index.d.ts +946 -0
  111. package/runtime/observability/db/schema/index.js +70 -0
  112. package/runtime/observability/index.d.ts +12 -0
  113. package/runtime/observability/index.js +11 -0
  114. package/runtime/observability/projections/guidance-audit.d.ts +16 -0
  115. package/runtime/observability/projections/guidance-audit.js +35 -0
  116. package/runtime/observability/projections/outreach-quality-audit.d.ts +15 -0
  117. package/runtime/observability/projections/outreach-quality-audit.js +9 -0
  118. package/runtime/observability/projections/reflection-audit.d.ts +17 -0
  119. package/runtime/observability/projections/reflection-audit.js +9 -0
  120. package/runtime/observability/query/compose-evidence.d.ts +56 -0
  121. package/runtime/observability/query/compose-evidence.js +43 -0
  122. package/runtime/observability/query/evidence-query-engine.d.ts +17 -0
  123. package/runtime/observability/query/evidence-query-engine.js +166 -0
  124. package/runtime/observability/redaction/manifest.d.ts +18 -0
  125. package/runtime/observability/redaction/manifest.js +109 -0
  126. package/runtime/observability/redaction/policy.d.ts +19 -0
  127. package/runtime/observability/redaction/policy.js +71 -0
  128. package/runtime/observability/services/decision-ledger.d.ts +33 -0
  129. package/runtime/observability/services/decision-ledger.js +115 -0
  130. package/runtime/observability/services/execution-telemetry.d.ts +32 -0
  131. package/runtime/observability/services/execution-telemetry.js +126 -0
  132. package/runtime/observability/services/governance-audit.d.ts +27 -0
  133. package/runtime/observability/services/governance-audit.js +139 -0
  134. package/runtime/observability/services/redaction-store.d.ts +3 -0
  135. package/runtime/observability/services/redaction-store.js +20 -0
  136. package/runtime/setup/HOST_SETUP.md +112 -0
  137. package/runtime/shared/types/continuity.d.ts +69 -0
  138. package/runtime/shared/types/continuity.js +1 -0
  139. package/runtime/shared/types/credential.d.ts +22 -0
  140. package/runtime/shared/types/credential.js +1 -0
  141. package/runtime/shared/types/index.d.ts +3 -0
  142. package/runtime/shared/types/index.js +3 -0
  143. package/runtime/shared/types/outreach.d.ts +19 -0
  144. package/runtime/shared/types/outreach.js +1 -0
  145. package/runtime/storage/bootstrap/repair.d.ts +3 -0
  146. package/runtime/storage/bootstrap/repair.js +5 -0
  147. package/runtime/storage/db/index.d.ts +10 -0
  148. package/runtime/storage/db/index.js +17 -0
  149. package/runtime/storage/db/schema/assets.d.ts +140 -0
  150. package/runtime/storage/db/schema/assets.js +10 -0
  151. package/runtime/storage/db/schema/credentials.d.ts +178 -0
  152. package/runtime/storage/db/schema/credentials.js +12 -0
  153. package/runtime/storage/db/schema/index.d.ts +6 -0
  154. package/runtime/storage/db/schema/index.js +6 -0
  155. package/runtime/storage/db/schema/intent-commits.d.ts +161 -0
  156. package/runtime/storage/db/schema/intent-commits.js +11 -0
  157. package/runtime/storage/db/schema/policies.d.ts +81 -0
  158. package/runtime/storage/db/schema/policies.js +7 -0
  159. package/runtime/storage/db/schema/proposals.d.ts +216 -0
  160. package/runtime/storage/db/schema/proposals.js +14 -0
  161. package/runtime/storage/db/schema/provenance.d.ts +104 -0
  162. package/runtime/storage/db/schema/provenance.js +8 -0
  163. package/runtime/storage/index.d.ts +16 -0
  164. package/runtime/storage/index.js +16 -0
  165. package/runtime/storage/memory/workspace/paths.d.ts +62 -0
  166. package/runtime/storage/memory/workspace/paths.js +160 -0
  167. package/runtime/storage/memory/workspace/store.d.ts +26 -0
  168. package/runtime/storage/memory/workspace/store.js +153 -0
  169. package/runtime/storage/memory/workspace/types.d.ts +45 -0
  170. package/runtime/storage/memory/workspace/types.js +1 -0
  171. package/runtime/storage/repositories/asset-repository.d.ts +8 -0
  172. package/runtime/storage/repositories/asset-repository.js +19 -0
  173. package/runtime/storage/repositories/credential-repository.d.ts +8 -0
  174. package/runtime/storage/repositories/credential-repository.js +19 -0
  175. package/runtime/storage/repositories/index.d.ts +6 -0
  176. package/runtime/storage/repositories/index.js +6 -0
  177. package/runtime/storage/repositories/intent-commit-repository.d.ts +10 -0
  178. package/runtime/storage/repositories/intent-commit-repository.js +35 -0
  179. package/runtime/storage/repositories/policy-repository.d.ts +8 -0
  180. package/runtime/storage/repositories/policy-repository.js +19 -0
  181. package/runtime/storage/repositories/proposal-repository.d.ts +9 -0
  182. package/runtime/storage/repositories/proposal-repository.js +26 -0
  183. package/runtime/storage/repositories/provenance-repository.d.ts +20 -0
  184. package/runtime/storage/repositories/provenance-repository.js +41 -0
  185. package/runtime/storage/services/credential-vault.d.ts +8 -0
  186. package/runtime/storage/services/credential-vault.js +78 -0
  187. package/runtime/storage/services/daily-log-pipeline.d.ts +47 -0
  188. package/runtime/storage/services/daily-log-pipeline.js +86 -0
  189. package/runtime/storage/services/effect-commit-store.d.ts +11 -0
  190. package/runtime/storage/services/effect-commit-store.js +93 -0
  191. package/runtime/storage/services/governance-layer.d.ts +40 -0
  192. package/runtime/storage/services/governance-layer.js +103 -0
  193. package/runtime/storage/services/persona-candidate-loader.d.ts +5 -0
  194. package/runtime/storage/services/persona-candidate-loader.js +41 -0
  195. package/runtime/storage/services/provenance-service.d.ts +40 -0
  196. package/runtime/storage/services/provenance-service.js +43 -0
  197. package/runtime/storage/services/quiet-input-loader.d.ts +40 -0
  198. package/runtime/storage/services/quiet-input-loader.js +131 -0
  199. package/runtime/storage/services/repair-and-backup.d.ts +22 -0
  200. package/runtime/storage/services/repair-and-backup.js +73 -0
  201. package/runtime/storage/state-api.d.ts +46 -0
  202. package/runtime/storage/state-api.js +73 -0
@@ -0,0 +1,40 @@
1
+ import type { AssetRepository } from "../repositories/asset-repository.js";
2
+ export interface CurationInputQuery {
3
+ dateRange?: {
4
+ start: string;
5
+ end: string;
6
+ };
7
+ assetFilters?: {
8
+ includeJournal?: boolean;
9
+ includeReports?: boolean;
10
+ includeCurated?: boolean;
11
+ };
12
+ }
13
+ export interface JournalEntry {
14
+ id: string;
15
+ timestamp: string;
16
+ content: string;
17
+ category: string;
18
+ }
19
+ export interface ReportEntry {
20
+ id: string;
21
+ day: string;
22
+ summary: string;
23
+ highlights: string[];
24
+ sources: string[];
25
+ }
26
+ export interface CurationInputBundle {
27
+ journalEntries: JournalEntry[];
28
+ dailyReports: ReportEntry[];
29
+ sourceCount: number;
30
+ }
31
+ export declare class QuietInputLoader {
32
+ private readonly assetRepository;
33
+ constructor(assetRepository: AssetRepository);
34
+ loadQuietInputs(query: CurationInputQuery): Promise<CurationInputBundle>;
35
+ private loadJournalEntries;
36
+ private loadSingleDayJournal;
37
+ private loadReportEntries;
38
+ private loadSingleDayReport;
39
+ }
40
+ export declare function createQuietInputLoader(assetRepository: AssetRepository): QuietInputLoader;
@@ -0,0 +1,131 @@
1
+ import { resolveDailyJournalPath, resolveDailyReportPath, readText } from "../memory/workspace/paths.js";
2
+ export class QuietInputLoader {
3
+ assetRepository;
4
+ constructor(assetRepository) {
5
+ this.assetRepository = assetRepository;
6
+ }
7
+ async loadQuietInputs(query) {
8
+ const filters = query.assetFilters ?? {
9
+ includeJournal: true,
10
+ includeReports: true,
11
+ includeCurated: false,
12
+ };
13
+ const journalEntries = [];
14
+ const dailyReports = [];
15
+ if (filters.includeJournal) {
16
+ const journalEntriesResult = await this.loadJournalEntries(query.dateRange);
17
+ journalEntries.push(...journalEntriesResult);
18
+ }
19
+ if (filters.includeReports) {
20
+ const reportEntriesResult = await this.loadReportEntries(query.dateRange);
21
+ dailyReports.push(...reportEntriesResult);
22
+ }
23
+ return {
24
+ journalEntries,
25
+ dailyReports,
26
+ sourceCount: journalEntries.length + dailyReports.length,
27
+ };
28
+ }
29
+ async loadJournalEntries(dateRange) {
30
+ if (!dateRange) {
31
+ const today = new Date().toISOString().split("T")[0];
32
+ return this.loadSingleDayJournal(today);
33
+ }
34
+ const entries = [];
35
+ const startDate = new Date(dateRange.start);
36
+ const endDate = new Date(dateRange.end);
37
+ const current = new Date(startDate);
38
+ while (current <= endDate) {
39
+ const day = current.toISOString().split("T")[0];
40
+ const dayEntries = await this.loadSingleDayJournal(day);
41
+ entries.push(...dayEntries);
42
+ current.setDate(current.getDate() + 1);
43
+ }
44
+ return entries;
45
+ }
46
+ async loadSingleDayJournal(day) {
47
+ const journalPath = resolveDailyJournalPath(day);
48
+ const content = await readText(journalPath);
49
+ if (!content) {
50
+ return [];
51
+ }
52
+ const entries = [];
53
+ const lines = content.split("\n").filter((line) => line.trim().startsWith("- ["));
54
+ for (const line of lines) {
55
+ const match = line.match(/- \[(\d{4}-\d{2}-\d{2}T[\d:]+)\] (.+)/);
56
+ if (match) {
57
+ const [, timestamp, rest] = match;
58
+ const categoryMatch = rest.match(/^\[(.*?)\]\s*(.*)/);
59
+ const category = categoryMatch ? categoryMatch[1] : "unknown";
60
+ const content = categoryMatch ? categoryMatch[2] : rest;
61
+ entries.push({
62
+ id: `journal:${day}:${entries.length}`,
63
+ timestamp,
64
+ content,
65
+ category,
66
+ });
67
+ }
68
+ }
69
+ return entries;
70
+ }
71
+ async loadReportEntries(dateRange) {
72
+ if (!dateRange) {
73
+ const today = new Date().toISOString().split("T")[0];
74
+ const report = await this.loadSingleDayReport(today);
75
+ return report ? [report] : [];
76
+ }
77
+ const entries = [];
78
+ const startDate = new Date(dateRange.start);
79
+ const endDate = new Date(dateRange.end);
80
+ const current = new Date(startDate);
81
+ while (current <= endDate) {
82
+ const day = current.toISOString().split("T")[0];
83
+ const dayEntry = await this.loadSingleDayReport(day);
84
+ if (dayEntry) {
85
+ entries.push(dayEntry);
86
+ }
87
+ current.setDate(current.getDate() + 1);
88
+ }
89
+ return entries;
90
+ }
91
+ async loadSingleDayReport(day) {
92
+ const reportPath = resolveDailyReportPath(day);
93
+ const content = await readText(reportPath);
94
+ if (!content) {
95
+ return null;
96
+ }
97
+ const summaryMatch = content.match(/## Summary\n([\s\S]*?)(?=##|$)/);
98
+ const highlightsMatch = content.match(/## Highlights\n([\s\S]*?)(?=##|$)/);
99
+ const sourcesMatch = content.match(/## Sources\n([\s\S]*?)$/);
100
+ const summary = summaryMatch ? summaryMatch[1].trim() : "";
101
+ const highlights = [];
102
+ if (highlightsMatch) {
103
+ const highlightLines = highlightsMatch[1].split("\n").filter((l) => l.trim().startsWith("-"));
104
+ for (const h of highlightLines) {
105
+ highlights.push(h.replace(/^-\s*/, "").trim());
106
+ }
107
+ }
108
+ const sources = [];
109
+ if (sourcesMatch) {
110
+ const sourceLines = sourcesMatch[1].split("\n").filter((l) => l.trim());
111
+ for (const s of sourceLines) {
112
+ const match = s.match(/- Activities: (.*)/);
113
+ const obsMatch = s.match(/- Observations: (.*)/);
114
+ if (match)
115
+ sources.push(...match[1].split(", "));
116
+ else if (obsMatch)
117
+ sources.push(...obsMatch[1].split(", "));
118
+ }
119
+ }
120
+ return {
121
+ id: `report:${day}`,
122
+ day,
123
+ summary,
124
+ highlights,
125
+ sources,
126
+ };
127
+ }
128
+ }
129
+ export function createQuietInputLoader(assetRepository) {
130
+ return new QuietInputLoader(assetRepository);
131
+ }
@@ -0,0 +1,22 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ export interface RepairAndBackupOptions {
3
+ now?: Date;
4
+ staleProposalDays?: number;
5
+ backupDir?: string;
6
+ }
7
+ export interface RepairAndBackupResult {
8
+ scannedAssetCount: number;
9
+ repairedOrphanIndexCount: number;
10
+ updatedHashCount: number;
11
+ staleProposalCount: number;
12
+ backupPath: string;
13
+ repairedOrphanAssetIds: string[];
14
+ updatedHashAssetIds: string[];
15
+ staleProposalIds: string[];
16
+ }
17
+ export declare class RepairAndBackupService {
18
+ private readonly database;
19
+ constructor(database: StateDatabase);
20
+ runStartupRepair(options?: RepairAndBackupOptions): Promise<RepairAndBackupResult>;
21
+ }
22
+ export declare function createRepairAndBackupService(database: StateDatabase): RepairAndBackupService;
@@ -0,0 +1,73 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { and, eq, inArray, lt } from "drizzle-orm";
4
+ import { assetRegistry, proposalRecords } from "../db/schema/index.js";
5
+ import { fileExists, hashFile } from "../memory/workspace/paths.js";
6
+ const DEFAULT_STALE_DAYS = 7;
7
+ const DEFAULT_BACKUP_DIR = "./workspace/backups";
8
+ export class RepairAndBackupService {
9
+ database;
10
+ constructor(database) {
11
+ this.database = database;
12
+ }
13
+ async runStartupRepair(options = {}) {
14
+ const now = options.now ?? new Date();
15
+ const staleProposalDays = options.staleProposalDays ?? DEFAULT_STALE_DAYS;
16
+ const backupDir = options.backupDir ?? DEFAULT_BACKUP_DIR;
17
+ const assets = await this.database.db.select().from(assetRegistry);
18
+ const repairedOrphanAssetIds = [];
19
+ const updatedHashAssetIds = [];
20
+ for (const asset of assets) {
21
+ const exists = await fileExists(asset.path);
22
+ if (!exists) {
23
+ repairedOrphanAssetIds.push(asset.id);
24
+ continue;
25
+ }
26
+ const currentHash = await hashFile(asset.path);
27
+ if (currentHash && currentHash !== asset.hash) {
28
+ updatedHashAssetIds.push(asset.id);
29
+ await this.database.db
30
+ .update(assetRegistry)
31
+ .set({
32
+ hash: currentHash,
33
+ lastIndexedAt: now.toISOString(),
34
+ })
35
+ .where(eq(assetRegistry.id, asset.id));
36
+ }
37
+ }
38
+ if (repairedOrphanAssetIds.length > 0) {
39
+ await this.database.db
40
+ .delete(assetRegistry)
41
+ .where(inArray(assetRegistry.id, repairedOrphanAssetIds));
42
+ }
43
+ const staleCutoff = new Date(now.getTime() - staleProposalDays * 24 * 60 * 60 * 1000).toISOString();
44
+ const staleProposals = await this.database.db
45
+ .select({ id: proposalRecords.id })
46
+ .from(proposalRecords)
47
+ .where(and(inArray(proposalRecords.status, ["draft", "requires_review"]), lt(proposalRecords.createdAt, staleCutoff)));
48
+ const staleProposalIds = staleProposals.map((item) => item.id);
49
+ if (staleProposalIds.length > 0) {
50
+ await this.database.db
51
+ .update(proposalRecords)
52
+ .set({ status: "rejected" })
53
+ .where(inArray(proposalRecords.id, staleProposalIds));
54
+ }
55
+ await fs.mkdir(backupDir, { recursive: true });
56
+ const backupFileName = `state-${now.toISOString().replace(/[:.]/g, "-")}.db`;
57
+ const backupPath = path.join(backupDir, backupFileName);
58
+ await this.database.sqlite.backup(backupPath);
59
+ return {
60
+ scannedAssetCount: assets.length,
61
+ repairedOrphanIndexCount: repairedOrphanAssetIds.length,
62
+ updatedHashCount: updatedHashAssetIds.length,
63
+ staleProposalCount: staleProposalIds.length,
64
+ backupPath,
65
+ repairedOrphanAssetIds,
66
+ updatedHashAssetIds,
67
+ staleProposalIds,
68
+ };
69
+ }
70
+ }
71
+ export function createRepairAndBackupService(database) {
72
+ return new RepairAndBackupService(database);
73
+ }
@@ -0,0 +1,46 @@
1
+ import type { StateDatabase } from "./db/index.js";
2
+ import type { NewPolicyRecord, PolicyRecord } from "./db/schema/index.js";
3
+ import { type ActivityLogWrite, type ObservationWrite, type DailyReportInput, type CuratedMemoryWrite, type AssetWriteAck } from "./services/daily-log-pipeline.js";
4
+ import { type CurationInputQuery, type CurationInputBundle } from "./services/quiet-input-loader.js";
5
+ import type { PersonaCandidate, SceneContext } from "../guidance/types.js";
6
+ type PolicyState = Omit<NewPolicyRecord, "updatedAt">;
7
+ export interface MemoryReadPort {
8
+ loadQuietInputs(query: CurationInputQuery): Promise<CurationInputBundle>;
9
+ loadPolicy(platformId: string): Promise<PolicyRecord | undefined>;
10
+ loadPersonaCandidates(sceneContext: SceneContext): Promise<PersonaCandidate[]>;
11
+ }
12
+ export interface MemoryWritePort {
13
+ appendActivityLog(entry: ActivityLogWrite): Promise<AssetWriteAck>;
14
+ appendObservation(entry: ObservationWrite): Promise<AssetWriteAck>;
15
+ generateDailyReport(input: DailyReportInput): Promise<AssetWriteAck>;
16
+ upsertCuratedMemory(item: CuratedMemoryWrite): Promise<AssetWriteAck>;
17
+ savePolicy(input: PolicyState): Promise<void>;
18
+ }
19
+ export interface CredentialContextPort {
20
+ loadCredentialContext(platformId: string): Promise<unknown>;
21
+ saveCredentialContext(input: unknown): Promise<void>;
22
+ }
23
+ export interface IntentCommitPort {
24
+ loadIntentCommitRecord(intentId: string): Promise<unknown>;
25
+ }
26
+ export interface ProvenancePort {
27
+ explainProvenance(assetId: string): Promise<unknown>;
28
+ }
29
+ export interface StateAPI {
30
+ readonly read: MemoryReadPort;
31
+ readonly write: MemoryWritePort;
32
+ readonly credentials: CredentialContextPort;
33
+ readonly commits: IntentCommitPort;
34
+ readonly provenance: ProvenancePort;
35
+ }
36
+ export declare class DefaultStateAPI implements StateAPI {
37
+ private readonly database;
38
+ readonly read: MemoryReadPort;
39
+ readonly write: MemoryWritePort;
40
+ readonly credentials: CredentialContextPort;
41
+ readonly commits: IntentCommitPort;
42
+ readonly provenance: ProvenancePort;
43
+ constructor(database: StateDatabase);
44
+ }
45
+ export declare function createStateAPI(database: StateDatabase): StateAPI;
46
+ export {};
@@ -0,0 +1,73 @@
1
+ import { AssetRepository } from "./repositories/asset-repository.js";
2
+ import { CredentialRepository } from "./repositories/credential-repository.js";
3
+ import { ProposalRepository } from "./repositories/proposal-repository.js";
4
+ import { ProvenanceRepository } from "./repositories/provenance-repository.js";
5
+ import { IntentCommitRepository } from "./repositories/intent-commit-repository.js";
6
+ import { PolicyRepository } from "./repositories/policy-repository.js";
7
+ import { createDailyLogPipeline, } from "./services/daily-log-pipeline.js";
8
+ import { createQuietInputLoader, } from "./services/quiet-input-loader.js";
9
+ import { createPersonaCandidateLoader } from "./services/persona-candidate-loader.js";
10
+ export class DefaultStateAPI {
11
+ database;
12
+ read;
13
+ write;
14
+ credentials;
15
+ commits;
16
+ provenance;
17
+ constructor(database) {
18
+ this.database = database;
19
+ const assetRepository = new AssetRepository(database);
20
+ const credentialRepository = new CredentialRepository(database);
21
+ const proposalRepository = new ProposalRepository(database);
22
+ const provenanceRepository = new ProvenanceRepository(database);
23
+ const intentCommitRepository = new IntentCommitRepository(database);
24
+ const policyRepository = new PolicyRepository(database);
25
+ const dailyLogPipeline = createDailyLogPipeline(assetRepository, provenanceRepository);
26
+ const quietInputLoader = createQuietInputLoader(assetRepository);
27
+ const personaCandidateLoader = createPersonaCandidateLoader();
28
+ this.read = {
29
+ loadQuietInputs: (query) => quietInputLoader.loadQuietInputs(query),
30
+ loadPolicy: (platformId) => policyRepository.findByPlatformId(platformId),
31
+ loadPersonaCandidates: (sceneContext) => personaCandidateLoader.loadPersonaCandidates(sceneContext),
32
+ };
33
+ this.write = {
34
+ appendActivityLog: (entry) => dailyLogPipeline.appendActivityLog(entry),
35
+ appendObservation: (entry) => dailyLogPipeline.appendObservation(entry),
36
+ generateDailyReport: (input) => dailyLogPipeline.generateDailyReport(input),
37
+ upsertCuratedMemory: (item) => dailyLogPipeline.upsertCuratedMemory(item),
38
+ savePolicy: async (policy) => {
39
+ await policyRepository.upsert({
40
+ platformId: policy.platformId,
41
+ socialDailyLimit: policy.socialDailyLimit,
42
+ quietEnabled: policy.quietEnabled,
43
+ updatedAt: new Date().toISOString(),
44
+ });
45
+ },
46
+ };
47
+ this.credentials = {
48
+ loadCredentialContext: async (platformId) => {
49
+ return credentialRepository.findByPlatformId(platformId);
50
+ },
51
+ saveCredentialContext: async (input) => {
52
+ const ctx = input;
53
+ await credentialRepository.upsert({
54
+ ...ctx,
55
+ updatedAt: ctx.updatedAt ?? new Date().toISOString(),
56
+ });
57
+ },
58
+ };
59
+ this.commits = {
60
+ loadIntentCommitRecord: async (intentId) => {
61
+ return intentCommitRepository.findByIntentId(intentId);
62
+ },
63
+ };
64
+ this.provenance = {
65
+ explainProvenance: async (assetId) => {
66
+ return provenanceRepository.traceAsset(assetId);
67
+ },
68
+ };
69
+ }
70
+ }
71
+ export function createStateAPI(database) {
72
+ return new DefaultStateAPI(database);
73
+ }