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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: key the CoS week id on the ISO week-numbering year, not the calendar year (#3465)
[._.]/ Adam Eivyf89ef14a881b
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9bd910ffd0..4a63d1dbd8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -35,3 +35,5 @@- **The tailnet identity guard had a bypass on exactly the leak class it exists to catch.** Its suffix pattern required a digit in the `tail<token>` segment, but Tailscale picks that token at random from lowercase alphanumerics — so a real hostname whose token happened to be all letters passed silently. It now matches the shape and subtracts known placeholder tokens by exact name, which fails closed: an unrecognized placeholder trips the guard and gets looked at, rather than a real hostname slipping through for lacking a digit.- **The MeatSpace life-progress bar was the one part of that panel that didn't follow the theme.** Its fill color was three inline hex literals (`#ef4444`/`#f59e0b`/`#3b82f6`) while the surrounding card already used `border-port-border` and `text-port-error` — so switching themes re-colored everything around the bar but not the bar. It now reads `rgb(var(--port-error))` / `rgb(var(--port-warning))` / `rgb(var(--port-accent))`. Separately, the `#3b82f6` default swatch was independently hardcoded at five places across the agents and calendar config UIs; a native `<input type="color">` genuinely needs a literal hex, so the literal stays — but there is now one `DEFAULT_AVATAR_COLOR` derived from the default theme's accent that all five import, instead of five edits to change the fallback (#3453).++- **The CoS week id paired the ISO week number with the calendar year, which both split and reused week ids around New Year.** `getWeekId()` was duplicated in `productivity.js` and `weeklyDigest.js` and built as `${date.getFullYear()}-W${isoWeek}` — so Mon 2025-12-29 and Thu 2026-01-01, one and the same ISO week, stamped `2025-W01` and `2026-W01` (breaking the weekly streak and mis-ordering the `longestWeekly` scan), while the *January* week of that same year stamped `2025-W01` too, so the late-December digest overwrote the early-January one on disk. The helper now lives once in `server/lib/isoWeek.js` and keys on the ISO week-numbering year — the calendar year of that week's Thursday — so one ISO week has one id and no id is ever reused. `isConsecutiveWeek` moved with it and now bridges a rollover only when the earlier week is genuinely its year's last, which a bare `week >= 52` check got wrong for the 53-week years (2026 is one). Migration 224 renames existing digest files and rewrites `streaks.lastActiveWeek`, resolving each record from its own stored `weekStart` / `lastActiveDate` and leaving anything it cannot resolve untouched rather than guessing a digest onto the wrong week.diff --git a/scripts/migrations/224-iso-week-numbering-year-ids.js b/scripts/migrations/224-iso-week-numbering-year-ids.jsnew file mode 100644index 0000000000..9f13cde1d3--- /dev/null+++ b/scripts/migrations/224-iso-week-numbering-year-ids.js@@ -0,0 +1,233 @@+/**+ * Migration 224 — re-key CoS week ids onto the ISO week-numbering year (#3465).+ *+ * Background:+ * `getWeekId()` used to pair the ISO week NUMBER with the CALENDAR year+ * (`${date.getFullYear()}-W${isoWeek}`). Those two disagree at either end of+ * the year, so a single ISO week could be filed under two ids (Mon+ * 2025-12-29 → `2025-W01`, Thu 2026-01-01 → `2026-W01`) and two different+ * weeks could collide on one id (the week of 2025-01-01 is `2025-W01` too,+ * so the late-December digest overwrote the early-January one on disk).+ *+ * `server/lib/isoWeek.js` now keys on the ISO week-numbering year — the+ * calendar year of that week's Thursday — so both boundary days above are+ * `2026-W01` and no id is ever reused. Two on-disk stores encode the old ids+ * and have to move with it:+ *+ * - `data/cos/digests/<weekId>.json` — the id IS the filename, plus the+ * stored `weekId` / `previousWeekId` fields. Left alone, every+ * boundary-week digest is orphaned (the service looks it up under the new+ * id, finds nothing, and regenerates over it).+ * - `data/cos/productivity.json` — `streaks.lastActiveWeek`. Left alone, the+ * next completed task sees a non-consecutive week and resets the user's+ * weekly streak.+ *+ * How an old id is resolved:+ * 1. Prefer the record's own date — a digest's `weekStart`, or productivity's+ * `streaks.lastActiveDate`. If re-deriving the OLD-form id from that date+ * reproduces the stored id, the date is authoritative and the new id is+ * simply `getWeekId(date)`. This is what resolves the collision case: the+ * surviving digest keeps its content and is renamed to whichever week its+ * `weekStart` actually covers.+ * 2. Otherwise fall back to arithmetic: a week number in 2..51 is nowhere near+ * a year boundary, so the calendar year and the ISO week-numbering year+ * agree for every day in it and the id is already correct.+ * 3. Anything else (`W01`, `W52`, `W53` with no usable date) is genuinely+ * ambiguous — two real weeks map to it. Leave it untouched and log; a stale+ * `lastActiveWeek` costs one reset streak, which is strictly better than+ * guessing a digest onto the wrong week.+ *+ * Idempotent: after a run, every id round-trips through rule 1 or 2 to itself,+ * so a second pass writes nothing. Safe on an install with no digests dir and+ * no productivity file at all — both are runtime-generated (neither ships a+ * `data.reference/` seed), so a fresh install simply has nothing to do.+ */++import { readdir, readFile, unlink } from 'fs/promises';+import { join } from 'path';+import { atomicWrite } from '../../server/lib/fileUtils.js';+import { getIsoWeekNumber, getWeekId, parseWeekId } from '../../server/lib/isoWeek.js';++const WEEK_MS = 7 * 24 * 60 * 60 * 1000;++/** The pre-#3465 id shape: ISO week number stamped with the CALENDAR year. */+export function legacyWeekId(date) {+ return `${date.getFullYear()}-W${String(getIsoWeekNumber(date)).padStart(2, '0')}`;+}++/** Coerce a stored date hint (ISO string / YYYY-MM-DD / Date) to a valid Date, or null. */+export function toDateHint(value) {+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;+ if (typeof value !== 'string' || value.trim() === '') return null;+ // A bare YYYY-MM-DD parses as UTC midnight, which reads as the PREVIOUS local+ // day west of Greenwich — and the week id is a local-calendar-day concept.+ // Pin it to local noon so the day can't slip across a boundary either way.+ const raw = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T12:00:00` : value;+ const date = new Date(raw);+ return Number.isNaN(date.getTime()) ? null : date;+}++/**+ * Resolve an old-form week id to its new form. Pure — exported for the test.+ *+ * @param {string} oldId stored `YYYY-Www`+ * @param {string|Date|null} dateHint a date known to fall in that week+ * @returns {string|null} the new id, or null when it cannot be resolved safely+ */+export function resolveNewWeekId(oldId, dateHint) {+ const parsed = parseWeekId(oldId);+ if (!parsed) return null;+ const date = toDateHint(dateHint);+ // Already in the new form (a re-run, or a record written after the fix) —+ // checked FIRST so a second pass reports "no change" instead of "ambiguous".+ if (date && getWeekId(date) === oldId) return oldId;+ if (date && legacyWeekId(date) === oldId) return getWeekId(date);+ if (parsed.week > 1 && parsed.week < 52) return oldId;+ return null;+}++const readJsonOrNull = async (path) => {+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) return null;+ try { return JSON.parse(raw); } catch { return null; }+};++/**+ * Plan the digest rename set. Pure over already-read records — exported so the+ * test can assert the conflict rules without touching a filesystem.+ *+ * @param {Array<{ file: string, digest: object }>} records+ * @returns {{ writes: Array<{ file: string, digest: object }>, deletes: string[], skipped: string[] }}+ */+export function planDigestRewrite(records) {+ const claims = new Map(); // newFile -> candidate[]+ const skipped = [];++ for (const { file, digest } of records) {+ const oldId = file.replace(/\.json$/, '');+ const newId = resolveNewWeekId(oldId, digest?.weekStart);+ if (!newId) { skipped.push(file); continue; }+ const candidate = { file, digest, oldId, newId, newFile: `${newId}.json` };+ if (!claims.has(candidate.newFile)) claims.set(candidate.newFile, []);+ claims.get(candidate.newFile).push(candidate);+ }++ // Two digests resolving to one name would clobber each other. Distinct weeks+ // cannot collide under the new scheme, so this only fires on hand-edited or+ // duplicated records — keep the most recently generated one and leave the+ // others under their original names rather than deleting a real digest.+ const winners = [];+ for (const [, candidates] of claims) {+ if (candidates.length === 1) { winners.push(candidates[0]); continue; }+ const sorted = [...candidates].sort((a, b) => {+ // The record already sitting at the target name wins over a rename into it.+ const aStays = a.oldId === a.newId;+ const bStays = b.oldId === b.newId;+ if (aStays !== bStays) return aStays ? -1 : 1;+ const at = String(a.digest?.generatedAt ?? '');+ const bt = String(b.digest?.generatedAt ?? '');+ if (at !== bt) return at < bt ? 1 : -1; // newest generatedAt first+ return a.file < b.file ? -1 : 1;+ });+ winners.push(sorted[0]);+ for (const loser of sorted.slice(1)) skipped.push(loser.file);+ }++ const writes = [];+ for (const candidate of winners) {+ const { digest, oldId, newId, newFile } = candidate;+ const next = { ...digest, weekId: newId };+ if (typeof digest?.previousWeekId === 'string') {+ const prevStart = toDateHint(digest.weekStart);+ const resolvedPrev = prevStart+ ? getWeekId(new Date(prevStart.getTime() - WEEK_MS))+ : resolveNewWeekId(digest.previousWeekId, null);+ if (resolvedPrev) next.previousWeekId = resolvedPrev;+ }+ const changed = newId !== oldId+ || digest?.weekId !== next.weekId+ || digest?.previousWeekId !== next.previousWeekId;+ if (changed) writes.push({ file: newFile, digest: next });+ }++ // Every name that survives the pass — winners' new names plus whatever we+ // left alone. Anything else was a rename source and is now redundant.+ const kept = new Set([...winners.map(w => w.newFile), ...skipped]);+ const deletes = records.map(r => r.file).filter(f => !kept.has(f));++ return { writes, deletes, skipped };+}++async function migrateDigests(rootDir) {+ const dir = join(rootDir, 'data', 'cos', 'digests');+ const entries = await readdir(dir).catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (entries == null) {+ console.log('📊 migration 224: no CoS digests directory — nothing to rename');+ return { renamed: 0, skipped: 0 };+ }++ // Read EVERY digest before writing anything: a rename target can be another+ // digest's current name, and reading up front means no pass ever reads a file+ // an earlier write already replaced.+ const records = [];+ for (const file of entries.filter(f => f.endsWith('.json')).sort()) {+ const digest = await readJsonOrNull(join(dir, file));+ if (digest && typeof digest === 'object' && !Array.isArray(digest)) records.push({ file, digest });+ }+ if (records.length === 0) {+ console.log('📊 migration 224: no readable digests — nothing to rename');+ return { renamed: 0, skipped: 0 };+ }++ const { writes, deletes, skipped } = planDigestRewrite(records);+ for (const { file, digest } of writes) await atomicWrite(join(dir, file), digest);+ for (const file of deletes) await unlink(join(dir, file)).catch(() => {});++ if (writes.length === 0) {+ console.log(`📊 migration 224: all ${records.length} digest(s) already use ISO week-numbering ids`);+ } else {+ console.log(`📊 migration 224: re-keyed ${writes.length} of ${records.length} digest(s) to ISO week-numbering ids`);+ }+ if (skipped.length > 0) {+ console.warn(`⚠️ migration 224: left ${skipped.length} digest(s) untouched — ambiguous week id with no usable weekStart`);+ }+ return { renamed: writes.length, skipped: skipped.length };+}++async function migrateProductivity(rootDir) {+ const file = join(rootDir, 'data', 'cos', 'productivity.json');+ const data = await readJsonOrNull(file);+ if (!data || typeof data !== 'object' || Array.isArray(data)) {+ console.log('📊 migration 224: no productivity record — no weekly streak to re-key');+ return { changed: false };+ }++ const oldId = data.streaks?.lastActiveWeek;+ if (typeof oldId !== 'string' || oldId === '') return { changed: false };++ const newId = resolveNewWeekId(oldId, data.streaks?.lastActiveDate);+ if (!newId) {+ console.warn(`⚠️ migration 224: left streaks.lastActiveWeek "${oldId}" untouched — ambiguous week id with no usable lastActiveDate (costs at most one reset weekly streak)`);+ return { changed: false };+ }+ if (newId === oldId) return { changed: false };++ data.streaks.lastActiveWeek = newId;+ await atomicWrite(file, data);+ console.log(`📊 migration 224: re-keyed streaks.lastActiveWeek ${oldId} → ${newId}`);+ return { changed: true };+}++export default {+ async up({ rootDir }) {+ const digests = await migrateDigests(rootDir);+ const productivity = await migrateProductivity(rootDir);+ return { ok: true, ...digests, lastActiveWeekChanged: productivity.changed };+ },+};diff --git a/scripts/migrations/224-iso-week-numbering-year-ids.test.js b/scripts/migrations/224-iso-week-numbering-year-ids.test.jsnew file mode 100644index 0000000000..4c48c83f21--- /dev/null+++ b/scripts/migrations/224-iso-week-numbering-year-ids.test.js@@ -0,0 +1,234 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest';+import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from 'fs/promises';+import { existsSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import migration, { legacyWeekId, planDigestRewrite, resolveNewWeekId, toDateHint } from './224-iso-week-numbering-year-ids.js';++const on = (year, month, day) => new Date(year, month - 1, day);+// A digest record with only the fields the migration reads. Values are+// obviously-synthetic, not lifted from any real install.+const digestFixture = (weekId, weekStart, extra = {}) => ({+ weekId,+ generatedAt: `${weekStart}T18:00:00.000Z`,+ weekStart: `${weekStart}T00:00:00.000Z`,+ summary: { totalTasks: 1 },+ ...extra,+});++describe('legacyWeekId', () => {+ it('reproduces the pre-#3465 calendar-year stamping', () => {+ expect(legacyWeekId(on(2025, 12, 29))).toBe('2025-W01');+ expect(legacyWeekId(on(2026, 1, 1))).toBe('2026-W01');+ expect(legacyWeekId(on(2025, 1, 1))).toBe('2025-W01');+ });+});++describe('toDateHint', () => {+ it('reads a bare YYYY-MM-DD as that LOCAL day, not UTC midnight', () => {+ // UTC midnight would read as Dec 28 west of Greenwich and pick the wrong week.+ expect(legacyWeekId(toDateHint('2025-12-29'))).toBe('2025-W01');+ });++ it('returns null for a non-date', () => {+ for (const bad of [null, undefined, '', ' ', 'nope', new Date('nope'), 42]) {+ expect(toDateHint(bad)).toBeNull();+ }+ });+});++describe('resolveNewWeekId', () => {+ it('uses the record date when it reproduces the stored old-form id', () => {+ expect(resolveNewWeekId('2025-W01', '2025-12-29')).toBe('2026-W01');+ expect(resolveNewWeekId('2026-W01', '2026-01-01')).toBe('2026-W01');+ // The collision case: the same old id, a January date — a DIFFERENT week.+ expect(resolveNewWeekId('2025-W01', '2025-01-01')).toBe('2025-W01');+ });++ it('recognizes an id already in the new form so a re-run is a no-op', () => {+ expect(resolveNewWeekId('2026-W01', '2025-12-29')).toBe('2026-W01');+ expect(resolveNewWeekId('2026-W53', '2027-01-01')).toBe('2026-W53');+ });++ it('leaves a mid-year id alone without needing a date at all', () => {+ expect(resolveNewWeekId('2026-W25', null)).toBe('2026-W25');+ expect(resolveNewWeekId('2026-W02', undefined)).toBe('2026-W02');+ expect(resolveNewWeekId('2026-W51', null)).toBe('2026-W51');+ });++ it('refuses to guess an ambiguous boundary id with no usable date', () => {+ expect(resolveNewWeekId('2026-W01', null)).toBeNull();+ expect(resolveNewWeekId('2025-W52', 'not-a-date')).toBeNull();+ expect(resolveNewWeekId('2026-W53', null)).toBeNull();+ });++ it('ignores a date that does not reproduce the stored id', () => {+ // Inconsistent record — fall back to the arithmetic rule, which cannot+ // resolve a W01, so leave it rather than move a digest onto a wrong week.+ expect(resolveNewWeekId('2025-W01', '2026-06-15')).toBeNull();+ });++ it('returns null for an unparseable id', () => {+ expect(resolveNewWeekId('garbage', '2026-01-01')).toBeNull();+ });+});++describe('planDigestRewrite', () => {+ it('renames the boundary digest and rewrites its stored weekId', () => {+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2025-W01.json', digest: digestFixture('2025-W01', '2025-12-29') },+ ]);+ expect(writes).toHaveLength(1);+ expect(writes[0].file).toBe('2026-W01.json');+ expect(writes[0].digest.weekId).toBe('2026-W01');+ expect(deletes).toEqual(['2025-W01.json']);+ expect(skipped).toEqual([]);+ });++ it('recomputes previousWeekId from weekStart so the chain still resolves', () => {+ const { writes } = planDigestRewrite([+ { file: '2025-W01.json', digest: digestFixture('2025-W01', '2025-12-29', { previousWeekId: '2025-W52' }) },+ ]);+ expect(writes[0].digest.previousWeekId).toBe('2025-W52');+ });++ it('leaves a null previousWeekId null', () => {+ const { writes } = planDigestRewrite([+ { file: '2025-W01.json', digest: digestFixture('2025-W01', '2025-12-29', { previousWeekId: null }) },+ ]);+ expect(writes[0].digest.previousWeekId).toBeNull();+ });++ it('plans nothing when every digest already uses the new ids', () => {+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2026-W01.json', digest: digestFixture('2026-W01', '2025-12-29') },+ { file: '2026-W25.json', digest: digestFixture('2026-W25', '2026-06-15') },+ ]);+ expect(writes).toEqual([]);+ expect(deletes).toEqual([]);+ expect(skipped).toEqual([]);+ });++ it('never deletes a digest it could not resolve', () => {+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2025-W52.json', digest: { weekId: '2025-W52' } },+ ]);+ expect(writes).toEqual([]);+ expect(deletes).toEqual([]);+ expect(skipped).toEqual(['2025-W52.json']);+ });++ it('keeps one winner when two records claim the same new name, dropping neither file', () => {+ const stays = digestFixture('2026-W01', '2025-12-29');+ const moves = digestFixture('2025-W01', '2025-12-30');+ const { writes, deletes, skipped } = planDigestRewrite([+ { file: '2025-W01.json', digest: moves },+ { file: '2026-W01.json', digest: stays },+ ]);+ // The record already sitting at the target name wins; nothing is written+ // over it, and the loser keeps its own file rather than being deleted.+ expect(writes).toEqual([]);+ expect(deletes).toEqual([]);+ expect(skipped).toEqual(['2025-W01.json']);+ });+});++describe('migration 224 up()', () => {+ let rootDir;+ const digestsDir = () => join(rootDir, 'data', 'cos', 'digests');+ const productivityFile = () => join(rootDir, 'data', 'cos', 'productivity.json');+ const readJson = async (path) => JSON.parse(await readFile(path, 'utf-8'));++ beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-224-'));+ await mkdir(join(rootDir, 'data', 'cos'), { recursive: true });+ });+ afterEach(async () => { await rm(rootDir, { recursive: true, force: true }); });++ it('no-ops on a fresh install with no digests and no productivity record', async () => {+ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true, renamed: 0 });+ });++ it('renames a boundary digest and removes the old-form file', async () => {+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(digestFixture('2025-W01', '2025-12-29')));++ await migration.up({ rootDir });++ expect(existsSync(join(digestsDir(), '2025-W01.json'))).toBe(false);+ expect(await readJson(join(digestsDir(), '2026-W01.json'))).toMatchObject({ weekId: '2026-W01' });+ });++ it('resolves the overwrite collision from weekStart, keeping the surviving content', async () => {+ // The pre-fix bug: the week of 2025-12-29 and the week of 2025-01-01 both+ // stamped '2025-W01', so only ONE file exists — whichever wrote last.+ await mkdir(digestsDir(), { recursive: true });+ const survivor = digestFixture('2025-W01', '2025-12-29', { summary: { totalTasks: 7 } });+ await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(survivor));++ await migration.up({ rootDir });++ const moved = await readJson(join(digestsDir(), '2026-W01.json'));+ expect(moved.summary.totalTasks).toBe(7);+ expect(moved.weekId).toBe('2026-W01');+ });++ it('leaves a mid-year digest byte-identical', async () => {+ await mkdir(digestsDir(), { recursive: true });+ const path = join(digestsDir(), '2026-W25.json');+ await writeFile(path, JSON.stringify(digestFixture('2026-W25', '2026-06-15')));+ const before = await readFile(path, 'utf-8');++ await migration.up({ rootDir });++ expect(await readFile(path, 'utf-8')).toBe(before);+ });++ it('skips an unreadable digest instead of throwing the boot migration run', async () => {+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2026-W25.json'), 'not json');++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ ok: true });+ expect(existsSync(join(digestsDir(), '2026-W25.json'))).toBe(true);+ });++ it('re-keys streaks.lastActiveWeek using lastActiveDate', async () => {+ await writeFile(productivityFile(), JSON.stringify({+ streaks: { lastActiveDate: '2025-12-29', lastActiveWeek: '2025-W01', currentWeekly: 3, longestWeekly: 3 },+ }));++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ lastActiveWeekChanged: true });++ const after = await readJson(productivityFile());+ expect(after.streaks).toMatchObject({ lastActiveWeek: '2026-W01', currentWeekly: 3 });+ });++ it('leaves an ambiguous lastActiveWeek alone rather than guessing a week', async () => {+ await writeFile(productivityFile(), JSON.stringify({+ streaks: { lastActiveDate: null, lastActiveWeek: '2025-W52' },+ }));++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ lastActiveWeekChanged: false });+ expect((await readJson(productivityFile())).streaks.lastActiveWeek).toBe('2025-W52');+ });++ it('is idempotent — a second run changes nothing on disk', async () => {+ await mkdir(digestsDir(), { recursive: true });+ await writeFile(join(digestsDir(), '2025-W01.json'), JSON.stringify(digestFixture('2025-W01', '2025-12-29', { previousWeekId: '2025-W52' })));+ await writeFile(join(digestsDir(), '2026-W25.json'), JSON.stringify(digestFixture('2026-W25', '2026-06-15')));+ await writeFile(productivityFile(), JSON.stringify({+ streaks: { lastActiveDate: '2025-12-29', lastActiveWeek: '2025-W01' },+ }));++ await migration.up({ rootDir });+ const snapshot = async () => {+ const names = (await readdir(digestsDir())).sort();+ const files = await Promise.all(names.map(n => readFile(join(digestsDir(), n), 'utf-8')));+ return { names, files, productivity: await readFile(productivityFile(), 'utf-8') };+ };+ const first = await snapshot();++ await expect(migration.up({ rootDir })).resolves.toMatchObject({ renamed: 0, lastActiveWeekChanged: false });+ expect(await snapshot()).toEqual(first);+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 24a296f906..4360015c58 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -298,6 +298,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. || `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. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. |+| `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), `isoWeeksInYear(year)` (52, or 53 in a leap-week year), and `isConsecutiveWeek(a, b)` — which bridges a year rollover only when `a` is genuinely its year's last week. Shared by `services/productivity.js` (streaks) and `services/weeklyDigest.js` (digest filenames). || `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. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |diff --git a/server/lib/index.js b/server/lib/index.jsindex 7a6abe08d0..4a43142229 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -267,6 +267,7 @@ export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './errorHandler.js';export * from './extensionErrors.js';+export * from './isoWeek.js';export * from './lwwTimestamp.js';export * from './mapWithConcurrency.js';export * from './markedSection.js';diff --git a/server/lib/isoWeek.js b/server/lib/isoWeek.jsnew file mode 100644index 0000000000..3d17c84418--- /dev/null+++ b/server/lib/isoWeek.js@@ -0,0 +1,117 @@+/**+ * ISO-8601 week identity (pure).+ *+ * The one place PortOS turns a date into a `YYYY-Www` week id. Both the CoS+ * productivity streaks (`services/productivity.js`) and the weekly digest+ * (`services/weeklyDigest.js`) used to carry their own copy, and both paired+ * the ISO week NUMBER with the CALENDAR year (#3465). Those two disagree at+ * either end of the year, which split one ISO week across two ids (breaking+ * streaks and week-over-week lookups) and collided two different weeks onto a+ * single id (a late-December digest overwriting the early-January one).+ *+ * The year here is the ISO week-numbering year — the calendar year of that+ * week's Thursday — so every day of an ISO week shares one id and no id is+ * ever reused. `2025-12-29` (Mon) and `2026-01-01` (Thu) are both `2026-W01`.+ *+ * Dates are read through their LOCAL calendar components (a task completed at+ * 23:00 local belongs to that local day, not the UTC one); the arithmetic then+ * runs in UTC so DST transitions can't shift a day boundary.+ */++const MS_PER_DAY = 86400000;++/**+ * UTC-midnight Date for the Thursday of the ISO week containing `date`.+ * Thursday is the ISO anchor: it always falls in the week's own numbering year.+ */+function isoWeekThursday(date) {+ const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));+ const isoDay = d.getUTCDay() || 7; // Mon=1 … Sun=7+ d.setUTCDate(d.getUTCDate() + 4 - isoDay);+ return d;+}++/**+ * Split a date into its ISO week-numbering year and week number.+ *+ * @param {Date} [date]+ * @returns {{ year: number, week: number }}+ */+export function isoWeekParts(date = new Date()) {+ const thursday = isoWeekThursday(date);+ const year = thursday.getUTCFullYear();+ const week = Math.ceil(((thursday.getTime() - Date.UTC(year, 0, 1)) / MS_PER_DAY + 1) / 7);+ return { year, week };+}++/** ISO week number (1–53) for a date. */+export function getIsoWeekNumber(date = new Date()) {+ return isoWeekParts(date).week;+}++/** ISO week-numbering year for a date — NOT `date.getFullYear()`. */+export function getIsoWeekYear(date = new Date()) {+ return isoWeekParts(date).year;+}++/**+ * Week identifier in `YYYY-Www` form (zero-padded week), keyed on the ISO+ * week-numbering year. Stable and collision-free across a New Year boundary.+ *+ * @param {Date} [date]+ * @returns {string}+ */+export function getWeekId(date = new Date()) {+ const { year, week } = isoWeekParts(date);+ return `${year}-W${String(week).padStart(2, '0')}`;+}++/**+ * Parse a `YYYY-Www` week id. Returns null for anything else, so callers can+ * distinguish "unparseable" from a real week rather than reading NaN.+ *+ * @param {string} weekId+ * @returns {{ year: number, week: number } | null}+ */+export function parseWeekId(weekId) {+ if (typeof weekId !== 'string') return null;+ const match = /^(\d{4})-W(\d{1,2})$/.exec(weekId);+ if (!match) return null;+ const year = Number(match[1]);+ const week = Number(match[2]);+ if (week < 1 || week > 53) return null;+ return { year, week };+}++/**+ * 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+ * its own numbering year, so this derives the answer from the same math as+ * every other export rather than re-deriving the leap rule.+ *+ * @param {number} year+ * @returns {number} 52 or 53+ */+export function isoWeeksInYear(year) {+ return isoWeekParts(new Date(year, 11, 28)).week;+}++/**+ * True when `week2` is the ISO week immediately after `week1`.+ *+ * Across a year rollover, `week1` must be the LAST week of its own numbering+ * year — 53 in a leap-week year, 52 otherwise. A bare `week1 >= 52` check would+ * wrongly bridge `2026-W52` → `2027-W01` even though `2026-W53` sits between.+ *+ * @param {string} week1+ * @param {string} week2+ * @returns {boolean}+ */+export function isConsecutiveWeek(week1, week2) {+ const a = parseWeekId(week1);+ const b = parseWeekId(week2);+ if (!a || !b) return false;+ if (a.year === b.year) return b.week - a.week === 1;+ if (b.year - a.year === 1 && b.week === 1) return a.week === isoWeeksInYear(a.year);+ return false;+}diff --git a/server/lib/isoWeek.test.js b/server/lib/isoWeek.test.jsnew file mode 100644index 0000000000..29e59f5623--- /dev/null+++ b/server/lib/isoWeek.test.js@@ -0,0 +1,130 @@+import { describe, expect, it } from 'vitest';+import {+ getIsoWeekNumber,+ getIsoWeekYear,+ getWeekId,+ isConsecutiveWeek,+ isoWeekParts,+ isoWeeksInYear,+ parseWeekId,+} from './isoWeek.js';++// Local-calendar dates: the week id is a local-day concept, so build the+// fixtures the same way a caller would (`new Date(agent.completedAt)`).+const on = (year, month, day) => new Date(year, month - 1, day);++describe('getWeekId', () => {+ it('gives one id to the ISO week that straddles New Year (#3465)', () => {+ // Mon 2025-12-29 and Thu 2026-01-01 are the SAME ISO week. The pre-#3465+ // helper stamped them '2025-W01' and '2026-W01'.+ expect(getWeekId(on(2025, 12, 29))).toBe('2026-W01');+ expect(getWeekId(on(2026, 1, 1))).toBe('2026-W01');+ expect(getWeekId(on(2025, 12, 29))).toBe(getWeekId(on(2026, 1, 1)));+ });++ it('keeps the early-January week of a mid-week Jan 1 distinct from the December one', () => {+ // The collision half: both weeks used to stamp '2025-W01', so the December+ // digest overwrote the January one on disk.+ expect(getWeekId(on(2025, 1, 1))).toBe('2025-W01');+ expect(getWeekId(on(2025, 1, 1))).not.toBe(getWeekId(on(2025, 12, 29)));+ });++ it('files late December under the following year when the week belongs to it', () => {+ expect(getWeekId(on(2024, 12, 30))).toBe('2025-W01');+ expect(getWeekId(on(2025, 12, 28))).toBe('2025-W52');+ });++ it('files early January under the previous year when the week belongs to it', () => {+ // 2026 is a leap-week year, so its W53 runs through Sun 2027-01-03.+ expect(getWeekId(on(2027, 1, 1))).toBe('2026-W53');+ expect(getWeekId(on(2027, 1, 3))).toBe('2026-W53');+ expect(getWeekId(on(2027, 1, 4))).toBe('2027-W01');+ });++ it('numbers the 53rd week of a leap-week year', () => {+ expect(getWeekId(on(2026, 12, 27))).toBe('2026-W52');+ expect(getWeekId(on(2026, 12, 28))).toBe('2026-W53');+ expect(getWeekId(on(2020, 12, 28))).toBe('2020-W53');+ });++ it('zero-pads single-digit week numbers', () => {+ expect(getWeekId(on(2026, 3, 4))).toBe('2026-W10');+ expect(getWeekId(on(2026, 2, 9))).toBe('2026-W07');+ });++ it('holds every day of one ISO week on the same id', () => {+ const ids = [29, 30, 31].map(day => getWeekId(on(2025, 12, day)))+ .concat([1, 2, 3, 4].map(day => getWeekId(on(2026, 1, day))));+ expect(new Set(ids)).toEqual(new Set(['2026-W01']));+ });+});++describe('isoWeekParts / getIsoWeekNumber / getIsoWeekYear', () => {+ it('splits a boundary date into the numbering year, not the calendar year', () => {+ expect(isoWeekParts(on(2025, 12, 29))).toEqual({ year: 2026, week: 1 });+ expect(getIsoWeekYear(on(2025, 12, 29))).toBe(2026);+ expect(getIsoWeekNumber(on(2025, 12, 29))).toBe(1);+ });++ it('agrees with the calendar year away from the boundary', () => {+ expect(isoWeekParts(on(2026, 6, 15))).toEqual({ year: 2026, week: 25 });+ });+});++describe('isoWeeksInYear', () => {+ it('reports 52 for an ordinary year and 53 for a leap-week year', () => {+ expect(isoWeeksInYear(2024)).toBe(52);+ expect(isoWeeksInYear(2025)).toBe(52);+ expect(isoWeeksInYear(2026)).toBe(53);+ expect(isoWeeksInYear(2020)).toBe(53);+ expect(isoWeeksInYear(2015)).toBe(53);+ });+});++describe('parseWeekId', () => {+ it('parses a well-formed id', () => {+ expect(parseWeekId('2026-W01')).toEqual({ year: 2026, week: 1 });+ expect(parseWeekId('2026-W53')).toEqual({ year: 2026, week: 53 });+ });++ it('returns null rather than NaN for anything else', () => {+ for (const bad of ['', '2026', '2026-01', 'W01', '2026-W', '2026-W00', '2026-W54', null, undefined, 20261, {}]) {+ expect(parseWeekId(bad)).toBeNull();+ }+ });+});++describe('isConsecutiveWeek', () => {+ it('accepts adjacent weeks inside a year', () => {+ expect(isConsecutiveWeek('2026-W10', '2026-W11')).toBe(true);+ });++ it('rejects a gap, a repeat, and a backwards step', () => {+ expect(isConsecutiveWeek('2026-W10', '2026-W12')).toBe(false);+ expect(isConsecutiveWeek('2026-W10', '2026-W10')).toBe(false);+ expect(isConsecutiveWeek('2026-W11', '2026-W10')).toBe(false);+ });++ it('still bridges a real year rollover', () => {+ expect(isConsecutiveWeek('2025-W52', '2026-W01')).toBe(true);+ });++ it('does NOT bridge W52 → W01 across a leap-week year, whose W53 sits between', () => {+ expect(isConsecutiveWeek('2026-W52', '2027-W01')).toBe(false);+ expect(isConsecutiveWeek('2026-W52', '2026-W53')).toBe(true);+ expect(isConsecutiveWeek('2026-W53', '2027-W01')).toBe(true);+ });++ it('rejects a multi-year jump and an unparseable id', () => {+ expect(isConsecutiveWeek('2024-W52', '2026-W01')).toBe(false);+ expect(isConsecutiveWeek(null, '2026-W01')).toBe(false);+ expect(isConsecutiveWeek('2026-W01', undefined)).toBe(false);+ expect(isConsecutiveWeek('not-a-week', '2026-W01')).toBe(false);+ });++ it('chains a whole rollover the way the streak scan walks it', () => {+ const weeks = ['2025-W51', '2025-W52', '2026-W01', '2026-W02'];+ const chained = weeks.slice(1).every((week, i) => isConsecutiveWeek(weeks[i], week));+ expect(chained).toBe(true);+ });+});diff --git a/server/services/productivity.js b/server/services/productivity.jsindex 41f723b05e..3c5c29cd46 100644--- a/server/services/productivity.js+++ b/server/services/productivity.js@@ -9,6 +9,7 @@ import { join } from 'path';import { cosEvents } from './cosEvents.js';import { getAgents } from './cosAgents.js';import { ensureDir, getDateString, PATHS, readJSONFile, atomicWrite } from '../lib/fileUtils.js';+import { getWeekId, isConsecutiveWeek } from '../lib/isoWeek.js';const DATA_DIR = PATHS.cos;const PRODUCTIVITY_FILE = join(DATA_DIR, 'productivity.json');@@ -69,18 +70,6 @@ async function saveProductivity(data) {return data;}-/**- * Get week identifier (YYYY-WXX format)- */-function getWeekId(date = new Date()) {- const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));- const dayNum = d.getUTCDay() || 7;- d.setUTCDate(d.getUTCDate() + 4 - dayNum);- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));- const week = Math.ceil((((d - yearStart) / 86400000) + 1) / 7);- return `${date.getFullYear()}-W${week.toString().padStart(2, '0')}`;-}-/*** Check if two dates are consecutive days*/@@ -94,20 +83,6 @@ function isConsecutiveDay(date1, date2) {return diffDays === 1;}-/**- * Check if two weeks are consecutive- */-function isConsecutiveWeek(week1, week2) {- if (!week1 || !week2) return false;- // Parse YYYY-WXX format- const [y1, w1] = week1.split('-W').map(Number);- const [y2, w2] = week2.split('-W').map(Number);-- if (y1 === y2) return w2 - w1 === 1;- if (y2 - y1 === 1 && w1 >= 52 && w2 === 1) return true;- return false;-}-/*** Recalculate all productivity metrics from agent history*/diff --git a/server/services/productivity.test.js b/server/services/productivity.test.jsindex cd2c959714..0ceb59c975 100644--- a/server/services/productivity.test.js+++ b/server/services/productivity.test.js@@ -334,22 +334,31 @@ describe('onTaskCompleted — incremental streak updates', () => {});});- it('splits an ISO week that straddles the new year into two week ids (#3465)', async () => {- // Characterization, not endorsement: getWeekId() pairs the ISO week NUMBER- // with the CALENDAR year, so Mon 2025-12-29 and Thu 2026-01-01 — one and- // the same ISO week — stamp as '2025-W01' and '2026-W01', and the rollover- // branch of isConsecutiveWeek (which only accepts w1 >= 52) does not bridge- // them. Pinned so the fix in #3465 has to update this deliberately.+ it('keeps an ISO week that straddles the new year on a single week id (#3465)', async () => {+ // Mon 2025-12-29 and Thu 2026-01-01 are the SAME ISO week. Before #3465 the+ // week id paired the ISO week NUMBER with the CALENDAR year, so they stamped+ // '2025-W01' and '2026-W01' — splitting the week (and reusing '2025-W01',+ // which is also the id of the JANUARY 2025 week). Both are now '2026-W01'.await productivity.onTaskCompleted(agentOn('dec', { month: 12, day: 29, completedAt: new Date(2025, 11, 29, 10).toISOString() }));- expect(readStore().streaks).toMatchObject({ lastActiveWeek: '2025-W01', currentWeekly: 1 });+ expect(readStore().streaks).toMatchObject({ lastActiveWeek: '2026-W01', currentWeekly: 1 });await productivity.onTaskCompleted(agentOn('jan', { month: 1, day: 1 }));+ // Same week, so the id does not move and the week is not counted twice.expect(readStore().streaks).toMatchObject({lastActiveWeek: '2026-W01',currentWeekly: 1,longestWeekly: 1,});++ // …and the following week extends the streak instead of resetting it.+ await productivity.onTaskCompleted(agentOn('next', { month: 1, day: 5 }));++ expect(readStore().streaks).toMatchObject({+ lastActiveWeek: '2026-W02',+ currentWeekly: 2,+ longestWeekly: 2,+ });});it('prunes daily history older than 90 days', async () => {diff --git a/server/services/weeklyDigest.js b/server/services/weeklyDigest.jsindex e70b37fb47..54ba4c18f3 100644--- a/server/services/weeklyDigest.js+++ b/server/services/weeklyDigest.js@@ -12,6 +12,7 @@ import { join } from 'path';import { cosEvents, emitLog } from './cosEvents.js';import { getAgents, getAgentDates, getAgentsByDate } from './cosAgents.js';import { atomicWrite, ensureDir, readJSONFile, formatDuration, PATHS } from '../lib/fileUtils.js';+import { getWeekId } from '../lib/isoWeek.js';const DIGESTS_DIR = PATHS.digests;@@ -25,26 +26,6 @@ function getWeekStart(date = new Date()) {return new Date(d.setDate(diff));}-/**- * Get the ISO week number for a date- */-function getWeekNumber(date = new Date()) {- const d = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));- const dayNum = d.getUTCDay() || 7;- d.setUTCDate(d.getUTCDate() + 4 - dayNum);- const yearStart = new Date(Date.UTC(d.getUTCFullYear(), 0, 1));- return Math.ceil((((d - yearStart) / 86400000) + 1) / 7);-}--/**- * Get week identifier (YYYY-WXX format)- */-function getWeekId(date = new Date()) {- const year = date.getFullYear();- const week = getWeekNumber(date);- return `${year}-W${week.toString().padStart(2, '0')}`;-}-/*** Ensure digest directory exists*/diff --git a/server/services/weeklyDigest.test.js b/server/services/weeklyDigest.test.jsindex 701c0ba92e..dafc09142b 100644--- a/server/services/weeklyDigest.test.js+++ b/server/services/weeklyDigest.test.js@@ -239,12 +239,11 @@ describe('generateWeeklyDigest — summary assembly', () => {expect(digest.accomplishments.map(a => a.id).sort()).toEqual(['dupe', 'state-only']);});- it('splits an ISO week straddling the new year across two digests (#3465)', async () => {- // Characterization, not endorsement: the week id pairs the ISO week NUMBER- // with the CALENDAR year, so the single ISO week containing Mon 2025-12-29- // and Thu 2026-01-01 is filed as '2025-W01' and '2026-W01' — and '2025-W01'- // is also the id of the *January* 2025 week, so the two overwrite each- // other on disk. Pinned so the fix in #3465 has to update this deliberately.+ it('files an ISO week straddling the new year as one digest, distinct from the earlier January (#3465)', async () => {+ // Mon 2025-12-29 and Thu 2026-01-01 are the SAME ISO week. Before #3465 the+ // week id paired the ISO week NUMBER with the CALENDAR year, so that week+ // was filed twice ('2025-W01' and '2026-W01') — and '2025-W01' was ALSO the+ // id of the *January 2025* week, so the two clobbered each other on disk.vi.setSystemTime(new Date(2025, 11, 29, 12, 0, 0));onDates([agent('dec', { year: 2025, month: 12, day: 29 }),@@ -253,34 +252,34 @@ describe('generateWeeklyDigest — summary assembly', () => {const december = await digestService.generateWeeklyDigest();- expect(december.weekId).toBe('2025-W01');- expect(december.summary.totalTasks).toBe(1);- expect(december.accomplishments.map(a => a.id)).toEqual(['dec']);- expect(existsSync(join(DIGESTS_DIR, '2025-W01.json'))).toBe(true);+ expect(december.weekId).toBe('2026-W01');+ expect(december.summary.totalTasks).toBe(2);+ expect(december.accomplishments.map(a => a.id).sort()).toEqual(['dec', 'jan']);+ expect(existsSync(join(DIGESTS_DIR, '2026-W01.json'))).toBe(true);+ expect(existsSync(join(DIGESTS_DIR, '2025-W01.json'))).toBe(false);- // Same ISO week, three days later — filed as a second, separate digest.+ // Same ISO week, three days later — the SAME digest, not a second one.vi.setSystemTime(new Date(2026, 0, 1, 12, 0, 0));const january = await digestService.generateWeeklyDigest();expect(january.weekId).toBe('2026-W01');- expect(january.summary.totalTasks).toBe(1);- expect(january.accomplishments.map(a => a.id)).toEqual(['jan']);+ expect(january.summary.totalTasks).toBe(2);+ expect(existsSync(join(DIGESTS_DIR, '2025-W01.json'))).toBe(false);- // And the collision half: the week of 2025-01-02 stamps '2025-W01' too, so- // regenerating it merges in the December-2025 agent and overwrites the file- // the first generation wrote.+ // And the former collision: the week of 2025-01-02 is its own id, holds only+ // its own agent, and leaves the December/January digest intact.onDates([agent('dec', { year: 2025, month: 12, day: 29 }),agent('jan', { year: 2026, month: 1, day: 1 }),agent('jan2025', { year: 2025, month: 1, day: 2 }),]);vi.setSystemTime(new Date(2025, 0, 2, 12, 0, 0));- const collided = await digestService.generateWeeklyDigest();+ const earlyJanuary = await digestService.generateWeeklyDigest();- expect(collided.weekId).toBe('2025-W01');- expect(collided.summary.totalTasks).toBe(2);- expect(collided.accomplishments.map(a => a.id).sort()).toEqual(['dec', 'jan2025']);- expect(readDigest('2025-W01').summary.totalTasks).toBe(2);+ expect(earlyJanuary.weekId).toBe('2025-W01');+ expect(earlyJanuary.summary.totalTasks).toBe(1);+ expect(earlyJanuary.accomplishments.map(a => a.id)).toEqual(['jan2025']);+ expect(readDigest('2026-W01').summary.totalTasks).toBe(2);});it('persists the digest and announces it on the CoS event bus', async () => {