Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -434,20 +434,20 @@ bee sync [--output <dir>] [--recent-days N] [--only <facts|todos|daily|conversat

After a first sync, re-running `bee sync` on the same output directory is
**incremental**: it re-fetches only the daily summaries and conversations that
have changed since the last run (facts and todos are always re-fetched in full,
since they are small). Sync state is tracked in a `.bee-sync.json` manifest
inside the output directory; delete it (or the directory) to force a full
re-sync.
have changed since the last run (facts and todos are re-fetched on every run,
in full unless `--recent-days` or `--since` limits them). Sync state is tracked
in a `.bee-sync.json` manifest inside the output directory; delete it (or the
directory) to force a full re-sync.

### Options

| Option | Default | Description |
|--------|---------|-------------|
| `--output <dir>` | `bee-sync` | Output directory for synced files |
| `--recent-days N` | all | Limit daily summaries and conversations to the last N days (facts and todos are always synced in full). Applies to full syncs only; ignored on an incremental run |
| `--recent-days N` | all | Limit daily summaries and conversations to the last N days; applies to full syncs only, ignored on an incremental run. Also limits facts and todos to those created in the last N days, on every run |
| `--only <targets>` | all | Limit sync to a comma-separated list: `facts`, `todos`, `daily`, `conversations` (or `all`) |
| `--full` | off | Force a complete re-sync, ignoring the saved manifest, and rewrite it with fresh cursors |
| `--since <epochMs>` | — | Advanced/recovery: override the saved incremental cursor with an explicit epoch-milliseconds timestamp for changefeed-driven targets |
| `--since <epochMs>` | — | Advanced/recovery: override the saved incremental cursor with an explicit epoch-milliseconds timestamp for changefeed-driven targets. Also limits facts and todos to those created after it |

### Output Structure

Expand Down Expand Up @@ -619,15 +619,15 @@ Sync only specific data:
bee sync --only facts,todos
```

Limit daily summaries and conversations to the last 7 days:
Limit daily summaries, conversations, facts and todos to the last 7 days:

```bash
bee sync --recent-days 7
```

### Notes

- The first sync (or `--full`) fetches everything; facts and todos are always re-fetched in full
- The first sync (or `--full`) fetches everything; facts and todos are re-fetched on every run, limited by `--recent-days` or `--since` when given (their files then hold only the matching items)
- Re-runs are incremental: only daily summaries and conversations that changed since the last run are re-fetched, tracked via the `.bee-sync.json` manifest in the output directory
- Conversations and daily summaries are fetched concurrently for faster syncing
- All timestamps are in ISO 8601 format (UTC)
Expand Down
116 changes: 116 additions & 0 deletions sources/commands/sync/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -957,3 +957,119 @@ describe("sync regression", () => {
expect(process.exitCode).toBe(1);
});
});

describe("sync facts/todos honor --recent-days and --since (#14)", () => {
const DAY = 86_400_000;

function fact(id: number, text: string, createdAt: number) {
return { id, text, tags: [], created_at: createdAt, confirmed: true };
}

function todo(id: number, text: string, createdAt: number) {
return { id, text, alarm_at: null, completed: false, created_at: createdAt };
}

it("createdAfterCutoff reads --since as epoch ms or a v1 cursor, else --recent-days", () => {
const { createdAfterCutoff, parseSyncArgs } = __testing;
expect(createdAfterCutoff(parseSyncArgs(["--since", "1700000000000"]))).toBe(1_700_000_000_000);
expect(createdAfterCutoff(parseSyncArgs(["--since", "v1-1700000000000"]))).toBe(1_700_000_000_000);
expect(createdAfterCutoff(parseSyncArgs([]))).toBeUndefined();
const today = `${new Date().toISOString().slice(0, 10)}T00:00:00Z`;
expect(createdAfterCutoff(parseSyncArgs(["--recent-days", "1"]))).toBe(Date.parse(today));
});

it("--recent-days keeps recent facts and stops paging once a newest-first page is older", async () => {
const now = Date.now();
const outputDir = await makeTempDir();
const { context, requests } = proxyContext((request) => {
const url = new URL(request.url);
if (url.pathname !== "/v1/facts") return Response.json({});
const cursor = url.searchParams.get("cursor");
if (cursor === null) {
return Response.json({
facts: [fact(3, "fresh fact", now), fact(2, "day-old fact", now - DAY)],
next_cursor: "v1-2",
});
}
if (cursor === "v1-2") {
return Response.json({ facts: [fact(1, "ancient fact", now - 10 * DAY)], next_cursor: "v1-1" });
}
return Response.json({ facts: [fact(0, "never fetched", now - 20 * DAY)], next_cursor: null });
});

await syncCommand.run(["--output", outputDir, "--only", "facts", "--recent-days", "3"], context);

const md = readFileSync(path.join(outputDir, "facts.md"), "utf8");
expect(md).toContain("fresh fact");
expect(md).toContain("day-old fact");
expect(md).not.toContain("ancient fact");
expect(md).not.toContain("never fetched");
expect(requests.filter((r) => r.pathname === "/v1/facts")).toHaveLength(2);
});

it("--since (epoch ms) bounds todos and stops after the first older page", async () => {
const now = Date.now();
const outputDir = await makeTempDir();
const { context, requests } = proxyContext((request) => {
const url = new URL(request.url);
if (url.pathname !== "/v1/todos") return Response.json({});
return Response.json({
todos: [todo(9, "new todo", now), todo(8, "old todo", now - 10 * DAY)],
next_cursor: "v1-8",
});
});

await syncCommand.run(
["--output", outputDir, "--only", "todos", "--since", String(now - 5 * DAY)],
context
);

const md = readFileSync(path.join(outputDir, "todos.md"), "utf8");
expect(md).toContain("new todo");
expect(md).not.toContain("old todo");
expect(requests.filter((r) => r.pathname === "/v1/todos")).toHaveLength(1);
});

it("pages that are not newest-first keep paging and are still filtered", async () => {
const now = Date.now();
const outputDir = await makeTempDir();
const { context, requests } = proxyContext((request) => {
const url = new URL(request.url);
if (url.pathname !== "/v1/facts") return Response.json({});
if (url.searchParams.get("cursor") === null) {
return Response.json({
facts: [fact(1, "old first", now - 10 * DAY), fact(2, "fresh second", now)],
next_cursor: "v1-5",
});
}
return Response.json({ facts: [fact(3, "fresh third", now - 3_600_000)], next_cursor: null });
});

await syncCommand.run(["--output", outputDir, "--only", "facts", "--recent-days", "3"], context);

const md = readFileSync(path.join(outputDir, "facts.md"), "utf8");
expect(md).toContain("fresh second");
expect(md).toContain("fresh third");
expect(md).not.toContain("old first");
expect(requests.filter((r) => r.pathname === "/v1/facts")).toHaveLength(2);
});

it("without --recent-days or --since every fact is still written", async () => {
const now = Date.now();
const outputDir = await makeTempDir();
const { context } = proxyContext((request) => {
const url = new URL(request.url);
if (url.pathname !== "/v1/facts") return Response.json({});
return Response.json({
facts: [fact(2, "fresh fact", now), fact(1, "ancient fact", now - 400 * DAY)],
next_cursor: null,
});
});

await syncCommand.run(["--output", outputDir, "--only", "facts"], context);

const md = readFileSync(path.join(outputDir, "facts.md"), "utf8");
expect(md).toContain("fresh fact");
expect(md).toContain("ancient fact");
});
});
82 changes: 68 additions & 14 deletions sources/commands/sync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,51 @@ function recentDaysFrom(days: number): string {
return start.toISOString().slice(0, 10);
}

// Facts and todos are always re-fetched in full and their list endpoints take no
// date filter, so --since / --recent-days bound them client-side by created_at.
function createdAfterCutoff(options: SyncOptions): number | undefined {
if (options.since !== undefined) {
if (/^\d+$/.test(options.since)) {
return Number(options.since);
}
const fromCursor = cursorEpochMs(options.since);
if (fromCursor !== null) {
return fromCursor;
}
}
if (options.recentDays !== undefined) {
return Date.parse(`${recentDaysFrom(options.recentDays)}T00:00:00Z`);
}
return undefined;
}

function keepCreatedSince<T extends { created_at: number }>(
items: T[],
cutoff: number | undefined
): T[] {
return cutoff === undefined ? items : items.filter((item) => item.created_at >= cutoff);
}

// Stop paging once a newest-first page reaches the cutoff. A page that is not
// newest-first never stops paging; the filter alone keeps the result correct.
function pageEndsBefore(
items: { created_at: number }[],
cutoff: number | undefined
): boolean {
const last = items[items.length - 1];
if (cutoff === undefined || last === undefined) {
return false;
}
for (let i = 1; i < items.length; i += 1) {
const previous = items[i - 1];
const current = items[i];
if (previous !== undefined && current !== undefined && previous.created_at < current.created_at) {
return false;
}
}
return last.created_at < cutoff;
}

function parseTargets(value: string): SyncTarget[] {
const parts = value
.split(",")
Expand Down Expand Up @@ -721,14 +766,16 @@ async function syncAll(
const syncPromises: Promise<void>[] = [];
const outcomes: Partial<Record<ChangefeedTarget, TargetSyncOutcome>> = {};

const createdAfter = createdAfterCutoff(options);

if (options.targets.has("facts")) {
const task = progress.addTask("facts");
syncPromises.push(syncFacts(context, options.outputDir, task));
syncPromises.push(syncFacts(context, options.outputDir, task, createdAfter));
}

if (options.targets.has("todos")) {
const task = progress.addTask("todos");
syncPromises.push(syncTodos(context, options.outputDir, task));
syncPromises.push(syncTodos(context, options.outputDir, task, createdAfter));
}

if (options.targets.has("daily")) {
Expand Down Expand Up @@ -959,9 +1006,10 @@ async function persistManifest(
async function syncFacts(
context: CommandContext,
outputDir: string,
task: ProgressTask
task: ProgressTask,
createdAfter?: number
): Promise<void> {
const facts = await fetchAllFacts(context, task);
const facts = await fetchAllFacts(context, task, createdAfter);
await writeFactsMarkdown(outputDir, facts);
task.setLabel("facts done");
task.complete();
Expand All @@ -970,9 +1018,10 @@ async function syncFacts(
async function syncTodos(
context: CommandContext,
outputDir: string,
task: ProgressTask
task: ProgressTask,
createdAfter?: number
): Promise<void> {
const todos = await fetchAllTodos(context, task);
const todos = await fetchAllTodos(context, task, createdAfter);
await writeTodosMarkdown(outputDir, todos);
task.setLabel("todos done");
task.complete();
Expand Down Expand Up @@ -1250,7 +1299,8 @@ function conversationSortKey(conversation: ConversationSummary): number {

async function fetchAllFacts(
context: CommandContext,
task: ProgressTask
task: ProgressTask,
createdAfter?: number
): Promise<Fact[]> {
const items: Fact[] = [];
let cursor: string | undefined;
Expand All @@ -1265,9 +1315,10 @@ async function fetchAllFacts(
const apiPath = params.toString() ? `/v1/facts?${params}` : "/v1/facts";
const data = await requestClientJson(context, apiPath, { method: "GET" });
const payload = parseFactsList(data);
items.push(...payload.facts);
task.advance(payload.facts.length);
if (!payload.next_cursor) {
const kept = keepCreatedSince(payload.facts, createdAfter);
items.push(...kept);
task.advance(kept.length);
if (!payload.next_cursor || pageEndsBefore(payload.facts, createdAfter)) {
break;
}
task.addTotal(1);
Expand All @@ -1279,7 +1330,8 @@ async function fetchAllFacts(

async function fetchAllTodos(
context: CommandContext,
task: ProgressTask
task: ProgressTask,
createdAfter?: number
): Promise<Todo[]> {
const items: Todo[] = [];
let cursor: string | undefined;
Expand All @@ -1294,9 +1346,10 @@ async function fetchAllTodos(
const apiPath = params.toString() ? `/v1/todos?${params}` : "/v1/todos";
const data = await requestClientJson(context, apiPath, { method: "GET" });
const payload = parseTodosList(data);
items.push(...payload.todos);
task.advance(payload.todos.length);
if (!payload.next_cursor) {
const kept = keepCreatedSince(payload.todos, createdAfter);
items.push(...kept);
task.advance(kept.length);
if (!payload.next_cursor || pageEndsBefore(payload.todos, createdAfter)) {
break;
}
task.addTotal(1);
Expand Down Expand Up @@ -1820,5 +1873,6 @@ export const __testing = {
persistCursor,
accountFingerprint,
normalizeSinceCursor,
createdAfterCutoff,
CHANGES_OVERLAP_MS,
};