@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,62 @@
1
+ export declare const ASSET_CONFIG: {
2
+ readonly workspaceRoot: "./workspace";
3
+ readonly journalsDir: "memory";
4
+ readonly reportsDir: "memory/reports";
5
+ readonly curatedDir: "memory/curated";
6
+ readonly proposalsDir: "memory/proposals";
7
+ readonly anchorAssets: readonly ["SOUL.md", "USER.md", "IDENTITY.md", "MEMORY.md", "AGENTS.md"];
8
+ };
9
+ export declare function ensureDirectory(dirPath: string): Promise<void>;
10
+ export declare function resolveDailyJournalPath(timestamp: string): string;
11
+ export declare function resolveDailyReportPath(day: string): string;
12
+ export declare function resolveCuratedPath(id: string): string;
13
+ export declare function resolveProposalPath(proposalId: string): string;
14
+ export declare function resolveAnchorPath(assetName: string): string;
15
+ export declare function writeCanonicalArtifact(filePath: string, content: string): Promise<void>;
16
+ export declare function appendLine(filePath: string, line: string): Promise<void>;
17
+ export declare function readText(filePath: string): Promise<string>;
18
+ export declare function hashFile(filePath: string): Promise<string>;
19
+ export declare function fileExists(filePath: string): Promise<boolean>;
20
+ export declare function buildJournalAssetId(filePath: string): string;
21
+ export declare function buildReportAssetId(day: string): string;
22
+ export declare function serializeActivityLog(entry: {
23
+ id: string;
24
+ timestamp: string;
25
+ platform?: string;
26
+ kind: string;
27
+ content: string;
28
+ sourceRefs: string[];
29
+ }): string;
30
+ export declare function serializeObservation(entry: {
31
+ id: string;
32
+ timestamp: string;
33
+ summary: string;
34
+ mood?: string;
35
+ sourceRefs: string[];
36
+ }): string;
37
+ export declare function renderDailyReport(input: {
38
+ day: string;
39
+ summary: string;
40
+ highlights: string[];
41
+ activityRefs: string[];
42
+ observationRefs: string[];
43
+ }): string;
44
+ export declare function renderCuratedMemory(item: {
45
+ id: string;
46
+ title: string;
47
+ summary: string;
48
+ confidence: number;
49
+ ttlClass: string;
50
+ sourceRefs: string[];
51
+ }): string;
52
+ export declare function renderProposal(proposal: {
53
+ id: string;
54
+ targetAssetId: string;
55
+ proposedDiff: string;
56
+ reason: string;
57
+ supportingSources: string[];
58
+ status: string;
59
+ }): string;
60
+ export declare function applyDiff(original: string, diff: string): string;
61
+ export declare function buildCuratedAssetId(id: string): string;
62
+ export declare function buildAnchorAssetId(name: string): string;
@@ -0,0 +1,160 @@
1
+ import * as fs from "fs/promises";
2
+ import * as path from "path";
3
+ import * as crypto from "crypto";
4
+ export const ASSET_CONFIG = {
5
+ workspaceRoot: "./workspace",
6
+ journalsDir: "memory",
7
+ reportsDir: "memory/reports",
8
+ curatedDir: "memory/curated",
9
+ proposalsDir: "memory/proposals",
10
+ anchorAssets: ["SOUL.md", "USER.md", "IDENTITY.md", "MEMORY.md", "AGENTS.md"],
11
+ };
12
+ export async function ensureDirectory(dirPath) {
13
+ await fs.mkdir(dirPath, { recursive: true });
14
+ }
15
+ export function resolveDailyJournalPath(timestamp) {
16
+ const date = timestamp.split("T")[0];
17
+ return path.join(ASSET_CONFIG.workspaceRoot, ASSET_CONFIG.journalsDir, `${date}.md`);
18
+ }
19
+ export function resolveDailyReportPath(day) {
20
+ return path.join(ASSET_CONFIG.workspaceRoot, ASSET_CONFIG.reportsDir, `${day}.md`);
21
+ }
22
+ export function resolveCuratedPath(id) {
23
+ return path.join(ASSET_CONFIG.workspaceRoot, ASSET_CONFIG.curatedDir, `${id}.md`);
24
+ }
25
+ export function resolveProposalPath(proposalId) {
26
+ return path.join(ASSET_CONFIG.workspaceRoot, ASSET_CONFIG.proposalsDir, `${proposalId}.md`);
27
+ }
28
+ export function resolveAnchorPath(assetName) {
29
+ return path.join(ASSET_CONFIG.workspaceRoot, assetName);
30
+ }
31
+ export async function writeCanonicalArtifact(filePath, content) {
32
+ await ensureDirectory(path.dirname(filePath));
33
+ const tempPath = `${filePath}.tmp`;
34
+ await fs.writeFile(tempPath, content, "utf-8");
35
+ await fs.rename(tempPath, filePath);
36
+ }
37
+ export async function appendLine(filePath, line) {
38
+ await ensureDirectory(path.dirname(filePath));
39
+ const exists = await fileExists(filePath);
40
+ const prefix = exists ? "\n" : "";
41
+ await fs.appendFile(filePath, `${prefix}${line}`, "utf-8");
42
+ }
43
+ export async function readText(filePath) {
44
+ try {
45
+ return await fs.readFile(filePath, "utf-8");
46
+ }
47
+ catch {
48
+ return "";
49
+ }
50
+ }
51
+ export async function hashFile(filePath) {
52
+ try {
53
+ const content = await fs.readFile(filePath);
54
+ return crypto.createHash("sha256").update(content).digest("hex");
55
+ }
56
+ catch {
57
+ return "";
58
+ }
59
+ }
60
+ export async function fileExists(filePath) {
61
+ try {
62
+ await fs.access(filePath);
63
+ return true;
64
+ }
65
+ catch {
66
+ return false;
67
+ }
68
+ }
69
+ export function buildJournalAssetId(filePath) {
70
+ return `journal:${path.basename(filePath, ".md")}`;
71
+ }
72
+ export function buildReportAssetId(day) {
73
+ return `report:${day}`;
74
+ }
75
+ export function serializeActivityLog(entry) {
76
+ const meta = entry.platform ? `[${entry.platform}] ` : "";
77
+ const sources = entry.sourceRefs.length > 0 ? ` (refs: ${entry.sourceRefs.join(", ")})` : "";
78
+ return `- [${entry.timestamp}] ${meta}${entry.kind}: ${entry.content}${sources}`;
79
+ }
80
+ export function serializeObservation(entry) {
81
+ const mood = entry.mood ? ` (${entry.mood})` : "";
82
+ const sources = entry.sourceRefs.length > 0 ? ` [${entry.sourceRefs.join(", ")}]` : "";
83
+ return `- [${entry.timestamp}] ${entry.summary}${mood}${sources}`;
84
+ }
85
+ export function renderDailyReport(input) {
86
+ const lines = [
87
+ `# Daily Report — ${input.day}`,
88
+ "",
89
+ "## Summary",
90
+ input.summary,
91
+ "",
92
+ "## Highlights",
93
+ ];
94
+ for (const h of input.highlights) {
95
+ lines.push(`- ${h}`);
96
+ }
97
+ lines.push("");
98
+ lines.push("## Sources");
99
+ lines.push(`- Activities: ${input.activityRefs.join(", ")}`);
100
+ lines.push(`- Observations: ${input.observationRefs.join(", ")}`);
101
+ return lines.join("\n");
102
+ }
103
+ export function renderCuratedMemory(item) {
104
+ const lines = [
105
+ `# ${item.title}`,
106
+ "",
107
+ item.summary,
108
+ "",
109
+ `**Confidence**: ${item.confidence.toFixed(2)} | **TTL**: ${item.ttlClass}`,
110
+ "",
111
+ "## Sources",
112
+ ];
113
+ for (const ref of item.sourceRefs) {
114
+ lines.push(`- ${ref}`);
115
+ }
116
+ return lines.join("\n");
117
+ }
118
+ export function renderProposal(proposal) {
119
+ const lines = [
120
+ `# Anchor Proposal — ${proposal.id}`,
121
+ "",
122
+ `**Target**: ${proposal.targetAssetId}`,
123
+ `**Status**: ${proposal.status}`,
124
+ "",
125
+ "## Reason",
126
+ proposal.reason,
127
+ "",
128
+ "## Diff",
129
+ "```diff",
130
+ proposal.proposedDiff,
131
+ "```",
132
+ "",
133
+ "## Supporting Sources",
134
+ ];
135
+ for (const src of proposal.supportingSources) {
136
+ lines.push(`- ${src}`);
137
+ }
138
+ return lines.join("\n");
139
+ }
140
+ export function applyDiff(original, diff) {
141
+ const lines = original.split("\n");
142
+ const diffLines = diff.split("\n").filter((l) => l.startsWith("+") || l.startsWith("-")).map((l) => l.substring(1));
143
+ for (const d of diffLines) {
144
+ if (d.startsWith("+")) {
145
+ lines.push(d.substring(1));
146
+ }
147
+ else if (d.startsWith("-")) {
148
+ const idx = lines.indexOf(d.substring(1));
149
+ if (idx !== -1)
150
+ lines.splice(idx, 1);
151
+ }
152
+ }
153
+ return lines.join("\n");
154
+ }
155
+ export function buildCuratedAssetId(id) {
156
+ return `curated:${id}`;
157
+ }
158
+ export function buildAnchorAssetId(name) {
159
+ return `anchor:${name}`;
160
+ }
@@ -0,0 +1,26 @@
1
+ import type { ActivityLogWrite, ObservationWrite, DailyReportInput, CuratedMemoryWrite, AnchorWriteProposal } from "./types.js";
2
+ import type { StateDatabase } from "../../db/index.js";
3
+ export interface WorkspaceArtifactStore {
4
+ appendActivityLog(entry: ActivityLogWrite): Promise<{
5
+ assetPath: string;
6
+ hash: string;
7
+ }>;
8
+ appendObservation(entry: ObservationWrite): Promise<{
9
+ assetPath: string;
10
+ hash: string;
11
+ }>;
12
+ generateDailyReport(input: DailyReportInput): Promise<{
13
+ assetPath: string;
14
+ hash: string;
15
+ }>;
16
+ upsertCuratedMemory(candidate: CuratedMemoryWrite): Promise<{
17
+ assetPath: string;
18
+ hash: string;
19
+ }>;
20
+ proposeAnchorWrite(proposal: AnchorWriteProposal): Promise<{
21
+ proposalPath: string;
22
+ status: string;
23
+ }>;
24
+ loadAnchorSnapshot(): Promise<Record<string, string>>;
25
+ }
26
+ export declare function createWorkspaceArtifactStore(db: StateDatabase["db"]): WorkspaceArtifactStore;
@@ -0,0 +1,153 @@
1
+ import { resolveDailyJournalPath, resolveDailyReportPath, resolveCuratedPath, resolveProposalPath, resolveAnchorPath, appendLine, readText, hashFile, writeCanonicalArtifact, buildJournalAssetId, buildReportAssetId, buildCuratedAssetId, ASSET_CONFIG } from "./paths.js";
2
+ import { assetRegistry } from "../../db/schema/index.js";
3
+ export function createWorkspaceArtifactStore(db) {
4
+ const indexStore = {
5
+ async upsertAsset(record) {
6
+ await db.insert(assetRegistry).values(record).onConflictDoUpdate({
7
+ target: assetRegistry.id,
8
+ set: record,
9
+ });
10
+ },
11
+ async findSimilarCuratedMemory(candidate) {
12
+ return undefined;
13
+ },
14
+ async upsertCurated(_candidate) { },
15
+ async registerProposal(_proposal) { },
16
+ async markProposalApplied(_proposalId, _afterHash) { },
17
+ async bumpAssetVersion(_assetId, _hash) { },
18
+ };
19
+ return {
20
+ async appendActivityLog(entry) {
21
+ const journalPath = resolveDailyJournalPath(entry.timestamp);
22
+ const serialized = `- [${entry.timestamp}] ${entry.platform ? `[${entry.platform}] ` : ""}${entry.kind}: ${entry.content}${entry.sourceRefs.length > 0 ? ` (refs: ${entry.sourceRefs.join(", ")})` : ""}`;
23
+ await appendLine(journalPath, serialized);
24
+ const hashVal = await hashFile(journalPath);
25
+ const assetRecord = {
26
+ id: buildJournalAssetId(journalPath),
27
+ kind: "daily_journal",
28
+ path: journalPath,
29
+ hash: hashVal,
30
+ version: 1,
31
+ layer: "daily_journal",
32
+ lastIndexedAt: new Date().toISOString(),
33
+ };
34
+ await indexStore.upsertAsset(assetRecord);
35
+ return { assetPath: journalPath, hash: hashVal };
36
+ },
37
+ async appendObservation(entry) {
38
+ const journalPath = resolveDailyJournalPath(entry.timestamp);
39
+ const serialized = `- [${entry.timestamp}] ${entry.summary}${entry.mood ? ` (${entry.mood})` : ""}${entry.sourceRefs.length > 0 ? ` [${entry.sourceRefs.join(", ")}]` : ""}`;
40
+ await appendLine(journalPath, serialized);
41
+ const hashVal = await hashFile(journalPath);
42
+ const assetRecord = {
43
+ id: buildJournalAssetId(journalPath),
44
+ kind: "daily_journal",
45
+ path: journalPath,
46
+ hash: hashVal,
47
+ version: 1,
48
+ layer: "daily_journal",
49
+ lastIndexedAt: new Date().toISOString(),
50
+ };
51
+ await indexStore.upsertAsset(assetRecord);
52
+ return { assetPath: journalPath, hash: hashVal };
53
+ },
54
+ async generateDailyReport(input) {
55
+ const reportPath = resolveDailyReportPath(input.day);
56
+ const lines = [
57
+ `# Daily Report — ${input.day}`,
58
+ "",
59
+ "## Summary",
60
+ input.summary,
61
+ "",
62
+ "## Highlights",
63
+ ];
64
+ for (const h of input.highlights)
65
+ lines.push(`- ${h}`);
66
+ lines.push("");
67
+ lines.push("## Sources");
68
+ lines.push(`- Activities: ${input.activityRefs.join(", ")}`);
69
+ lines.push(`- Observations: ${input.observationRefs.join(", ")}`);
70
+ const content = lines.join("\n");
71
+ await writeCanonicalArtifact(reportPath, content);
72
+ const hashVal = await hashFile(reportPath);
73
+ const assetRecord = {
74
+ id: buildReportAssetId(input.day),
75
+ kind: "daily_report",
76
+ path: reportPath,
77
+ hash: hashVal,
78
+ version: 1,
79
+ layer: "daily_journal",
80
+ lastIndexedAt: new Date().toISOString(),
81
+ };
82
+ await indexStore.upsertAsset(assetRecord);
83
+ return { assetPath: reportPath, hash: hashVal };
84
+ },
85
+ async upsertCuratedMemory(candidate) {
86
+ const curatedPath = resolveCuratedPath(candidate.id);
87
+ const lines = [
88
+ `# ${candidate.title}`,
89
+ "",
90
+ candidate.summary,
91
+ "",
92
+ `**Confidence**: ${candidate.confidence.toFixed(2)} | **TTL**: ${candidate.ttlClass}`,
93
+ "",
94
+ "## Sources",
95
+ ];
96
+ for (const ref of candidate.sourceRefs)
97
+ lines.push(`- ${ref}`);
98
+ const content = lines.join("\n");
99
+ await writeCanonicalArtifact(curatedPath, content);
100
+ const hashVal = await hashFile(curatedPath);
101
+ const assetRecord = {
102
+ id: buildCuratedAssetId(candidate.id),
103
+ kind: "curated_memory",
104
+ path: curatedPath,
105
+ hash: hashVal,
106
+ version: 1,
107
+ layer: "curated_memory",
108
+ lastIndexedAt: new Date().toISOString(),
109
+ };
110
+ await indexStore.upsertAsset(assetRecord);
111
+ return { assetPath: curatedPath, hash: hashVal };
112
+ },
113
+ async proposeAnchorWrite(proposal) {
114
+ if (!proposal.supportingSources.length) {
115
+ throw new Error("anchor_proposal_requires_sources");
116
+ }
117
+ if (proposal.confidence < 0.8) {
118
+ throw new Error("anchor_proposal_confidence_too_low");
119
+ }
120
+ const proposalPath = resolveProposalPath(proposal.id);
121
+ const lines = [
122
+ `# Anchor Proposal — ${proposal.id}`,
123
+ "",
124
+ `**Target**: ${proposal.targetAssetId}`,
125
+ `**Status**: ${proposal.status}`,
126
+ "",
127
+ "## Reason",
128
+ proposal.reason,
129
+ "",
130
+ "## Diff",
131
+ "```diff",
132
+ proposal.proposedDiff,
133
+ "```",
134
+ "",
135
+ "## Supporting Sources",
136
+ ];
137
+ for (const src of proposal.supportingSources)
138
+ lines.push(`- ${src}`);
139
+ const content = lines.join("\n");
140
+ await writeCanonicalArtifact(proposalPath, content);
141
+ await indexStore.registerProposal({ ...proposal, status: "draft" });
142
+ return { proposalPath, status: proposal.status };
143
+ },
144
+ async loadAnchorSnapshot() {
145
+ const snapshot = {};
146
+ for (const name of ASSET_CONFIG.anchorAssets) {
147
+ const anchorPath = resolveAnchorPath(name);
148
+ snapshot[name] = await readText(anchorPath);
149
+ }
150
+ return snapshot;
151
+ },
152
+ };
153
+ }
@@ -0,0 +1,45 @@
1
+ export interface ActivityLogWrite {
2
+ id: string;
3
+ timestamp: string;
4
+ platform?: string;
5
+ kind: "browse" | "action" | "failure" | "task" | "heartbeat";
6
+ content: string;
7
+ sourceRefs: string[];
8
+ }
9
+ export interface ObservationWrite {
10
+ id: string;
11
+ timestamp: string;
12
+ summary: string;
13
+ mood?: string;
14
+ sourceRefs: string[];
15
+ }
16
+ export interface DailyReportInput {
17
+ day: string;
18
+ activityRefs: string[];
19
+ observationRefs: string[];
20
+ reflectionSummary: string;
21
+ summary: string;
22
+ highlights: string[];
23
+ }
24
+ export interface CuratedMemoryWrite {
25
+ id: string;
26
+ title: string;
27
+ summary: string;
28
+ confidence: number;
29
+ ttlClass: "short" | "medium" | "long";
30
+ sourceRefs: string[];
31
+ supersedes?: string[];
32
+ }
33
+ export interface AnchorWriteProposal {
34
+ id: string;
35
+ targetAssetId: string;
36
+ beforeHash?: string;
37
+ afterHash?: string;
38
+ status: "draft" | "requires_review" | "approved" | "rejected" | "applied" | "conflicted";
39
+ proposedDiff: string;
40
+ reason: string;
41
+ supportingSources: string[];
42
+ confidence: number;
43
+ riskFlags: string[];
44
+ createdAt: string;
45
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,8 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ import { type AssetRegistryRecord, type NewAssetRegistryRecord } from "../db/schema/index.js";
3
+ export declare class AssetRepository {
4
+ private readonly database;
5
+ constructor(database: StateDatabase);
6
+ upsert(record: NewAssetRegistryRecord): Promise<void>;
7
+ findById(id: string): Promise<AssetRegistryRecord | undefined>;
8
+ }
@@ -0,0 +1,19 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { assetRegistry } from "../db/schema/index.js";
3
+ export class AssetRepository {
4
+ database;
5
+ constructor(database) {
6
+ this.database = database;
7
+ }
8
+ async upsert(record) {
9
+ await this.database.db.insert(assetRegistry).values(record).onConflictDoUpdate({
10
+ target: assetRegistry.id,
11
+ set: record,
12
+ });
13
+ }
14
+ async findById(id) {
15
+ return this.database.db.query.assetRegistry.findFirst({
16
+ where: eq(assetRegistry.id, id),
17
+ });
18
+ }
19
+ }
@@ -0,0 +1,8 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ import { type CredentialRecord, type NewCredentialRecord } from "../db/schema/index.js";
3
+ export declare class CredentialRepository {
4
+ private readonly database;
5
+ constructor(database: StateDatabase);
6
+ upsert(record: NewCredentialRecord): Promise<void>;
7
+ findByPlatformId(platformId: string): Promise<CredentialRecord | undefined>;
8
+ }
@@ -0,0 +1,19 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { credentialRecords } from "../db/schema/index.js";
3
+ export class CredentialRepository {
4
+ database;
5
+ constructor(database) {
6
+ this.database = database;
7
+ }
8
+ async upsert(record) {
9
+ await this.database.db.insert(credentialRecords).values(record).onConflictDoUpdate({
10
+ target: credentialRecords.platformId,
11
+ set: record,
12
+ });
13
+ }
14
+ async findByPlatformId(platformId) {
15
+ return this.database.db.query.credentialRecords.findFirst({
16
+ where: eq(credentialRecords.platformId, platformId),
17
+ });
18
+ }
19
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./asset-repository.js";
2
+ export * from "./credential-repository.js";
3
+ export * from "./intent-commit-repository.js";
4
+ export * from "./policy-repository.js";
5
+ export * from "./proposal-repository.js";
6
+ export * from "./provenance-repository.js";
@@ -0,0 +1,6 @@
1
+ export * from "./asset-repository.js";
2
+ export * from "./credential-repository.js";
3
+ export * from "./intent-commit-repository.js";
4
+ export * from "./policy-repository.js";
5
+ export * from "./proposal-repository.js";
6
+ export * from "./provenance-repository.js";
@@ -0,0 +1,10 @@
1
+ import type { IntentCommitRecord } from "../../shared/types/index.js";
2
+ import type { StateDatabase } from "../db/index.js";
3
+ import { type NewIntentCommitDbRecord } from "../db/schema/index.js";
4
+ export declare class IntentCommitRepository {
5
+ private readonly database;
6
+ constructor(database: StateDatabase);
7
+ create(record: NewIntentCommitDbRecord): Promise<void>;
8
+ update(record: NewIntentCommitDbRecord): Promise<void>;
9
+ findByIntentId(intentId: string): Promise<IntentCommitRecord | undefined>;
10
+ }
@@ -0,0 +1,35 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { intentCommitRecords } from "../db/schema/index.js";
3
+ function mapToDomain(record) {
4
+ return {
5
+ id: record.id,
6
+ intentId: record.intentId,
7
+ decisionId: record.decisionId,
8
+ checkpointId: record.checkpointId ?? undefined,
9
+ state: record.state,
10
+ outcomeRef: record.outcomeRef ?? undefined,
11
+ metadata: record.metadataJson ? JSON.parse(record.metadataJson) : undefined,
12
+ updatedAt: record.updatedAt,
13
+ };
14
+ }
15
+ export class IntentCommitRepository {
16
+ database;
17
+ constructor(database) {
18
+ this.database = database;
19
+ }
20
+ async create(record) {
21
+ await this.database.db.insert(intentCommitRecords).values(record);
22
+ }
23
+ async update(record) {
24
+ await this.database.db.insert(intentCommitRecords).values(record).onConflictDoUpdate({
25
+ target: intentCommitRecords.id,
26
+ set: record,
27
+ });
28
+ }
29
+ async findByIntentId(intentId) {
30
+ const record = await this.database.db.query.intentCommitRecords.findFirst({
31
+ where: eq(intentCommitRecords.intentId, intentId),
32
+ });
33
+ return record ? mapToDomain(record) : undefined;
34
+ }
35
+ }
@@ -0,0 +1,8 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ import { type NewPolicyRecord, type PolicyRecord } from "../db/schema/index.js";
3
+ export declare class PolicyRepository {
4
+ private readonly database;
5
+ constructor(database: StateDatabase);
6
+ upsert(record: NewPolicyRecord): Promise<void>;
7
+ findByPlatformId(platformId: string): Promise<PolicyRecord | undefined>;
8
+ }
@@ -0,0 +1,19 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { policyRecords } from "../db/schema/index.js";
3
+ export class PolicyRepository {
4
+ database;
5
+ constructor(database) {
6
+ this.database = database;
7
+ }
8
+ async upsert(record) {
9
+ await this.database.db.insert(policyRecords).values(record).onConflictDoUpdate({
10
+ target: policyRecords.platformId,
11
+ set: record,
12
+ });
13
+ }
14
+ async findByPlatformId(platformId) {
15
+ return this.database.db.query.policyRecords.findFirst({
16
+ where: eq(policyRecords.platformId, platformId),
17
+ });
18
+ }
19
+ }
@@ -0,0 +1,9 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ import { type NewProposalRecord, type ProposalRecord } from "../db/schema/index.js";
3
+ export declare class ProposalRepository {
4
+ private readonly database;
5
+ constructor(database: StateDatabase);
6
+ create(record: NewProposalRecord): Promise<void>;
7
+ findById(id: string): Promise<ProposalRecord | undefined>;
8
+ updateStatus(id: string, status: string, afterHash?: string): Promise<void>;
9
+ }
@@ -0,0 +1,26 @@
1
+ import { eq } from "drizzle-orm";
2
+ import { proposalRecords } from "../db/schema/index.js";
3
+ export class ProposalRepository {
4
+ database;
5
+ constructor(database) {
6
+ this.database = database;
7
+ }
8
+ async create(record) {
9
+ await this.database.db.insert(proposalRecords).values(record);
10
+ }
11
+ async findById(id) {
12
+ return this.database.db.query.proposalRecords.findFirst({
13
+ where: eq(proposalRecords.id, id),
14
+ });
15
+ }
16
+ async updateStatus(id, status, afterHash) {
17
+ await this.database.db
18
+ .update(proposalRecords)
19
+ .set({
20
+ status,
21
+ afterHash: afterHash ?? undefined,
22
+ appliedAt: status === "applied" ? new Date().toISOString() : undefined,
23
+ })
24
+ .where(eq(proposalRecords.id, id));
25
+ }
26
+ }
@@ -0,0 +1,20 @@
1
+ import type { StateDatabase } from "../db/index.js";
2
+ import { type NewProvenanceEdgeRecord, type ProvenanceEdgeRecord } from "../db/schema/index.js";
3
+ export declare class ProvenanceRepository {
4
+ private readonly database;
5
+ constructor(database: StateDatabase);
6
+ create(record: NewProvenanceEdgeRecord): Promise<void>;
7
+ listByTarget(toId: string): Promise<ProvenanceEdgeRecord[]>;
8
+ linkEntrySources(entryId: string, sourceRefs: string[]): Promise<void>;
9
+ traceAsset(assetId: string): Promise<{
10
+ assetId: string;
11
+ upstreamSources: string[];
12
+ proposalIds: string[];
13
+ applyIds: string[];
14
+ }>;
15
+ recordApply(proposalId: string, assetId: string, info: {
16
+ beforeHash: string;
17
+ afterHash: string;
18
+ diff: string;
19
+ }): Promise<void>;
20
+ }