@amoree-code/ocean 1.7.0 → 1.9.0
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.
- package/README.md +3 -1
- package/dist/infrastructure/process/service.js +22 -1
- package/dist/interfaces/cli/command-registry.js +8 -1
- package/dist/interfaces/cli/daily-command.js +7 -73
- package/dist/interfaces/cli/harvest-command.js +58 -0
- package/dist/interfaces/cli/help-command.js +10 -2
- package/dist/interfaces/cli/rhythm-command.js +81 -0
- package/dist/interfaces/cli/session-facts-command.js +1 -1
- package/node_modules/@ocean/brain/dist/memory/brain-dump.js +55 -0
- package/node_modules/@ocean/brain/dist/memory/session-facts.js +44 -3
- package/node_modules/@ocean/brain/package.json +1 -1
- package/node_modules/@ocean/context/package.json +1 -1
- package/node_modules/@ocean/core/package.json +1 -1
- package/node_modules/@ocean/loop/dist/hooks/desktop-facts.js +21 -1
- package/node_modules/@ocean/loop/dist/hooks/session-facts-hook.js +19 -1
- package/node_modules/@ocean/loop/dist/sessions/session-closeout.js +2 -9
- package/node_modules/@ocean/loop/package.json +1 -1
- package/node_modules/@ocean/market/package.json +1 -1
- package/node_modules/@ocean/services/dist/brief/brief.js +5 -1
- package/node_modules/@ocean/services/dist/day/day.js +203 -0
- package/node_modules/@ocean/services/dist/day/note.js +78 -0
- package/node_modules/@ocean/services/dist/distill/distill.js +1 -1
- package/node_modules/@ocean/services/dist/harvest/harvest.js +506 -0
- package/node_modules/@ocean/services/package.json +1 -1
- package/ocean-marketplace.json +66 -30
- package/package.json +7 -7
- package/skills/core/daily-harvest/SKILL.md +78 -0
- package/skills/core/memory-review/SKILL.md +53 -0
- package/skills/index.json +12 -0
- package/templates/workspace/06-templates/daily.md +0 -5
|
@@ -0,0 +1,506 @@
|
|
|
1
|
+
import { copyFile, mkdir, readdir, readFile, rename, rm, } from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { syncMemoryIndexes } from "@ocean/brain/memory/index-sync.js";
|
|
4
|
+
import { containsKnownSecret } from "@ocean/core/domain/redaction/redaction.js";
|
|
5
|
+
import { atomicWrite, parseFrontmatter, withFileLock, } from "@ocean/core/shared/fs-utils.js";
|
|
6
|
+
import { DAILY_DIR, INBOX_DIR, KNOWLEDGE_DIR, oceanPath, SYSTEM_DIR, } from "@ocean/core/shared/paths.js";
|
|
7
|
+
import { keepTicks, noteFile, putBlock, readBlock } from "../day/note.js";
|
|
8
|
+
import { section } from "../distill/distill.js";
|
|
9
|
+
// The daily harvest (T-314): every session of a day, from every AI client, becomes one summary in
|
|
10
|
+
// that day's note, and what the sessions decided, fixed and learned is filed into 05-knowledge on
|
|
11
|
+
// its own, with no review step (owner's decision, 2026-11-16). Safety instead of review: a record
|
|
12
|
+
// that already says the same thing is strengthened, not duplicated; every write is in a ledger
|
|
13
|
+
// with the record's previous version, and `ocean harvest undo <date>` takes a day back. Nothing
|
|
14
|
+
// here calls a model: the judgement work (legacy records, imports, corrections that become rules)
|
|
15
|
+
// is the daily-harvest skill's.
|
|
16
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
17
|
+
const MAX_SESSION_MS = 8 * 60 * 60 * 1000;
|
|
18
|
+
const MIN_ITEM = 25;
|
|
19
|
+
const SAME_TITLE = 0.6;
|
|
20
|
+
// Where each kind of harvested item is filed, and the record type it carries.
|
|
21
|
+
const KINDS = {
|
|
22
|
+
decision: { heading: "Decisions", folder: "decisions" },
|
|
23
|
+
solution: { heading: "Problems → fixes", folder: "solutions" },
|
|
24
|
+
discovery: { heading: "Learned", folder: "discoveries" },
|
|
25
|
+
};
|
|
26
|
+
const relativeOf = (file) => path.relative(oceanPath(), file).split(path.sep).join("/");
|
|
27
|
+
const sessionsRoot = () => oceanPath(DAILY_DIR, "sessions");
|
|
28
|
+
const stateDir = (...parts) => oceanPath(SYSTEM_DIR, "state", "harvest", ...parts);
|
|
29
|
+
async function markdownIn(dir, skipArchive = true) {
|
|
30
|
+
const entries = await readdir(dir, { withFileTypes: true }).catch(() => []);
|
|
31
|
+
const files = [];
|
|
32
|
+
for (const entry of entries) {
|
|
33
|
+
if (entry.name.startsWith("."))
|
|
34
|
+
continue;
|
|
35
|
+
if (skipArchive && entry.name === "archive")
|
|
36
|
+
continue;
|
|
37
|
+
const file = path.join(dir, entry.name);
|
|
38
|
+
if (entry.isDirectory())
|
|
39
|
+
files.push(...(await markdownIn(file, skipArchive)));
|
|
40
|
+
else if (entry.name.endsWith(".md"))
|
|
41
|
+
files.push(file);
|
|
42
|
+
}
|
|
43
|
+
return files.sort();
|
|
44
|
+
}
|
|
45
|
+
// A title made from a client's raw first turn carries its tags (`<command-message>…`,
|
|
46
|
+
// `<ide_opened_file>…`); what is left after them, or the project, is the title.
|
|
47
|
+
export function cleanTitle(raw, fallback) {
|
|
48
|
+
const text = raw
|
|
49
|
+
.replace(/<([\w-]+)>[\s\S]*?<\/\1>/g, (whole, tag) => /^(command-name|command-args)$/.test(tag)
|
|
50
|
+
? whole.replace(/<[^>]+>/g, " ")
|
|
51
|
+
: " ")
|
|
52
|
+
.replace(/<[^>]+>/g, " ")
|
|
53
|
+
.replace(/\s+/g, " ")
|
|
54
|
+
.trim();
|
|
55
|
+
return (text || fallback).slice(0, 120);
|
|
56
|
+
}
|
|
57
|
+
export async function daySessions(date) {
|
|
58
|
+
const sessions = [];
|
|
59
|
+
for (const file of await markdownIn(path.join(sessionsRoot(), date.slice(0, 7)))) {
|
|
60
|
+
const text = (await readFile(file, "utf8")).replace(/\r\n/g, "\n");
|
|
61
|
+
const fields = parseFrontmatter(text);
|
|
62
|
+
if (fields.type !== "session" || fields.date !== date)
|
|
63
|
+
continue;
|
|
64
|
+
sessions.push({
|
|
65
|
+
file,
|
|
66
|
+
relative: relativeOf(file),
|
|
67
|
+
title: cleanTitle(/^# (.+)$/m.exec(text)?.[1] ?? "", fields.project || path.basename(file, ".md")),
|
|
68
|
+
date,
|
|
69
|
+
project: fields.project || /^- Project: (.+)$/m.exec(text)?.[1]?.trim() || "",
|
|
70
|
+
// A legacy record keeps its client in the body ("- Provider: claude").
|
|
71
|
+
provider: fields.provider || /^- Provider: (.+)$/m.exec(text)?.[1]?.trim() || "",
|
|
72
|
+
status: fields.status || "",
|
|
73
|
+
text,
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return sessions;
|
|
77
|
+
}
|
|
78
|
+
const clean = (text) => text
|
|
79
|
+
.replace(/^[-*]\s+/, "")
|
|
80
|
+
.replace(/\s+/g, " ")
|
|
81
|
+
.trim();
|
|
82
|
+
// A section's items: its bullets, or the whole paragraph when it has none. Placeholders and
|
|
83
|
+
// fragments too short to stand alone are dropped.
|
|
84
|
+
export function sectionItems(text, heading) {
|
|
85
|
+
const body = section(text, heading);
|
|
86
|
+
if (!body)
|
|
87
|
+
return [];
|
|
88
|
+
const lines = body.split("\n").filter((line) => line.trim());
|
|
89
|
+
const bullets = lines.filter((line) => /^\s*[-*]\s+/.test(line));
|
|
90
|
+
const items = bullets.length ? bullets.map(clean) : [clean(body)];
|
|
91
|
+
return items.filter((item) => item.length >= MIN_ITEM &&
|
|
92
|
+
!/^(none|n\/a|nothing|no )/i.test(item) &&
|
|
93
|
+
!containsKnownSecret(item));
|
|
94
|
+
}
|
|
95
|
+
// A record written with sections (Goal, Outcome, Decisions, …) can be mined here; an older dump
|
|
96
|
+
// (one "What happened" paragraph) needs the skill's reading.
|
|
97
|
+
export const structured = (session) => /^## (Goal|Outcome|Decisions|Learned)$/m.test(session.text);
|
|
98
|
+
export function harvestItems(sessions) {
|
|
99
|
+
const items = [];
|
|
100
|
+
for (const session of sessions)
|
|
101
|
+
for (const kind of Object.keys(KINDS))
|
|
102
|
+
for (const text of sectionItems(session.text, KINDS[kind].heading))
|
|
103
|
+
items.push({ kind, text, session });
|
|
104
|
+
return items;
|
|
105
|
+
}
|
|
106
|
+
// What the owner said to correct an AI ("no, not like that", "غلط", "don't …"): candidates for a
|
|
107
|
+
// standing rule. Read from his own turns only, never the model's.
|
|
108
|
+
const CORRECTION = /(^|[\s,.!])(no,|nope|wrong|don't|do not|stop |not like that|i said|instead of)|(^|\s)(لا |غلط|مو هيچ|مو هيج|مو هيك|ما اريد|لا تسوي|ليش سويت|گلتلك|قلتلك)/i;
|
|
109
|
+
export function detectCorrections(events) {
|
|
110
|
+
const found = [];
|
|
111
|
+
for (const event of events) {
|
|
112
|
+
if (event.type !== "user_input")
|
|
113
|
+
continue;
|
|
114
|
+
const text = event.data.replace(/\s+/g, " ").trim();
|
|
115
|
+
if (!text || text.length > 600 || containsKnownSecret(text))
|
|
116
|
+
continue;
|
|
117
|
+
// Text a client injects as the user's turn (a skill body, a command, a notice) is not his.
|
|
118
|
+
if (/^(base directory for this skill|<|caveat:|\[request interrupted|this session is being continued)/i.test(text))
|
|
119
|
+
continue;
|
|
120
|
+
if (CORRECTION.test(text))
|
|
121
|
+
found.push(text.slice(0, 160));
|
|
122
|
+
}
|
|
123
|
+
return found;
|
|
124
|
+
}
|
|
125
|
+
const localDay = (iso) => {
|
|
126
|
+
const day = new Date(iso);
|
|
127
|
+
return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, "0")}-${String(day.getDate()).padStart(2, "0")}`;
|
|
128
|
+
};
|
|
129
|
+
// Minutes per project for sessions started that day: from the start to the latest of its close,
|
|
130
|
+
// its last update and its last event, each session capped at eight hours. A session the store saw
|
|
131
|
+
// only for seconds counts nothing, and a project with nothing recorded is left out.
|
|
132
|
+
export function minutesByProject(sessions, date, eventsOf = () => []) {
|
|
133
|
+
const minutes = {};
|
|
134
|
+
for (const session of sessions) {
|
|
135
|
+
if (localDay(session.createdAt) !== date)
|
|
136
|
+
continue;
|
|
137
|
+
const ends = [
|
|
138
|
+
session.closedAt,
|
|
139
|
+
session.updatedAt,
|
|
140
|
+
...eventsOf(session.sessionId).map((event) => event.createdAt),
|
|
141
|
+
]
|
|
142
|
+
.map((time) => Date.parse(time ?? ""))
|
|
143
|
+
.filter((time) => !Number.isNaN(time));
|
|
144
|
+
const span = Math.min(Math.max(0, Math.max(...ends, 0) - Date.parse(session.createdAt)), MAX_SESSION_MS);
|
|
145
|
+
const counted = Math.round(span / 60_000);
|
|
146
|
+
if (!counted)
|
|
147
|
+
continue;
|
|
148
|
+
const project = session.projectId || path.basename(session.workingDirectory) || "other";
|
|
149
|
+
minutes[project] = (minutes[project] ?? 0) + counted;
|
|
150
|
+
}
|
|
151
|
+
return minutes;
|
|
152
|
+
}
|
|
153
|
+
const slug = (text) => text
|
|
154
|
+
.toLowerCase()
|
|
155
|
+
.replace(/`[^`]*`/g, (code) => code.slice(1, -1))
|
|
156
|
+
.replace(/[^a-z0-9-ۿ]+/g, " ")
|
|
157
|
+
.trim()
|
|
158
|
+
.split(" ")
|
|
159
|
+
.filter(Boolean)
|
|
160
|
+
.slice(0, 8)
|
|
161
|
+
.join("-")
|
|
162
|
+
.slice(0, 80);
|
|
163
|
+
const words = (text) => new Set(text
|
|
164
|
+
.toLowerCase()
|
|
165
|
+
.split(/[^a-z0-9-ۿ]+/)
|
|
166
|
+
.filter((word) => word.length > 2));
|
|
167
|
+
function similarity(a, b) {
|
|
168
|
+
const left = words(a);
|
|
169
|
+
const right = words(b);
|
|
170
|
+
// Too few words to tell two statements apart: never the same record.
|
|
171
|
+
if (Math.min(left.size, right.size) < 3)
|
|
172
|
+
return 0;
|
|
173
|
+
let shared = 0;
|
|
174
|
+
for (const word of left)
|
|
175
|
+
if (right.has(word))
|
|
176
|
+
shared++;
|
|
177
|
+
return shared / Math.min(left.size, right.size);
|
|
178
|
+
}
|
|
179
|
+
const titleOf = (text) => {
|
|
180
|
+
const sentence = text.split(/(?<=[.!?])\s/)[0] ?? text;
|
|
181
|
+
return sentence.length > 90 ? `${sentence.slice(0, 87).trim()}…` : sentence;
|
|
182
|
+
};
|
|
183
|
+
function setField(text, key, value) {
|
|
184
|
+
const end = text.startsWith("---\n") ? text.indexOf("\n---", 3) : -1;
|
|
185
|
+
if (end < 0)
|
|
186
|
+
return text;
|
|
187
|
+
const head = text.slice(0, end);
|
|
188
|
+
const line = new RegExp(`^${key}:.*$`, "m");
|
|
189
|
+
const next = line.test(head)
|
|
190
|
+
? head.replace(line, `${key}: ${value}`)
|
|
191
|
+
: `${head}\n${key}: ${value}`;
|
|
192
|
+
return next + text.slice(end);
|
|
193
|
+
}
|
|
194
|
+
// One harvested item into 05-knowledge: the record that already says it gains this day as
|
|
195
|
+
// evidence and a fresh last_verified; otherwise a new record. Returns the file and what happened.
|
|
196
|
+
async function fileItem(item, ledger) {
|
|
197
|
+
const folder = oceanPath(KNOWLEDGE_DIR, KINDS[item.kind].folder);
|
|
198
|
+
const title = titleOf(item.text);
|
|
199
|
+
let match = null;
|
|
200
|
+
for (const name of await readdir(folder).catch(() => [])) {
|
|
201
|
+
if (!name.endsWith(".md"))
|
|
202
|
+
continue;
|
|
203
|
+
const existing = await readFile(path.join(folder, name), "utf8");
|
|
204
|
+
const heading = /^# (.+)$/m.exec(existing)?.[1] ?? name;
|
|
205
|
+
if (name === `${slug(item.text)}.md` ||
|
|
206
|
+
similarity(heading, title) >= SAME_TITLE) {
|
|
207
|
+
match = path.join(folder, name);
|
|
208
|
+
break;
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const link = `- ${item.session.date}: [${item.session.title.replace(/[[\]]/g, "")}](${path
|
|
212
|
+
.relative(folder, item.session.file)
|
|
213
|
+
.split(path.sep)
|
|
214
|
+
.join("/")})`;
|
|
215
|
+
if (match) {
|
|
216
|
+
const current = await readFile(match, "utf8");
|
|
217
|
+
if (current.includes(link))
|
|
218
|
+
return { file: relativeOf(match), action: "same" };
|
|
219
|
+
const copy = stateDir("versions", ledger.date, relativeOf(match));
|
|
220
|
+
await mkdir(path.dirname(copy), { recursive: true });
|
|
221
|
+
await copyFile(match, copy);
|
|
222
|
+
ledger.updated.push({ file: relativeOf(match), copy: relativeOf(copy) });
|
|
223
|
+
let next = setField(current, "last_verified", item.session.date);
|
|
224
|
+
next = /^## Evidence$/m.test(next)
|
|
225
|
+
? next.replace(/^## Evidence\n+/m, (head) => `${head}${link}\n`)
|
|
226
|
+
: `${next.replace(/\n*$/, "")}\n\n## Evidence\n\n${link}\n`;
|
|
227
|
+
await atomicWrite(match, next);
|
|
228
|
+
return { file: relativeOf(match), action: "strengthened" };
|
|
229
|
+
}
|
|
230
|
+
const file = path.join(folder, `${slug(item.text) || "untitled"}.md`);
|
|
231
|
+
const body = [
|
|
232
|
+
"---",
|
|
233
|
+
`type: ${item.kind}`,
|
|
234
|
+
`title: ${JSON.stringify(title)}`,
|
|
235
|
+
"status: active",
|
|
236
|
+
"origin: harvested",
|
|
237
|
+
`source: ${JSON.stringify(`session:${item.session.provider || "unknown"}`)}`,
|
|
238
|
+
...(item.session.project
|
|
239
|
+
? [`project: ${JSON.stringify(item.session.project)}`]
|
|
240
|
+
: []),
|
|
241
|
+
`created: ${item.session.date}`,
|
|
242
|
+
`last_verified: ${item.session.date}`,
|
|
243
|
+
"---",
|
|
244
|
+
"",
|
|
245
|
+
`# ${title}`,
|
|
246
|
+
"",
|
|
247
|
+
item.text,
|
|
248
|
+
"",
|
|
249
|
+
"## Evidence",
|
|
250
|
+
"",
|
|
251
|
+
link,
|
|
252
|
+
"",
|
|
253
|
+
].join("\n");
|
|
254
|
+
await mkdir(folder, { recursive: true });
|
|
255
|
+
await atomicWrite(file, body);
|
|
256
|
+
ledger.created.push(relativeOf(file));
|
|
257
|
+
return { file: relativeOf(file), action: "created" };
|
|
258
|
+
}
|
|
259
|
+
function dayBlock(input) {
|
|
260
|
+
const link = (session) => `[${session.title.replace(/[[\]]/g, "")}](${path
|
|
261
|
+
.relative(oceanPath(DAILY_DIR), session.file)
|
|
262
|
+
.split(path.sep)
|
|
263
|
+
.join("/")})`;
|
|
264
|
+
const byProvider = new Map();
|
|
265
|
+
for (const session of input.sessions)
|
|
266
|
+
byProvider.set(session.provider || "unknown", (byProvider.get(session.provider || "unknown") ?? 0) + 1);
|
|
267
|
+
const kind = (k, label) => {
|
|
268
|
+
const items = input.items.filter((item) => item.kind === k);
|
|
269
|
+
return items.length
|
|
270
|
+
? [
|
|
271
|
+
"",
|
|
272
|
+
`### ${label}`,
|
|
273
|
+
"",
|
|
274
|
+
...items.map((item) => {
|
|
275
|
+
const filed = input.filed.get(item);
|
|
276
|
+
return `- ${item.text}${filed ? ` → \`${filed}\`` : ""} (${link(item.session)})`;
|
|
277
|
+
}),
|
|
278
|
+
]
|
|
279
|
+
: [];
|
|
280
|
+
};
|
|
281
|
+
// Every Next a session left is an open loop: carried forward each morning until ticked.
|
|
282
|
+
const loops = input.sessions.flatMap((session) => sectionItems(session.text, "Next").map((item) => `- [ ] ${item} (${link(session)})`));
|
|
283
|
+
const minutes = Object.entries(input.minutes).sort((a, b) => b[1] - a[1]);
|
|
284
|
+
return [
|
|
285
|
+
"## Day summary",
|
|
286
|
+
"",
|
|
287
|
+
`${input.sessions.length} session(s): ${[...byProvider].map(([provider, n]) => `${provider} ${n}`).join(", ") || "none"}.`,
|
|
288
|
+
"",
|
|
289
|
+
"### Sessions",
|
|
290
|
+
"",
|
|
291
|
+
...(input.sessions.length
|
|
292
|
+
? input.sessions.map((session) => `- ${link(session)} — ${[session.project, session.provider, session.status].filter(Boolean).join(" · ")}`)
|
|
293
|
+
: ["- none"]),
|
|
294
|
+
...kind("decision", "Decisions"),
|
|
295
|
+
...kind("solution", "Problems → fixes"),
|
|
296
|
+
...kind("discovery", "Learned"),
|
|
297
|
+
...(input.captures.length
|
|
298
|
+
? ["", "### Captured", "", ...input.captures]
|
|
299
|
+
: []),
|
|
300
|
+
...(input.filed.size
|
|
301
|
+
? [
|
|
302
|
+
"",
|
|
303
|
+
`_Filed into knowledge on its own; undo with \`ocean harvest undo ${input.date}\`._`,
|
|
304
|
+
]
|
|
305
|
+
: []),
|
|
306
|
+
...(loops.length ? ["", "## Open loops", "", ...loops] : []),
|
|
307
|
+
...(input.corrections.length
|
|
308
|
+
? [
|
|
309
|
+
"",
|
|
310
|
+
"## Corrections",
|
|
311
|
+
"",
|
|
312
|
+
...input.corrections.map((text) => `- ${text}`),
|
|
313
|
+
]
|
|
314
|
+
: []),
|
|
315
|
+
...(minutes.length
|
|
316
|
+
? [
|
|
317
|
+
"",
|
|
318
|
+
"## Time",
|
|
319
|
+
"",
|
|
320
|
+
...minutes.map(([project, n]) => `- ${project}: ${Math.floor(n / 60)}h ${String(n % 60).padStart(2, "0")}m`),
|
|
321
|
+
]
|
|
322
|
+
: []),
|
|
323
|
+
].join("\n");
|
|
324
|
+
}
|
|
325
|
+
// Captures written that day (00-inbox/captures/), linked from the day's account.
|
|
326
|
+
async function dayCaptures(date) {
|
|
327
|
+
const dir = oceanPath(INBOX_DIR, "captures");
|
|
328
|
+
const lines = [];
|
|
329
|
+
for (const name of (await readdir(dir).catch(() => [])).sort()) {
|
|
330
|
+
if (!name.endsWith(".md"))
|
|
331
|
+
continue;
|
|
332
|
+
const text = await readFile(path.join(dir, name), "utf8").catch(() => "");
|
|
333
|
+
const fields = parseFrontmatter(text);
|
|
334
|
+
const created = fields.created || fields.date || name;
|
|
335
|
+
if (!created.startsWith(date) && localDay(created) !== date)
|
|
336
|
+
continue;
|
|
337
|
+
const title = /^# (.+)$/m.exec(text)?.[1]?.trim() || name.replace(/\.md$/, "");
|
|
338
|
+
lines.push(`- [${title.replace(/[[\]]/g, "")}](../${INBOX_DIR}/captures/${name})`);
|
|
339
|
+
}
|
|
340
|
+
return lines;
|
|
341
|
+
}
|
|
342
|
+
const ledgerFile = (date) => stateDir("ledger", `${date}.json`);
|
|
343
|
+
export async function harvestDay(options) {
|
|
344
|
+
const { date } = options;
|
|
345
|
+
const sessions = await daySessions(date);
|
|
346
|
+
const items = harvestItems(sessions);
|
|
347
|
+
const ofDay = (options.store?.sessions ?? []).filter((session) => localDay(session.createdAt) === date);
|
|
348
|
+
const corrections = [
|
|
349
|
+
...new Set(ofDay.flatMap((session) => detectCorrections(options.store?.eventsOf(session.sessionId) ?? []))),
|
|
350
|
+
];
|
|
351
|
+
const minutes = minutesByProject(ofDay, date, (id) => options.store ? options.store.eventsOf(id) : []);
|
|
352
|
+
const result = {
|
|
353
|
+
date,
|
|
354
|
+
sessions: sessions.length,
|
|
355
|
+
note: null,
|
|
356
|
+
created: [],
|
|
357
|
+
strengthened: [],
|
|
358
|
+
corrections,
|
|
359
|
+
minutes,
|
|
360
|
+
};
|
|
361
|
+
const captures = await dayCaptures(date);
|
|
362
|
+
if (!sessions.length && !ofDay.length && !captures.length)
|
|
363
|
+
return result;
|
|
364
|
+
result.note = `${DAILY_DIR}/${date}.md`;
|
|
365
|
+
if (!options.apply) {
|
|
366
|
+
result.created = items.map((item) => `${KINDS[item.kind].folder}: ${titleOf(item.text)}`);
|
|
367
|
+
return result;
|
|
368
|
+
}
|
|
369
|
+
const previous = JSON.parse(await readFile(ledgerFile(date), "utf8").catch(() => "null")) ?? { date, created: [], updated: [] };
|
|
370
|
+
const filed = new Map();
|
|
371
|
+
for (const item of items) {
|
|
372
|
+
const { file, action } = await fileItem(item, previous);
|
|
373
|
+
filed.set(item, file);
|
|
374
|
+
if (action === "created")
|
|
375
|
+
result.created.push(file);
|
|
376
|
+
if (action === "strengthened")
|
|
377
|
+
result.strengthened.push(file);
|
|
378
|
+
}
|
|
379
|
+
await mkdir(path.dirname(ledgerFile(date)), { recursive: true });
|
|
380
|
+
await atomicWrite(ledgerFile(date), `${JSON.stringify(previous, null, 2)}\n`);
|
|
381
|
+
const file = noteFile(date);
|
|
382
|
+
await mkdir(path.dirname(file), { recursive: true });
|
|
383
|
+
const body = dayBlock({
|
|
384
|
+
sessions,
|
|
385
|
+
items,
|
|
386
|
+
filed,
|
|
387
|
+
corrections,
|
|
388
|
+
minutes,
|
|
389
|
+
captures,
|
|
390
|
+
date,
|
|
391
|
+
});
|
|
392
|
+
await withFileLock(file, async () => {
|
|
393
|
+
const note = await readFile(file, "utf8").catch(() => null);
|
|
394
|
+
const kept = keepTicks(note ? readBlock(note, "harvest") : "", body);
|
|
395
|
+
await atomicWrite(file, putBlock(note, date, "harvest", kept));
|
|
396
|
+
});
|
|
397
|
+
// A legacy record (no sections) is summarized here but read by the daily-harvest skill, which
|
|
398
|
+
// marks it once it has mined it.
|
|
399
|
+
for (const session of sessions.filter(structured))
|
|
400
|
+
await atomicWrite(session.file, setField(session.text, "harvested", date));
|
|
401
|
+
if (result.created.length || result.strengthened.length)
|
|
402
|
+
await syncMemoryIndexes(true);
|
|
403
|
+
return result;
|
|
404
|
+
}
|
|
405
|
+
// Days before today whose session records have not been harvested yet (the service runs this).
|
|
406
|
+
export async function pendingDays(today, lookbackDays = 45) {
|
|
407
|
+
const cutoff = new Date(Date.parse(today) - lookbackDays * DAY_MS)
|
|
408
|
+
.toISOString()
|
|
409
|
+
.slice(0, 10);
|
|
410
|
+
const days = new Set();
|
|
411
|
+
for (const file of await markdownIn(sessionsRoot())) {
|
|
412
|
+
const head = (await readFile(file, "utf8")).slice(0, 4096);
|
|
413
|
+
const fields = parseFrontmatter(head);
|
|
414
|
+
if (fields.type !== "session" || fields.harvested)
|
|
415
|
+
continue;
|
|
416
|
+
if (fields.date && fields.date < today && fields.date >= cutoff)
|
|
417
|
+
days.add(fields.date);
|
|
418
|
+
}
|
|
419
|
+
return [...days].sort();
|
|
420
|
+
}
|
|
421
|
+
// Undo one day's knowledge writes: records it created are removed, records it strengthened get
|
|
422
|
+
// their earlier version back. The day's summary and session flags stay.
|
|
423
|
+
export async function undoDay(date) {
|
|
424
|
+
const ledger = JSON.parse(await readFile(ledgerFile(date), "utf8").catch(() => "null"));
|
|
425
|
+
if (!ledger)
|
|
426
|
+
throw new Error(`no harvest ledger for ${date}`);
|
|
427
|
+
const removed = [];
|
|
428
|
+
const restored = [];
|
|
429
|
+
for (const file of ledger.created) {
|
|
430
|
+
await rm(oceanPath(file), { force: true });
|
|
431
|
+
removed.push(file);
|
|
432
|
+
}
|
|
433
|
+
// Oldest version first wins: a file strengthened twice returns to how it was before the day.
|
|
434
|
+
const seen = new Set();
|
|
435
|
+
for (const { file, copy } of ledger.updated) {
|
|
436
|
+
if (seen.has(file))
|
|
437
|
+
continue;
|
|
438
|
+
seen.add(file);
|
|
439
|
+
await copyFile(oceanPath(copy), oceanPath(file));
|
|
440
|
+
restored.push(file);
|
|
441
|
+
}
|
|
442
|
+
await rename(ledgerFile(date), stateDir("ledger", `${date}.undone.json`));
|
|
443
|
+
return { removed, restored };
|
|
444
|
+
}
|
|
445
|
+
// After `days`, a harvested day leaves the working folders: the day's note to
|
|
446
|
+
// 01-daily/archive/<YYYY-MM>/, its session records to 01-daily/sessions/archive/<YYYY-MM>/ (still
|
|
447
|
+
// searched). Nothing is deleted, and nothing unharvested moves.
|
|
448
|
+
export async function archiveHarvested(options) {
|
|
449
|
+
const cutoff = new Date(Date.parse(options.today) - (options.days ?? 30) * DAY_MS)
|
|
450
|
+
.toISOString()
|
|
451
|
+
.slice(0, 10);
|
|
452
|
+
const moves = [];
|
|
453
|
+
for (const file of await markdownIn(sessionsRoot())) {
|
|
454
|
+
const fields = parseFrontmatter((await readFile(file, "utf8")).slice(0, 4096));
|
|
455
|
+
if (fields.type !== "session" || !fields.date || fields.date >= cutoff)
|
|
456
|
+
continue;
|
|
457
|
+
if (!fields.harvested)
|
|
458
|
+
continue;
|
|
459
|
+
moves.push({
|
|
460
|
+
from: file,
|
|
461
|
+
to: path.join(sessionsRoot(), "archive", fields.date.slice(0, 7), path.basename(file)),
|
|
462
|
+
kind: "sessions",
|
|
463
|
+
});
|
|
464
|
+
}
|
|
465
|
+
for (const name of await readdir(oceanPath(DAILY_DIR)).catch(() => [])) {
|
|
466
|
+
const day = /^(\d{4}-\d{2}-\d{2})\.md$/.exec(name)?.[1];
|
|
467
|
+
if (!day || day >= cutoff)
|
|
468
|
+
continue;
|
|
469
|
+
// A day leaves once none of its sessions waits to be harvested.
|
|
470
|
+
if ((await daySessions(day)).some((session) => !/^harvested:/m.test(session.text)))
|
|
471
|
+
continue;
|
|
472
|
+
moves.push({
|
|
473
|
+
from: oceanPath(DAILY_DIR, name),
|
|
474
|
+
to: oceanPath(DAILY_DIR, "archive", day.slice(0, 7), name),
|
|
475
|
+
kind: "notes",
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
const result = {
|
|
479
|
+
notes: [],
|
|
480
|
+
sessions: [],
|
|
481
|
+
emptied: [],
|
|
482
|
+
};
|
|
483
|
+
for (const move of moves) {
|
|
484
|
+
result[move.kind].push(relativeOf(move.to));
|
|
485
|
+
if (!options.apply)
|
|
486
|
+
continue;
|
|
487
|
+
await mkdir(path.dirname(move.to), { recursive: true });
|
|
488
|
+
await rename(move.from, move.to);
|
|
489
|
+
}
|
|
490
|
+
// The inbox keeps no empty folders: reviewed candidate days, the retired brain-dump folder.
|
|
491
|
+
const candidates = oceanPath(INBOX_DIR, "candidates");
|
|
492
|
+
const empty = [
|
|
493
|
+
...(await readdir(candidates).catch(() => [])).map((name) => path.join(candidates, name)),
|
|
494
|
+
oceanPath(INBOX_DIR, "brain-dump"),
|
|
495
|
+
];
|
|
496
|
+
for (const dir of empty) {
|
|
497
|
+
const inside = await readdir(dir).catch(() => null);
|
|
498
|
+
if (!inside || inside.some((name) => name !== ".DS_Store"))
|
|
499
|
+
continue;
|
|
500
|
+
result.emptied.push(relativeOf(dir));
|
|
501
|
+
if (options.apply)
|
|
502
|
+
await rm(dir, { recursive: true, force: true });
|
|
503
|
+
}
|
|
504
|
+
return result;
|
|
505
|
+
}
|
|
506
|
+
//# sourceMappingURL=harvest.js.map
|