Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: derive weekly digest weekStart from the target weekId (#7009)

[._.]/ Adam Eivy57f48bc83907
diff --git a/server/lib/README.md b/server/lib/README.md
index 6b058af272..29d03bad89 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -555,7 +555,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and
| `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. |
| `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. Re-exported by `client/src/lib/extensionErrors.js`, so both sides classify identically. |
| `fetchErrorChain.js` | `describeFetchError(err)` flattens a fetch rejection's whole `cause` chain (depth-bounded, cycle-guarded) into one searchable `code: message` string — undici reports every network failure as the same opaque `TypeError: fetch failed` with the real reason nested inside, so a classifier reading only `err.message` misjudges every one of them. `isReplayableConnectionError(err)` is the narrow predicate over that string for connection-REUSE artifacts (HTTP/2 GOAWAY, reset, hang-up) that are safe to replay once via `fetchWithTimeout`'s `shouldRetry`; it deliberately EXCLUDES timeouts, which broader classifiers like `ollamaManager`'s `isTransientPullError` include. |
-| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by productivity week aggregates and weekly digest filenames. |
+| `isoWeek.js` | ISO-8601 week identity — the single source of the `YYYY-Www` week id. `getWeekId(date)` keys on the ISO week-numbering **year** (the calendar year of that week's Thursday), not `date.getFullYear()`, so one ISO week is never split across two ids and two weeks never collide on one (#3465). Also `isoWeekParts`, `getIsoWeekNumber`, `getIsoWeekYear`, `parseWeekId` (null on garbage), `weekStartFromWeekId` (local-midnight Monday of that id; null on garbage), and `isoWeeksInYear(year)` (52, or 53 in a leap-week year). Shared by productivity week aggregates and weekly digest filenames. |
| `snapshotChecksum.js` | The two snapshot-checksum flavours a sync category can want. `snapshotChecksum(data)` hashes `JSON.stringify` — insertion-order SENSITIVE, correct only where the getter already canonicalizes its own ordering (`dataSync.js`, `digital-twin-sync.js`). `canonicalSnapshotChecksum(data)` hashes `canonicalStringify`, so two converged machines hash identically regardless of the order they learned the data (`peerUsage.js`, whose payload is a map keyed by wire-supplied instance ids). Picking the wrong one is not a crash — it is two synced peers whose checksums never match, which the sync UI reads as "behind" forever. |
| `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. |
| `syncManifest.js` | Wire contract for the snapshot-sync MANIFEST leg — the fix for a category that is always dirty AND a map of per-instance slots (`usage`), where one instance advancing dragged every other instance's digest across the wire. `isManifestEnvelope(value)` validates a `{ data: { instances }, checksum }` response (a legacy peer that 404s the endpoint fails it, and the puller falls back to the whole snapshot); `diffManifestSlots(remoteInstances, localInstances)` returns the sorted slot ids whose REMOTE LWW stamp is strictly newer than ours — exactly the slots worth fetching. Comparison goes through `lwwTimestamp.js`, so a tie breaks to what we already hold. Consumed by `syncOrchestrator.syncDataCategoryFromPeer`; served by `dataSync.getManifest`. |
diff --git a/server/lib/isoWeek.js b/server/lib/isoWeek.js
index 0dcbfba541..c00b8806c6 100644
--- a/server/lib/isoWeek.js
+++ b/server/lib/isoWeek.js
@@ -83,6 +83,30 @@ export function parseWeekId(weekId) {
return { year, week };
}
+/**
+ * Local-midnight Monday of the ISO week identified by `weekId`.
+ * Inverse of `getWeekId` for a well-formed id; null for the same garbage
+ * `parseWeekId` rejects, so a caller can tell "unparseable" from a real Monday.
+ *
+ * Arithmetic runs in UTC on the local Y-M-D (same as `isoWeekThursday`) so a
+ * DST spring-forward cannot skip the Monday; the returned Date is then rebuilt
+ * from those UTC Y-M-D parts as a local midnight.
+ *
+ * @param {string} weekId
+ * @returns {Date | null}
+ */
+export function weekStartFromWeekId(weekId) {
+ const parsed = parseWeekId(weekId);
+ if (!parsed) return null;
+ // Jan 4 is always in ISO week 1 of `year`. Its Thursday is the week-1 anchor.
+ const week1Thursday = new Date(Date.UTC(parsed.year, 0, 4));
+ const isoDay = week1Thursday.getUTCDay() || 7;
+ week1Thursday.setUTCDate(week1Thursday.getUTCDate() + 4 - isoDay);
+ const monday = new Date(week1Thursday);
+ monday.setUTCDate(week1Thursday.getUTCDate() - 3 + (parsed.week - 1) * 7);
+ return new Date(monday.getUTCFullYear(), monday.getUTCMonth(), monday.getUTCDate());
+}
+
/**
* How many ISO weeks a week-numbering year holds — 52, or 53 in a "leap week"
* year (2015, 2020, 2026, …). December 28th is always in the last ISO week of
diff --git a/server/lib/isoWeek.test.js b/server/lib/isoWeek.test.js
index 0a6decf920..1a98a875e1 100644
--- a/server/lib/isoWeek.test.js
+++ b/server/lib/isoWeek.test.js
@@ -6,6 +6,7 @@ import {
isoWeekParts,
isoWeeksInYear,
parseWeekId,
+ weekStartFromWeekId,
} from './isoWeek.js';
// Local-calendar dates: the week id is a local-day concept, so build the
@@ -92,3 +93,26 @@ describe('parseWeekId', () => {
}
});
});
+
+describe('weekStartFromWeekId', () => {
+ it('returns the local-midnight Monday of the named week', () => {
+ expect(weekStartFromWeekId('2026-W12')).toEqual(on(2026, 3, 16));
+ expect(weekStartFromWeekId('2026-W15')).toEqual(on(2026, 4, 6));
+ });
+
+ it('lands on the December Monday when week 1 belongs to the next year', () => {
+ expect(weekStartFromWeekId('2026-W01')).toEqual(on(2025, 12, 29));
+ });
+
+ it('round-trips through getWeekId for ordinary, leap-week, and year-boundary ids', () => {
+ for (const id of ['2025-W01', '2025-W52', '2026-W01', '2026-W15', '2026-W53']) {
+ expect(getWeekId(weekStartFromWeekId(id))).toBe(id);
+ }
+ });
+
+ it('returns null for the same garbage parseWeekId rejects', () => {
+ for (const bad of ['', '2026', '2026-W00', '2026-W54', null, undefined]) {
+ expect(weekStartFromWeekId(bad)).toBeNull();
+ }
+ });
+});
diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.js
index 71498a242d..3fcefefbe8 100644
--- a/server/services/weeklyDigest.js
+++ b/server/services/weeklyDigest.js
@@ -13,7 +13,7 @@ import { cosEvents, emitLog } from './cosEvents.js';
import { getAgents } from './cosAgentLifecycle.js';
import { getAgentDates, getAgentsByDate } from './cosAgentIndex.js';
import { atomicWrite, ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';
-import { getWeekId } from '../lib/isoWeek.js';
+import { getWeekId, weekStartFromWeekId } from '../lib/isoWeek.js';
const DIGESTS_DIR = PATHS.digests;
@@ -76,7 +76,9 @@ function percentChange(current, previous) {
*/
export async function generateWeeklyDigest(weekId = null) {
const targetWeekId = weekId || getWeekId();
- const weekStart = getWeekStart(new Date());
+ // Derive the window from the target id — `new Date()` would stamp the current
+ // week onto a historical backfill and chain week-over-week to the wrong neighbor.
+ const weekStart = weekStartFromWeekId(targetWeekId) ?? getWeekStart(new Date());
weekStart.setHours(0, 0, 0, 0);
emitLog('info', `Generating weekly digest for ${targetWeekId}`, { weekId: targetWeekId }, '📊 WeeklyDigest');
@@ -376,8 +378,8 @@ export async function listWeeklyDigests() {
weekId: digest.weekId,
weekStart: digest.weekStart,
weekEnd: digest.weekEnd,
- totalTasks: digest.summary.totalTasks,
- successRate: digest.summary.successRate,
+ totalTasks: digest.summary?.totalTasks,
+ successRate: digest.summary?.successRate,
generatedAt: digest.generatedAt
}));
diff --git a/server/services/weeklyDigest.test.js b/server/services/weeklyDigest.test.js
index 8f3db34763..2e82e5c8f7 100644
--- a/server/services/weeklyDigest.test.js
+++ b/server/services/weeklyDigest.test.js
@@ -282,6 +282,26 @@ describe('generateWeeklyDigest — summary assembly', () => {
expect(readDigest('2026-W01').summary.totalTasks).toBe(2);
});
+ it('stamps weekStart/weekEnd/previousWeekId from a historical weekId, not now (#7009)', async () => {
+ // Frozen now is 2026-W12. Generating W15 must not inherit W12's Monday or
+ // chain week-over-week to W11 (the current week's neighbor).
+ writeDigest('2026-W14', storedDigest('2026-W14', { totalTasks: 3, successRate: 100, totalWorkTimeMs: 1000 }));
+ writeDigest(LAST_WEEK, storedDigest(LAST_WEEK, { totalTasks: 9, successRate: 50, totalWorkTimeMs: 1000 }));
+ onDates([
+ agent('w15', { month: 4, day: 7 }),
+ agent('w12', { day: 18 }),
+ ]);
+
+ const digest = await digestService.generateWeeklyDigest('2026-W15');
+
+ expect(digest.weekId).toBe('2026-W15');
+ expect(digest.weekStart).toBe(new Date(2026, 3, 6, 0, 0, 0).toISOString());
+ expect(digest.weekEnd).toBe(new Date(2026, 3, 12, 0, 0, 0).toISOString());
+ expect(digest.previousWeekId).toBe('2026-W14');
+ expect(digest.summary.totalTasks).toBe(1);
+ expect(digest.accomplishments.map(a => a.id)).toEqual(['w15']);
+ });
+
it('persists the digest and announces it on the CoS event bus', async () => {
const emitted = [];
const listener = (d) => emitted.push(d.weekId);
@@ -488,6 +508,21 @@ describe('listWeeklyDigests', () => {
it('returns an empty list when nothing has been generated', async () => {
expect(await digestService.listWeeklyDigests()).toEqual([]);
});
+
+ it('lists a stored digest that has no summary without throwing (#7009)', async () => {
+ writeDigest('2026-W09', { weekStart: at(23, 0, 2), weekEnd: at(1, 0, 3), generatedAt: at(1, 0, 3) });
+
+ const list = await digestService.listWeeklyDigests();
+
+ expect(list).toEqual([{
+ weekId: '2026-W09',
+ weekStart: at(23, 0, 2),
+ weekEnd: at(1, 0, 3),
+ totalTasks: undefined,
+ successRate: undefined,
+ generatedAt: at(1, 0, 3),
+ }]);
+ });
});
describe('compareWeeks', () => {