Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(conversation-parser): read chat timestamps in the page's declared timezone (#5430)

garrytand8968c14d68e
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index 8547d532a7..08a34fda4b 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -4,7 +4,7 @@
Current behavior and load-bearing invariants; history belongs in Git and CHANGELOG.
Fact and page purge modules (`src/core/facts/purge*.ts`, `deletion-inventory.ts`): [memory purge](memory-purge.md).
-- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns `skipped` with `fixture_unavailable`, which the autopilot wiring audits, and the wiring reads the embedded fixtures from `cycle/nightly-probe-fixtures.ts`). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).
+- `src/core/conversation-parser/` — 19-pattern built-in chat-format registry + opt-in LLM fallback. Modules: `types.ts` (PatternEntry + ParseResult + DateContext + CaptureMap + TimezonePolicy), `builtins.ts` (19 hand-vetted patterns sourced from public format docs — iMessage/Slack, Telegram bracket + text-export, bold-paren-time, bold-time-dash, bold-name-no-time, chatgpt-export-you-chatgpt, Discord classic + export, WhatsApp ISO + US, Signal, Matrix/Element, IRC classic + weechat, Teams export, markdown-heading-turn; module-load validation runs every `test_positive[]` + `test_negative[]` sample at startup so a typo in any built-in regex makes gbrain refuse to start; `DEFAULT_SPEAKER_CLEAN` exported as a module-level default), `parse.ts` (orchestrator with pattern-priority scoring across the first 10 lines + date derivation chain `explicit > frontmatter.date > effective_date > '1970-01-01'` + multi-line continuation + timezone warning; #5430 (W14 P1.9): a valid `frontmatter.timezone` (IANA) converts every built timestamp from that zone's wall clock to UTC through `localToUtcIso(date, hour, minute, tz)` (`Intl` `longOffset`, no dependency, host-TZ independent; a DST fold takes the first occurrence, a gap the pre-transition offset), an invalid zone is reported as `DateContext.invalid_timezone` and the warning names it while timestamps stay UTC (`test/conversation-parser/timezone.test.ts`); also populates `ParseResult.unrecognized_headings` — when the WINNING pattern is heading-anchored, heading-shaped lines whose label is outside the pattern's speaker set FOLD into the previous turn's body (or drop before the first anchor) while the parse still returns `regex_match`, silently crediting one speaker with another's words; detection is diagnostic-only and unconditional (not behind `opts.diagnostic` — the extractor's decline gate depends on it), fence-aware (a fence closes only on ITS OWN marker; an unclosed fence suppresses detection below it), labels deduped/capped at 10 entries ≤48 chars, undefined when empty so healthy-page JSON stays byte-identical; `gbrain conversation-parser scan` surfaces the field in both human and JSON output; `applyPattern` never DROPS a matched anchor whose date it cannot reconstruct (a localized month name, malformed digits) — dropping it would fold that speaker's body into the previous turn on a multi_line pattern, so the message opens anyway, inheriting the previous anchor's timestamp (page fallback date at midnight for the first), and the count surfaces as `ParseResult.date_fallback_count`, undefined when zero), `llm-base.ts` (shared `runLlmCall<T>` with content-hash cache in-process + DB-persistent via migration v97 + 4-strategy JSON repair + Anthropic-key probe; fallback is a thin wrapper), `llm-fallback.ts` (opt-IN; NO regex inference + NO persistence), `eval.ts` (`scoreFixture` + `aggregateScores` + `parseFixtureJsonl` for the fixture-corpus CI gate), `nightly-probe.ts` (DI-stubbed; mode-gated default tokenmax=ON, conservative/balanced opt-in; adversarial false-positive detection; an unreadable fixture returns `skipped` with `fixture_unavailable`, which the autopilot wiring audits, and the wiring reads the embedded fixtures from `cycle/nightly-probe-fixtures.ts`). Pattern `bold-name-no-time` (regex `/^\*\*(?!\[)(.+?):\*\*\s*(.*)$/`, ordered after the time-bearing bold patterns) parses `**Speaker:** text` with NO per-line timestamp (Circleback/Granola/Zoom), anchoring every message at `T00:00:00Z` of the frontmatter date (line order preserves sequence, same no-time convention as `irc-classic`); the `(?!\[)` lookahead rejects telegram-bracket `**[18:37] Name:**`; non-shadow is the colon-INSIDE-bold regex (NOT declaration order — `parse.ts` scores every candidate independently, order is only the tie-break). Because `**Label:** text` is a common prose idiom, the pattern sets optional `PatternEntry.score_full_body: true` so `parse.ts` recomputes the winner's acceptance score over the FULL body before the `SCORING_MIN_ACCEPTANCE` floor, keeping a bold-label notes page at `no_match`. Pattern `chatgpt-export-you-chatgpt` (regex `/^\*\*(You|ChatGPT):\*\*\s*(.*)$/`, declared just before `bold-name-no-time` so it wins the score tie on the two literal ChatGPT-export labels) parses ChatGPT's web-export → Markdown shape, where each turn's `**You:**` / `**ChatGPT:**` anchor is followed by a blank line and a multi-paragraph reply; `bold-name-no-time` alone cannot absorb that shape (`multi_line: false` scores a long reply's density near zero and falls below `SCORING_MIN_ACCEPTANCE`), so this pattern sets `multi_line: true` + `score_continuations_as_body: true` (excludes non-`**`-prefixed reply lines from the density denominator) + `score_full_body: true`. The speaker capture is a closed two-value enumeration (`You` or `ChatGPT` exactly, never an arbitrary `(.+?)` label), so it cannot reopen `bold-name-no-time`'s BROAD-REGEX GUARD against notes pages. Because a bare `**You:**`/`**ChatGPT:**` heading is plausible in prose ABOUT ChatGPT, the pattern also sets the optional `PatternEntry.score_continuations_min_distinct_speakers: 2`: `scoreFromLines` only grants the continuation-density-exclusion score when the anchor lines that fully match `regex` collectively capture at least that many DISTINCT `speaker_group` values, so a page with only one role falls back to the ordinary flat-density score. It ALSO sets `PatternEntry.score_continuations_max_preamble_lines: 5`, because one genuine pair embedded deep in an unrelated long document would otherwise pass: `scoreFromLines` tracks the index of the FIRST fully-matching anchor line and only grants the immunity when that index is at or before the bound (a short title preamble is tolerated). Pattern `bold-paren-time` parses `**Speaker** (HH:MM): text` and `(HH:MM:SS)` (date_source: frontmatter). Fallback gates: `SCORING_HEAD_TRIGGER_THRESHOLD = 0.3` triggers a full-body re-score when the head pass scores below that; `SCORING_MIN_ACCEPTANCE = 0.05` blocks essay false-positives. Exported `scorePatternFull(body, entry)`; private `getNonBlankLines(body, headCap?)` + `scoreFromLines(lines, entry)` DRY the quick_reject+regex loop. CLI surfaces at `src/commands/eval-conversation-parser.ts` (`gbrain eval conversation-parser <fixture.jsonl>` exit 0/1/2, wired into `bun run verify` via `check:conversation-parser`) and `src/commands/conversation-parser.ts` (`scan <slug>` debug, `list-builtins`, `validate <file>`). Doctor checks: `conversation_format_coverage`, `progressive_batch_audit_health`, `conversation_parser_probe_health`. Pinned by `test/conversation-parser/{parse,llm-base,llm-fallback,nightly-probe}.test.ts` + the 27-case baseline at `test/extract-conversation-facts.test.ts` (back-compat invariant). Migration v97 (`conversation_parser_llm_cache_table`). Fixtures at `test/fixtures/conversation-formats/{imessage,imessage-time-only-12h,telegram-bracket,whatsapp-iso,whatsapp-us,signal-export,irc-classic,irc-weechat,matrix-element,teams-export,all,adversarial,bold-name-no-time,bold-time-dash,chatgpt-export-you-chatgpt}.jsonl` with `scripts/check-fixture-privacy.sh` banning real-name leaks. Maintainer guidance: [conversation parser patterns](../conversation-parser-patterns.md).
- `src/core/facts/conversation-types.ts` — single-source conversation-type allowlist (`ALLOWED_TYPES`: conversation, meeting, slack, email, imessage, imessage-daily + `AllowedType`). It also owns the granular collector aliases (`ALLOWED_TYPE_ALIASES`, `pageTypesForAllowed`) and the one eligibility rule (#5330): `isConversationFactsEligiblePage` and its SQL twin `conversationFactsEligibleSql` admit an allowed concrete type unless frontmatter says `conversation_parseable: false`; with `cycle.conversation_facts_backfill.require_parseable_flag` on, only `type: conversation` or `conversation_parseable: true`. The extractor (slug, batch and enumeration paths), the doctor backlog SQL and its in-process verifier, and the format-coverage sample all use it, so the backlog can drain. Every consumer derives from this frozen leaf module — `extract-conversation-facts.ts` (which re-exports both names verbatim for its existing importers), the cycle backfill phase, `doctor.ts` + `doctor/checks/search-eval.ts`, `sources.ts`, `jobs.ts` — so no hand-copied list can drift. It lives under `src/core/facts/` (not `src/commands/`) because `scripts/generate-flag-registry.ts` scans option-shaped literals one relative-import level deep — importing the constant straight from `extract-conversation-facts.ts` would transitively attribute that command's whole option surface to doctor/jobs/sources in the generated CLI_ONLY registry. Drift-guarded by `test/conversation-facts-type-allowlist-drift.test.ts`. `isFrontmatterFlagOff` (the same off spellings) is shared with `facts/eligibility.ts`.
- `src/core/facts/eligibility.ts` — `isFactsBackstopEligible`, the one automatic facts-extraction predicate (page-write outbox, its `body_unchanged` check, sync's post-import hook, the facts-absorb job's re-check). Skips `wiki/agents/`, `dream_generated: true`, `facts_backstop` set off (`opted_out`, #6232: a writer's opt-out for a page whose facts another page carries, such as a meeting's raw transcript; removing it re-offers the page even with an unchanged body), bodies under 80 characters, and types outside `ELIGIBLE_TYPES` unless the slug is under a rescue prefix. Receipt reasons are documented under `facts_backstop_skipped` in the error registry. Pinned by `test/facts-eligibility.test.ts`, `test/persistence-facts-backstop.test.ts`. #6259: a quarantined page (the gate's `quarantine` marker) is ineligible with reason `quarantined`, which the page-write receipt reports as `facts_backstop.skipped` (registered in `facts_backstop_skipped`).
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 5aafbb2abf..9f2090d9f4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -383,6 +383,8 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.156.0', text: '`gbrain sources archive`, `remove` and `purge` no longer walk and hash a canonical checkout that already has a verified manifest: they compare no bytes, so a symlink or submodule that appeared in the checkout after it was claimed no longer refuses them with `writer_manifest_unsafe` while their dry run said they would succeed. The stored manifest keeps its digest and gets a fresh `canonical_stamp`; a source claimed before activation, whose manifest was never recorded, still records it on retire. Claim, set-path (rebind), restore and reclone still hash the checkout, and every lifecycle dry run now reports `manifest_required`.' },
// W14 PR1 P1.5b (#5186). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
{ since: '0.60.156.0', text: 'A root-level `AGENTS.md` or `CLAUDE.md` in a source (the agent instructions `gbrain harden` writes) is no longer imported as a page: sync and `gbrain import` classify it as a metafile like `README.md`, while the same file inside a directory is still a page. A root `agents` or `claude` page an earlier version indexed is kept, not deleted; `gbrain delete agents` removes it if it is unwanted.' },
+ // W14 PR1 P1.9 (#5430). `since` is a placeholder equal to the branch's VERSION until the merge-slot stamp.
+ { since: '0.60.156.0', text: 'The conversation parser now reads chat timestamps in the page\'s declared `timezone:` (an IANA zone such as Asia/Tokyo) and stores them in UTC, so a 09:00 Tokyo message is 00:00Z and the facts extracted from it carry the right `valid_from`; before, the zone only silenced the UTC warning and every timestamp was stored as if it were UTC. Conversation pages with a declared zone give different timestamps than before on re-extraction. A zone the runtime does not know keeps UTC and the warning names it. In a daylight-saving fold the first occurrence is taken; a time inside a spring-forward gap resolves with the offset in force before the change.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/conversation-parser/parse.ts b/src/core/conversation-parser/parse.ts
index bbba9d4416..e72ef28d65 100644
--- a/src/core/conversation-parser/parse.ts
+++ b/src/core/conversation-parser/parse.ts
@@ -104,7 +104,7 @@ export function deriveDateContext(opts: ParseConversationOpts): DateContext {
if (/^\d{4}-\d{2}-\d{2}$/.test(sliced)) {
return {
fallbackDate: sliced,
- timezone: extractTimezone(opts.page),
+ ...extractTimezone(opts.page),
source: 'explicit',
};
}
@@ -117,7 +117,7 @@ export function deriveDateContext(opts: ParseConversationOpts): DateContext {
if (/^\d{4}-\d{2}-\d{2}$/.test(sliced)) {
return {
fallbackDate: sliced,
- timezone: extractTimezone(page),
+ ...extractTimezone(page),
source: 'frontmatter_date',
};
}
@@ -126,20 +126,77 @@ export function deriveDateContext(opts: ParseConversationOpts): DateContext {
if (page?.effective_date) {
return {
fallbackDate: page.effective_date.toISOString().slice(0, 10),
- timezone: extractTimezone(page),
+ ...extractTimezone(page),
source: 'effective_date',
};
}
return {
fallbackDate: '1970-01-01',
- timezone: extractTimezone(page),
+ ...extractTimezone(page),
source: 'epoch_default',
};
}
-function extractTimezone(page: ParseConversationOpts['page']): string | undefined {
+function extractTimezone(page: ParseConversationOpts['page']): Pick<DateContext, 'timezone' | 'invalid_timezone'> {
const tz = page?.frontmatter?.timezone;
- return typeof tz === 'string' && tz.length > 0 ? tz : undefined;
+ if (typeof tz !== 'string' || tz.length === 0) return {};
+ return isValidTimeZone(tz) ? { timezone: tz } : { invalid_timezone: tz };
+}
+
+const timeZoneFormatters = new Map<string, Intl.DateTimeFormat>();
+
+function timeZoneFormatter(tz: string): Intl.DateTimeFormat {
+ let formatter = timeZoneFormatters.get(tz);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat('en-US', { timeZone: tz, timeZoneName: 'longOffset', year: 'numeric' });
+ timeZoneFormatters.set(tz, formatter);
+ }
+ return formatter;
+}
+
+/** Whether `tz` is an IANA zone the runtime knows (`Intl` throws RangeError on an unknown one). */
+export function isValidTimeZone(tz: string): boolean {
+ try { timeZoneFormatter(tz); return true; } catch { return false; }
+}
+
+/** The zone's UTC offset in minutes at `instantMs` (`GMT-07:00` -> -420; `GMT` -> 0). */
+function offsetMinutesAt(instantMs: number, tz: string): number {
+ const name = timeZoneFormatter(tz).formatToParts(new Date(instantMs)).find(part => part.type === 'timeZoneName')?.value ?? 'GMT';
+ const m = /^GMT(?:([+-])(\d{1,2})(?::?(\d{2}))?)?$/.exec(name);
+ if (!m || !m[1]) return 0;
+ return (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3] ?? 0));
+}
+
+/**
+ * #5430 (W14 P1.9): the UTC instant of a wall-clock time in an IANA zone,
+ * as `YYYY-MM-DDTHH:MM:00Z`. Pure `Date.UTC` arithmetic plus `Intl` offsets,
+ * so the host timezone never enters. Two DST edge cases have a fixed policy:
+ * a FOLD (the wall time occurs twice, autumn) resolves to the first
+ * occurrence (the earlier instant, still on daylight time); a GAP (the wall
+ * time never occurs, spring) resolves with the offset in force before the
+ * transition, so the instant lands just after the gap (02:30 in a 02:00->03:00
+ * gap becomes the instant 03:30 names).
+ */
+export function localToUtcIso(date: string, hour: number, minute: number, tz: string): string {
+ const [y, mo, d] = date.split('-').map(Number);
+ const wall = Date.UTC(y, mo - 1, d, hour, minute);
+ const day = 24 * 60 * 60 * 1000;
+ const candidates = new Set<number>();
+ for (const probe of [wall - day, wall, wall + day]) {
+ const offset = offsetMinutesAt(probe, tz);
+ const instant = wall - offset * 60 * 1000;
+ if (offsetMinutesAt(instant, tz) === offset) candidates.add(instant);
+ }
+ const instant = candidates.size > 0
+ ? Math.min(...candidates)
+ : wall - offsetMinutesAt(wall - day, tz) * 60 * 1000;
+ return new Date(instant).toISOString().replace(/\.\d{3}Z$/, 'Z');
+}
+
+/** A message timestamp: the wall time in the context's zone when one is declared, else the UTC reading. */
+function stampIso(date: string, hour: number, minute: number, dateCtx: DateContext): string {
+ if (dateCtx.timezone) return localToUtcIso(date, hour, minute, dateCtx.timezone);
+ return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
}
/**
@@ -188,7 +245,7 @@ function buildIso(
if (month < 0 || !Number.isFinite(day) || !Number.isFinite(year)) return null;
const hour = to24h(hourRaw, ampm);
const date = `${year}-${String(month + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
case 'whatsapp-iso': {
// groups: 1=dd, 2=mm, 3=yy, 4=hh, 5=mm, 6=ss, 7=speaker, 8=text
@@ -200,7 +257,7 @@ function buildIso(
const minute = Number(match[5]);
if (![day, month, year, hour, minute].every(Number.isFinite)) return null;
const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
case 'whatsapp-us': {
// groups: 1=mm, 2=dd, 3=yy, 4=hh, 5=mm, 6=ampm, 7=speaker, 8=text
@@ -214,7 +271,7 @@ function buildIso(
if (![month, day, year, hourRaw, minute].every(Number.isFinite)) return null;
const hour = to24h(hourRaw, ampm);
const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
case 'discord-export': {
// groups: 1=mm, 2=dd, 3=yyyy, 4=hh, 5=mm, 6=ampm, 7=speaker
@@ -227,7 +284,7 @@ function buildIso(
if (![month, day, year, hourRaw, minute].every(Number.isFinite)) return null;
const hour = to24h(hourRaw, ampm);
const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
case 'teams-export': {
// groups: 1=speaker, 2=mm, 3=dd, 4=yyyy, 5=hh, 6=mm, 7=ampm, 8=text
@@ -240,7 +297,7 @@ function buildIso(
if (![month, day, year, hourRaw, minute].every(Number.isFinite)) return null;
const hour = to24h(hourRaw, ampm);
const date = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
}
@@ -262,7 +319,7 @@ function buildIso(
const ampm =
captures.ampm_group !== undefined ? match[captures.ampm_group] : undefined;
const hour = to24h(hourRaw, ampm);
- return `${date}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(date, hour, minute, dateCtx);
}
// Time-only patterns: date from DateContext.
@@ -277,7 +334,7 @@ function buildIso(
const ampm =
captures.ampm_group !== undefined ? match[captures.ampm_group] : undefined;
const hour = to24h(hourRaw, ampm);
- return `${dateCtx.fallbackDate}T${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:00Z`;
+ return stampIso(dateCtx.fallbackDate, hour, minute, dateCtx);
}
// No-time patterns (irc-classic): only frontmatter date is
@@ -285,7 +342,7 @@ function buildIso(
// Honest: messages lose intra-day ordering, but at least they
// parse and the day-level fact attribution is correct.
if (entry.date_source === 'frontmatter' && captures.hour_group === undefined) {
- return `${dateCtx.fallbackDate}T00:00:00Z`;
+ return stampIso(dateCtx.fallbackDate, 0, 0, dateCtx);
}
return null;
@@ -417,7 +474,7 @@ export function applyPattern(
// message anyway and count it. Inherit the previous anchor's
// timestamp so ordering and downstream segment continuity survive;
// midnight of the page date only when this is the first anchor.
- iso = out[out.length - 1]?.timestamp ?? `${runningCtx.fallbackDate}T00:00:00Z`;
+ iso = out[out.length - 1]?.timestamp ?? stampIso(runningCtx.fallbackDate, 0, 0, runningCtx);
if (diag) diag.date_fallback_count = (diag.date_fallback_count ?? 0) + 1;
}
const rawSpeaker = m[entry.captures.speaker_group] ?? '';
@@ -783,7 +840,10 @@ export function parseConversation(
// Timezone warning surface (D19).
let timezone_warning: string | undefined;
- if (
+ if (dateCtx.invalid_timezone && messages.length > 0) {
+ // #5430: a declared zone the runtime does not know keeps UTC, and says so.
+ timezone_warning = `[conversation-parser] pattern=${top.entry.id} frontmatter timezone '${dateCtx.invalid_timezone}' is not a valid IANA zone; assumed UTC for timestamps. Fix 'timezone:' in the page frontmatter (for example America/Los_Angeles) for accurate facts`;
+ } else if (
top.entry.timezone_policy === 'utc_assumed_with_warn' &&
!dateCtx.timezone &&
messages.length > 0
diff --git a/src/core/conversation-parser/types.ts b/src/core/conversation-parser/types.ts
index 113a47bbe9..91a41d1ac2 100644
--- a/src/core/conversation-parser/types.ts
+++ b/src/core/conversation-parser/types.ts
@@ -288,8 +288,10 @@ export interface ParseConversationOpts {
export interface DateContext {
/** ISO YYYY-MM-DD string. */
fallbackDate: string;
- /** IANA timezone (e.g. 'America/Los_Angeles') or undefined. */
+ /** Valid IANA timezone (e.g. 'America/Los_Angeles') or undefined. */
timezone?: string;
+ /** #5430: a declared `frontmatter.timezone` that is not a valid IANA zone; timestamps stay UTC and the warning names it. */
+ invalid_timezone?: string;
/** Which step of the derivation chain won (for debug). */
source: 'frontmatter_date' | 'effective_date' | 'explicit' | 'epoch_default';
}
diff --git a/test/conversation-parser/parse.test.ts b/test/conversation-parser/parse.test.ts
index e9fafe409b..8437b61a46 100644
--- a/test/conversation-parser/parse.test.ts
+++ b/test/conversation-parser/parse.test.ts
@@ -677,9 +677,9 @@ describe('bold-time-dash pattern (normalized Slack Markdown)', () => {
'2026-04-09T09:15:00Z',
);
expect(withoutTimezone.timezone_warning).toContain('bold-time-dash');
- // Current time-only policy records the captured wall-clock fields with Z;
- // timezone metadata suppresses the warning but does not convert the time.
- expect(withTimezone.messages[0].timestamp).toBe('2026-04-09T09:15:00Z');
+ // #5430 (W14 P1.9): a declared zone converts the wall-clock time (09:15
+ // PDT is 16:15Z) and suppresses the warning; before, it only suppressed.
+ expect(withTimezone.messages[0].timestamp).toBe('2026-04-09T16:15:00Z');
expect(withTimezone.timezone_warning).toBeUndefined();
});
diff --git a/test/conversation-parser/timezone.test.ts b/test/conversation-parser/timezone.test.ts
new file mode 100644
index 0000000000..d290023bd3
--- /dev/null
+++ b/test/conversation-parser/timezone.test.ts
@@ -0,0 +1,100 @@
+/**
+ * #5430 (W14 P1.9, E.1): the conversation parser honours the page's declared
+ * IANA timezone when it builds message timestamps. Before, every builder
+ * emitted `:00Z`, so a Tokyo 09:00 message carried `T09:00:00Z` (18:00 Tokyo)
+ * and every derived fact's `valid_from` was off by the zone offset.
+ *
+ * Policy for the two DST edge cases (documented in parse.ts `localToUtcIso`):
+ * - a FOLD (the local time happens twice, autumn) resolves to the first
+ * occurrence (the earlier instant, still on daylight time);
+ * - a GAP (the local time never happens, spring) resolves with the offset in
+ * force before the transition, so the instant lands just after the gap.
+ * An invalid zone keeps UTC and the warning says so.
+ */
+import { describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { deriveDateContext, localToUtcIso, parseConversation } from '../../src/core/conversation-parser/parse.ts';
+import type { Page } from '../../src/core/types.ts';
+
+function makePage(frontmatter: Record<string, unknown>): Page {
+ return {
+ id: 1, slug: 'conv/test', type: 'conversation', title: 'Test', frontmatter,
+ compiled_truth: '', timeline: '', created_at: new Date(), updated_at: new Date(), source_id: 'default',
+ } as unknown as Page;
+}
+
+const TELEGRAM = ['**[09:00] \u{1f464} Alice:** good morning', '**[09:05] \u{1f464} Bob:** morning'].join('\n');
+
+describe('localToUtcIso', () => {
+ test('Asia/Tokyo 09:00 is 00:00Z (positive offset)', () => {
+ expect(localToUtcIso('2024-03-15', 9, 0, 'Asia/Tokyo')).toBe('2024-03-15T00:00:00Z');
+ });
+ test('America/Los_Angeles 09:00 is 16:00Z in March (negative offset, daylight time) and 17:00Z in January', () => {
+ expect(localToUtcIso('2024-03-15', 9, 0, 'America/Los_Angeles')).toBe('2024-03-15T16:00:00Z');
+ expect(localToUtcIso('2024-01-15', 9, 0, 'America/Los_Angeles')).toBe('2024-01-15T17:00:00Z');
+ });
+ test('Asia/Kolkata 09:00 is 03:30Z (half-hour offset) and Asia/Kathmandu 09:00 is 03:15Z', () => {
+ expect(localToUtcIso('2024-03-15', 9, 0, 'Asia/Kolkata')).toBe('2024-03-15T03:30:00Z');
+ expect(localToUtcIso('2024-03-15', 9, 0, 'Asia/Kathmandu')).toBe('2024-03-15T03:15:00Z');
+ });
+ test('a local time that crosses the date line moves the UTC date', () => {
+ expect(localToUtcIso('2024-03-15', 1, 30, 'Asia/Tokyo')).toBe('2024-03-14T16:30:00Z');
+ expect(localToUtcIso('2024-03-15', 22, 0, 'America/Los_Angeles')).toBe('2024-03-16T05:00:00Z');
+ });
+ test('a DST fold resolves to the first occurrence (New York 2024-11-03 01:30 is still EDT)', () => {
+ expect(localToUtcIso('2024-11-03', 1, 30, 'America/New_York')).toBe('2024-11-03T05:30:00Z');
+ expect(localToUtcIso('2024-11-03', 0, 30, 'America/New_York')).toBe('2024-11-03T04:30:00Z');
+ expect(localToUtcIso('2024-11-03', 2, 30, 'America/New_York')).toBe('2024-11-03T07:30:00Z');
+ });
+ test('a DST gap resolves with the pre-transition offset (New York 2024-03-10 02:30 does not exist; EST gives 07:30Z, 03:30 EDT)', () => {
+ expect(localToUtcIso('2024-03-10', 2, 30, 'America/New_York')).toBe('2024-03-10T07:30:00Z');
+ expect(localToUtcIso('2024-03-10', 1, 59, 'America/New_York')).toBe('2024-03-10T06:59:00Z');
+ expect(localToUtcIso('2024-03-10', 3, 0, 'America/New_York')).toBe('2024-03-10T07:00:00Z');
+ });
+ test('UTC and Etc/GMT zones are identity', () => {
+ expect(localToUtcIso('2024-03-15', 9, 0, 'UTC')).toBe('2024-03-15T09:00:00Z');
+ expect(localToUtcIso('2024-03-15', 9, 0, 'Etc/GMT+5')).toBe('2024-03-15T14:00:00Z');
+ });
+ test('independent of the host timezone', () => {
+ const script = `import { localToUtcIso } from ${JSON.stringify(new URL('../../src/core/conversation-parser/parse.ts', import.meta.url).pathname)};
+ console.log(JSON.stringify([localToUtcIso('2024-03-15', 9, 0, 'Asia/Tokyo'), localToUtcIso('2024-11-03', 1, 30, 'America/New_York'), localToUtcIso('2024-03-10', 2, 30, 'America/New_York')]));`;
+ for (const TZ of ['Pacific/Kiritimati', 'America/Anchorage', 'UTC']) {
+ const out = execFileSync(process.execPath, ['-e', script], { env: { ...process.env, TZ }, encoding: 'utf8' }).trim();
+ expect(JSON.parse(out)).toEqual(['2024-03-15T00:00:00Z', '2024-11-03T05:30:00Z', '2024-03-10T07:30:00Z']);
+ }
+ }, 60_000);
+});
+
+describe('parseConversation honours frontmatter.timezone', () => {
+ test('time-only pattern: Tokyo 09:00 becomes 00:00Z and no UTC warning is raised', () => {
+ const r = parseConversation(TELEGRAM, { page: makePage({ date: '2024-03-15', timezone: 'Asia/Tokyo' }) });
+ expect(r.messages.map(m => m.timestamp)).toEqual(['2024-03-15T00:00:00Z', '2024-03-15T00:05:00Z']);
+ expect(r.timezone_warning).toBeUndefined();
+ });
+ test('inline-date pattern (whatsapp-iso) applies the zone too', () => {
+ const body = ['[15/03/24, 09:00:00] Alice: hi', '[15/03/24, 09:05:00] Bob: hello'].join('\n');
+ const r = parseConversation(body, { page: makePage({ timezone: 'America/Los_Angeles' }) });
+ expect(r.matched_pattern_id).toBe('whatsapp-iso');
+ expect(r.messages.map(m => m.timestamp)).toEqual(['2024-03-15T16:00:00Z', '2024-03-15T16:05:00Z']);
+ });
+ test('no-time pattern (irc-classic) anchors at local midnight', () => {
+ const body = ['<alice> hi there', '<bob> hello'].join('\n');
+ const r = parseConversation(body, { page: makePage({ date: '2024-03-15', timezone: 'Asia/Tokyo' }) });
+ expect(r.matched_pattern_id).toBe('irc-classic');
+ expect(r.messages[0].timestamp).toBe('2024-03-14T15:00:00Z');
+ });
+ test('an invalid zone keeps UTC and the warning names it', () => {
+ const ctx = deriveDateContext({ page: makePage({ date: '2024-03-15', timezone: 'Mars/Olympus_Mons' }) });
+ expect(ctx.timezone).toBeUndefined();
+ expect(ctx.invalid_timezone).toBe('Mars/Olympus_Mons');
+ const r = parseConversation(TELEGRAM, { page: makePage({ date: '2024-03-15', timezone: 'Mars/Olympus_Mons' }) });
+ expect(r.messages[0].timestamp).toBe('2024-03-15T09:00:00Z');
+ expect(r.timezone_warning).toContain("'Mars/Olympus_Mons'");
+ expect(r.timezone_warning).toContain('not a valid IANA');
+ });
+ test('no zone keeps UTC with the existing warning', () => {
+ const r = parseConversation(TELEGRAM, { fallbackDate: '2024-03-15' });
+ expect(r.messages[0].timestamp).toBe('2024-03-15T09:00:00Z');
+ expect(r.timezone_warning).toContain('assumed UTC');
+ });
+});