From f313f45205cc8399b3bfb08e2fc93557d55dfd84 Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 15:42:54 -0500 Subject: [PATCH 1/5] Harness: Add exemplar zone and UTC serialization ruling --- ai/contributing/decisions.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index 2700868..0e8c419 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -20,6 +20,10 @@ Append-only log of adjudicated decisions governing what `native-dates` exports a --- +## Ruled 2026-11-05: Treat `Z` and numeric offsets in `datetime()` inputs as instant markers rather than time zones, and serialize `toString()` and `toJSON()` in UTC + +`DateTime` wraps `Temporal.ZonedDateTime` and resolves `.zone` from an explicit `zone` argument, a bracketed RFC 9557 `[Zone]` suffix in the input string, `configure({ zone })`, or the runtime's local IANA zone. A trailing `Z` or numeric offset (`-05:00`) in an input string fixes the instant in time without setting `.zone` to `'UTC'` or a fixed offset, and `date()` and `time()` resolve instant strings in that same target zone (`datetime('2026-03-08T04:30:00Z', 'America/New_York').zone` is `'America/New_York'`, and omitting the second argument uses the configured or local zone). On output, `DateTime.prototype.toString()` and `toJSON()` serialize standard ISO 8601 UTC strings (`'2026-03-08T04:30:00.000Z'`). Database rows and JSON payloads normally arrive with `Z`. Locking `.zone` to `'UTC'` whenever `Z` is present silently disables daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless the caller remembers `.in(zone)`. Emitting Temporal's `-05:00[America/New_York]` string from `toString()` was rejected because `Date.parse()`, PostgreSQL `timestamptz`, and standard ISO 8601 parsers reject bracketed zone suffixes. Preserving input offsets as `.zone` (like Moment's `parseZone` or Luxon's `{ setZone: true }`) was also rejected. Callers who want UTC wall-clock fields pass `'UTC'` as the zone, and callers who need the RFC 9557 string call `toTemporal().toString()`. (stamped, reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to UTC rather than the configured or local zone) + ## Ruled 2026-11-19: Step to adjacent unit boundaries with `startOfNext()` and `startOfPrevious()` rather than overloading `next()` and `previous()` `CalendarDate` and `DateTime` expose `startOfNext(unit, firstDay?)` and `startOfPrevious(unit, firstDay?)`, and `Time` exposes `startOfNext(unit)` and `startOfPrevious(unit)`, returning the start of the enclosing unit's next or previous sibling (`date('2026-11-16').startOfNext('month')` is `'2026-12-01'`, `datetime('2026-11-16T09:30').startOfNext('month')` is December 1 at `00:00`). On `CalendarDate` and `DateTime`, weekday names such as `'wednesday'` are also accepted and return the start of that upcoming or most recent weekday, whereas numeric weekdays are rejected as `unknownUnit` so misplaced counts like `startOfNext(2, 'months')` do not silently resolve to Tuesday. Overloading `next('month')` and `previous('month')` was rejected because `DateTime.prototype.next('friday')` preserves the time of day (`09:30`) while a unit boundary resets the clock to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. (stamped, reopen: user studies or downstream issue reports show callers consistently expecting unit names in `next()` and `previous()`, or numeric weekdays and `MonthDay` targets in `startOfNext()`) From 0a3acc2b4bbb7f1a125f133468936c9b0b7f2bb9 Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 15:48:44 -0500 Subject: [PATCH 2/5] Harness: Remove AI session markers and calibrate decision confidence scores --- AGENTS.md | 2 +- ai/contributing/README.md | 2 +- ai/contributing/decisions.md | 20 +++++++++----------- ai/contributing/workflows/contribute.md | 2 +- 4 files changed, 12 insertions(+), 14 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e4783d7..72024de 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -42,7 +42,7 @@ Files in [`ai/contributing/standards/`](ai/contributing/standards/README.md) are - **Structured errors:** Build every error via `refuse()` or `refuseType()` in `src/helpers/errors.js` (`dates refused [code] at`). Explanations are gated behind `isDevelopment` (`NODE_ENV !== 'production'`) so production builds omit diagnostic prose (`ai/contributing/standards/legibility/errors-and-logs.md`, checked by `npm run errors` and `npm run size`). - **Behavioral tests and environments:** Assert `error.code` and `error.at` rather than matching prose sentences (`ai/contributing/standards/legibility/tests-and-test-names.md`). Each package's tests live with it (`test/` for `native-dates` and `packages//test/` for the others) and import packages by their public names; repo and CI tooling tests live under `tools/`. Place pure Node tests in `test/` (core nouns at the top, cross-cutting suites in subfolders like `test/format/` and `test/helpers/`), DOM tests in `test/dom/`, and real Chromium Playwright tests in `test/browser/` (`vitest.config.js`). - **Category-grouped helpers:** Group free functions by domain in `src/helpers/` (`intl.js`, `zones.js`, `parse.js`, `format.js`, `errors.js`, `utils.js`, `environment.js`). -- **Decision records:** Record package behavior decisions in `ai/contributing/decisions.md` and repository process decisions in `ai/contributing/project-decisions.md`, each dated with the maintainer's confidence score and a reopen condition. +- **Decision records:** Record package behavior decisions in `ai/contributing/decisions.md` and repository process decisions in `ai/contributing/project-decisions.md`, each dated with a reopen condition and an optional maintainer confidence score. - **Scratch directory:** Put temporary plans and notes in git-ignored `ai/workspace/`. ## Undecided diff --git a/ai/contributing/README.md b/ai/contributing/README.md index e36ed07..8db4600 100644 --- a/ai/contributing/README.md +++ b/ai/contributing/README.md @@ -25,7 +25,7 @@ Internal records and workflows for developing `native-dates`. Application develo | Record | Path | Policy | |---|---|---| | North star | [`north-star.md`](north-star.md) | Hand-authored by the maintainer on project goals, the Golden Rule, call-site SNR, lowercase-"c" correctness, conciseness, and Bayesian rulings (do not edit or polish) | -| Package decisions | [`decisions.md`](decisions.md) | Append-only dated entries with maintainer confidence score and reopen condition | +| Package decisions | [`decisions.md`](decisions.md) | Append-only dated entries with reopen conditions and optional maintainer confidence scores | | Project decisions | [`project-decisions.md`](project-decisions.md) | Append-only dated entries for repo process, CI, and docs conventions | | Size budget | [`budget.md`](budget.md) | Entry bundles, Brotli ceilings, and per-PR growth rules, updated only by the maintainer | | Launch plan | [`plan/`](plan/roadmap.md) | Pending rows in `roadmap.md`, completed rows in `landed.md`, and briefs in `plan/scopes/` | diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index 0e8c419..893f5c9 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -4,26 +4,24 @@ Append-only log of adjudicated decisions governing what `native-dates` exports a **Inclusion test.** Record decisions here when they bind package behavior across multiple changes. One-off implementation choices belong in the PR, and subjective repository conventions (CI, docs workflow, release process) belong in [`project-decisions.md`](project-decisions.md). Ask: *Does someone modifying this package two years from now need to follow this rule?* -**Prose style.** Direct, factual specification prose. State what the package does first, why it was chosen, and what alternative was rejected. Omit PR numbers and conversational session filler, and quote the maintainer verbatim when exact phrasing carries the decision. +**Prose style.** Direct, factual specification prose. State what the package does first, why it was chosen, and what alternative was rejected. Omit PR numbers, chat history, and process commentary. -**Entry format.** `## : `, followed by the rationale, closing with `(, reopen: )`. Kinds: `Ruled`, `Amended`, `Corrected`, `Reverted`, `VOID`, and `Lean` (guidance for future API surface). +**Entry format.** `## : `, followed by the rationale, closing with `(, reopen: )` when scored or `(reopen: )` when unscored. Kinds: `Ruled`, `Amended`, `Corrected`, `Reverted`, `VOID`, and `Lean` (guidance for future API surface). -**Confidence scores.** Each score (`ruled at 60`) is the maintainer's 0-100 confidence at decision time, never an agent's estimate. A score of 70 reflects a 30% chance of reversal given new evidence: +**Confidence scores.** Optional 0-100 probability assigned by the maintainer at decision time. Calibrated scores reflect actual odds of reversal rather than rhetorical finality: a 70 expects roughly 3 in 10 such calls to flip with new evidence, and a 90 still expects 1 in 10 to turn out wrong: -- **90+:** Settled. Do not reopen without strong new empirical evidence. -- **~60:** Active working decision. Raise it if its reopen condition occurs. -- **<40:** Provisional default awaiting real-world usage data. -- **`stamped`:** Decided in conversation without a numeric score. Treat as settled unless its reopen clause triggers. -- **`(agent-ruled at N, veto-eligible)`:** Delegated agent decision within maintainer-approved bounds, subject to maintainer veto. +- **90+:** High confidence, though roughly 1 in 10 calls at 90 will still prove wrong. Reopen when its `reopen:` condition is met or concrete counter-evidence appears. +- **~60-75:** Working decision under real tradeoffs, with a meaningful chance real-world usage flips it. +- **<50:** Provisional default chosen to unblock shipping until usage data arrives. -**Reopening a decision.** Showing with concrete evidence that a decision's `reopen:` condition has been met is explicitly invited. Reopening a decision whose condition has not been met requires evidence not considered in the original entry, or a clear usability hazard that would turn away a new user of the package. +**Reopening a decision.** Any decision may be reopened when concrete evidence shows its `reopen:` condition has been met, surfaces a tradeoff not weighed in the original entry, or exposes a clear usability hazard for downstream callers. --- ## Ruled 2026-11-05: Treat `Z` and numeric offsets in `datetime()` inputs as instant markers rather than time zones, and serialize `toString()` and `toJSON()` in UTC -`DateTime` wraps `Temporal.ZonedDateTime` and resolves `.zone` from an explicit `zone` argument, a bracketed RFC 9557 `[Zone]` suffix in the input string, `configure({ zone })`, or the runtime's local IANA zone. A trailing `Z` or numeric offset (`-05:00`) in an input string fixes the instant in time without setting `.zone` to `'UTC'` or a fixed offset, and `date()` and `time()` resolve instant strings in that same target zone (`datetime('2026-03-08T04:30:00Z', 'America/New_York').zone` is `'America/New_York'`, and omitting the second argument uses the configured or local zone). On output, `DateTime.prototype.toString()` and `toJSON()` serialize standard ISO 8601 UTC strings (`'2026-03-08T04:30:00.000Z'`). Database rows and JSON payloads normally arrive with `Z`. Locking `.zone` to `'UTC'` whenever `Z` is present silently disables daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless the caller remembers `.in(zone)`. Emitting Temporal's `-05:00[America/New_York]` string from `toString()` was rejected because `Date.parse()`, PostgreSQL `timestamptz`, and standard ISO 8601 parsers reject bracketed zone suffixes. Preserving input offsets as `.zone` (like Moment's `parseZone` or Luxon's `{ setZone: true }`) was also rejected. Callers who want UTC wall-clock fields pass `'UTC'` as the zone, and callers who need the RFC 9557 string call `toTemporal().toString()`. (stamped, reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to UTC rather than the configured or local zone) +`DateTime` wraps `Temporal.ZonedDateTime` and resolves `.zone` from an explicit `zone` argument, a bracketed RFC 9557 `[Zone]` suffix in the input string, `configure({ zone })`, or the runtime's local IANA zone. A trailing `Z` or numeric offset (`-05:00`) in an input string fixes the instant in time without setting `.zone` to `'UTC'` or a fixed offset, and `date()` and `time()` resolve instant strings in that same target zone (`datetime('2026-03-08T04:30:00Z', 'America/New_York').zone` is `'America/New_York'`, and omitting the second argument uses the configured or local zone). On output, `DateTime.prototype.toString()` and `toJSON()` serialize standard ISO 8601 UTC strings (`'2026-03-08T04:30:00.000Z'`). Database rows and JSON payloads normally arrive with `Z`. Locking `.zone` to `'UTC'` whenever `Z` is present silently disables daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless the caller remembers `.in(zone)`. Emitting Temporal's `-05:00[America/New_York]` string from `toString()` was rejected because `Date.parse()`, PostgreSQL `timestamptz`, and standard ISO 8601 parsers reject bracketed zone suffixes. Preserving input offsets as `.zone` (like Moment's `parseZone` or Luxon's `{ setZone: true }`) was also rejected. Callers who want UTC wall-clock fields pass `'UTC'` as the zone, and callers who need the RFC 9557 string call `toTemporal().toString()`. (reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to UTC rather than the configured or local zone) ## Ruled 2026-11-19: Step to adjacent unit boundaries with `startOfNext()` and `startOfPrevious()` rather than overloading `next()` and `previous()` -`CalendarDate` and `DateTime` expose `startOfNext(unit, firstDay?)` and `startOfPrevious(unit, firstDay?)`, and `Time` exposes `startOfNext(unit)` and `startOfPrevious(unit)`, returning the start of the enclosing unit's next or previous sibling (`date('2026-11-16').startOfNext('month')` is `'2026-12-01'`, `datetime('2026-11-16T09:30').startOfNext('month')` is December 1 at `00:00`). On `CalendarDate` and `DateTime`, weekday names such as `'wednesday'` are also accepted and return the start of that upcoming or most recent weekday, whereas numeric weekdays are rejected as `unknownUnit` so misplaced counts like `startOfNext(2, 'months')` do not silently resolve to Tuesday. Overloading `next('month')` and `previous('month')` was rejected because `DateTime.prototype.next('friday')` preserves the time of day (`09:30`) while a unit boundary resets the clock to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. (stamped, reopen: user studies or downstream issue reports show callers consistently expecting unit names in `next()` and `previous()`, or numeric weekdays and `MonthDay` targets in `startOfNext()`) +`CalendarDate` and `DateTime` expose `startOfNext(unit, firstDay?)` and `startOfPrevious(unit, firstDay?)`, and `Time` exposes `startOfNext(unit)` and `startOfPrevious(unit)`, returning the start of the enclosing unit's next or previous sibling (`date('2026-11-16').startOfNext('month')` is `'2026-12-01'`, `datetime('2026-11-16T09:30').startOfNext('month')` is December 1 at `00:00`). On `CalendarDate` and `DateTime`, weekday names such as `'wednesday'` are also accepted and return the start of that upcoming or most recent weekday, whereas numeric weekdays are rejected as `unknownUnit` so misplaced counts like `startOfNext(2, 'months')` do not silently resolve to Tuesday. Overloading `next('month')` and `previous('month')` was rejected because `DateTime.prototype.next('friday')` preserves the time of day (`09:30`) while a unit boundary resets the clock to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. (reopen: user studies or downstream issue reports show callers consistently expecting unit names in `next()` and `previous()`, or numeric weekdays and `MonthDay` targets in `startOfNext()`) diff --git a/ai/contributing/workflows/contribute.md b/ai/contributing/workflows/contribute.md index 76d7ead..5fb6982 100644 --- a/ai/contributing/workflows/contribute.md +++ b/ai/contributing/workflows/contribute.md @@ -35,7 +35,7 @@ Read these documents before editing code: 5. [`ai/contributing/reference/architecture.md`](../reference/architecture.md): workspace package responsibilities, zero-dependency rules, and invariants. 6. [`ai/contributing/budget.md`](../budget.md): bundle ceilings and per-PR byte limits. 7. [`ai/contributing/standards/legibility/errors-and-logs.md`](../standards/legibility/errors-and-logs.md): required whenever adding or editing error explanations (`npm run errors`). -8. [`ai/contributing/decisions.md`](../decisions.md): grep the relevant noun and read the latest dated decision. Decisions scored 90+ require new empirical evidence to reopen, whereas decisions whose `reopen:` condition is met should be surfaced. +8. [`ai/contributing/decisions.md`](../decisions.md): grep the relevant noun and read the latest dated decision. Surface a decision to reopen when its `reopen:` condition is met or new counter-evidence appears rather than silently overriding it. Next, read the target source files and tests directly on `HEAD` rather than relying on prior assumptions. From 8970d75566aaca25ba1c5d5d5fb23bda20a660bc Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 15:50:16 -0500 Subject: [PATCH 3/5] Harness: Tighten exemplar decision entry for human scannability --- ai/contributing/decisions.md | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index 893f5c9..5986a9a 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -4,24 +4,28 @@ Append-only log of adjudicated decisions governing what `native-dates` exports a **Inclusion test.** Record decisions here when they bind package behavior across multiple changes. One-off implementation choices belong in the PR, and subjective repository conventions (CI, docs workflow, release process) belong in [`project-decisions.md`](project-decisions.md). Ask: *Does someone modifying this package two years from now need to follow this rule?* -**Prose style.** Direct, factual specification prose. State what the package does first, why it was chosen, and what alternative was rejected. Omit PR numbers, chat history, and process commentary. +**Prose style.** Keep entries brief and human-scannable. The heading states the rule, and 2-3 sentences explain the tradeoff or failure mode that ruled out the obvious alternative. Do not restate signatures or behavior already readable in source or API docs, and omit PR numbers and session history. -**Entry format.** `## : `, followed by the rationale, closing with `(, reopen: )` when scored or `(reopen: )` when unscored. Kinds: `Ruled`, `Amended`, `Corrected`, `Reverted`, `VOID`, and `Lean` (guidance for future API surface). +**Entry format.** `## : `, a concise rationale, and a closing `Reopen: ` line (or `Confidence: <0-100> · Reopen: ` when scored). Kinds: `Ruled`, `Amended`, `Corrected`, `Reverted`, `VOID`, and `Lean` (guidance for future API surface). **Confidence scores.** Optional 0-100 probability assigned by the maintainer at decision time. Calibrated scores reflect actual odds of reversal rather than rhetorical finality: a 70 expects roughly 3 in 10 such calls to flip with new evidence, and a 90 still expects 1 in 10 to turn out wrong: -- **90+:** High confidence, though roughly 1 in 10 calls at 90 will still prove wrong. Reopen when its `reopen:` condition is met or concrete counter-evidence appears. +- **90+:** High confidence, though roughly 1 in 10 calls at 90 will still prove wrong. Reopen when its `Reopen:` condition is met or concrete counter-evidence appears. - **~60-75:** Working decision under real tradeoffs, with a meaningful chance real-world usage flips it. - **<50:** Provisional default chosen to unblock shipping until usage data arrives. -**Reopening a decision.** Any decision may be reopened when concrete evidence shows its `reopen:` condition has been met, surfaces a tradeoff not weighed in the original entry, or exposes a clear usability hazard for downstream callers. +**Reopening a decision.** Any decision may be reopened when concrete evidence shows its `Reopen:` condition has been met, surfaces a tradeoff not weighed in the original entry, or exposes a clear usability hazard for downstream callers. --- -## Ruled 2026-11-05: Treat `Z` and numeric offsets in `datetime()` inputs as instant markers rather than time zones, and serialize `toString()` and `toJSON()` in UTC +## Ruled 2026-11-05: Input `Z` and numeric offsets fix the instant, never `.zone` -`DateTime` wraps `Temporal.ZonedDateTime` and resolves `.zone` from an explicit `zone` argument, a bracketed RFC 9557 `[Zone]` suffix in the input string, `configure({ zone })`, or the runtime's local IANA zone. A trailing `Z` or numeric offset (`-05:00`) in an input string fixes the instant in time without setting `.zone` to `'UTC'` or a fixed offset, and `date()` and `time()` resolve instant strings in that same target zone (`datetime('2026-03-08T04:30:00Z', 'America/New_York').zone` is `'America/New_York'`, and omitting the second argument uses the configured or local zone). On output, `DateTime.prototype.toString()` and `toJSON()` serialize standard ISO 8601 UTC strings (`'2026-03-08T04:30:00.000Z'`). Database rows and JSON payloads normally arrive with `Z`. Locking `.zone` to `'UTC'` whenever `Z` is present silently disables daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless the caller remembers `.in(zone)`. Emitting Temporal's `-05:00[America/New_York]` string from `toString()` was rejected because `Date.parse()`, PostgreSQL `timestamptz`, and standard ISO 8601 parsers reject bracketed zone suffixes. Preserving input offsets as `.zone` (like Moment's `parseZone` or Luxon's `{ setZone: true }`) was also rejected. Callers who want UTC wall-clock fields pass `'UTC'` as the zone, and callers who need the RFC 9557 string call `toTemporal().toString()`. (reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to UTC rather than the configured or local zone) +Database and JSON timestamps normally arrive with `Z` (`'2026-03-08T04:30:00Z'`). Adopting `'UTC'` or a fixed offset from the input string (like Moment's `parseZone`) would silently disable DST rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless callers remember `.in(zone)`. -## Ruled 2026-11-19: Step to adjacent unit boundaries with `startOfNext()` and `startOfPrevious()` rather than overloading `next()` and `previous()` +Reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to `'UTC'`. -`CalendarDate` and `DateTime` expose `startOfNext(unit, firstDay?)` and `startOfPrevious(unit, firstDay?)`, and `Time` exposes `startOfNext(unit)` and `startOfPrevious(unit)`, returning the start of the enclosing unit's next or previous sibling (`date('2026-11-16').startOfNext('month')` is `'2026-12-01'`, `datetime('2026-11-16T09:30').startOfNext('month')` is December 1 at `00:00`). On `CalendarDate` and `DateTime`, weekday names such as `'wednesday'` are also accepted and return the start of that upcoming or most recent weekday, whereas numeric weekdays are rejected as `unknownUnit` so misplaced counts like `startOfNext(2, 'months')` do not silently resolve to Tuesday. Overloading `next('month')` and `previous('month')` was rejected because `DateTime.prototype.next('friday')` preserves the time of day (`09:30`) while a unit boundary resets the clock to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. (reopen: user studies or downstream issue reports show callers consistently expecting unit names in `next()` and `previous()`, or numeric weekdays and `MonthDay` targets in `startOfNext()`) +## Ruled 2026-11-19: Use `startOfNext()` and `startOfPrevious()` for unit boundaries rather than overloading `next()` and `previous()` + +Overloading `next('month')` conflicts with `DateTime.prototype.next('friday')`, which preserves the time of day (`09:30`) while a unit boundary resets to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. Numeric weekdays are rejected in `startOfNext()` so misplaced counts like `startOfNext(2, 'months')` cannot silently resolve `2` as Tuesday. + +Reopen: callers consistently try unit names in `next()` and `previous()`, or expect numeric weekdays in `startOfNext()`. From df660f6957df48a954396e12f9d7c7805d213a0f Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 16:04:16 -0500 Subject: [PATCH 4/5] Harness: Backfill pre-1.0 package decisions with plain-claim headings --- ai/contributing/decisions.md | 102 ++++++++++++++++++++++++++++++++--- 1 file changed, 96 insertions(+), 6 deletions(-) diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index 5986a9a..c03d898 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -1,12 +1,12 @@ # Decisions: Package Design Log -Append-only log of adjudicated decisions governing what `native-dates` exports and how it behaves: semantics, public API names, option shapes, bundle ceilings, and constraints on future surface. Entries are dated, and the latest entry on a topic supersedes earlier ones while preserving prior entries for context. +Append-only log of decisions governing what `native-dates` exports and how it behaves: semantics, public API names, option shapes, bundle ceilings, and constraints on future surface. Entries are ordered chronologically, and the latest entry on a topic supersedes earlier ones while preserving prior entries for context. -**Inclusion test.** Record decisions here when they bind package behavior across multiple changes. One-off implementation choices belong in the PR, and subjective repository conventions (CI, docs workflow, release process) belong in [`project-decisions.md`](project-decisions.md). Ask: *Does someone modifying this package two years from now need to follow this rule?* +**Inclusion test.** Record decisions here when they bind package behavior across multiple changes. One-off implementation choices belong in the PR, obvious facts already visible in source stay tacit, and repository conventions (CI, docs workflow, release process) belong in [`project-decisions.md`](project-decisions.md). Ask: *Does someone modifying this package two years from now need to follow this rule?* -**Prose style.** Keep entries brief and human-scannable. The heading states the rule, and 2-3 sentences explain the tradeoff or failure mode that ruled out the obvious alternative. Do not restate signatures or behavior already readable in source or API docs, and omit PR numbers and session history. +**Prose style.** Keep entries brief and human-scannable. Write the heading as a plain claim (`A uses B instead of C`), followed by 2-3 sentences on the tradeoff or failure mode that ruled out the alternative. Skip signatures or mechanics already readable in source or API docs, and omit PR numbers and session history. -**Entry format.** `## : `, a concise rationale, and a closing `Reopen: ` line (or `Confidence: <0-100> · Reopen: ` when scored). Kinds: `Ruled`, `Amended`, `Corrected`, `Reverted`, `VOID`, and `Lean` (guidance for future API surface). +**Entry format.** `## ()`, an optional `*<0-100>% confident*` line when scored (omitted when unscored), a concise rationale, and a closing `Reopen: ` line. When a later decision overturns an earlier one, add `Superseded by .` to the earlier entry. **Confidence scores.** Optional 0-100 probability assigned by the maintainer at decision time. Calibrated scores reflect actual odds of reversal rather than rhetorical finality: a 70 expects roughly 3 in 10 such calls to flip with new evidence, and a 90 still expects 1 in 10 to turn out wrong: @@ -18,13 +18,103 @@ Append-only log of adjudicated decisions governing what `native-dates` exports a --- -## Ruled 2026-11-05: Input `Z` and numeric offsets fix the instant, never `.zone` +## Trailing `Z` and numeric offsets in `datetime()` set the instant, not `.zone` (2026-11-05) Database and JSON timestamps normally arrive with `Z` (`'2026-03-08T04:30:00Z'`). Adopting `'UTC'` or a fixed offset from the input string (like Moment's `parseZone`) would silently disable DST rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls unless callers remember `.in(zone)`. Reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to `'UTC'`. -## Ruled 2026-11-19: Use `startOfNext()` and `startOfPrevious()` for unit boundaries rather than overloading `next()` and `previous()` +## `DateTime` serializes to ISO 8601 UTC rather than Temporal's bracketed `[Zone]` string (2026-11-05) + +`Temporal.ZonedDateTime.prototype.toString()` appends `-05:00[America/New_York]`, which `Date.parse()`, PostgreSQL `timestamptz`, and standard ISO 8601 parsers reject. `toString()` and `toJSON()` output standard UTC strings (`...Z`) so `DateTime` values work directly in JSON payloads and database parameters. + +Reopen: RFC 9557 bracketed zone strings gain broad database and parser support and callers request round-tripping `.zone` through JSON. + +## Instances freeze on construction with `text` as an eager own property (2026-11-05) + +Setting `text` as the first enumerable own property shows the human-readable value first in `console.log()` and object spreads without clicking prototype getters in DevTools or Node. On `Duration`, eager `Intl.DurationFormat` formatting (~14 µs in Node) was accepted over a lazy getter so console output behaves the same across every class. + +Reopen: benchmark profiles in `bench/` show eager `text` construction dominating hot arithmetic or `range.points()` loops. + +## Plugins attach on subpath import instead of requiring `use()` or `extend()` (2026-11-08) + +Explicit registration (`use(plugin)`, used initially and removed) recreates Day.js's load-order bug when a module parses or formats a date before startup code runs, and requires TypeScript callers to keep runtime `use()` calls in sync with type imports. Because prototype methods and parser hooks are process-wide anyway, `use()` added ordering bugs without isolating instances. + +Reopen: a standard bundler configuration tree-shakes an imported `@native-dates/plugins/*` module despite `"sideEffects": ["./src/*.js"]`. + +## `DateRange` includes its end date while `DateTimeRange` and `TimeRange` are half-open (2026-11-12) + +In everyday English, SQL `BETWEEN`, and date pickers, "Monday to Friday" means 5 days rather than 4, so half-open `DateRange` bounds would cause off-by-one end dates. Timestamps and clock times use `[start, end)` so adjacent slots (`09:00` to `10:00`, `10:00` to `11:00`) share `10:00` without overlap or a 1 ms gap, and `TimeRange` treats `end < start` as crossing midnight (`22:00` to `06:00`) for overnight shifts. + +Reopen: bug reports show callers frequently off by one day when converting between `DateRange` and `DateTimeRange`. + +## `.locale()` attaches a formatting locale to values without affecting equality or JSON (2026-11-14) + +Process-wide `configure({ locale })` leaks across concurrent requests on Node servers, so instances carry an optional locale (+320 B Brotli) through method chains while keeping `equals()`, `compare()`, `toString()`, and `toJSON()` locale-independent. `.locale()` also accepts POSIX `'en_US'` tags and HTTP `Accept-Language` headers in core (+130 B) because `.locale()` has no `{ loose: true }` option. + +Reopen: callers hit assertion bugs because two `.equals()` values in different locales have different `.text` own properties under deep-object equality. + +## Default week boundaries follow the locale while `weekOfYear` stays ISO Monday (2026-11-14) + +Defaulting `startOf('week')`, `endOf('week')`, `range('week')`, and `weekdayNames()` to Monday produced the wrong calendar week out of the box in Sunday-start (`en-US`, `ja-JP`, `pt-BR`) and Saturday-start (`ar-EG`, `fa-IR`) locales (+70 B Brotli via `Intl.Locale.prototype.getWeekInfo`). `weekOfYear` and the `W` token keep ISO 8601 Monday numbering because business week numbers are an unlocalized standard. + +Reopen: server code accidentally partitions stored weekly aggregates differently across requests carrying different `.locale()` tags. + +## Format tokens output ASCII digits and Gregorian years while presets localize the calendar (2026-11-14) + +Developers use `'YYYY-MM-DD'` for URLs, filenames, and API payloads that need ASCII digits and Gregorian years even when the active locale uses Arabic-Indic digits (`ar-EG`) or non-Gregorian calendars (`fa-IR`, `th-TH`). `MonthDay` and `YearMonth` also use Gregorian months because ISO anniversaries fall on different Persian or Islamic dates each year, and `YearMonth` `'short'` uses 4-digit years (`'11/2026'`) so `'11/26'` is not misread as November 26. + +Reopen: native speakers request an opt-in localized-numeral token mode or non-Gregorian partial dates. + +## Core has zero runtime dependencies and trims forked `@semantic-ui/utils` helpers to used branches (2026-11-16) + +Depending on `@semantic-ui/utils` was tried and reverted because zero dependencies is a common requirement when picking a date library. Copying the shared helpers verbatim saved apps already bundling `@semantic-ui/utils` 61 B Brotli while costing standalone consumers 300 B from unused branches in `each()` and `createErrors` that bundlers could not tree-shake, so `src/helpers/utils.js` keeps only the branches `native-dates` uses. + +Reopen: `@semantic-ui/utils` publishes tree-shakeable single-branch entrypoints with zero unreached bytes and consumers favor cross-package deduplication over zero dependencies. + +## Error explanations use inline `isDevelopment` checks, and `{ loose: true }` still throws on bad options (2026-11-16) + +Error calls pass `explanation: isDevelopment ? '...' : 0` inline at the callsite because minifiers cannot strip string literals passed unconditionally into a helper. When `{ loose: true }` is enabled, only malformed input data returns `null`, while invalid caller options (`unknownZone`, `unknownLocale`, `unknownFormat`) still throw. + +Reopen: callers building dynamic zone or format inputs from untrusted user text need a non-throwing validation helper. + +## Custom `weekdayNames`, `ordinals`, and named `formats` live in `configure()` instead of locale plugins (2026-11-16) + +`dd` and `Do` are the only Moment/Day.js tokens with no `Intl` field. A `@native-dates/plugins/weekdays` plugin and hard-coded French `1er` rule were removed once `Intl`-derived defaults covered nearly all locales (+220 B for `weekdayNames`/`ordinals`, +70 B for `formats`), avoiding per-language tables in core and a plugin name suggesting weekdays required an extra import. `weekdayNames` keys days by name (`fri`, `sun`) rather than array index to avoid Sunday-0 vs. Monday-1 off-by-one bugs. + +Reopen: multiple downstream apps duplicate the same locale ordinal or `dd` overrides and warrant a shared community table. + +## Core parses unambiguous non-ISO inputs and refuses inputs with two readings (2026-11-16) + +Year-first `'2026/1/5'`, leading epoch-ms numbers in `compare(Date.now(), dt)`, and fixed-ratio duration borrowing (`years(1).minus(months(1))` -> 11 months, `weeks(1).minus(days(1))` -> 6 days) each have a single valid interpretation (+230 B total). Core still refuses `'11/06/2026'` (ambiguous between US and European order), `days(1).minus(hours(1))` (differs by an hour from `.plus(days(1)).minus(hours(1))` across DST), and `compare(CalendarDate, DateTime)` (treating dates as midnight contradicts `isBefore()`, while tying across the day breaks `Array.prototype.sort`). + +Reopen: a non-ISO form accepted in core misparses real input, or callers repeatedly hit one of the remaining refusals where an explicit option could disambiguate. + +## Unix timestamp properties include their unit (`epochSeconds`, `epochMilliseconds`, `epochNanoseconds`) with no bare `.epoch` (2026-11-17) + +Shells, Python, SQL, and JWT `exp`/`iat` claims count Unix time in seconds while `Date.now()` uses milliseconds, so an unqualified `.epoch` or `.timestamp` makes `claims.exp = dt.epoch` silently 1,000x too large. Requiring the unit in the property name gives up short round-tripping with `datetime(ms)` to prevent seconds-vs-milliseconds bugs at API boundaries. + +Reopen: migration feedback shows omitting `.epoch` causes widespread friction without preventing real seconds-vs-milliseconds bugs. + +## Numeric day of the week is `dayOfWeek` (`1`-`7`) while token `d` keeps Moment's `0`-`6` (2026-11-17) + +Naming the `1`-`7` property `.weekday` made `sunday.weekday` return `7` while `sunday.isWeekday()` returned `false`, and collided with custom display names in `configure({ weekdayNames })`. Format token `d` keeps `0` = Sunday through `6` = Saturday to match Moment and Day.js token strings, omitting the ISO `1`-`7` token `E` until requested. + +Reopen: callers hit bugs from `format('d')` returning `0` on Sunday while `.dayOfWeek` returns `7`, or request the `E` token. + +## `Duration` uses `balance()` without a `normalize()` alias, and `total(unit)` instead of `in(unit)` (2026-11-17) + +Blind naming reviewers guessed `normalize()` for cascading `90 minutes` into `1 hour 30 minutes` and preferred `hours(36).in('days')` for numeric conversion. Aliasing `normalize` to `balance` was rejected because Luxon's `Duration.prototype.normalize()` leaves `{ minutes: 90 }` unchanged instead of promoting into absent units, and `.in()` returns an object instance everywhere else (`datetime.in(zone)`, `monthDay.in(year)`, `range.in(zone)`). + +Reopen: cold-reader studies or user issues show callers repeatedly reaching for `duration.in(unit)` or `duration.normalize()`. + +## Ranges accept `.for()` for durations alongside `.to()`, and only `CalendarDate` has `.through()` (2026-11-17) + +Cold readers misread `start.to(3, 'days')` as a unit conversion and ranked `start.for(3, 'days')` first (+10 B), which also avoids inclusive-end off-by-one math on `CalendarDate`. `.to()` still accepts durations because restricting `.to()` to endpoints would make `time('9am').to(8, 'hours')` parse `8` as `08:00` and return a 23-hour range, while `.through()` is limited to `CalendarDate` because `DateTimeRange` and `TimeRange` exclude their end. + +Reopen: callers pass endpoints to `.for()` expecting runtime rejection, or expect `.through()` on `DateTime` with inclusive end semantics. + +## Adjacent unit boundaries use `startOfNext()` and `startOfPrevious()` instead of overloading `next()` and `previous()` (2026-11-19) Overloading `next('month')` conflicts with `DateTime.prototype.next('friday')`, which preserves the time of day (`09:30`) while a unit boundary resets to `00:00`, and callers split on whether `next('month')` means the 1st of next month or `plus(1, 'month')`. Numeric weekdays are rejected in `startOfNext()` so misplaced counts like `startOfNext(2, 'months')` cannot silently resolve `2` as Tuesday. From bb97a05b0fc8b1634cfa5619bbb55d3faeb5f933 Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 16:07:20 -0500 Subject: [PATCH 5/5] Harness: Add decisions-index generator and ai gate check --- AGENTS.md | 5 +- ai/contributing/README.md | 4 +- ai/contributing/decisions-index.md | 104 +++++++++++++++ ai/contributing/decisions.md | 2 +- package.json | 1 + tools/gates/ai.js | 4 + tools/gates/decisions-index.js | 198 ++++++++++++++++++++++++++++ tools/gates/decisions-index.test.js | 80 +++++++++++ 8 files changed, 393 insertions(+), 5 deletions(-) create mode 100644 ai/contributing/decisions-index.md create mode 100644 tools/gates/decisions-index.js create mode 100644 tools/gates/decisions-index.test.js diff --git a/AGENTS.md b/AGENTS.md index 72024de..fa3f5eb 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -35,7 +35,7 @@ Files in [`ai/contributing/standards/`](ai/contributing/standards/README.md) are - **Natural-language legibility wins:** Judge every method and signature by how clearly it reads aloud at the callsite (`today().plus(2, 'days').at('9am').in('Europe/Berlin')`). - **Zero runtime dependencies:** `native-dates` installs nothing. Fork and copy only minimal needed helpers from `@semantic-ui/utils` into `src/helpers/` rather than adding dependencies or inventing ad-hoc names. - **Comment voice:** Comment only non-obvious constraints, invariants, or gotchas (`npm run comments`). Start with a lowercase word, avoid em-dashes, prose semicolons, and unicode arrows, and omit trailing periods on single-line comments. -- **Commit format:** `Category: Description` (both capitalized, without a trailing period or `Co-Authored-By` trailer). Categories: `Feat`, `Bug`, `Docs`, `Chore`, `Harness`, `Test`, `Perf`, `Refactor`, `Build`, `Bench`, `BREAKING`. Git hooks in `tools/hooks/` enforce this format and block agent commits directly to `main`. +- **Commit and PR format:** Single-line commit subject only: `Category: Description` (both capitalized, without a body, trailing period, `Co-Authored-By`, or session trailer). Leave pull request descriptions blank (`--body ""`) for human authorship. Categories: `Feat`, `Bug`, `Docs`, `Chore`, `Harness`, `Test`, `Perf`, `Refactor`, `Build`, `Bench`, `BREAKING`. Git hooks in `tools/hooks/` enforce this format and block agent commits directly to `main`. - **Hand-authored maintainer files (`README.md`, `ai/contributing/north-star.md`, `ai/contributing/standards/lessons/naming-lessons.md`):** Written by the maintainer in his own voice. Leave them untouched and never edit or polish them unless explicitly asked; keep READMEs under `packages/` as brief factual descriptions until the maintainer authors them. - **Bespoke homepage:** `docs/src/views/Home.astro` is custom-built around `native-dates`'s specific value proposition with interactive demos verified at build time. - **Bundle size budget:** Run `npm run size` after editing `src/` or `packages/`. Bug fixes aim for 0 added bytes, features declare expected bytes up front, and unused headroom is not a justification (`ai/contributing/budget.md`). @@ -59,7 +59,8 @@ Ask the maintainer rather than inventing conventions for: - `npm run types`: Type-check `.d.ts` declarations via `tsc --noEmit` under NodeNext and `bundler` resolution (`test/types.ts`) - `npm run errors`: Check error and log prose register (`tools/gates/errors.js`) - `npm run comments`: Check comment density, overlap, and banned jargon (`tools/gates/comments.js`) -- `npm run ai`: Validate markdown links, `#anchors`, GFM tables, `ai/` paths, and `AGENTS.md` symlinks (`tools/gates/ai.js`) +- `npm run ai`: Validate markdown links, `#anchors`, GFM tables, `ai/` paths, `decisions-index.md`, and `AGENTS.md` symlinks (`tools/gates/ai.js`) +- `npm run ai:index`: Regenerate `ai/contributing/decisions-index.md` from `ai/contributing/decisions.md` (`tools/gates/decisions-index.js`) - `npm run size`: Measure minified and Brotli-11 sizes for `native-dates` and every plugin in `@native-dates/plugins`, and check `ai/contributing/budget.md` ([`tools/ci/bundle/README.md`](tools/ci/bundle/README.md)) - `npm run docs`: Start the Astro docs dev server (`docs/`, see [`docs/README.md`](docs/README.md)) - `npm run format`: Format files with `dprint` diff --git a/ai/contributing/README.md b/ai/contributing/README.md index 8db4600..d4ab24f 100644 --- a/ai/contributing/README.md +++ b/ai/contributing/README.md @@ -7,7 +7,7 @@ Internal records and workflows for developing `native-dates`. Application develo | Task | Reading order | |---|---| | Fix a bug, add a feature, or file a bug report | [`CONTRIBUTING.md`](../../CONTRIBUTING.md), then [`workflows/contribute.md`](workflows/contribute.md) | -| Check design or process rulings | [`decisions.md`](decisions.md) for package behavior and [`project-decisions.md`](project-decisions.md) for repo process | +| Check design or process rulings | [`decisions-index.md`](decisions-index.md) and [`decisions.md`](decisions.md) for package behavior, [`project-decisions.md`](project-decisions.md) for repo process | | Check bundle size limits | [`budget.md`](budget.md), checked by `npm run size` | | Configure GitHub secrets, bots, and Vercel deploys | [`reference/setup.md`](reference/setup.md) | | View pending and completed launch tasks | [`plan/roadmap.md`](plan/roadmap.md) and [`plan/landed.md`](plan/landed.md) | @@ -25,7 +25,7 @@ Internal records and workflows for developing `native-dates`. Application develo | Record | Path | Policy | |---|---|---| | North star | [`north-star.md`](north-star.md) | Hand-authored by the maintainer on project goals, the Golden Rule, call-site SNR, lowercase-"c" correctness, conciseness, and Bayesian rulings (do not edit or polish) | -| Package decisions | [`decisions.md`](decisions.md) | Append-only dated entries with reopen conditions and optional maintainer confidence scores | +| Package decisions | [`decisions.md`](decisions.md), [`decisions-index.md`](decisions-index.md) | Append-only dated entries with reopen conditions and optional maintainer confidence scores (`npm run ai:index` updates the index) | | Project decisions | [`project-decisions.md`](project-decisions.md) | Append-only dated entries for repo process, CI, and docs conventions | | Size budget | [`budget.md`](budget.md) | Entry bundles, Brotli ceilings, and per-PR growth rules, updated only by the maintainer | | Launch plan | [`plan/`](plan/roadmap.md) | Pending rows in `roadmap.md`, completed rows in `landed.md`, and briefs in `plan/scopes/` | diff --git a/ai/contributing/decisions-index.md b/ai/contributing/decisions-index.md new file mode 100644 index 0000000..f552d89 --- /dev/null +++ b/ai/contributing/decisions-index.md @@ -0,0 +1,104 @@ +# Decisions Index + +> Generated from [`decisions.md`](decisions.md) by `npm run ai:index` and checked by `npm run ai`. Do not edit by hand. + +## By Topic + +Active decisions grouped by area, newest first. + +### Zones, Offsets, and Serialization + +- [L27](decisions.md#datetime-serializes-to-iso-8601-utc-rather-than-temporals-bracketed-zone-string-2026-11-05) · `DateTime` serializes to ISO 8601 UTC rather than Temporal's bracketed `[Zone]` string (2026-11-05) + - Reopen: RFC 9557 bracketed zone strings gain broad database and parser support and callers request round-tripping `.zone` through JSON. +- [L21](decisions.md#trailing-z-and-numeric-offsets-in-datetime-set-the-instant-not-zone-2026-11-05) · Trailing `Z` and numeric offsets in `datetime()` set the instant, not `.zone` (2026-11-05) + - Reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to `'UTC'`. + +### Ranges + +- [L111](decisions.md#ranges-accept-for-for-durations-alongside-to-and-only-calendardate-has-through-2026-11-17) · Ranges accept `.for()` for durations alongside `.to()`, and only `CalendarDate` has `.through()` (2026-11-17) + - Reopen: callers pass endpoints to `.for()` expecting runtime rejection, or expect `.through()` on `DateTime` with inclusive end semantics. +- [L45](decisions.md#daterange-includes-its-end-date-while-datetimerange-and-timerange-are-half-open-2026-11-12) · `DateRange` includes its end date while `DateTimeRange` and `TimeRange` are half-open (2026-11-12) + - Reopen: bug reports show callers frequently off by one day when converting between `DateRange` and `DateTimeRange`. + +### Durations + +- [L105](decisions.md#duration-uses-balance-without-a-normalize-alias-and-totalunit-instead-of-inunit-2026-11-17) · `Duration` uses `balance()` without a `normalize()` alias, and `total(unit)` instead of `in(unit)` (2026-11-17) + - Reopen: cold-reader studies or user issues show callers repeatedly reaching for `duration.in(unit)` or `duration.normalize()`. + +### Arithmetic, Boundaries, and Weekdays + +- [L117](decisions.md#adjacent-unit-boundaries-use-startofnext-and-startofprevious-instead-of-overloading-next-and-previous-2026-11-19) · Adjacent unit boundaries use `startOfNext()` and `startOfPrevious()` instead of overloading `next()` and `previous()` (2026-11-19) + - Reopen: callers consistently try unit names in `next()` and `previous()`, or expect numeric weekdays in `startOfNext()`. +- [L99](decisions.md#numeric-day-of-the-week-is-dayofweek-1-7-while-token-d-keeps-moments-0-6-2026-11-17) · Numeric day of the week is `dayOfWeek` (`1`-`7`) while token `d` keeps Moment's `0`-`6` (2026-11-17) + - Reopen: callers hit bugs from `format('d')` returning `0` on Sunday while `.dayOfWeek` returns `7`, or request the `E` token. +- [L57](decisions.md#default-week-boundaries-follow-the-locale-while-weekofyear-stays-iso-monday-2026-11-14) · Default week boundaries follow the locale while `weekOfYear` stays ISO Monday (2026-11-14) + - Reopen: server code accidentally partitions stored weekly aggregates differently across requests carrying different `.locale()` tags. + +### Formatting, Tokens, and Locales + +- [L81](decisions.md#custom-weekdaynames-ordinals-and-named-formats-live-in-configure-instead-of-locale-plugins-2026-11-16) · Custom `weekdayNames`, `ordinals`, and named `formats` live in `configure()` instead of locale plugins (2026-11-16) + - Reopen: multiple downstream apps duplicate the same locale ordinal or `dd` overrides and warrant a shared community table. +- [L63](decisions.md#format-tokens-output-ascii-digits-and-gregorian-years-while-presets-localize-the-calendar-2026-11-14) · Format tokens output ASCII digits and Gregorian years while presets localize the calendar (2026-11-14) + - Reopen: native speakers request an opt-in localized-numeral token mode or non-Gregorian partial dates. +- [L51](decisions.md#locale-attaches-a-formatting-locale-to-values-without-affecting-equality-or-json-2026-11-14) · `.locale()` attaches a formatting locale to values without affecting equality or JSON (2026-11-14) + - Reopen: callers hit assertion bugs because two `.equals()` values in different locales have different `.text` own properties under deep-object equality. + +### Parsing, Inputs, and Comparisons + +- [L87](decisions.md#core-parses-unambiguous-non-iso-inputs-and-refuses-inputs-with-two-readings-2026-11-16) · Core parses unambiguous non-ISO inputs and refuses inputs with two readings (2026-11-16) + - Reopen: a non-ISO form accepted in core misparses real input, or callers repeatedly hit one of the remaining refusals where an explicit option could disambiguate. + +### Nouns, Instances, and Epoch + +- [L93](decisions.md#unix-timestamp-properties-include-their-unit-epochseconds-epochmilliseconds-epochnanoseconds-with-no-bare-epoch-2026-11-17) · Unix timestamp properties include their unit (`epochSeconds`, `epochMilliseconds`, `epochNanoseconds`) with no bare `.epoch` (2026-11-17) + - Reopen: migration feedback shows omitting `.epoch` causes widespread friction without preventing real seconds-vs-milliseconds bugs. +- [L33](decisions.md#instances-freeze-on-construction-with-text-as-an-eager-own-property-2026-11-05) · Instances freeze on construction with `text` as an eager own property (2026-11-05) + - Reopen: benchmark profiles in `bench/` show eager `text` construction dominating hot arithmetic or `range.points()` loops. + +### Plugins, Errors, and Dependencies + +- [L75](decisions.md#error-explanations-use-inline-isdevelopment-checks-and--loose-true--still-throws-on-bad-options-2026-11-16) · Error explanations use inline `isDevelopment` checks, and `{ loose: true }` still throws on bad options (2026-11-16) + - Reopen: callers building dynamic zone or format inputs from untrusted user text need a non-throwing validation helper. +- [L69](decisions.md#core-has-zero-runtime-dependencies-and-trims-forked-semantic-uiutils-helpers-to-used-branches-2026-11-16) · Core has zero runtime dependencies and trims forked `@semantic-ui/utils` helpers to used branches (2026-11-16) + - Reopen: `@semantic-ui/utils` publishes tree-shakeable single-branch entrypoints with zero unreached bytes and consumers favor cross-package deduplication over zero dependencies. +- [L39](decisions.md#plugins-attach-on-subpath-import-instead-of-requiring-use-or-extend-2026-11-08) · Plugins attach on subpath import instead of requiring `use()` or `extend()` (2026-11-08) + - Reopen: a standard bundler configuration tree-shakes an imported `@native-dates/plugins/*` module despite `"sideEffects": ["./src/*.js"]`. + +## Chronological + +Every entry in file order. + +- [L21](decisions.md#trailing-z-and-numeric-offsets-in-datetime-set-the-instant-not-zone-2026-11-05) · Trailing `Z` and numeric offsets in `datetime()` set the instant, not `.zone` (2026-11-05) + - Reopen: downstream bug reports show callers passing `Z` strings expecting `.hour` and `.zone` to default to `'UTC'`. +- [L27](decisions.md#datetime-serializes-to-iso-8601-utc-rather-than-temporals-bracketed-zone-string-2026-11-05) · `DateTime` serializes to ISO 8601 UTC rather than Temporal's bracketed `[Zone]` string (2026-11-05) + - Reopen: RFC 9557 bracketed zone strings gain broad database and parser support and callers request round-tripping `.zone` through JSON. +- [L33](decisions.md#instances-freeze-on-construction-with-text-as-an-eager-own-property-2026-11-05) · Instances freeze on construction with `text` as an eager own property (2026-11-05) + - Reopen: benchmark profiles in `bench/` show eager `text` construction dominating hot arithmetic or `range.points()` loops. +- [L39](decisions.md#plugins-attach-on-subpath-import-instead-of-requiring-use-or-extend-2026-11-08) · Plugins attach on subpath import instead of requiring `use()` or `extend()` (2026-11-08) + - Reopen: a standard bundler configuration tree-shakes an imported `@native-dates/plugins/*` module despite `"sideEffects": ["./src/*.js"]`. +- [L45](decisions.md#daterange-includes-its-end-date-while-datetimerange-and-timerange-are-half-open-2026-11-12) · `DateRange` includes its end date while `DateTimeRange` and `TimeRange` are half-open (2026-11-12) + - Reopen: bug reports show callers frequently off by one day when converting between `DateRange` and `DateTimeRange`. +- [L51](decisions.md#locale-attaches-a-formatting-locale-to-values-without-affecting-equality-or-json-2026-11-14) · `.locale()` attaches a formatting locale to values without affecting equality or JSON (2026-11-14) + - Reopen: callers hit assertion bugs because two `.equals()` values in different locales have different `.text` own properties under deep-object equality. +- [L57](decisions.md#default-week-boundaries-follow-the-locale-while-weekofyear-stays-iso-monday-2026-11-14) · Default week boundaries follow the locale while `weekOfYear` stays ISO Monday (2026-11-14) + - Reopen: server code accidentally partitions stored weekly aggregates differently across requests carrying different `.locale()` tags. +- [L63](decisions.md#format-tokens-output-ascii-digits-and-gregorian-years-while-presets-localize-the-calendar-2026-11-14) · Format tokens output ASCII digits and Gregorian years while presets localize the calendar (2026-11-14) + - Reopen: native speakers request an opt-in localized-numeral token mode or non-Gregorian partial dates. +- [L69](decisions.md#core-has-zero-runtime-dependencies-and-trims-forked-semantic-uiutils-helpers-to-used-branches-2026-11-16) · Core has zero runtime dependencies and trims forked `@semantic-ui/utils` helpers to used branches (2026-11-16) + - Reopen: `@semantic-ui/utils` publishes tree-shakeable single-branch entrypoints with zero unreached bytes and consumers favor cross-package deduplication over zero dependencies. +- [L75](decisions.md#error-explanations-use-inline-isdevelopment-checks-and--loose-true--still-throws-on-bad-options-2026-11-16) · Error explanations use inline `isDevelopment` checks, and `{ loose: true }` still throws on bad options (2026-11-16) + - Reopen: callers building dynamic zone or format inputs from untrusted user text need a non-throwing validation helper. +- [L81](decisions.md#custom-weekdaynames-ordinals-and-named-formats-live-in-configure-instead-of-locale-plugins-2026-11-16) · Custom `weekdayNames`, `ordinals`, and named `formats` live in `configure()` instead of locale plugins (2026-11-16) + - Reopen: multiple downstream apps duplicate the same locale ordinal or `dd` overrides and warrant a shared community table. +- [L87](decisions.md#core-parses-unambiguous-non-iso-inputs-and-refuses-inputs-with-two-readings-2026-11-16) · Core parses unambiguous non-ISO inputs and refuses inputs with two readings (2026-11-16) + - Reopen: a non-ISO form accepted in core misparses real input, or callers repeatedly hit one of the remaining refusals where an explicit option could disambiguate. +- [L93](decisions.md#unix-timestamp-properties-include-their-unit-epochseconds-epochmilliseconds-epochnanoseconds-with-no-bare-epoch-2026-11-17) · Unix timestamp properties include their unit (`epochSeconds`, `epochMilliseconds`, `epochNanoseconds`) with no bare `.epoch` (2026-11-17) + - Reopen: migration feedback shows omitting `.epoch` causes widespread friction without preventing real seconds-vs-milliseconds bugs. +- [L99](decisions.md#numeric-day-of-the-week-is-dayofweek-1-7-while-token-d-keeps-moments-0-6-2026-11-17) · Numeric day of the week is `dayOfWeek` (`1`-`7`) while token `d` keeps Moment's `0`-`6` (2026-11-17) + - Reopen: callers hit bugs from `format('d')` returning `0` on Sunday while `.dayOfWeek` returns `7`, or request the `E` token. +- [L105](decisions.md#duration-uses-balance-without-a-normalize-alias-and-totalunit-instead-of-inunit-2026-11-17) · `Duration` uses `balance()` without a `normalize()` alias, and `total(unit)` instead of `in(unit)` (2026-11-17) + - Reopen: cold-reader studies or user issues show callers repeatedly reaching for `duration.in(unit)` or `duration.normalize()`. +- [L111](decisions.md#ranges-accept-for-for-durations-alongside-to-and-only-calendardate-has-through-2026-11-17) · Ranges accept `.for()` for durations alongside `.to()`, and only `CalendarDate` has `.through()` (2026-11-17) + - Reopen: callers pass endpoints to `.for()` expecting runtime rejection, or expect `.through()` on `DateTime` with inclusive end semantics. +- [L117](decisions.md#adjacent-unit-boundaries-use-startofnext-and-startofprevious-instead-of-overloading-next-and-previous-2026-11-19) · Adjacent unit boundaries use `startOfNext()` and `startOfPrevious()` instead of overloading `next()` and `previous()` (2026-11-19) + - Reopen: callers consistently try unit names in `next()` and `previous()`, or expect numeric weekdays in `startOfNext()`. diff --git a/ai/contributing/decisions.md b/ai/contributing/decisions.md index c03d898..a060aea 100644 --- a/ai/contributing/decisions.md +++ b/ai/contributing/decisions.md @@ -1,6 +1,6 @@ # Decisions: Package Design Log -Append-only log of decisions governing what `native-dates` exports and how it behaves: semantics, public API names, option shapes, bundle ceilings, and constraints on future surface. Entries are ordered chronologically, and the latest entry on a topic supersedes earlier ones while preserving prior entries for context. +Append-only log of decisions governing what `native-dates` exports and how it behaves: semantics, public API names, option shapes, bundle ceilings, and constraints on future surface. Entries are ordered chronologically, and the latest entry on a topic supersedes earlier ones while preserving prior entries for context (see [`decisions-index.md`](decisions-index.md) for the generated topic and chronological index). **Inclusion test.** Record decisions here when they bind package behavior across multiple changes. One-off implementation choices belong in the PR, obvious facts already visible in source stay tacit, and repository conventions (CI, docs workflow, release process) belong in [`project-decisions.md`](project-decisions.md). Ask: *Does someone modifying this package two years from now need to follow this rule?* diff --git a/package.json b/package.json index e0e6945..4298e3e 100644 --- a/package.json +++ b/package.json @@ -37,6 +37,7 @@ "errors": "node tools/gates/errors.js --all", "comments": "node tools/gates/comments.js --all", "ai": "node tools/gates/ai.js", + "ai:index": "node tools/gates/decisions-index.js --write", "size": "node tools/gates/budget.js", "types": "tsc --noEmit && tsc --noEmit --module preserve --moduleResolution bundler", "check": "npm test && npm run ai && npm run size", diff --git a/tools/gates/ai.js b/tools/gates/ai.js index d2193dc..e828cc6 100644 --- a/tools/gates/ai.js +++ b/tools/gates/ai.js @@ -4,6 +4,8 @@ import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSyn import { dirname, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { checkDecisions } from './decisions-index.js'; + const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); const errors = []; @@ -193,6 +195,8 @@ for (const link of ['CLAUDE.md', 'GEMINI.md']) { if (!linked) { errors.push(`${link}: not a symlink to AGENTS.md`); } } +errors.push(...checkDecisions()); + if (process.argv[1] === fileURLToPath(import.meta.url)) { for (const error of errors) { console.error(` x ${error}`); } console.log(errors.length ? `\nai ${errors.length} to fix` : `ai ok (${files.length} files)`); diff --git a/tools/gates/decisions-index.js b/tools/gates/decisions-index.js new file mode 100644 index 0000000..c3a3ad0 --- /dev/null +++ b/tools/gates/decisions-index.js @@ -0,0 +1,198 @@ +// builds and checks ai/contributing/decisions-index.md from ai/contributing/decisions.md + +import { existsSync, readFileSync, writeFileSync } from 'node:fs'; +import { dirname, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +const decisionsPath = resolve(root, 'ai/contributing/decisions.md'); +const indexPath = resolve(root, 'ai/contributing/decisions-index.md'); + +const headingPattern = /^##\s+(.+?)\s+\((\d{4}-\d{2}-\d{2})\)\s*$/; +const confidencePattern = /^\*(\d{1,3})%\s+confident\*$/i; +const reopenPattern = /^Reopen:\s*(.+)$/i; +const supersededPattern = /^Superseded by\s+(.+?)\.?\s*$/i; + +// ordered from specific domain nouns to broader categories, first match wins +const topicGroups = [ + ['Zones, Offsets, and Serialization', /\.zone\b|\boffsets?\b|serializes?\b|\bUTC\b|time ?zone|IANA/i], + ['Ranges', /DateRange|DateTimeRange|TimeRange|\bRanges?\b|\.for\(\)|\.through\(\)|\.points\(\)/i], + ['Durations', /\bDuration\b|\bbalance\(\)|\btotal\(|\bnormalize\(\)/i], + ['Arithmetic, Boundaries, and Weekdays', /startOf|endOf|unit boundaries|week boundaries|dayOfWeek|weekOfYear/i], + [ + 'Formatting, Tokens, and Locales', + /\.locale\(\)|Format tokens|\btokens?\b|ordinal|weekdayNames|\bformats\b|Gregorian/i, + ], + ['Parsing, Inputs, and Comparisons', /non-ISO|two readings|\bcompare\(|earliest|latest/i], + ['Nouns, Instances, and Epoch', /\bepoch|\bfreeze\b|own property|Unix timestamp|\bMonthDay\b|\bYearMonth\b/i], + [ + 'Plugins, Errors, and Dependencies', + /\bPlugins?\b|subpath|dependencies|@semantic-ui\/utils|Error explanations|isDevelopment|ceiling|\bBrotli\b/i, + ], +]; + +const slugBase = (heading) => + heading + .replace(/<[^>]+>/g, '') + .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1') + .replace(/[`*_~]/g, '') + .trim() + .toLowerCase() + .replace(/[^\p{L}\p{N}\s_-]/gu, '') + .replace(/ /g, '-'); + +const paragraphsOf = (body) => + body + .split(/\n\s*\n/) + .map((block) => block.replace(/\s*\n\s*/g, ' ').trim()) + .filter(Boolean); + +export function parseDecisions(source) { + const lines = source.split('\n'); + const slugCounts = new Map(); + const headings = []; + const findings = []; + let inFence = false; + + lines.forEach((line, index) => { + if (/^\s*(`{3,}|~{3,})/.test(line)) { + inFence = !inFence; + return; + } + if (inFence) { return; } + const headingMatch = /^#{1,6}\s+(.+?)\s*#*\s*$/.exec(line); + if (!headingMatch) { return; } + const base = slugBase(headingMatch[1]); + const seen = slugCounts.get(base) ?? 0; + slugCounts.set(base, seen + 1); + const anchor = seen === 0 ? base : `${base}-${seen}`; + + if (!line.startsWith('## ')) { return; } + const parsed = headingPattern.exec(line); + if (!parsed) { + findings.push(`L${index + 1}: expected '## ()' heading`); + return; + } + headings.push({ line: index + 1, title: parsed[1].trim(), date: parsed[2], anchor }); + }); + + const entries = headings.map((entry, index) => { + const nextLine = index + 1 < headings.length ? headings[index + 1].line - 1 : lines.length; + const paragraphs = paragraphsOf(lines.slice(entry.line, nextLine).join('\n')); + let confidence = null; + let reopen = ''; + let supersededBy = ''; + + paragraphs.forEach((paragraph, position) => { + const confMatch = confidencePattern.exec(paragraph); + if (confMatch) { + const value = Number(confMatch[1]); + if (position !== 0 || value > 100) { + findings.push(`L${entry.line}: confidence line must lead the entry as '*0-100% confident*'`); + } + confidence = value; + return; + } + const reopenMatch = reopenPattern.exec(paragraph); + if (reopenMatch) { + reopen = reopenMatch[1].trim(); + return; + } + const supMatch = supersededPattern.exec(paragraph); + if (supMatch) { + supersededBy = supMatch[1].trim(); + } + }); + + const topic = topicGroups.find(([, pattern]) => pattern.test(entry.title))?.[0] ?? 'Unsorted'; + if (topic === 'Unsorted') { + findings.push(`L${entry.line}: no topic group matched '${entry.title}'`); + } + if (!reopen && !supersededBy) { + findings.push(`L${entry.line}: missing 'Reopen: ' line`); + } + if (index > 0 && entry.date < headings[index - 1].date) { + findings.push(`L${entry.line}: date ${entry.date} precedes earlier entry ${headings[index - 1].date}`); + } + + return { ...entry, confidence, reopen, supersededBy, topic }; + }); + + return { entries, findings }; +} + +const formatItem = (entry) => { + const stamp = entry.confidence === null ? entry.date : `${entry.date}, ${entry.confidence}% confident`; + const lines = [`- [L${entry.line}](decisions.md#${entry.anchor}) · ${entry.title} (${stamp})`]; + if (entry.supersededBy) { + lines.push(` - Superseded by ${entry.supersededBy}`); + } + else if (entry.reopen) { + lines.push(` - Reopen: ${entry.reopen}`); + } + return lines.join('\n'); +}; + +export function renderDecisionsIndex(entries) { + const out = [ + '# Decisions Index', + '', + '> Generated from [`decisions.md`](decisions.md) by `npm run ai:index` and checked by `npm run ai`. Do not edit by hand.', + '', + '## By Topic', + '', + 'Active decisions grouped by area, newest first.', + '', + ]; + + for (const [name] of topicGroups) { + const matching = entries + .filter((entry) => entry.topic === name && !entry.supersededBy) + .sort((a, b) => b.date.localeCompare(a.date) || b.line - a.line); + if (!matching.length) { continue; } + out.push(`### ${name}`, ''); + for (const entry of matching) { + out.push(formatItem(entry)); + } + out.push(''); + } + + out.push('## Chronological', '', 'Every entry in file order.', ''); + for (const entry of entries) { + out.push(formatItem(entry)); + } + out.push(''); + return out.join('\n'); +} + +export function checkDecisions( + source = readFileSync(decisionsPath, 'utf8'), + indexSource = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : '', +) { + const { entries, findings } = parseDecisions(source); + const issues = findings.map((finding) => `ai/contributing/decisions.md: ${finding}`); + if (!findings.length && indexSource !== renderDecisionsIndex(entries)) { + issues.push('ai/contributing/decisions-index.md: stale index (run `npm run ai:index`)'); + } + return issues; +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + const { entries, findings } = parseDecisions(readFileSync(decisionsPath, 'utf8')); + if (findings.length) { + for (const finding of findings) { + console.error(` x ai/contributing/decisions.md: ${finding}`); + } + process.exitCode = 1; + } + else { + const output = renderDecisionsIndex(entries); + if (process.argv.includes('--write')) { + writeFileSync(indexPath, output); + console.log(`wrote ${relative(root, indexPath)} (${entries.length} decisions)`); + } + else { + process.stdout.write(output); + } + } +} diff --git a/tools/gates/decisions-index.test.js b/tools/gates/decisions-index.test.js new file mode 100644 index 0000000..9b92d7d --- /dev/null +++ b/tools/gates/decisions-index.test.js @@ -0,0 +1,80 @@ +import { describe, expect, it } from 'vitest'; + +import { checkDecisions, parseDecisions, renderDecisionsIndex } from './decisions-index.js'; + +describe('decisions-index', () => { + const sample = [ + '# Decisions', + '', + '## `DateRange` includes its end date while `TimeRange` is half-open (2026-11-10)', + '', + 'Old range entry.', + '', + 'Superseded by 2026-11-12.', + '', + '## `DateRange` includes its end date and `TimeRange` wraps midnight (2026-11-12)', + '', + '*90% confident*', + '', + 'Civil date ranges include their final day.', + '', + 'Reopen: callers hit off-by-one bugs when converting ranges.', + '', + '## `Duration` uses `balance()` without a `normalize()` alias (2026-11-17)', + '', + 'Luxon `normalize()` leaves `{ minutes: 90 }` unchanged.', + '', + 'Reopen: cold-reader studies show callers expecting `normalize()`.', + '', + ].join('\n'); + + it('parses optional confidence lines, reopen clauses, and supersession notes into topic and file-order indexes', () => { + const { entries, findings } = parseDecisions(sample); + expect(findings).toEqual([]); + expect(entries.map((entry) => [entry.topic, entry.confidence, Boolean(entry.supersededBy)])).toEqual([ + ['Ranges', null, true], + ['Ranges', 90, false], + ['Durations', null, false], + ]); + + const rendered = renderDecisionsIndex(entries); + expect(rendered).toContain('### Ranges\n\n- [L9](decisions.md#'); + expect(rendered).toContain('(2026-11-12, 90% confident)'); + // superseded entries appear only in the chronological section + expect(rendered.split('## Chronological')[0]).not.toContain('2026-11-10'); + expect(rendered.split('## Chronological')[1]).toContain('Superseded by 2026-11-12'); + expect(checkDecisions(sample, rendered)).toEqual([]); + }); + + it('flags malformed headings, out-of-order dates, missing reopen lines, unsorted titles, and stale indexes', () => { + const broken = [ + '# Decisions', + '', + '## Missing date heading', + '', + '## `Duration` uses `balance()` (2026-11-18)', + '', + '*120% confident*', + '', + 'Body without reopen.', + '', + '## Unmatched widget knob (2026-11-15)', + '', + 'Body.', + '', + 'Reopen: never.', + ].join('\n'); + + expect(checkDecisions(broken, '')).toEqual([ + "ai/contributing/decisions.md: L3: expected '## ()' heading", + "ai/contributing/decisions.md: L5: confidence line must lead the entry as '*0-100% confident*'", + "ai/contributing/decisions.md: L5: missing 'Reopen: ' line", + "ai/contributing/decisions.md: L11: no topic group matched 'Unmatched widget knob'", + 'ai/contributing/decisions.md: L11: date 2026-11-15 precedes earlier entry 2026-11-18', + ]); + + expect(checkDecisions(sample, 'stale')).toEqual([ + 'ai/contributing/decisions-index.md: stale index (run `npm run ai:index`)', + ]); + }); +});