Compare commits

...
Author SHA1 Message Date
timmy 2e8efdb2bb test: cover fallback lease for Week replay
CI / lint (pull_request) Successful in 3m2s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 6m49s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 04:38:26 +00:00
timmy e92e476f49 test: exercise real cross-tab replay coordinator
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 57s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 04:36:02 +00:00
timmy 4a6a829401 fix: serialize Week-to-Today replay across tabs
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 3s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 04:25:01 +00:00
timmy c03d0a091f Revert "ci: pin checkout and Python setup actions"
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 12s
CI / release-candidate (pull_request) Has been skipped
This reverts commit 59c87f06a2.
2026-08-22 03:41:03 +00:00
timmy 2f5df33020 Revert "ci: prepare act runner action mount"
This reverts commit 5d517861f0.
2026-08-22 03:41:03 +00:00
timmy 5d517861f0 ci: prepare act runner action mount
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 3s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 03:40:21 +00:00
timmy 59c87f06a2 ci: pin checkout and Python setup actions
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 57s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 03:38:27 +00:00
timmy f76b2f8289 refactor: simplify pull queue admission
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 1s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 03:33:34 +00:00
timmy 7c4e798776 feat: queue offline Week-to-Today pulls (Closes #1249)
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 33s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 03:31:34 +00:00
timmy 317fc7371a Merge pull request 'Keep Week-to-Today pulls through offline reloads' (#1247) from timmy/1246-durable-week-today-pulls into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 4m56s
CI / release-candidate (push) Successful in 6s
CI / lint (push) Successful in 3m10s
2026-08-22 02:50:55 +00:00
timmy c7d38593dd feat: keep Week-to-Today pulls through reloads (Closes #1246)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 5m2s
CI / lint (pull_request) Successful in 3m7s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 02:41:29 +00:00
rockachopa a13a13d90c Merge pull request 'Confirm Today capacity before pulling Week Ahead work' (#1245) from timmy/1244-capacity-confirm-week-pull into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m34s
CI / release-candidate (push) Successful in 6s
CI / lint (push) Successful in 3m21s
2026-08-22 01:43:15 +00:00
timmy 666671ee59 feat: confirm capacity before Week-to-Today pulls (Closes #1244)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 5m18s
CI / lint (pull_request) Successful in 3m11s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 01:33:04 +00:00
rockachopa d01f502e70 Merge pull request 'Pull one Week Ahead item into an active Today plan' (#1243) from timmy/1242-week-item-to-today into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m26s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m25s
2026-08-22 00:24:40 +00:00
timmy 3fd5983df6 feat: pull Week Ahead work into Today (Closes #1242)
CI / lint (pull_request) Successful in 3m22s
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 5m11s
CI / release-candidate (pull_request) Has been skipped
2026-08-22 00:10:39 +00:00
rockachopa 6afdad6fe4 Merge pull request 'Remove active work from Week Ahead with Undo' (#1241) from timmy/1240-week-ahead-unplan-undo into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m10s
CI / release-candidate (push) Successful in 6s
CI / lint (push) Successful in 3m11s
2026-08-21 22:59:20 +00:00
timmy 449ab78991 feat: unplan Week Ahead work with undo (Closes #1240)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m20s
CI / lint (pull_request) Successful in 3m58s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 22:45:15 +00:00
timmy 95887d7493 Merge pull request 'Rotate shared private-state encryption keys without downtime' (#1238)
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 5m17s
CI / release-candidate (push) Successful in 6s
CI / lint (push) Successful in 3m19s
Closes #1237
2026-08-21 21:37:25 +00:00
timmy 965a73ab49 feat: rotate shared private-state keys (Closes #1237)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 5m2s
CI / lint (pull_request) Successful in 3m24s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 21:12:54 +00:00
rockachopa 067fb76ebd Merge pull request 'Retire completed work from Week Ahead' (#1236) from timmy/1235-retire-completed-week-work into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m17s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m26s
2026-08-21 20:30:03 +00:00
timmy d47205a561 test: verify mobile Week Ahead retirement
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m4s
CI / lint (pull_request) Successful in 3m10s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 20:19:20 +00:00
timmy 1be9da3685 feat: retire completed Week Ahead work (Closes #1235) 2026-08-21 20:12:48 +00:00
timmy a8c1329676 Merge pull request 'Queue multiple offline Today-to-Week moves' (#1234) from timmy/1233-queue-offline-reschedules into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m4s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m8s
2026-08-21 19:12:01 +00:00
timmy d63765a9b1 feat: queue offline Today-to-Week moves (Closes #1233)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m10s
CI / lint (pull_request) Successful in 3m20s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 19:02:30 +00:00
rockachopa c87d56c939 Merge pull request 'Keep Today-to-Week rescheduling through offline reloads' (#1232)
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m20s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m10s
2026-08-21 18:27:28 +00:00
timmy e234d6b6c3 feat: keep Today-to-Week moves through offline reloads (Closes #1231)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 4m57s
CI / lint (pull_request) Successful in 3m21s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 18:18:14 +00:00
rockachopa edaeba4a4e Merge pull request 'Reschedule an active Today item into Week Ahead' (#1229) from timmy/1228-reschedule-today-to-week into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 4m47s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m16s
2026-08-21 17:13:00 +00:00
timmy 9d8a362583 feat: reschedule active Today work into Week Ahead (Closes #1228)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 4m57s
CI / lint (pull_request) Successful in 3m33s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 16:59:40 +00:00
rockachopa c63df3c46d Merge pull request 'Reflow overloaded Week Ahead plans' (#1227) from timmy/1226-week-ahead-reflow into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m38s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m31s
2026-08-21 15:49:07 +00:00
timmy ffba6f1212 feat: reflow overloaded Week Ahead plans (Closes #1226)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 5m47s
CI / lint (pull_request) Successful in 3m55s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 15:34:31 +00:00
timmy b7dd9757aa Merge pull request 'Start the next Week Ahead day early from mobile' (#1225) from timmy/1224-start-week-day-early into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 5m26s
CI / release-candidate (push) Successful in 10s
CI / lint (push) Successful in 3m49s
Start the next Week Ahead day early from mobile (#1225)
2026-08-21 14:48:16 +00:00
timmy f64ce3acc4 feat: start Week Ahead days early (Closes #1224)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 5m38s
CI / lint (pull_request) Successful in 3m53s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 14:37:50 +00:00
timmy 25597d1f05 Merge pull request 'Open Week Ahead planned work and return to the overview' (#1223) from timmy/1222-week-ahead-item-detail into main
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 5m38s
CI / release-candidate (push) Successful in 10s
CI / lint (push) Successful in 3m50s
2026-08-21 13:50:37 +00:00
timmy 9f5baaef6e feat: open Week Ahead planned work (Closes #1222)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 5m53s
CI / lint (pull_request) Successful in 3m47s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 13:38:48 +00:00
rockachopa a3861da125 Preserve Search-planned work details in offline Week Ahead (#1221)
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 5m31s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m52s
Closes #1220
2026-08-21 12:27:32 +00:00
timmy 2b874d8427 feat: preserve Search work details offline (Closes #1220)
CI / lint (pull_request) Successful in 3m46s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m16s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 12:03:25 +00:00
rockachopa ba50784022 Merge pull request 'Keep the confirmed Week Ahead overview available offline' (#1219) from timmy/1218-offline-week-overview into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Successful in 5m6s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m39s
2026-08-21 11:08:47 +00:00
timmy 37950bd0ed feat: keep Week Ahead available offline (Closes #1218)
CI / lint (pull_request) Successful in 3m40s
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 5m26s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 10:43:59 +00:00
rockachopa bb6a4c4305 Merge pull request 'Make Week Ahead a read-first mobile overview' (#1217) from timmy/1216-week-ahead-overview into main
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m57s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m44s
2026-08-21 09:31:56 +00:00
timmy 42e97b4a79 feat: add read-first Week Ahead overview (Closes #1216)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m19s
CI / lint (pull_request) Successful in 3m37s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 09:07:27 +00:00
timmy 45e2798d37 Merge pull request 'Update repeated Week Ahead calendar exports without duplicate blocks' (#1215)
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m59s
CI / release-candidate (push) Successful in 9s
CI / lint (push) Successful in 3m37s
Closes #1214
2026-08-21 07:39:04 +00:00
timmy 218dd43764 feat: update repeated Week Ahead calendar exports (Closes #1214)
CI / lint (pull_request) Successful in 3m45s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m2s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 07:29:23 +00:00
timmy 4d9c936b86 Merge pull request 'Make Week Ahead calendar import timezone-correct and range-bounded' (#1213) from timmy/1212-week-calendar-timezone into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 5m2s
CI / release-candidate (push) Successful in 9s
CI / lint (push) Successful in 3m30s
2026-08-21 06:57:16 +00:00
timmy 69a3a2c568 feat: make calendar import timezone-correct and bounded (Closes #1212)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m8s
CI / lint (pull_request) Successful in 3m47s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 06:43:44 +00:00
rockachopa 7a9347bd2a Merge pull request 'Avoid imported busy time in Week Ahead calendar export' (#1211) from timmy/1210-week-calendar-availability into main
CI / build-release (push) Successful in 9s
CI / browser-journey (push) Successful in 5m35s
CI / release-candidate (push) Successful in 12s
CI / lint (push) Successful in 3m54s
2026-08-21 06:00:10 +00:00
timmy 4e275b1518 feat: avoid imported busy time in Week Ahead export (Closes #1210)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m38s
CI / lint (pull_request) Successful in 3m17s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 05:50:23 +00:00
rockachopa 865083a835 Merge pull request 'Make Week Ahead calendar import recurrence-aware and truthful' (#1209) from timmy/1208-week-calendar-recurrence into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 5m3s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m42s
2026-08-21 05:03:41 +00:00
timmy 15be0ec026 test: cover private recurrence additions on mobile
CI / lint (pull_request) Successful in 3m26s
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m55s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 04:53:57 +00:00
timmy ab74426cbc test: validate truthful mobile calendar import gating
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Failing after 5m18s
CI / lint (pull_request) Successful in 3m51s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 04:42:06 +00:00
timmy f1adffef6b feat: make calendar capacity recurrence-aware (Closes #1208)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Failing after 5m15s
CI / lint (pull_request) Successful in 4m1s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 04:27:11 +00:00
rockachopa 359d4337eb Merge pull request 'Set Week Ahead capacity from a private calendar import' (#1207) from timmy/1206-week-calendar-capacity into main
CI / build-release (push) Successful in 10s
CI / browser-journey (push) Successful in 5m37s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 4m10s
2026-08-21 03:28:00 +00:00
timmy e77ad7c809 feat: import private calendar capacity for Week Ahead (Closes #1206)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 5m19s
CI / lint (pull_request) Successful in 4m1s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 03:16:40 +00:00
rockachopa aa46196d1e Merge pull request 'fix: restore Today break after sync recovery' (#1205) from timmy/1204-today-break-recovery into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m48s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m37s
2026-08-21 02:17:28 +00:00
timmy e5ccfb0c5e fix: restore Today break after sync recovery (Closes #1204)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 5m17s
CI / lint (pull_request) Successful in 3m57s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 01:56:04 +00:00
rockachopa e3c7df25c8 Merge pull request 'feat: CI regression: mobile Today handoff content is obscured on 568px viewport' (#1203) from timmy/1202-ci-regression-mobile-today-handoff-content-is-ob into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Failing after 4m57s
CI / release-candidate (push) Has been skipped
CI / lint (push) Successful in 3m30s
2026-08-21 01:03:10 +00:00
timmy f11fc17a2c Fix mobile Today handoff clearance (#1202)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m37s
CI / lint (pull_request) Successful in 3m27s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 00:42:07 +00:00
rockachopa ecc79ce50f Merge pull request 'Reconcile unfinished Today with due Week Ahead work' (#1201) from timmy/1200-reconcile-week-today into main
CI / build-release (push) Successful in 6s
CI / browser-journey (push) Failing after 4m23s
CI / release-candidate (push) Has been skipped
CI / lint (push) Successful in 3m17s
2026-08-21 00:18:01 +00:00
timmy a10592c349 feat: reconcile Today with due Week Ahead work (Closes #1200)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m51s
CI / lint (pull_request) Successful in 3m32s
CI / release-candidate (pull_request) Has been skipped
2026-08-21 00:08:43 +00:00
rockachopa 5ac90d01e6 Merge pull request 'Export Week Ahead as timed calendar blocks' (#1199) from timmy/1198-week-calendar-blocks into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m41s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m18s
2026-08-20 23:24:36 +00:00
timmy dd3016b96b feat: export Week Ahead as calendar blocks (Closes #1198)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m38s
CI / lint (pull_request) Successful in 3m18s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 23:12:28 +00:00
rockachopa 875f4eea29 Merge pull request 'Batch-plan Search results into Week Ahead' (#1197)
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m36s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m24s
2026-08-20 22:11:15 +00:00
timmy 78839a50fe feat: batch-plan Search results into Week Ahead (Closes #1196)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m51s
CI / lint (pull_request) Successful in 3m20s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 22:01:58 +00:00
rockachopa f557f06bc5 Merge pull request 'Plan Search results directly into Week Ahead' (#1195) from timmy/1194-search-week-ahead into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m47s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m19s
2026-08-20 21:07:52 +00:00
timmy c8998eb1ba test: require Search Week Ahead browser coverage
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 4m55s
CI / lint (pull_request) Successful in 3m33s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 20:58:36 +00:00
timmy b5b1a3b0d7 ci: exercise Search Week Ahead mobile sheet
CI / build-release (pull_request) Has been skipped
CI / browser-journey (pull_request) Has been skipped
CI / lint (pull_request) Failing after 3m23s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 20:51:34 +00:00
timmy ea1b5a77f5 feat: plan Search results into Week Ahead (Closes #1194)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Failing after 4m48s
CI / lint (pull_request) Successful in 3m30s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 20:39:53 +00:00
rockachopa 5c74051aab Merge pull request 'Remind from due Week Ahead plans' (#1193) from timmy/1192-week-ahead-start-day-reminder into main
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m22s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m19s
2026-08-20 19:38:32 +00:00
timmy daffa894d8 feat: remind from due Week Ahead plans (Closes #1192)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 4m28s
CI / lint (pull_request) Successful in 3m35s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 19:28:32 +00:00
rockachopa 67a3285412 Merge pull request 'Make Week Ahead review readable and editable' (#1191) from timmy/1190-readable-editable-week-review into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m48s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m37s
2026-08-20 18:42:52 +00:00
timmy 9f40a4c5ac feat: make Week Ahead review readable and editable (Closes #1190)
CI / build-release (pull_request) Successful in 6s
CI / browser-journey (pull_request) Successful in 4m38s
CI / lint (pull_request) Successful in 3m21s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 18:33:37 +00:00
rockachopa 356f11b9c1 Merge pull request 'Review and rebalance Week Ahead before confirmation' (#1189) from timmy/1188-review-rebalance-week-ahead into main
CI / build-release (push) Successful in 10s
CI / browser-journey (push) Successful in 5m27s
CI / release-candidate (push) Successful in 9s
CI / lint (push) Successful in 3m22s
Merge pull request 'Review and rebalance Week Ahead before confirmation' (#1189)
2026-08-20 17:46:31 +00:00
timmy d5f13c4afb feat: review and rebalance Week Ahead (Closes #1188)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m48s
CI / lint (pull_request) Successful in 3m31s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 17:36:02 +00:00
timmy 69532bdc1f Merge pull request 'Plan Week Ahead in one continuous mobile pass' (#1187) from timmy/1186-continuous-week-ahead into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m36s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m31s
2026-08-20 16:45:31 +00:00
timmy 55e1c3d6dd feat: plan Week Ahead in one mobile pass (Closes #1186)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m39s
CI / lint (pull_request) Successful in 4m5s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 16:30:45 +00:00
timmy 6718160381 Merge pull request 'Reconcile concurrent Week Ahead edits per day' (#1185) from timmy/1184-reconcile-week-ahead-per-day into main
CI / build-release (push) Successful in 7s
CI / browser-journey (push) Successful in 4m35s
CI / release-candidate (push) Successful in 8s
CI / lint (push) Successful in 3m17s
2026-08-20 15:54:53 +00:00
timmy e0f7c711ed feat: reconcile Week Ahead edits per day (Closes #1184)
CI / build-release (pull_request) Successful in 10s
CI / browser-journey (pull_request) Successful in 5m36s
CI / lint (pull_request) Successful in 3m52s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 15:43:35 +00:00
timmy 43066a0822 Merge pull request 'Preserve Today before Week Ahead rollover' (#1183) from timmy/1182-preserve-today-before-week-rollover into main
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m31s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m29s
2026-08-20 14:44:23 +00:00
timmy f0706e2e6f feat: preserve Today before Week Ahead rollover (Closes #1182)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 5m37s
CI / lint (pull_request) Successful in 3m25s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 14:33:15 +00:00
timmy 3edc4e36b3 Merge pull request 'Keep Week Ahead plans through offline saves' (#1181) from timmy/1180-offline-week-ahead-sync into main
CI / build-release (push) Successful in 8s
CI / browser-journey (push) Successful in 4m44s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m35s
2026-08-20 13:57:04 +00:00
timmy 47cad77312 feat: keep Week Ahead plans through offline saves (Closes #1180)
CI / build-release (pull_request) Successful in 7s
CI / browser-journey (pull_request) Successful in 4m19s
CI / lint (pull_request) Successful in 3m20s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 13:40:33 +00:00
rockachopa 99a2f28440 Merge pull request 'feat: Plan the next seven days from mobile' (#1179) from timmy/1177-plan-the-next-seven-days-from-mobile into main
CI / build-release (push) Successful in 9s
CI / browser-journey (push) Successful in 4m24s
CI / release-candidate (push) Successful in 7s
CI / lint (push) Successful in 3m29s
2026-08-20 13:01:21 +00:00
timmy 53c4340d76 fix: tolerate invalid device timezones in Week Ahead (Closes #1177)
CI / build-release (pull_request) Successful in 8s
CI / browser-journey (pull_request) Successful in 4m30s
CI / lint (pull_request) Successful in 3m19s
CI / release-candidate (pull_request) Has been skipped
2026-08-20 12:26:35 +00:00
60 changed files with 7489 additions and 149 deletions

No files matched your search

+1 -1
View File
@@ -57,7 +57,7 @@ jobs:
pip install -r requirements-e2e.txt
python3 -m playwright install --with-deps chromium
- name: Exercise packaged mobile work journeys
run: python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py tests/e2e/test_mobile_search_preview_navigation.py tests/e2e/test_mobile_find_work_release.py tests/e2e/test_mobile_home_bootstrap_release.py tests/e2e/test_mobile_sign_out_release.py tests/e2e/test_mobile_today_handoff_release.py tests/e2e/test_mobile_today_wrap_up_release.py tests/e2e/test_mobile_today_summary_release.py tests/e2e/test_mobile_tomorrow_conflict_release.py tests/e2e/test_mobile_week_ahead_release.py tests/e2e/test_mobile_wrap_up_handoff_release.py -q
run: python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py tests/e2e/test_mobile_search_preview_navigation.py tests/e2e/test_mobile_search_week_plan.py tests/e2e/test_mobile_find_work_release.py tests/e2e/test_mobile_home_bootstrap_release.py tests/e2e/test_mobile_sign_out_release.py tests/e2e/test_mobile_today_handoff_release.py tests/e2e/test_mobile_today_wrap_up_release.py tests/e2e/test_mobile_today_summary_release.py tests/e2e/test_mobile_tomorrow_conflict_release.py tests/e2e/test_mobile_week_ahead_release.py tests/e2e/test_mobile_today_week_reschedule_release.py tests/e2e/test_mobile_wrap_up_handoff_release.py -q
release-candidate:
runs-on: ubuntu-latest
+61 -1
View File
@@ -75,6 +75,23 @@ Today or interrupting active work. Cancel and browser Back preserve the Search p
confirmation claims only when needed, syncs the Later plan across devices, and returns to the preserved
query, filters, results, and scroll position. If assignment succeeds but Later storage fails, the issue
remains recoverable in My Work and the dashboard reports the partial outcome instead of claiming success.
Eligible open issue previews also expose **Plan ahead**: choose one of the next seven local dates, review
that day's current load and capacity, and enter a required estimate without leaving Search. Existing Week
Ahead placement is moved only after an explicit day change, never duplicated; full days are blocked and
over-capacity admission requires a second confirmation. The action claims unassigned work only after these
checks, stages the canonical issue through the account-bound Week Ahead outbox, and preserves the Search
preview through cancel or browser Back. Offline saves report **sync pending**; if assignment succeeds but
local planning fails, the dashboard reports **Assigned, not planned** and leaves the issue recoverable in My Work.
The live mobile Week Ahead overview also offers **Remove from week** for active planned work. It removes only the
private planning placement—not assignment, issue state, or Gitea content—and immediately recalculates the day's
load. A 10-second **Undo** receipt restores the exact day, list position, and estimate. Both transitions use the
account-bound Week Ahead outbox, remain **sync pending** after delivery failure, and stay unavailable in a read-only
offline snapshot.
Search selection mode extends that flow across several open issues with **Plan Week Ahead**. One phone-safe
review assigns each issue a future day and estimate, validates five-item limits and daily capacity before any
claim, and requires a second confirmation for overload. Confirmed rows are staged into one canonical Week
Ahead update and flushed together; partial assignment or offline sync is reported without discarding the
selection, so claimed work remains recoverable from My Work.
Commentable mobile Search previews support camera capture and gallery selection for up to five ordered
photos, including captions, crop/annotation/redaction review, and metadata-stripping re-encoding. Operators
can queue photo-only, text-only, or mixed replies without leaving their Search pass, including while offline.
@@ -120,7 +137,10 @@ explicit **Add blocked item anyway** override, while an unavailable dependency l
as unknown rather than unblocked. Completing any Today item now exposes a 10-second, touch-safe
**Undo** receipt. Undo restores the item's original order and estimate, queues the inverse cross-device
plan changes, and leaves the already-advanced work session on its current item; expiry, capacity, or a
concurrently changed plan is reported without overwriting newer work. Starting a Today work session also
concurrently changed plan is reported without overwriting newer work. Rescheduling Today work into
Week Ahead uses a bounded account-scoped FIFO on the device: multiple offline moves survive reload,
deliver oldest-first with stable operation IDs, and rebase each later move on the confirmed plan revisions
without concurrent requests. Starting a Today work session also
stores an account-bound checkpoint on the current device and starts an account-bound actual-time timer for the exact item. The sticky mobile session controls show elapsed time beside the estimate and let the operator pause or resume it. An opt-in, privacy-safe lock-screen notification mirrors the current pause/resume control and adds **Finish current**: its opaque one-shot action is bound to the exact active item, reuses **Done & next** or recap, and never changes the underlying Gitea issue or pull request. Switching items preserves each item's elapsed value, while wall-clock checkpoints keep a running timer accurate through app backgrounding, reloads, and installed-app restarts without double counting. **End session** stops accumulation but retains measured time with the private device data. The recap identifies each item by title and repository, reports per-item estimate variance, and **Save recap & adjust plan** continues into the current ordered Today plan without changing Gitea time entries. Eligible non-zero rows also offer an unchecked **Log Xm to Gitea** control. **Log selected time to Gitea** saves the recap and sends only those corrected durations to each canonical issue or pull request; confirmed account-scoped receipts prevent a completed row from being posted again, while definite failures retain the draft for an explicit retry. If the upstream response is lost after sending, Stackchain marks the row for verification in Gitea instead of risking an automatic duplicate. Actual time appears in planning as an explicit estimate recommendation; it changes only the planning draft until the operator chooses **Save plan** or **Save & start**. After the recap is confirmed, this recommendation handoff remains account-bound on the device through reloads, app restarts, planner cancellation, and failed plan admission. Opening **Plan Today** resumes it without reposting the recap; a successful plan save clears it, while **Discard recap feedback** removes only the handoff and leaves recap history unchanged. The recap and any corrected actual minutes are also saved as an account-bound device draft: an offline save failure can survive a reload and retry with the same idempotent session ID, while another account cannot view it. The draft and timer are cleared only after the account confirms the recap.
After wrap-up, **Share day summary** opens a private review of the exact worked-on and tomorrow selections. Every row is opt-in adjustable, actual time is excluded by default, and an optional bounded note is previewed before the native share sheet or clipboard fallback. Canceling or closing keeps the account-scoped device draft; successful sharing or **Discard draft** removes it.
@@ -155,6 +175,35 @@ storage before closing on a phone. The Queues summary marks it **sync pending**
foreground, and midnight lifecycle checks share one delivery flight. A successful account receipt removes
the pending copy, while a revision conflict preserves both the phone plan and fresh server snapshot for
review. Unsynced Tomorrow work is never promoted into Today.
**Week Ahead** opens as a read-first seven-day mobile overview, so operators can inspect the next planned day,
work titles and references, load versus capacity, overloads, and pending sync without staging a change. When Today
is empty and no work session is active, **Start this day early** confirms the next planned date, item count, minutes,
and capacity before atomically moving only that day into Today; offline, pending, stale, or non-empty plans remain
unchanged. **Edit day** enters one date and returns to the refreshed overview; **Edit week** starts the continuous
planning pass. Closing an issue from its Week Ahead detail retires that identity and estimate from every future
week day in one durable update while preserving sibling order and daily capacity. The open overview recalculates
immediately; an unavailable save remains visibly **sync pending** and retries through the existing lifecycle.
**Plan Week Ahead** continues through seven local dates and now finishes on a mobile review step instead of
closing after the seventh save. The review shows planned minutes against each day’s capacity, marks overloads,
and flags work assigned to more than one date. Operators can move an item to another date without copying it;
the estimate follows the item and the server rejects duplicate cross-day assignments without advancing the
week revision. When capacity changes create overload, **Reflow remaining week** previews a deterministic,
order-preserving redistribution across the seven visible dates. No day exceeds its capacity or five-item limit;
work that cannot fit is named and remains in My Work, while missing estimates block apply. Cancel performs no
write, and apply stages one durable whole-week transition through the existing conflict-safe sync path.
Confirmation remains disabled while duplicates exist or the account-bound week is still syncing.
Rapid saves and review moves use one network flight plus a coalesced latest-state delivery, so later staged days
are not stranded behind an earlier request. From the same review, **Set capacity from calendar** reads a local
`.ics` file on-device, unions overlapping busy periods within chosen working hours, and previews seven daily
availability totals before one atomic apply. IANA `TZID` values from Google and Outlook calendars are converted
to the device's local workday, including daylight-saving transitions. Daily and weekly recurrence (`COUNT`,
`UNTIL`, `INTERVAL`, and weekly `BYDAY`), `RDATE`/`EXDATE`, and all-day events are evaluated with work bounded
to the seven review dates; cancelled and transparent events do not consume capacity. If a time zone is unknown,
or a recurring event that could affect the week uses another frequency or unsupported rule part, the review
reports only an affected-event count and disables apply rather than understating busy time. Export a simpler
seven-day calendar to proceed. Raw calendar data and event
metadata are never persisted, rendered in diagnostics, or sent; only the reviewed capacity-minute totals use
the existing encrypted, account-bound Week Ahead sync.
Planning edits can remain offline for up to 30 days. After that, the
expired edit is discarded visibly and the account plan is kept rather than replaying stale
intent. The server retains no more than 4,096 operation receipts per account and removes
@@ -287,7 +336,18 @@ export STACKCHAIN_LOGIN_ATTEMPT_DB='/var/lib/stackchain-dashboard/login-attempts
# it. Missing, malformed, wrong-key, or modified state fails closed without
# returning content. Legacy Today/Later, Saved Search, and Security activity rows
# migrate atomically on first use without changing logical revisions or journal IDs.
# The single-key setting remains the compatible first deployment and writes v1 envelopes.
export STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY='<base64-encoded-32-byte-key>'
# After all workers run keyring-capable code, configure at most four named keys and
# select the active write key. Keep the old key present during the rolling deployment.
# Key IDs use 1-32 letters, digits, underscores, or hyphens.
export STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS='{"legacy":"<old-base64-key>","2026-08":"<new-base64-key>"}'
export STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID='2026-08'
# New writes use authenticated v2 envelopes carrying the active key ID. Rewrap every
# shared store with the restart-safe command; output contains store-level counts only.
# Run it again until every store reports failed=0, migrated=0, and current=total,
# then remove the old key from every worker. Retain all keys and investigate if it exits 1.
python3 scripts/rotate_private_state.py
# Required for cross-device unfiled Draft sync. The single-key setting remains
# supported for the first deployment of keyring-capable code and writes v1 envelopes.
# Inject the base64 encoding of exactly 32 random bytes from a secret manager.
+147
View File
@@ -50,6 +50,20 @@ header { position: sticky; top: 0; z-index: 20; padding: 12px 16px; display:flex
.app-menu-panel { display:flex; gap:10px; align-items:center; flex-wrap:wrap; }
#open-insights { display:none; }
button { background: linear-gradient(180deg,#1f3a5f,#15324d); border:1px solid #2a496e; color:#e5e7eb; padding:8px 12px; border-radius:10px; cursor:pointer; }
.search-week-plan-sheet { position:fixed; inset:0; z-index:118; display:flex; align-items:flex-end; justify-content:center; background:rgba(5,12,21,.82); backdrop-filter:blur(4px); }
.search-week-plan-sheet[hidden] { display:none; }
.search-week-plan-panel { box-sizing:border-box; width:min(560px,100%); max-height:100dvh; overflow:auto; overflow-x:hidden; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); border:1px solid #60a5fa; border-radius:18px 18px 0 0; background:#0b1526; }
.search-week-plan-panel header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
.search-week-plan-panel h2 { margin:.2rem 0; }
.search-week-plan-panel fieldset { min-width:0; margin:12px 0; padding:0; border:0; }
.search-week-plan-days { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:8px; }
.search-week-plan-days button { display:grid; min-width:0; min-height:44px; text-align:left; overflow-wrap:anywhere; }
.search-week-plan-days button[aria-pressed="true"] { border-color:#60a5fa; box-shadow:0 0 0 1px #60a5fa inset; }
.search-week-plan-days small { color:#9fb3c8; }
.search-week-plan-estimate { display:grid; gap:6px; }
.search-week-plan-estimate input, #confirm-search-week-plan, #cancel-search-week-plan { box-sizing:border-box; min-height:44px; }
#confirm-search-week-plan { width:100%; }
@media (max-width:359px) { .search-week-plan-days { grid-template-columns:1fr; } }
.notification-undo { position:fixed; }
.notification-undo button { min-height:44px; }
.notification-undo, .today-completion-undo { position:fixed; z-index:110; left:50%; bottom:calc(88px + env(safe-area-inset-bottom)); transform:translateX(-50%); box-sizing:border-box; width:min(520px,calc(100vw - 24px)); display:flex; align-items:center; justify-content:space-between; gap:12px; padding:10px 12px; border:1px solid #60a5fa; border-radius:12px; background:#10233d; box-shadow:0 12px 36px rgba(0,0,0,.5); overflow-wrap:anywhere; }
@@ -198,6 +212,13 @@ textarea { resize: vertical; min-height: 120px; }
.search-batch-estimate-review input { min-height:44px; width:76px; }
.search-batch-estimate-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding-bottom:env(safe-area-inset-bottom); background:#101f36; }
.search-batch-estimate-actions button { min-height:44px; }
.search-week-batch-review { display:grid; gap:12px; max-height:calc(100dvh - 48px); overflow:auto; overflow-x:hidden; padding:12px; border:1px solid #2a496e; border-radius:12px; background:#101f36; }
.search-week-batch-review[hidden] { display:none; }
.search-week-batch-review > div:first-child, #search-week-batch-list { display:grid; gap:10px; }
.search-week-batch-row { display:grid; gap:8px; padding:10px 0; border-bottom:1px solid #2a496e; overflow-wrap:anywhere; }
.search-week-batch-row-controls { display:grid; grid-template-columns:minmax(0,1fr) minmax(96px,.45fr); gap:8px; }
.search-week-batch-row select, .search-week-batch-row input, .search-week-batch-actions button { min-height:44px; width:100%; }
.search-week-batch-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 1fr; gap:8px; padding-bottom:env(safe-area-inset-bottom); background:#101f36; }
.search-release-review { display:grid; gap:12px; max-height:calc(100dvh - 48px); overflow:auto; padding:12px; border:1px solid #2a496e; border-radius:12px; background:#101f36; overflow-wrap:anywhere; }
.search-release-review[hidden] { display:none; }
.search-release-review > div:first-child, #search-release-list, .search-release-row { display:grid; gap:6px; }
@@ -241,10 +262,25 @@ textarea { resize: vertical; min-height: 120px; }
.plan-today-header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
.plan-today-header h2, .plan-today-header p { margin-top:0; }
.plan-today-header button { min-width:44px; min-height:44px; }
.week-plan-progress { margin:8px 0 4px; color:#bfdbfe; font-weight:700; }
.week-plan-dates { display:flex; gap:8px; margin:8px 0 12px; padding:2px 0 8px; overflow-x:auto; overscroll-behavior-inline:contain; }
.week-plan-dates[hidden] { display:none; }
.week-plan-dates button { min-height:44px; min-width:86px; flex:0 0 auto; padding:6px 10px; }
.week-plan-dates button[aria-current="date"] { color:#bfdbfe; background:#17365a; border-color:#60a5fa; }
.today-week-reschedule { box-sizing:border-box; width:100%; max-width:none; height:100%; max-height:none; margin:0; padding:0; border:0; background:rgba(5,12,21,.82); color:inherit; }
.today-week-reschedule::backdrop { background:rgba(5,12,21,.82); }
.today-week-reschedule-panel { width:min(100%,560px); box-sizing:border-box; min-height:100%; margin-left:auto; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); background:#0b1526; overflow-x:hidden; }
.today-week-reschedule-panel header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
.today-week-reschedule-panel h2, .today-week-reschedule-panel header p { margin-top:0; }
.today-week-reschedule-panel input { box-sizing:border-box; width:100%; min-height:44px; margin:6px 0 10px; font-size:16px; }
.today-week-reschedule-days { display:grid; gap:8px; margin:14px 0; }
.today-week-reschedule-days button { min-height:44px; display:grid; grid-template-columns:minmax(0,1fr) auto; gap:8px; text-align:left; overflow-wrap:anywhere; }
.today-week-reschedule-days button[aria-checked="true"] { border-color:#60a5fa; background:#17365a; color:#eff6ff; }
.today-week-reschedule-days button:disabled { opacity:.58; }
#cancel-today-week-reschedule { min-height:44px; }
#confirm-today-week-reschedule { position:sticky; bottom:0; width:100%; min-height:48px; }
#today-week-reschedule-status { min-height:1.4em; color:#fde68a; }
.back-to-week-review { width:100%; min-height:44px; margin:4px 0 12px; }
.tomorrow-conflict-review { margin-top:14px; }
.tomorrow-conflict-plans { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }
.tomorrow-conflict-plans > section { min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
@@ -264,6 +300,115 @@ textarea { resize: vertical; min-height: 120px; }
.tomorrow-conflict-plans { grid-template-columns:1fr; }
.tomorrow-conflict-actions { flex-direction:column; }
}
.week-conflict-review { margin-top:14px; }
.week-conflict-plans { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:12px; }
.week-conflict-plans > section { min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
.week-conflict-plans h4 { margin:0 0 8px; }
.week-conflict-day { margin:0 0 10px; padding-bottom:10px; border-bottom:1px solid #31577f; }
.week-conflict-day:last-child { margin-bottom:0; padding-bottom:0; border-bottom:0; }
.week-conflict-day strong { display:block; color:#bfdbfe; }
.week-conflict-actions { display:flex; gap:8px; margin-top:14px; }
.week-conflict-actions button { min-height:44px; flex:1 1 0; }
.week-conflict-days { display:grid; gap:12px; }
.week-conflict-date { min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
.week-conflict-date h4 { margin:0 0 8px; color:#bfdbfe; }
.week-conflict-choice { min-height:44px; display:flex; align-items:center; gap:10px; padding:8px; border-radius:8px; }
.week-conflict-choice:has(input:checked) { background:#17365a; outline:1px solid #60a5fa; }
.week-conflict-choice input { min-width:20px; min-height:20px; }
.week-conflict-choice span { display:grid; min-width:0; }
.week-conflict-choice small { color:#a9bdd3; }
#save-merged-week { width:100%; min-height:44px; margin-top:14px; }
.week-conflict-status { min-height:1.4em; margin-top:8px; }
.plan-today-sheet.week-conflict-mode .week-plan-dates,
.plan-today-sheet.week-conflict-mode .mobile-plan-today-nav,
.plan-today-sheet.week-conflict-mode #plan-today-fit,
.plan-today-sheet.week-conflict-mode #plan-today-selected,
.plan-today-sheet.week-conflict-mode #plan-today-available-work,
.plan-today-sheet.week-conflict-mode .plan-today-actions { display:none; }
@media (max-width:480px) {
.week-conflict-plans { grid-template-columns:1fr; }
.week-conflict-actions { flex-direction:column; }
}
.week-review { margin-top:14px; }
.week-review h2 { margin-bottom:6px; }
.week-review-days { display:grid; gap:12px; }
.week-review-day { padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
.week-review-day.is-overloaded { border-color:#f59e0b; background:#2a1c12; }
.week-review-day.is-next-up { border-color:#60a5fa; box-shadow:0 0 0 1px #60a5fa inset; }
.week-next-up { display:inline-block; margin-left:6px; padding:2px 7px; border-radius:999px; background:#1d4f7a; color:#dbeafe; font-size:11px; vertical-align:middle; }
.week-review-day header { display:flex; align-items:center; justify-content:space-between; gap:8px; }
.week-review-day header button { flex:0 0 auto; min-height:44px; }
.week-review-day h3, .week-review-day p { margin:0 0 8px; }
.week-review-load { color:#bfdbfe; font-weight:700; }
.week-review-day ul { display:grid; gap:10px; margin:0; padding:0; list-style:none; }
.week-review-day li { display:grid; grid-template-columns:minmax(0,1fr) auto; gap:8px; align-items:end; padding-top:8px; border-top:1px solid #31577f; overflow-wrap:anywhere; }
.week-review-item-copy { display:grid; min-width:0; gap:3px; }
.week-review-item-open { display:block; width:100%; min-width:0; min-height:44px; padding:8px; border:0; border-radius:8px; background:transparent; color:inherit; text-align:left; }
.week-review-item-open:hover { background:#173453; }
.week-review-item-open:focus-visible { outline:3px solid #93c5fd; outline-offset:2px; }
.week-review-unplan { width:100%; min-height:44px; border-color:#6b87a6; background:transparent; color:#d7e5f5; }
.week-review-pull { grid-column:1/-1; width:100%; min-height:44px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
.week-review-unplan { grid-column:1/-1; }
.week-unplan-receipt { margin:12px 0 6px; padding:10px 12px; border:1px solid #60a5fa; border-radius:10px; background:#112d4d; color:#dbeafe; }
#undo-week-unplan { width:100%; min-height:44px; margin-bottom:8px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
.week-start-early { display:block; width:100%; min-height:44px; margin-top:12px; border-color:#60a5fa; background:#1d4f7a; color:#eff6ff; font-weight:800; }
.week-start-early:focus-visible { outline:3px solid #bfdbfe; outline-offset:2px; }
.week-review-item-copy strong, .week-review-item-copy small { overflow-wrap:anywhere; }
.week-review-item-copy small { color:#a9bdd3; }
.week-review-move { display:flex; align-items:end; gap:8px; }
.week-review-day label { display:grid; gap:4px; font-size:12px; }
.week-review-day select, .week-review-day button { min-height:44px; }
.week-review-day button { min-height:44px; }
.week-review-duplicates { margin:12px 0; padding:12px; border:1px solid #f59e0b; border-radius:10px; background:#2a1c12; }
.week-review-status { min-height:1.4em; margin:10px 0; }
.week-offline-snapshot { margin:10px 0 8px; padding:10px 12px; border:1px solid #f59e0b; border-radius:10px; background:#2a1c12; color:#fde68a; overflow-wrap:anywhere; }
#retry-week-live { min-height:44px; width:100%; margin-bottom:8px; border-color:#f59e0b; }
#confirm-week-plan { width:100%; min-height:48px; position:sticky; bottom:0; }
#edit-week-plan { width:100%; min-height:48px; position:sticky; bottom:0; }
#open-week-capacity-import { width:100%; min-height:44px; margin:8px 0 12px; }
#open-week-reflow { width:100%; min-height:48px; margin:0 0 12px; border-color:#60a5fa; }
.week-reflow-review { box-sizing:border-box; width:100%; margin:0 0 14px; padding:14px; border:1px solid #60a5fa; border-radius:12px; background:#10233d; overflow-x:hidden; }
.week-reflow-review h3 { margin:.25rem 0; }
.week-reflow-days { display:grid; gap:6px; margin:12px 0; }
.week-reflow-day { display:flex; justify-content:space-between; gap:10px; min-width:0; padding:8px; border-radius:8px; background:#0b1526; overflow-wrap:anywhere; }
.week-reflow-unscheduled { min-height:1.4em; color:#fde68a; overflow-wrap:anywhere; }
.week-reflow-actions { display:grid; grid-template-columns:1fr 2fr; gap:8px; margin-top:12px; }
.week-reflow-actions button { min-width:0; min-height:48px; }
.week-capacity-import { position:fixed; z-index:121; inset:0; box-sizing:border-box; width:100%; max-width:560px; margin-inline:auto; padding:18px; padding-bottom:calc(18px + env(safe-area-inset-bottom)); background:#0b1526; overflow:auto; overflow-x:hidden; }
.week-capacity-import[hidden] { display:none; }
.week-capacity-import > header { display:flex; align-items:flex-start; justify-content:space-between; gap:12px; }
.week-capacity-import h2 { margin:.2rem 0; }
.week-capacity-import > label, .week-capacity-hours label { display:grid; min-width:0; gap:6px; margin:12px 0; }
.week-capacity-import input, .week-capacity-import button { box-sizing:border-box; min-width:0; min-height:44px; max-width:100%; }
.week-capacity-hours { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:10px; }
.week-capacity-days { display:grid; gap:8px; margin:10px 0 14px; }
.week-capacity-day { display:grid; min-width:0; gap:3px; padding:10px; border:1px solid #31577f; border-radius:10px; background:#10233a; overflow-wrap:anywhere; }
.week-capacity-day span { color:#bfdbfe; font-weight:700; }
.week-capacity-day small { color:#a9bdd3; }
#apply-week-capacities { width:100%; min-height:48px; position:sticky; bottom:0; }
@media (max-width:359px) { .week-capacity-hours { grid-template-columns:1fr; } }
.week-calendar-handoff h2 { margin-bottom:6px; }
.week-calendar-days { display:grid; gap:12px; margin:14px 0; }
.week-calendar-day { min-width:0; padding:12px; border:1px solid #31577f; border-radius:12px; background:#10233a; }
.week-calendar-day header { display:flex; align-items:center; justify-content:space-between; gap:12px; }
.week-calendar-day h3 { margin:0; }
.week-calendar-day input[type="time"] { min-height:44px; font-size:16px; }
.week-calendar-item { display:grid; grid-template-columns:auto minmax(0,1fr); gap:10px; align-items:center; min-height:44px; padding:8px 0; overflow-wrap:anywhere; }
.week-calendar-item input { width:22px; height:22px; }
.week-calendar-item span { display:grid; gap:3px; }
.week-calendar-item small { color:#a9bdd3; }
.week-calendar-status { min-height:1.4em; margin:10px 0; }
.week-calendar-actions { position:sticky; bottom:0; display:grid; grid-template-columns:1fr 2fr; gap:8px; padding-bottom:env(safe-area-inset-bottom); background:#0b1526; }
.week-calendar-actions button { min-width:0; min-height:48px; }
.plan-today-sheet.week-review-mode .week-plan-dates,
.plan-today-sheet.week-review-mode .mobile-plan-today-nav,
.plan-today-sheet.week-review-mode #plan-today-fit,
.plan-today-sheet.week-review-mode #plan-today-selected,
.plan-today-sheet.week-review-mode #plan-today-available-work,
.plan-today-sheet.week-review-mode .plan-today-actions { display:none; }
@media (max-width:480px) {
.week-review-day li { grid-template-columns:1fr; }
}
.mobile-plan-today-nav { position:sticky; top:0; z-index:5; display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:4px; margin:0 -18px 10px; padding:4px 18px; background:rgba(11,21,38,.98); border-block:1px solid #2a496e; }
.mobile-plan-today-nav button { min-width:0; min-height:44px; padding:4px; border-color:transparent; font-size:12px; }
.mobile-plan-today-nav button[aria-current="location"] { color:#bfdbfe; background:#17365a; border-color:#31577f; }
@@ -653,6 +798,7 @@ textarea { resize: vertical; min-height: 120px; }
.update-decision-bar button, .update-decision-bar summary { min-height:44px; min-width:0; padding-inline:6px; }
.update-retry { min-height:44px; width:100%; margin-top:10px; }
.issue-sheet { position:fixed; inset:0; z-index:56; display:none; justify-content:flex-end; background:rgba(5,12,21,.72); backdrop-filter:blur(4px); }
.task-overlay-open .issue-sheet.open, .task-overlay-open .pull-sheet.open { z-index:76; }
.issue-sheet.open { display:flex; }
.issue-sheet-panel { width:min(560px,100%); height:100%; overflow:auto; padding:18px; background:#0b1526; border-left:1px solid #2a496e; }
.issue-sheet-header { display:flex; align-items:center; justify-content:space-between; gap:10px; }
@@ -1096,6 +1242,7 @@ textarea { resize: vertical; min-height: 120px; }
@media (max-width: 600px) {
body { padding-bottom:calc(66px + env(safe-area-inset-bottom)); }
body.mobile-today-active { padding-bottom:calc(var(--mobile-today-clearance, 166px) + env(safe-area-inset-bottom)); }
body:has(.mobile-today-hud:not([hidden]):not([data-overlay-hidden="true"])) { padding-bottom:calc(var(--mobile-today-clearance, 166px) + env(safe-area-inset-bottom)); }
header { min-height:56px; max-height:64px; padding:6px 10px; align-items:center; gap:8px; background:rgba(11,21,38,.98); }
.app-brand .muted, #clock { display:none; }
.app-live-status { margin-left:auto; }
+119 -24
View File
@@ -391,12 +391,14 @@
});
const weekPlan = createWeekPlan({
fetchJson:fetchReviewJson,localDate:todayRollover.localDate,timeZone:todayRollover.timeZone,
storage:localStorage,getLogin:() => planningOwnerLogin,coordinator:outboxCoordinator,
});
function openWeekPlanner(trigger) { planningTomorrow=false; return weekWorkflow.open(trigger); }
function openWeekPlanner(trigger) { planningTomorrow=false; return weekFlow.open(trigger); }
function renderTomorrowQueueSummary(value) {
qs('#mobile-tomorrow-summary').textContent = value ? tomorrowPlan.summary(value) : tomorrowPlan.summary();
}
function syncPendingTomorrow() {
weekFlow.resumePull()&&weekFlow.flushPull();
if (!tomorrowPlan.pending()) return Promise.resolve(false);
return tomorrowPlan.flush().then(saved => {
renderTomorrowQueueSummary(saved);
@@ -409,7 +411,7 @@
if (conflict) renderTomorrowQueueSummary({ids:[],sync_pending:false,conflict:true});
qs('#mobile-tomorrow-summary').textContent = conflict ? 'Conflict · review required' : qs('#mobile-tomorrow-summary').textContent;
qs('#my-work-action-status').textContent = conflict ?
'Another device changed Tomorrow. Both plans are preserved; open Tomorrow to choose one.' :
'Another device changed Tomorrow. Review it.' :
`${error.message || 'Tomorrow sync is unavailable.'} Saved on this phone · sync pending.`;
return false;
});
@@ -451,9 +453,16 @@
storage: localStorage,
getLogin: () => planningOwnerLogin,
});
const weekWorkflow=createWeekPlanWorkflow({controller:weekPlan,qs,getLogin:()=>planningOwnerLogin,
openPlanner:openPlanToday,escapeHtml,escapeAttribute:escAttr,todayWork,
refresh:refreshMyWorkView,warm:warmTodayOffline});
const weekItem=id=>[...todayMyWork,...activeMyWork].find(item=>todayWork.identity(item)===id);
const weekFlow=createWeekPlanWorkflow({controller:weekPlan,qs,
getItem:weekItem,openItem:openRoutedWork,
openPlanner:openPlanToday,setReviewMode:v=>qs('#plan-today-sheet').classList.toggle('week-review-mode',v),
escapeHtml,escapeAttribute:escAttr,todayWork,
t:v=>v?latestTodayPlan=v:latestTodayPlan,r:refreshMyWorkView,w:warmTodayOffline,
x:currentTodayProgressTarget});
const weekCalendar=StackchainWeekCalendar.mountWeekCalendarHandoff({qs,getItem:weekItem,escapeHtml,escapeAttribute:escAttr,
onDone:()=>{weekFlow.finish();taskOverlayHistory.leave();},
});
const todaySync = createTodaySync({
storage: localStorage,
getLogin: () => planningOwnerLogin,
@@ -467,9 +476,8 @@
onRemotePlan: plan => {
if (!planningOwnerLogin) return;
latestTodayPlan = plan;
const startDayLaunch = window.location.hash === '#/my-work/start-day';
weekWorkflow.promote(plan).finally(() => {
if (!startDayLaunch) return;
weekFlow.promote(plan).finally(() => {
if (window.location.hash !== '#/my-work/start-day') return;
window.history.replaceState({}, '', '#/my-work/today');
openMobileStartDay();
});
@@ -477,8 +485,8 @@
capacity_minutes: plan.capacity_minutes ?? null,
estimates: plan.estimates || {},
});
const reviewState = todayRollover.reviewState(plan);
if (!['stale', 'legacy'].includes(reviewState)) {
const s = todayRollover.reviewState(plan);
if (!['stale', 'legacy'].includes(s)) {
rolloverReviewPlan = null;
qs('#plan-today').textContent = 'Plan Today';
return;
@@ -511,7 +519,8 @@
documentObject:document,
check:() => Promise.all([
syncPendingTomorrow(),
latestTodayPlan ? weekWorkflow.promote(latestTodayPlan) : false,
weekPlan.pending() ? weekPlan.flush().catch(() => false) : false,
latestTodayPlan ? weekFlow.promote(latestTodayPlan) : false,
]),
});
const todayHandoff = createTodayHandoff({
@@ -2697,9 +2706,12 @@
}
planToday.cancel();
planningTomorrow = false;
weekWorkflow.clear();
weekCalendar.close();
weekFlow.clear();
qs('#tomorrow-conflict-review').hidden = true;
qs('#plan-today-sheet').classList.remove('tomorrow-conflict-mode');
qs('#week-conflict-review').hidden = true;
qs('#plan-today-sheet').classList.remove('week-conflict-mode');
qs('#plan-today-sheet').hidden = true;
document.body.classList.remove('task-overlay-open');
if (planTodayTrigger?.dataset.mobileQueue === 'tomorrow') {
@@ -2754,7 +2766,7 @@
const planToday = createPlanToday({
identity: item => todayWork.identity(item),
limit: todayWork.limit,
save: plan => weekWorkflow.active() ? weekWorkflow.save(plan) :
save: plan => weekFlow.active() ? weekFlow.save(plan) :
(planningTomorrow ? saveTomorrowPlan(plan) : saveTodayPlan(plan)),
start: () => {
qs('[data-work-filter="today"]').click();
@@ -3059,13 +3071,24 @@
requestAnimationFrame(() => keep.focus());
}
function showWeekConflict(conflict) {
qs('#plan-today-title').textContent='Resolve Week Ahead conflict';
const focus=weekFlow.renderConflict(conflict);
qs('#week-conflict-status').textContent='';
qs('#week-conflict-review').hidden=false;
qs('#plan-today-sheet').classList.add('week-conflict-mode');
qs('#plan-today-sheet').hidden=false;
document.body.classList.add('task-overlay-open');
focus.focus();requestAnimationFrame(()=>focus.focus());
}
function openPlanToday(trigger, navigate = true, actualMinutes = null) {
if (!planningOwnerLogin && !weekWorkflow.active()) {
if (!planningOwnerLogin && !weekFlow.active()) {
qs('#my-work-action-status').textContent = 'Planning is unavailable until your operator identity is restored.';
return;
}
if (trigger) planTodayTrigger = trigger;
const weekCopy=weekWorkflow.copy();
const weekCopy=weekFlow.copy();
qs('#plan-today-title').textContent = weekCopy ? weekCopy.title : (planningTomorrow ? 'Plan Tomorrow' :
(pendingProtectToday ? 'Protect Today' : (rolloverReviewPlan ? 'New day review' : 'Plan Today')));
if (actualMinutes) pendingPlanActualMinutes = actualMinutes;
@@ -3078,13 +3101,17 @@
showTomorrowConflict(conflict);
return;
}
const weekConflict=weekFlow.active()?weekPlan.conflict():null;
if(weekConflict){showWeekConflict(weekConflict);return;}
qs('#tomorrow-conflict-review').hidden = true;
qs('#plan-today-sheet').classList.remove('tomorrow-conflict-mode');
qs('#week-conflict-review').hidden=true;
qs('#plan-today-sheet').classList.remove('week-conflict-mode');
const recommendations = actualMinutes || pendingPlanActualMinutes || todayRecapView.pendingReplan()?.actual_minutes;
pendingPlanActualMinutes = null;
const protectProposal = pendingProtectToday;
const tomorrow = planningTomorrow ? tomorrowPlan.state() : null;
const weekDay = weekWorkflow.day();
const weekDay = weekFlow.day();
const availablePlanningItems = [...todayMyWork, ...activeMyWork].filter((item, index, items) =>
items.findIndex(candidate => todayWork.identity(candidate) === todayWork.identity(item)) === index
);
@@ -3101,8 +3128,8 @@
qs('#plan-today-error').textContent = '';
qs('#plan-today-sheet').hidden = false;
document.body.classList.add('task-overlay-open');
weekWorkflow.renderDates();
renderPlanToday();
weekFlow.renderDates();
if (protectProposal) qs('#plan-today-build-status').textContent = protectProposal.summary +
(protectProposal.displaced.length ? '. Displaced work remains unchanged until you save.' : '. Review estimates and capacity before saving.');
qs('#cancel-plan-today').focus();
@@ -4395,7 +4422,7 @@
selectedIssueOffline = false;
selectedIssueDetail = null;
issueConversation = null;
if (issueTrigger?.isConnected) issueTrigger.focus();
setTimeout(()=>issueTrigger?.focus());
}
function closeIssueEditorFromHistory() {
@@ -5454,7 +5481,7 @@
activeFlushLogin = contextIdentityFresh ? String(snapshot.context.user?.login || '').trim() : '';
if (activeFlushLogin) {
confirmedOwnerLogin = activeFlushLogin;
timerView.render();
timerView.restore(todaySync.flush());
restoreReleaseReceipt();
updateDeliveryReceiptControls();
interruptionPrompt.restore();
@@ -5590,6 +5617,7 @@
const claimButton = qs('#claim-search-result');
const deferButton = qs('#defer-search-result');
const queueButton = qs('#queue-search-result');
const planButton = qs('#plan-search-result');
const startButton = qs('#start-search-result');
const shareButton = qs('#share-search-result');
@@ -5606,6 +5634,8 @@
deferButton.hidden = true;
deferButton.disabled = false;
queueButton.hidden = true;
planButton.hidden = true;
planButton.disabled = false;
startButton.hidden = true;
startButton.disabled = false;
shareButton.disabled = true;
@@ -5654,6 +5684,9 @@
queueButton.hidden = !(detail.kind === 'issue' && detail.state === 'open' &&
(detail.claimable || detail.assigned_to_me));
queueButton.textContent = detail.assigned_to_me ? 'Add to Today' : 'Assign & add to Today';
planButton.hidden = !searchWeekPlan.eligible(detail);
planButton.textContent = detail.assigned_to_me ? 'Plan ahead' : 'Assign & plan ahead';
planButton.disabled = searchWeekPlan.pending();
startButton.hidden = !(detail.reviewable || (detail.kind === 'issue' &&
(detail.reopenable || (detail.state === 'open' && (detail.claimable || detail.assigned_to_me)))));
startButton.textContent = detail.reviewable ? 'Review now' : detail.reopenable ? 'Reopen & resume' :
@@ -5711,10 +5744,19 @@
session:[()=>commandSearchState, commandSearch, item=>taskOverlayHistory.update({preview:item})],
onState: renderSearchPreview,
});
const searchWeekPlan = createSearchWeekPlan({
week:weekPlan,claim:detail=>searchPreview.claim(detail),accept:acceptClaimedIssue,
identity:item=>todayWork.identity(item),
});
createSearchWeekPlanUI({planner:searchWeekPlan,document,window,escapeHtml,escapeAttribute:escAttr,
getDetail:()=>searchPreviewDetail,
announce:message=>{qs('#search-preview-status').textContent=message;},
onPlanned:item=>{searchPreviewDetail={...item,assigned_to_me:true,claimable:false};},
});
searchBatchPlanning = mountSearchBatchPlanning(
document, createBatchFindWork, todayWork, ()=>planningOwnerLogin, fetchReviewJson,
searchPreviewPath, queueToday, todaySync, acceptClaimedIssue, i=>commandItems[i]?.result,
()=>renderCommands(qs('#cmd-input').value), escapeHtml, escAttr, laterWork, laterPicker
()=>renderCommands(qs('#cmd-input').value), escapeHtml, escAttr, laterWork, laterPicker, weekPlan, localStorage
);
searchDefer = createSearchDefer({
claim: detail => searchPreview.claim(detail),
@@ -6068,6 +6110,7 @@
(!detail.claimable && !detail.assigned_to_me) || searchDefer.pending()) return;
laterPicker.open(detail, event.currentTarget, 'search');
});
qs('#queue-search-result').addEventListener('click', async () => {
const detail = searchPreviewDetail;
if (!detail || detail.kind !== 'issue' || detail.state !== 'open' ||
@@ -7073,11 +7116,11 @@
closeIssueSheet();
refreshMyWorkView({ reconcileSession:false });
if (!outcome.advanced) {
qs('#my-work-action-status').textContent = 'Issue closure queued, but Today still needs completion.';
qs('#my-work-action-status').textContent = 'Issue close queued; Today still needs completion.';
} else if (outcome.admission.background) {
qs('#my-work-action-status').textContent = 'Issue closure queued for reconnect. Next Today item opened.';
qs('#my-work-action-status').textContent = 'Issue close queued. Next Today item opened.';
} else {
qs('#my-work-action-status').textContent = 'Issue closure saved for next launch. Next Today item opened.';
qs('#my-work-action-status').textContent = 'Issue close saved. Next Today item opened.';
}
} catch (error) {
qs('#issue-sheet-status').textContent = error.message + ' The issue remains in Today; retry.';
@@ -7691,6 +7734,7 @@
planningOwnerLogin = confirmedOwnerLogin;
interruptionPrompt.restore();
updatePlanningAvailability();
syncPendingTomorrow();
saved.notifications = notificationReadOutbox.suppress(saved.notifications || []);
lastNotifications = saved.notifications;
notificationPagination = saved.notification_pagination || { page:1, total:lastNotifications.length, has_more:false };
@@ -7832,7 +7876,58 @@
qs('#my-work-action-status').textContent = 'Saved account Tomorrow plan selected. Today was not changed.';
closePlanToday();
});
qs('#keep-phone-week').addEventListener('click', async () => {
const keep=qs('#keep-phone-week'),use=qs('#use-server-week');
keep.disabled=true;use.disabled=true;
qs('#week-conflict-status').textContent='Saving this phone’s complete week…';
try {
await weekPlan.keepLocal();
qs('#mobile-week-summary').textContent=weekPlan.summary();
qs('#my-work-action-status').textContent='This phone’s Week Ahead plan is saved. Today was not changed.';
closePlanToday();
} catch(error) {
const conflict=weekPlan.conflict();
if(conflict)showWeekConflict(conflict);
qs('#week-conflict-status').textContent=error?.status===409?
'Week Ahead changed again. Both latest weeks are preserved; choose again.':
`${error.message||'Week Ahead could not be saved.'} Both weeks are still preserved.`;
} finally {keep.disabled=false;use.disabled=false;}
});
qs('#use-server-week').addEventListener('click', () => {
const adopted=weekPlan.useRemote();
if(!adopted)return;
qs('#mobile-week-summary').textContent=weekPlan.summary();
qs('#my-work-action-status').textContent='Saved account Week Ahead plan selected. Today was not changed.';
closePlanToday();
});
qs('#save-merged-week').addEventListener('click', async () => {
const save=qs('#save-merged-week');
save.disabled=true;
qs('#week-conflict-status').textContent='Saving combined Week Ahead plan…';
try {
await weekPlan.saveMerged();
qs('#mobile-week-summary').textContent=weekPlan.summary();
qs('#my-work-action-status').textContent='Combined Week Ahead changes are saved. Today was not changed.';
closePlanToday();
} catch(error) {
const conflict=weekPlan.conflict();
if(conflict)showWeekConflict(conflict);
qs('#week-conflict-status').textContent=error?.status===409?
'Week Ahead changed again. The latest days are preserved; review the remaining choices.':
`${error.message||'The combined week could not be saved.'} Your phone plan is still preserved.`;
} finally {
const conflict=weekPlan.conflict();
save.disabled=Boolean(conflict?.conflicts?.some(item=>!item.choice));
}
});
qs('#cancel-plan-today').addEventListener('click', closePlanToday);
qs('#confirm-week-plan').addEventListener('click', () => {
if(!weekFlow.confirm()){
qs('#week-review-status').textContent=weekPlan.pending()?'Wait for Week Ahead to finish syncing before confirming.':'Move duplicated work to one date before confirming.';
return;
}
weekCalendar.open(weekPlan.state());
});
qs('#plan-today-sheet').addEventListener('click', event => {
if (event.target === qs('#plan-today-sheet')) closePlanToday();
});
@@ -7857,7 +7952,7 @@
const result = planToday.commit({ start, confirmOverCapacity: button.dataset.confirmOverCapacity === 'true' });
if (result === 'saved') {
button.dataset.confirmOverCapacity = '';
taskOverlayHistory.leave();
if (!weekFlow.active() || !weekFlow.advance()) taskOverlayHistory.leave();
} else if (result === 'confirm-over-capacity') {
button.dataset.confirmOverCapacity = 'true';
qs('#plan-today-error').textContent = 'This plan exceeds your available time. Press again to save over capacity.';
+128
View File
@@ -460,7 +460,9 @@
<div><h2 id="plan-today-title">Plan Today</h2><p class="small muted">Choose and order the work you want to finish next.</p></div>
<button id="cancel-plan-today" type="button">Cancel</button>
</div>
<p class="week-plan-progress" id="week-plan-progress" aria-live="polite" hidden></p>
<nav class="week-plan-dates" id="week-plan-dates" aria-label="Week Ahead dates" hidden></nav>
<button class="back-to-week-review" id="back-to-week-review" type="button" hidden>Back to week review</button>
<section class="tomorrow-conflict-review" id="tomorrow-conflict-review" aria-labelledby="tomorrow-conflict-title" hidden>
<div class="small">Cross-device change</div>
<h3 id="tomorrow-conflict-title">Choose which Tomorrow plan to keep</h3>
@@ -481,6 +483,84 @@
</div>
<div class="small tomorrow-conflict-status" id="tomorrow-conflict-status" role="status" aria-live="assertive"></div>
</section>
<section class="week-conflict-review" id="week-conflict-review" aria-labelledby="week-conflict-title" hidden>
<div class="small">Cross-device change</div>
<h3 id="week-conflict-title">Resolve Week Ahead changes</h3>
<p class="small muted">Changes on different days are combined automatically. Choose only where both devices changed the same day.</p>
<div class="week-conflict-days" id="week-conflict-days" hidden></div>
<button id="save-merged-week" type="button" hidden disabled>Save combined week</button>
<div class="week-conflict-plans" id="week-conflict-legacy-plans">
<section aria-labelledby="week-conflict-phone-title">
<h4 id="week-conflict-phone-title">This phone</h4>
<div id="week-conflict-phone-plan"></div>
</section>
<section aria-labelledby="week-conflict-server-title">
<h4 id="week-conflict-server-title">Saved on your account</h4>
<div id="week-conflict-server-plan"></div>
</section>
</div>
<div class="week-conflict-actions" id="week-conflict-legacy-actions">
<button id="keep-phone-week" type="button">Keep this phone’s week</button>
<button id="use-server-week" type="button">Use saved account week</button>
</div>
<div class="small week-conflict-status" id="week-conflict-status" role="status" aria-live="assertive"></div>
</section>
<section class="week-review" id="week-review" aria-labelledby="week-review-title" hidden>
<div class="small">Seven-day overview</div>
<h2 id="week-review-title">Week Ahead</h2>
<p class="small muted">See what is next and check each day’s load. Edit only when you are ready.</p>
<p class="week-offline-snapshot" id="week-offline-snapshot" role="status" aria-live="polite" hidden></p>
<button id="retry-week-live" type="button" hidden>Retry live Week Ahead</button>
<button id="open-week-capacity-import" type="button">Set capacity from calendar</button>
<button id="open-week-reflow" type="button" hidden>Reflow remaining week</button>
<section class="week-reflow-review" id="week-reflow-review" aria-labelledby="week-reflow-title" hidden>
<div class="small">Capacity-safe preview</div>
<h3 id="week-reflow-title">Reflow remaining week?</h3>
<p class="small muted">Work keeps its current order. Anything that cannot fit stays unscheduled in My Work.</p>
<div class="week-reflow-days" id="week-reflow-days"></div>
<div class="week-reflow-unscheduled" id="week-reflow-unscheduled" role="status"></div>
<div class="week-reflow-actions">
<button id="cancel-week-reflow" type="button">Cancel</button>
<button id="apply-week-reflow" type="button">Apply reflow</button>
</div>
</section>
<div class="week-review-duplicates" id="week-review-duplicates" role="alert" hidden></div>
<div class="week-review-days" id="week-review-days"></div>
<div class="week-unplan-receipt" id="week-unplan-receipt" role="status" aria-live="polite" hidden></div>
<button id="undo-week-unplan" type="button" hidden>Undo</button>
<div class="small week-review-status" id="week-review-status" role="status" aria-live="polite"></div>
<button id="edit-week-plan" type="button" hidden>Edit week</button>
<button id="confirm-week-plan" type="button">Confirm Week Ahead</button>
</section>
<section class="week-capacity-import" id="week-capacity-import" aria-labelledby="week-capacity-title" hidden>
<header><div><div class="small">Private calendar import</div><h2 id="week-capacity-title">Set Week Ahead capacity</h2></div>
<button id="cancel-week-capacity-import" type="button">Cancel</button></header>
<p class="small muted">Your calendar is read only on this device. Event titles, people, locations, and the file are never saved or uploaded.</p>
<label>Calendar file
<input id="week-capacity-file" type="file" accept=".ics,text/calendar" />
</label>
<div class="week-capacity-hours">
<label>Workday starts <input id="week-capacity-start" type="time" value="09:00" required /></label>
<label>Workday ends <input id="week-capacity-end" type="time" value="17:00" required /></label>
</div>
<div id="week-capacity-status" class="small" role="status" aria-live="assertive"></div>
<section id="week-capacity-review" aria-labelledby="week-capacity-review-title" hidden>
<h3 id="week-capacity-review-title">Review available time</h3>
<div id="week-capacity-days" class="week-capacity-days"></div>
<button id="apply-week-capacities" type="button">Apply seven capacities</button>
</section>
</section>
<section class="week-calendar-handoff" id="week-calendar-handoff" aria-labelledby="week-calendar-title" hidden>
<div class="small">Calendar handoff</div>
<h2 id="week-calendar-title">Add Week Ahead to calendar</h2>
<p class="small muted">Titles, references, dates, and times are included in a local calendar file; nothing is uploaded. Imported busy time is used only until this page reloads; otherwise times follow the chosen start.</p>
<div class="week-calendar-days" id="week-calendar-days"></div>
<div class="small week-calendar-status" id="week-calendar-status" role="status" aria-live="assertive"></div>
<div class="week-calendar-actions">
<button id="back-to-week-review-from-calendar" type="button">Back to review</button>
<button id="share-week-calendar" type="button">Share calendar blocks</button>
</div>
</section>
<nav class="mobile-plan-today-nav" aria-label="Plan Today sections">
<button type="button" data-plan-today-section="fit" aria-current="location">Fit</button>
<button type="button" data-plan-today-section="today">Today</button>
@@ -705,6 +785,7 @@
<span id="search-selection-status" class="small" aria-live="polite">No issues selected.</span>
<button id="cancel-search-selection" type="button">Cancel</button>
<button id="defer-selected-search-results" type="button" disabled>Defer</button>
<button id="week-selected-search-results" type="button" disabled>Plan Week Ahead</button>
<button id="plan-selected-search-results" type="button" disabled>Plan release</button>
<button id="queue-selected-search-results" type="button" disabled>Assign &amp; add to Today</button>
</div>
@@ -718,6 +799,16 @@
<button id="confirm-search-batch-estimates" type="button">Confirm &amp; assign</button>
</div>
</section>
<section class="search-week-batch-review" id="search-week-batch-review" role="dialog" aria-modal="true"
aria-labelledby="search-week-batch-heading" hidden>
<div><strong id="search-week-batch-heading">Plan selected issues into Week Ahead</strong>
<span class="small" id="search-week-batch-summary" aria-live="polite"></span></div>
<div id="search-week-batch-list"></div>
<div class="search-week-batch-actions">
<button id="cancel-search-week-batch" type="button">Back</button>
<button id="confirm-search-week-batch" type="button">Assign &amp; plan</button>
</div>
</section>
<section class="search-release-review" id="search-release-review"
aria-labelledby="search-release-heading" hidden>
<div><strong id="search-release-heading">Plan selected issues into a release</strong>
@@ -820,6 +911,7 @@
<button id="claim-search-result" type="button" hidden>Assign to me</button>
<button id="defer-search-result" type="button" hidden>Assign &amp; defer</button>
<button id="queue-search-result" type="button" hidden>Assign &amp; add to Today</button>
<button id="plan-search-result" type="button" hidden>Plan ahead</button>
<button id="start-search-result" type="button" hidden>Assign &amp; start</button>
</div>
@@ -829,6 +921,23 @@
</section>
</div>
<section class="search-week-plan-sheet" id="search-week-plan-sheet" role="dialog" aria-modal="true"
aria-labelledby="search-week-plan-title" hidden>
<div class="search-week-plan-panel">
<header>
<div><div class="small">Week Ahead</div><h2 id="search-week-plan-title">Plan this issue</h2></div>
<button id="cancel-search-week-plan" type="button">Cancel</button>
</header>
<p id="search-week-plan-copy" class="muted"></p>
<fieldset><legend>Choose a day</legend><div class="search-week-plan-days" id="search-week-plan-days"></div></fieldset>
<label class="search-week-plan-estimate" for="search-week-plan-estimate">Estimate in minutes
<input id="search-week-plan-estimate" type="number" inputmode="numeric" min="1" max="1440" step="5" required />
</label>
<p id="search-week-plan-status" class="small" aria-live="polite"></p>
<button id="confirm-search-week-plan" type="button">Plan</button>
</div>
</section>
<div id="whiteboard-modal">
<div class="modal">
<div class="modal-actions">
@@ -1713,10 +1822,25 @@
<button class="mobile-today-blocked" data-mobile-today-blocked type="button" hidden>Report blocker</button>
<button data-today-break-open type="button">Take break</button>
<button data-work-session-adjust-plan type="button" hidden>Adjust remaining plan</button>
<button data-work-session-reschedule-week type="button">Reschedule to Week Ahead</button>
<button data-mobile-today-end type="button">End session</button>
</div>
</section>
</dialog>
<dialog class="today-week-reschedule" id="today-week-reschedule" aria-labelledby="today-week-reschedule-title">
<section class="today-week-reschedule-panel">
<header>
<div><p class="small muted">Active Today item</p><h2 id="today-week-reschedule-title">Reschedule to Week Ahead</h2></div>
<button id="cancel-today-week-reschedule" type="button">Cancel</button>
</header>
<p class="small">Choose a future day after reviewing its current planned load. Today will continue with the next ready item.</p>
<div class="today-week-reschedule-days" id="today-week-reschedule-days" role="radiogroup" aria-label="Week Ahead destination"></div>
<label for="today-week-reschedule-estimate">Estimate in minutes</label>
<input id="today-week-reschedule-estimate" type="number" inputmode="numeric" min="5" max="1440" step="5" required />
<p id="today-week-reschedule-status" class="small" role="status" aria-live="assertive"></p>
<button id="confirm-today-week-reschedule" type="button" disabled>Move to Week Ahead &amp; continue</button>
</section>
</dialog>
<dialog class="today-progress-sheet" id="today-progress-sheet" aria-labelledby="today-progress-title">
<section class="today-progress-panel">
<header><div><p class="small muted">Active Today item</p><h2 id="today-progress-title">Add progress update</h2></div><button id="cancel-today-progress" type="button">Cancel</button></header>
@@ -1954,7 +2078,11 @@
<script src="static/plan-today-readiness.js"></script>
<script src="static/plan-today-preview.js"></script>
<script src="static/tomorrow-plan.js"></script>
<script src="static/week-calendar.js"></script>
<script src="static/week-calendar-import.js"></script>
<script src="static/week-plan.js"></script>
<script src="static/today-week-reschedule.js"></script>
<script src="static/search-week-plan.js"></script>
<script src="static/today-sync.js"></script>
<script src="static/today-rollover.js"></script>
<script src="static/update-ownership.js"></script>
+1
View File
@@ -572,6 +572,7 @@ function createIssueSheet({ fetchJson, storage, renderMarkdown = globalThis.rend
headers: { Accept: 'application/json' },
}).then(result => {
if (result?.state !== 'closed') throw new Error('Issue closure was not confirmed.');
globalThis.dispatchEvent?.(new CustomEvent('stackchain:issue-closed',{detail:item}));
return result;
}).finally(() => { closeRequest = null; });
return closeRequest;
+171 -2
View File
@@ -64,10 +64,100 @@
return { identity, eligible, start, cancel, toggle, snapshot, prepare, releaseRepository, limit:maximum };
}
function createWeekBatchPlan({
week,
prepare = item => Promise.resolve(item),
accept = item => item,
identity = item => String(item?.repository || '') + '#' + String(item?.number || ''),
maxItems = 5,
onProgress = () => {},
} = {}) {
let running = null;
const load = async () => {
await week.load();
return week.dates().map(day => ({ ...day, ...week.day(day.date) }));
};
function validate(items, assignments, days, confirmOverload = false) {
const allowed = new Set(days.map(day => day.date));
const errors = [];
const simulated = new Map(days.map(day => [day.date, {
ids:[...(day.ids || [])], estimates:{...(day.estimates || {})},
capacity_minutes:Number(day.capacity_minutes) || 0,
}]));
items.forEach(item => {
const id = identity(item), choice = assignments?.[id] || {};
const estimate = Number(choice.estimate);
if (!allowed.has(choice.date)) errors.push({ id, reason:'date-required' });
if (!Number.isFinite(estimate) || estimate <= 0) errors.push({ id, reason:'estimate-required' });
if (!allowed.has(choice.date) || !Number.isFinite(estimate) || estimate <= 0) return;
simulated.forEach((day, date) => {
if (day.ids.includes(id) && choice.date !== date) {
day.ids = day.ids.filter(value => value !== id); delete day.estimates[id];
}
});
const destination = simulated.get(choice.date);
if (!destination.ids.includes(id) && destination.ids.length >= maxItems) {
errors.push({ id, reason:'day-full', date:choice.date, limit:maxItems }); return;
}
if (!destination.ids.includes(id)) destination.ids.push(id);
destination.estimates[id] = estimate;
});
const overloads = [];
simulated.forEach((day, date) => {
const planned = day.ids.reduce((sum, id) => sum + (Number(day.estimates[id]) || 0), 0);
if (day.capacity_minutes > 0 && planned > day.capacity_minutes) {
overloads.push({ date, planned_minutes:planned, capacity_minutes:day.capacity_minutes });
}
});
if (errors.length) return { status:'invalid', errors, overloads:[] };
if (overloads.length && !confirmOverload) return { status:'overload-confirmation-required', errors:[], overloads };
return { status:'ready', errors:[], overloads };
}
async function preview(items) {
const days = await load();
return { days, placements:Object.fromEntries(items.map(item => [identity(item), week.placement(identity(item))])) };
}
function run(items, assignments, { confirmOverload = false } = {}) {
if (running) return running;
running = (async () => {
const selected = Array.isArray(items) ? items.slice() : [];
const days = await load();
const checked = validate(selected, assignments, days, confirmOverload);
if (checked.status !== 'ready') return checked;
const failed = [], planned = [];
for (let index = 0; index < selected.length; index += 1) {
const source = selected[index], originalId = identity(source), choice = assignments[originalId];
try {
const confirmed = accept(await prepare(source)) || source;
const id = identity(confirmed);
const existing = week.placement(id);
if (!week.place(id, choice.date, Number(choice.estimate), {move:Boolean(existing && existing.date !== choice.date)})) {
failed.push({id:originalId, reason:'assigned-not-planned'});
} else {
week.rememberPendingItem?.(id, confirmed);
planned.push(id);
}
} catch (error) {
failed.push({id:originalId, reason:error?.message || 'assignment failed'});
}
onProgress({status:'running',processed:index + 1,selected:selected.length});
}
if (planned.length) {
try { await week.flush(); }
catch (_error) { return {status:'planned-pending',planned:planned.length,failed}; }
}
return {status:failed.length?'partial':'planned',planned:planned.length,failed};
})().finally(() => { running = null; });
return running;
}
return { preview, validate, run, pending:() => Boolean(running) };
}
createSearchBatchPlan.createWeekBatchPlan = createWeekBatchPlan;
createSearchBatchPlan.mount = function mountSearchBatchPlanning(
document, batchFactory, todayWork, getOwner, fetchJson, previewPath, queueToday,
todaySync, acceptIssue, lookup, render, escapeHtml, escapeAttribute,
laterWork = null, laterPicker = null
laterWork = null, laterPicker = null, weekPlan = null, storage = null
) {
const get = selector => document.querySelector(selector);
let processor;
@@ -87,6 +177,7 @@
get('#queue-selected-search-results').disabled = state.count === 0;
get('#defer-selected-search-results').disabled = state.count === 0;
get('#plan-selected-search-results').disabled = state.count === 0;
if (get('#week-selected-search-results')) get('#week-selected-search-results').disabled = state.count === 0;
get('#search-selection-status').textContent = state.count ?
state.count + ' issue' + (state.count === 1 ? '' : 's') + ' selected.' : 'No issues selected.';
render();
@@ -194,6 +285,81 @@
}
},
});
const weekProcessor = weekPlan ? createWeekBatchPlan({
week:weekPlan,prepare:item=>plan.prepare(item),accept:acceptIssue,
identity:item=>todayWork.identity(item),
onProgress:progress=>{
if (progress.status === 'running') get('#search-week-batch-summary').textContent =
'Planning ' + progress.processed + ' of ' + progress.selected + '…';
},
storage,
}) : null;
let weekOverload = false;
function weekAssignments() {
const values = {};
document.querySelectorAll('[data-search-week-batch-date]').forEach(select => {
const id = select.dataset.searchWeekBatchDate;
const estimate = document.querySelector('[data-search-week-batch-estimate="' + id + '"]');
values[id] = {date:select.value,estimate:Number(estimate?.value)};
});
return values;
}
function closeWeekReview() {
if (!get('#search-week-batch-review')) return;
get('#search-week-batch-review').hidden = true;
get('#search-batch-actions').hidden = !plan.snapshot().active;
weekOverload = false;
get('#confirm-search-week-batch').textContent = 'Assign & plan';
}
async function openWeekReview() {
const items = plan.snapshot().items;
if (!weekProcessor || !items.length) return;
const button = get('#week-selected-search-results');
button.disabled = true;
get('#search-selection-status').textContent = 'Loading Week Ahead…';
try {
const preview = await weekProcessor.preview(items);
const options = selected => preview.days.map(day => '<option value="' + escapeAttribute(day.date) + '"' +
(day.date === selected ? ' selected' : '') + '>' + escapeHtml(day.label + ' · ' + (day.ids || []).length + ' planned') + '</option>').join('');
get('#search-week-batch-list').innerHTML = items.map(item => {
const id = todayWork.identity(item), existing = preview.placements[id];
return '<div class="search-week-batch-row"><div><span class="small">' + escapeHtml(id) + '</span><strong>' +
escapeHtml(item.title || 'Untitled work') + '</strong></div><div class="search-week-batch-row-controls"><label>Day<select data-search-week-batch-date="' +
escapeAttribute(id) + '">' + options(existing?.date || preview.days[0]?.date) + '</select></label><label>Minutes<input type="number" inputmode="numeric" min="5" max="1440" step="5" value="' +
escapeAttribute(existing?.estimate || '') + '" data-search-week-batch-estimate="' + escapeAttribute(id) +
'" aria-label="Estimate for ' + escapeAttribute(item.title || id) + ' in minutes"></label></div></div>';
}).join('');
get('#search-week-batch-summary').textContent = items.length + ' selected · review every day and estimate before assignment.';
get('#search-batch-actions').hidden = true;
get('#search-week-batch-review').hidden = false;
document.querySelector('[data-search-week-batch-date]')?.focus();
} catch (error) {
get('#search-selection-status').textContent = error?.message || 'Week Ahead is unavailable. Retry when connected.';
} finally { button.disabled = false; }
}
async function confirmWeekReview() {
if (!weekProcessor || weekProcessor.pending()) return;
const button = get('#confirm-search-week-batch');
button.disabled = true;
const outcome = await weekProcessor.run(plan.snapshot().items, weekAssignments(), {confirmOverload:weekOverload});
if (outcome.status === 'invalid') {
const reasons = [...new Set(outcome.errors.map(error => error.reason))];
get('#search-week-batch-summary').textContent = reasons.includes('day-full') ?
'A day already has five items. Choose another day.' : 'Choose a valid day and estimate for every issue.';
} else if (outcome.status === 'overload-confirmation-required') {
weekOverload = true;
button.textContent = 'Confirm over capacity';
get('#search-week-batch-summary').textContent = outcome.overloads.map(day =>
day.planned_minutes + ' of ' + day.capacity_minutes + ' min on ' + day.date).join(' · ') + '. Confirm to plan anyway.';
} else {
const pending = outcome.status === 'planned-pending';
get('#cmd-search-action-status').textContent = outcome.planned + ' planned' +
(pending ? ' · sync pending' : '') + (outcome.failed.length ? ' · ' + outcome.failed.length + ' need attention.' : '.');
closeWeekReview();
if (!outcome.failed.length) plan.cancel();
}
button.disabled = false;
}
function estimateValues() {
return Object.fromEntries(Array.from(document.querySelectorAll('[data-search-batch-estimate]')).map(input =>
[input.dataset.searchBatchEstimate, Number(input.value)]
@@ -274,6 +440,9 @@
) }, event.currentTarget, 'search-batch');
});
get('#plan-selected-search-results').addEventListener('click', openReleaseReview);
get('#week-selected-search-results')?.addEventListener('click', openWeekReview);
get('#cancel-search-week-batch')?.addEventListener('click', closeWeekReview);
get('#confirm-search-week-batch')?.addEventListener('click', confirmWeekReview);
get('#cancel-search-release').addEventListener('click', closeReleaseReview);
get('#confirm-search-release').addEventListener('click', () => {
const milestoneSelect = get('#search-release-milestone');
@@ -322,7 +491,7 @@
escapeHtml(result.repository) + ' #' + escapeHtml(result.number) + ' · ' +
(allowed ? 'Open issue' : 'Not eligible') + '</span></label>';
}
return { plan, processor, laterProcessor, releaseProcessor, restore, resultHtml };
return { plan, processor, laterProcessor, releaseProcessor, weekProcessor, restore, resultHtml };
};
return createSearchBatchPlan;
+116
View File
@@ -0,0 +1,116 @@
function createSearchWeekPlan({week,claim,accept=item=>item,identity,maxItems=5}={}) {
let running=null;
const eligible=detail=>Boolean(detail&&detail.kind==='issue'&&detail.state==='open'&&
(detail.claimable||detail.assigned_to_me));
const loadDay=date=>{
const value=week.day(date),estimates=value.estimates||{};
return {...value,planned_minutes:(value.ids||[]).reduce((total,id)=>total+(Number(estimates[id])||0),0)};
};
async function preview(detail) {
if(!eligible(detail))return {eligible:false,days:[]};
await week.load();
const id=identity(detail),existing=week.placement(id);
return {eligible:true,existing,days:week.dates().map(item=>({...item,...loadDay(item.date)}))};
}
function plan(detail,options={}) {
if(running)return running;
const perform=async()=>{
if(!eligible(detail))return {status:'ineligible'};
const estimate=Number(options.estimate);
if(!Number.isFinite(estimate)||estimate<=0)return {status:'estimate-required'};
await week.load();
if(!week.dates().some(item=>item.date===options.date))return {status:'date-required'};
const originalId=identity(detail),existing=week.placement(originalId);
if(existing&&existing.date!==options.date&&!options.move)
return {status:'already-planned',date:existing.date,estimate:existing.estimate};
const destination=loadDay(options.date);
const alreadyThere=(destination.ids||[]).includes(originalId);
if(!alreadyThere&&(destination.ids||[]).length>=maxItems)return {status:'day-full',limit:maxItems};
const previous=alreadyThere?(Number(destination.estimates?.[originalId])||0):0;
const plannedMinutes=destination.planned_minutes-previous+estimate;
if(Number(destination.capacity_minutes)>0&&plannedMinutes>Number(destination.capacity_minutes)&&!options.confirmOverload)
return {status:'overload-confirmation-required',planned_minutes:plannedMinutes,
capacity_minutes:Number(destination.capacity_minutes)};
let item=detail,assigned=false;
if(detail.claimable){item=await claim(detail);assigned=true;}
item=accept(item)||item;
const id=identity(item);
if(!week.place(id,options.date,estimate,{move:Boolean(options.move)}))
return {status:assigned?'assigned-not-planned':'not-planned',item};
week.rememberPendingItem?.(id,item);
try {
await week.flush();
return {status:'planned',date:options.date,estimate,item};
} catch(_error) {
return {status:'planned-pending',date:options.date,estimate};
}
};
running=perform().finally(()=>{running=null;});
return running;
}
return {eligible,preview,plan,pending:()=>Boolean(running)};
}
function createSearchWeekPlanUI({planner,document,window,getDetail,onPlanned=()=>{},announce=()=>{},escapeHtml,escapeAttribute}={}) {
const qs=selector=>document.querySelector(selector);
let trigger=null,detail=null,preview=null,overload=false;
function close(navigate=false) {
if(navigate&&window.history.state?.searchWeekPlan){window.history.back();return;}
qs('#search-week-plan-sheet').hidden=true;
detail=null;preview=null;overload=false;trigger?.focus?.();trigger=null;
}
function selectDate(date) {
qs('#search-week-plan-days').querySelectorAll('[data-search-week-date]').forEach(button=>
button.setAttribute('aria-pressed',String(button.dataset.searchWeekDate===date)));
qs('#search-week-plan-days').dataset.selected=date;
overload=false;qs('#confirm-search-week-plan').textContent='Plan';
}
async function open(button) {
const selected=getDetail();
if(!selected||planner.pending())return false;
trigger=button;detail=selected;overload=false;
const sheet=qs('#search-week-plan-sheet'),status=qs('#search-week-plan-status');
sheet.hidden=false;status.textContent='Loading Week Ahead…';qs('#confirm-search-week-plan').disabled=true;
window.history.pushState({...window.history.state,searchWeekPlan:true},'',window.location.href);
qs('#search-week-plan-copy').textContent=detail.title||'Untitled issue';
try {
preview=await planner.preview(detail);
const existing=preview.existing;
qs('#search-week-plan-days').innerHTML=preview.days.map((day,index)=>
'<button type="button" data-search-week-date="'+escapeAttribute(day.date)+'" aria-pressed="'+String(index===0)+'"><strong>'+escapeHtml(day.label)+
'</strong><small>'+escapeHtml(day.planned_minutes+(day.capacity_minutes?' of '+day.capacity_minutes:'')+' min · '+day.ids.length+' planned')+'</small></button>').join('');
qs('#search-week-plan-days').querySelectorAll('[data-search-week-date]').forEach(dayButton=>
dayButton.addEventListener('click',()=>selectDate(dayButton.dataset.searchWeekDate)));
selectDate(existing?.date||preview.days[0].date);
qs('#search-week-plan-estimate').value=existing?.estimate||'';
status.textContent=existing?'Already planned for '+existing.date+'. Choose another day to move it.':'Choose a day and add an estimate.';
qs('#confirm-search-week-plan').disabled=false;qs('#search-week-plan-estimate').focus();return true;
} catch(error) {status.textContent=(error.message||'Week Ahead is unavailable.')+' Retry when connected.';return false;}
}
async function confirm() {
if(!detail||planner.pending())return;
const date=qs('#search-week-plan-days').dataset.selected,estimate=Number(qs('#search-week-plan-estimate').value);
const existing=preview?.existing,move=Boolean(existing&&existing.date!==date);
const button=qs('#confirm-search-week-plan'),status=qs('#search-week-plan-status');button.disabled=true;
const outcome=await planner.plan(detail,{date,estimate,move,confirmOverload:overload});
if(outcome.status==='overload-confirmation-required'){
overload=true;button.textContent='Confirm over capacity';
status.textContent=outcome.planned_minutes+' min exceeds '+outcome.capacity_minutes+' min capacity. Confirm to plan anyway.';
} else if(outcome.status==='estimate-required')status.textContent='Enter an estimate in minutes.';
else if(outcome.status==='day-full')status.textContent='That day already has '+outcome.limit+' items. Choose another day.';
else if(outcome.status==='already-planned')status.textContent='Already planned for '+outcome.date+'. Choose Move to change the day.';
else if(outcome.status==='assigned-not-planned')status.textContent='Assigned, not planned. Find it in My Work and retry.';
else if(outcome.status==='planned-pending'){announce('Planned for '+date+' · sync pending.');onPlanned(detail,true);close(true);}
else if(outcome.status==='planned'){announce('Planned for '+date+'.');onPlanned(detail,false);close(true);}
else status.textContent='Could not plan this issue. Retry.';
button.disabled=false;
}
qs('#plan-search-result').addEventListener('click',event=>open(event.currentTarget));
qs('#cancel-search-week-plan').addEventListener('click',()=>close(true));
qs('#confirm-search-week-plan').addEventListener('click',confirm);
window.addEventListener('popstate',()=>{if(!qs('#search-week-plan-sheet').hidden)close();});
document.addEventListener('keydown',event=>{
if(event.key==='Escape'&&!qs('#search-week-plan-sheet').hidden){event.preventDefault();close(true);}
});
return {open,close,confirm};
}
if(typeof module!=='undefined'&&module.exports){module.exports=createSearchWeekPlan;module.exports.UI=createSearchWeekPlanUI;}
+5 -1
View File
@@ -1,7 +1,7 @@
const BASE = new URL('./', self.location.href).pathname;
importScripts(BASE + 'static/private-data-registry.js');
importScripts(BASE + 'static/background-issue-sync.js');
const CACHE = 'stackchain-dashboard-shell-v126';
const CACHE = 'stackchain-dashboard-shell-v130';
const OFFLINE_LEASE_URL = new URL(BASE + '__offline-session-lease', self.location.origin).href;
const OUTAGE_STATUSES = new Set([500, 502, 503, 504]);
const NAVIGATION_TIMEOUT_MS = self.__STACKCHAIN_NAVIGATION_TIMEOUT_MS || 4000;
@@ -124,7 +124,11 @@ const SHELL = [
BASE + 'static/plan-today-readiness.js',
BASE + 'static/plan-today-preview.js',
BASE + 'static/tomorrow-plan.js',
BASE + 'static/week-calendar.js',
BASE + 'static/week-calendar-import.js',
BASE + 'static/week-plan.js',
BASE + 'static/today-week-reschedule.js',
BASE + 'static/search-week-plan.js',
BASE + 'static/today-sync.js',
BASE + 'static/today-rollover.js',
BASE + 'static/update-ownership.js',
+7 -1
View File
@@ -4,7 +4,13 @@ function createTodayRollover(options = {}) {
Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC');
function timeZone() {
return options.timeZone?.() || resolvedTimeZone();
const candidate = options.timeZone?.() || resolvedTimeZone();
try {
new Intl.DateTimeFormat('en', { timeZone: candidate }).format(now());
return candidate;
} catch (_error) {
return 'UTC';
}
}
function localDate() {
+4
View File
@@ -542,6 +542,10 @@ function createTodayTimerView({ timer, isActive, queryAll, formatEstimate, getRu
},
finishCapture() { return captureView.finish(); },
transferCapture() { return captureView.transfer(); },
restore(recovery) {
render();
return Promise.resolve(recovery).catch(() => false).then(() => { render(); return !!timer.breakSnapshot?.(); });
},
render,
};
queryAll('#new-issue').forEach(button => button.addEventListener('click', () => {
+329
View File
@@ -0,0 +1,329 @@
function createTodayWeekReschedule({
week,
api,
getToday,
adoptToday = () => {},
operationId = () => globalThis.crypto?.randomUUID?.() || String(Date.now()),
storage = null,
getLogin = () => '',
now = () => Date.now(),
} = {}) {
let current = null;
let flushing = null;
const storagePrefix = 'stackchain.today-week-reschedule.v1.';
function storageKey() {
const login = String(getLogin?.() || '').trim().toLowerCase();
return login ? storagePrefix + encodeURIComponent(login) : '';
}
function validRecord(value) {
return typeof value?.body?.operation_id === 'string' &&
Array.isArray(value?.today?.ids) && Array.isArray(value?.week?.days);
}
function readQueue() {
const key = storageKey();
if (!key || !storage) return [];
try {
const value = JSON.parse(storage.getItem(key) || 'null');
if (Array.isArray(value?.records)) return value.records.filter(validRecord);
return validRecord(value) ? [value] : [];
} catch (_error) { return []; }
}
function saveQueue(records) {
const key = storageKey();
if (!key || !storage) return false;
try {
if (!records.length) storage.removeItem(key);
else storage.setItem(key, JSON.stringify({version:2, records}));
return true;
}
catch (_error) { return false; }
}
function persist(record) { return saveQueue([...readQueue(), record]); }
function pending() {
const key = storageKey();
if (!key || !storage) return null;
return readQueue()[0] || null;
}
function resume() {
const records = readQueue();
const record = records[records.length - 1];
if (!record) return null;
adoptToday(record.today);
week.adopt(record.week);
return {...record, sync_pending:true, pending_count:records.length};
}
async function restoreConflict(error) {
if (error?.status !== 409) throw error;
const [today, weekState] = await Promise.all([api('api/v1/today'), api('api/v1/week')]);
adoptToday(today);
week.adopt(weekState);
const conflict = new Error('Plans changed on another device. Review and retry this saved move.');
conflict.status = 409;
throw conflict;
}
function flush() {
if (flushing) return flushing;
if (!pending()) return Promise.resolve(false);
flushing = (async () => {
let result = null;
while (true) {
const records = readQueue();
const record = records[0];
if (!record) return result ? {...result, sync_pending:false, pending_count:0} : false;
try {
result = await api('api/v1/week/reschedule', {
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(record.body),
});
} catch (error) { await restoreConflict(error); }
adoptToday(result.today);
week.adopt(result.week);
const latest = readQueue();
if (latest[0]?.body?.operation_id !== record.body.operation_id) continue;
const remaining = latest.slice(1).map((entry, index) => index ? entry : ({
...entry,
body:{...entry.body, today_revision:result.today.revision, week_revision:result.week.revision},
}));
if (!saveQueue(remaining)) throw new Error('Move synced, but its local queue could not be updated.');
}
})().finally(() => { flushing = null; });
return flushing;
}
function optimisticSnapshots(planDate, estimate) {
const today = {
...current.today,
ids: current.today.ids.filter(id => id !== current.identity),
estimates: {...(current.today.estimates || {})},
};
delete today.estimates[current.identity];
const days = (current.week.days || []).map(day => {
const estimates = {...(day.estimates || {})}; delete estimates[current.identity];
return {...day, ids:(day.ids || []).filter(id => id !== current.identity), estimates};
});
let destination = days.find(day => day.plan_date === planDate);
if (!destination) {
destination = {plan_date:planDate, ids:[], capacity_minutes:null, estimates:{}};
days.push(destination);
}
destination.ids.push(current.identity);
destination.estimates[current.identity] = estimate;
return {today, week:{revision:current.week_revision, timezone:current.week.timezone || null, days}};
}
async function open(identity) {
let today;
const queued = readQueue().length;
let offline = Boolean(queued);
if (queued) {
today = getToday?.();
} else {
try { today = await api('api/v1/today'); }
catch (error) {
if (error?.status === 401 || error?.status === 403) throw error;
today = getToday?.(); offline = true;
}
}
if (!identity || !today?.ids?.includes(identity)) {
throw new Error('The active Today item changed. Reopen rescheduling.');
}
const loaded = queued ? week.state?.() : await week.load();
if (!loaded) throw new Error('Reload Today before rescheduling another saved move.');
if (loaded?.sync_pending) {
throw new Error('Reconnect before rescheduling Today into Week Ahead.');
}
offline = offline || Boolean(loaded?.offline_snapshot);
const estimate = Number(today.estimates?.[identity]);
const estimateMinutes = Number.isFinite(estimate) && estimate > 0 ? estimate : null;
const days = week.review().days.map(day => {
const ids = (day.ids || []).filter(id => id !== identity);
const planned = Number(day.planned_minutes) || 0;
const existing = Number(day.estimates?.[identity]) || 0;
return {
...day,
ids,
planned_minutes: Math.max(0, planned - existing),
load: `${Math.max(0, planned - existing)} / ${Number(day.capacity_minutes) || 0} min`,
eligible: ids.length < 5,
};
});
current = {
identity,
today_revision: today.revision,
week_revision: loaded.revision,
operation_id: operationId(),
estimate_minutes: estimateMinutes,
days,
today,
week: loaded,
offline,
};
return {...current, days:days.map(day => ({...day, ids:[...day.ids]}))};
}
async function confirm(planDate, estimateMinutes, {allowOverload = false} = {}) {
if (!current) throw new Error('Open rescheduling before choosing a day.');
const day = current.days.find(value => value.plan_date === planDate);
if (!day) throw new Error('Choose one of the next seven days.');
const estimate = Number(estimateMinutes);
if (!Number.isFinite(estimate) || estimate < 5 || estimate > 1440) {
throw new Error('Estimate must be between 5 and 1440 minutes.');
}
if (!day.eligible) throw new Error('That Week Ahead day already has five items.');
const capacity = Number(day.capacity_minutes) || 0;
if (capacity && day.planned_minutes + estimate > capacity && !allowOverload) {
throw new Error("That move exceeds the day's capacity. Confirm overload before rescheduling.");
}
const body = {
operation_id:current.operation_id,
identity:current.identity,
estimate_minutes:estimate,
plan_date:planDate,
today_revision:current.today_revision,
week_revision:current.week_revision,
allow_over_capacity:allowOverload,
};
const optimistic = optimisticSnapshots(planDate, estimate);
const durable = Boolean(storageKey() && storage);
const admitted = durable && persist({body, ...optimistic, queued_at:now()});
if (durable && !admitted) {
throw new Error('Could not save this move on this device. Nothing changed.');
}
if (admitted) {
adoptToday(optimistic.today);
week.adopt(optimistic.week);
}
if (current.offline) {
current = null;
return {...optimistic, sync_pending:true, pending_count:readQueue().length};
}
let result;
try {
result = admitted ? await flush() : await api('api/v1/week/reschedule', {
method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(body),
});
} catch(error) {
if (admitted && error?.status === 409) await restoreConflict(error);
if (admitted && error?.status !== 401 && error?.status !== 403) {
current = null;
return {...optimistic, sync_pending:true};
}
throw error;
}
adoptToday(result.today);
week.adopt(result.week);
current = null;
return result;
}
function cancel() { current = null; }
return {open, confirm, cancel, state:() => current, pending, resume, flush};
}
function mountTodayWeekReschedule({
qs, document=globalThis.document, window=globalThis.window, week, api, getToday, adoptToday, currentTarget, closeActions,
refresh, warm, continueToday, announce, storage=null, getLogin=()=>'', schedule=callback=>requestAnimationFrame(callback),
}={}) {
const dialog=qs('#today-week-reschedule'),daysRoot=qs('#today-week-reschedule-days');
const estimate=qs('#today-week-reschedule-estimate'),status=qs('#today-week-reschedule-status');
const confirm=qs('#confirm-today-week-reschedule'),launcher=qs('[data-work-session-reschedule-week]');
let selectedDate=null,allowOverload=false;
const controller=createTodayWeekReschedule({week,api,getToday,adoptToday,storage,getLogin});
async function flushPending() {
if(!controller.pending())return false;
try {
const result=await controller.flush();
announce('Today-to-Week move synced to your account.');
await refresh();warm();
return result;
} catch(error) {
announce(`${error.message||'Sync unavailable.'} Move saved on this device · sync pending.`);
return false;
}
}
function resumePending() {
const restored=controller.resume();
if(!restored)return false;
announce('Today-to-Week move saved on this device · sync pending.');
flushPending();
return restored;
}
window?.addEventListener('online', flushPending);
document?.addEventListener('visibilitychange',()=>document.hidden?false:flushPending());
let restoreAttempts=0;
function restoreWhenOwned(){
if(resumePending()||getLogin()||restoreAttempts++>=20)return;
window?.setTimeout(restoreWhenOwned,250);
}
restoreWhenOwned();
function close() {
controller.cancel();selectedDate=null;allowOverload=false;
if(dialog.open)dialog.close();schedule(()=>{
qs('[data-mobile-today-more]').click();launcher.focus();
});
}
function render(opened) {
daysRoot.replaceChildren(...opened.days.map(day=>{
const button=document.createElement('button');
button.type='button';button.dataset.planDate=day.plan_date;button.setAttribute('role','radio');
button.setAttribute('aria-checked','false');button.disabled=!day.eligible;
const label=document.createElement('strong');label.textContent=day.label;
const load=document.createElement('span');load.className='small';
load.textContent=day.eligible?day.load:'5 items · full';button.append(label,load);
button.addEventListener('click',()=>{
selectedDate=day.plan_date;allowOverload=false;
daysRoot.querySelectorAll('button').forEach(choice=>choice.setAttribute(
'aria-checked',String(choice===button)
));
status.textContent='';confirm.disabled=false;confirm.textContent='Move to Week Ahead & continue';
});
return button;
}));
}
launcher.addEventListener('click',async()=>{
const target=currentTarget();
if(!target){announce('Start or resume a checkpointed Today item before rescheduling.');return;}
closeActions();status.textContent='Loading Week Ahead…';confirm.disabled=true;dialog.showModal();
try{
const opened=await controller.open(target.identity);render(opened);
estimate.value=opened.estimate_minutes||'';
status.textContent=opened.estimate_minutes?'Choose a future day.':'Add an estimate, then choose a future day.';
schedule(()=>daysRoot.querySelector('button:not(:disabled)')?.focus());
}catch(error){status.textContent=error.message;}
});
qs('#cancel-today-week-reschedule').addEventListener('click',close);
dialog.addEventListener('cancel',event=>{event.preventDefault();close();});
confirm.addEventListener('click',async()=>{
if(!selectedDate)return;
confirm.disabled=true;status.textContent='Moving Today into Week Ahead…';
try{
const result=await controller.confirm(selectedDate,Number(estimate.value),{allowOverload});
dialog.close();
if(result.sync_pending){
announce('Moved locally. Saved on this device · sync pending.');warm();
}else{
await refresh();warm();announce('Moved to Week Ahead. Continuing Today.');
}
await continueToday();
}catch(error){
const overload=error.message.includes('Confirm overload');allowOverload=overload;
status.textContent=error.message;
confirm.textContent=overload?'Confirm overload & continue':'Move to Week Ahead & continue';
confirm.disabled=false;
}
});
return {controller,close,flushPending,resumePending};
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = createTodayWeekReschedule;
module.exports.mount = mountTodayWeekReschedule;
}
+263
View File
@@ -0,0 +1,263 @@
function createWeekCalendarImport() {
const maxBytes=1024*1024;
function clock(value) {
const match=/^(\d{2}):(\d{2})$/.exec(String(value||''));
if(!match)return null;
const minutes=Number(match[1])*60+Number(match[2]);
return Number(match[1])<24&&Number(match[2])<60?minutes:null;
}
function instant(value) {
const match=/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})(Z?)$/.exec(value||'');
if(!match)return null;
const parts=match.slice(1,7).map(Number);
const milliseconds=match[7]?Date.UTC(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]):
new Date(parts[0],parts[1]-1,parts[2],parts[3],parts[4],parts[5]).getTime();
return Number.isFinite(milliseconds)?milliseconds:null;
}
function zonedInstant(value,timeZone) {
if(!timeZone)return instant(value);
const match=/^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})$/.exec(value||'');
if(!match)return null;
try {
const wanted=match.slice(1).map(Number),formatter=new Intl.DateTimeFormat('en-CA',{
timeZone,year:'numeric',month:'2-digit',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit',hourCycle:'h23',
});
let result=Date.UTC(wanted[0],wanted[1]-1,wanted[2],wanted[3],wanted[4],wanted[5]);
for(let attempt=0;attempt<2;attempt+=1) {
const shown=Object.fromEntries(formatter.formatToParts(new Date(result)).map(part=>[part.type,part.value]));
const represented=Date.UTC(Number(shown.year),Number(shown.month)-1,Number(shown.day),Number(shown.hour),Number(shown.minute),Number(shown.second));
result+=Date.UTC(wanted[0],wanted[1]-1,wanted[2],wanted[3],wanted[4],wanted[5])-represented;
}
return result;
} catch(error) { return null; }
}
function supportedTimeZone(timeZone) {
if(!timeZone)return true;
try {new Intl.DateTimeFormat('en-US',{timeZone}).format(0);return true;}
catch(error) {return false;}
}
function zoneParts(value,timeZone) {
const date=new Date(value);
if(!timeZone)return {year:date.getFullYear(),month:date.getMonth()+1,day:date.getDate(),weekday:date.getDay(),
hour:date.getHours(),minute:date.getMinutes(),second:date.getSeconds()};
const formatter=new Intl.DateTimeFormat('en-US',{timeZone,year:'numeric',month:'2-digit',day:'2-digit',
hour:'2-digit',minute:'2-digit',second:'2-digit',weekday:'short',hourCycle:'h23'});
const parts=Object.fromEntries(formatter.formatToParts(date).map(part=>[part.type,part.value]));
return {year:Number(parts.year),month:Number(parts.month),day:Number(parts.day),
weekday:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].indexOf(parts.weekday),hour:Number(parts.hour),
minute:Number(parts.minute),second:Number(parts.second)};
}
function addCalendarDays(value,days,timeZone) {
if(!timeZone) {const date=new Date(value);date.setDate(date.getDate()+days);return date.getTime();}
const parts=zoneParts(value,timeZone),day=new Date(Date.UTC(parts.year,parts.month-1,parts.day+days));
const wall=[day.getUTCFullYear(),String(day.getUTCMonth()+1).padStart(2,'0'),String(day.getUTCDate()).padStart(2,'0')].join('')+
'T'+[parts.hour,parts.minute,parts.second].map(part=>String(part).padStart(2,'0')).join('');
return zonedInstant(wall,timeZone);
}
function dateInstant(value) {
const match=/^(\d{4})(\d{2})(\d{2})$/.exec(value||'');
return match?new Date(Number(match[1]),Number(match[2])-1,Number(match[3])).getTime():null;
}
function events(source) {
if(typeof source!=='string'||!source.includes('BEGIN:VCALENDAR'))throw new Error('Choose a valid .ics calendar file.');
if(new TextEncoder().encode(source).length>maxBytes)throw new Error('Calendar files must be 1 MB or smaller.');
const lines=source.replace(/\r\n[ \t]/g,'').split(/\r?\n/);
const result=[];let current=null;
lines.forEach(line=>{
if(line==='BEGIN:VEVENT'){current={};return;}
if(line==='END:VEVENT'){
if((current?.unsupportedTimezone||(current?.start!=null&&current?.end>current.start))&&
current.status!=='CANCELLED'&&current.transparency!=='TRANSPARENT')result.push(current);
current=null;return;
}
if(!current)return;
const separator=line.indexOf(':');if(separator<0)return;
const property=line.slice(0,separator),parts=property.split(';'),name=parts[0],value=line.slice(separator+1);
const parameters=Object.fromEntries(parts.slice(1).map(part=>part.split('=')));
if(parameters.TZID&&!supportedTimeZone(parameters.TZID))current.unsupportedTimezone=true;
const allDay=parameters.VALUE==='DATE',parsed=allDay?dateInstant(value):zonedInstant(value,parameters.TZID);
if(name==='DTSTART'){current.start=parsed;current.timeZone=parameters.TZID||null;}
if(name==='DTEND')current.end=parsed;
if(name==='RRULE')current.rule=value;
if(name==='RDATE')current.rdates=(current.rdates||[]).concat(value.split(',').map(item=>allDay?dateInstant(item):zonedInstant(item,parameters.TZID)).filter(value=>value!=null));
if(name==='EXDATE')current.exdates=(current.exdates||[]).concat(value.split(',').map(item=>allDay?dateInstant(item):zonedInstant(item,parameters.TZID)).filter(value=>value!=null));
if(name==='STATUS')current.status=value.toUpperCase();
if(name==='TRANSP')current.transparency=value.toUpperCase();
});
return result;
}
function recurrenceRule(value) {
return Object.fromEntries(String(value||'').split(';').filter(Boolean).map(part=>part.split('=')));
}
function supportedRecurrence(value) {
const rule=recurrenceRule(value),keys=Object.keys(rule);
if(!['DAILY','WEEKLY'].includes(rule.FREQ))return false;
const allowed=new Set(['FREQ','COUNT','INTERVAL','UNTIL',...(rule.FREQ==='WEEKLY'?['BYDAY']:[])]);
if(keys.some(key=>!allowed.has(key)))return false;
if(rule.COUNT&&(!/^\d+$/.test(rule.COUNT)||Number(rule.COUNT)<1))return false;
if(rule.INTERVAL&&(!/^\d+$/.test(rule.INTERVAL)||Number(rule.INTERVAL)<1))return false;
if(rule.COUNT&&rule.UNTIL)return false;
if(rule.UNTIL&&instant(rule.UNTIL)==null&&dateInstant(rule.UNTIL)==null)return false;
return !rule.BYDAY||rule.BYDAY.split(',').every(day=>/^(MO|TU|WE|TH|FR|SA|SU)$/.test(day));
}
function occurrences(event,rangeStart,rangeEnd) {
const duration=event.end-event.start,excluded=new Set(event.exdates||[]);
if(!event.rule) {
return [event.start,...(event.rdates||[])].filter((start,index,all)=>start<rangeEnd&&!excluded.has(start)&&all.indexOf(start)===index)
.map(start=>({start,end:start+duration}));
}
const rule=recurrenceRule(event.rule);
if(!['DAILY','WEEKLY'].includes(rule.FREQ))return [event];
const count=Math.max(1,Math.min(Number(rule.COUNT)||10000,10000));
const result=[];
const weekdays={SU:0,MO:1,TU:2,WE:3,TH:4,FR:5,SA:6};
const selected=new Set((rule.BYDAY||'').split(',').map(day=>weekdays[day]).filter(day=>day!=null));
if(rule.FREQ==='WEEKLY'&&!selected.size)selected.add(zoneParts(event.start,event.timeZone).weekday);
const interval=Math.max(1,Number(rule.INTERVAL)||1),origin=zoneParts(event.start,event.timeZone);
const until=rule.UNTIL?(rule.UNTIL.endsWith('Z')?instant(rule.UNTIL):
(zonedInstant(rule.UNTIL,event.timeZone)??dateInstant(rule.UNTIL))):null;
const originDay=Date.UTC(origin.year,origin.month-1,origin.day);
let start=event.start,matched=0;
if(rule.FREQ==='DAILY'&&start+duration<=rangeStart) {
const target=zoneParts(rangeStart-duration,event.timeZone);
const targetDay=Date.UTC(target.year,target.month-1,target.day);
const elapsed=Math.max(0,Math.floor((targetDay-originDay)/(24*60*60*1000)));
const jumps=Math.floor(elapsed/interval);
if(jumps) {start=addCalendarDays(start,jumps*interval,event.timeZone);matched=jumps;}
while(start+duration<=rangeStart&&matched<count) {start=addCalendarDays(start,interval,event.timeZone);matched+=1;}
}
if(rule.FREQ==='WEEKLY'&&start+duration<=rangeStart) {
const target=zoneParts(rangeStart-duration,event.timeZone);
const targetDay=Date.UTC(target.year,target.month-1,target.day);
const elapsed=Math.max(0,Math.floor((targetDay-originDay)/(24*60*60*1000)));
const cycleDays=7*interval,cycles=Math.floor(elapsed/cycleDays),offset=elapsed-cycles*cycleDays;
matched=cycles*selected.size;
start=addCalendarDays(event.start,cycles*cycleDays+(offset>=7?offset:0),event.timeZone);
while(start+duration<=rangeStart&&matched<count) {
const cursor=zoneParts(start,event.timeZone),cursorDay=Date.UTC(cursor.year,cursor.month-1,cursor.day);
const weeks=Math.floor((cursorDay-originDay)/(7*24*60*60*1000));
if(weeks%interval===0&&selected.has(cursor.weekday))matched+=1;
start=addCalendarDays(start,1,event.timeZone);
}
}
while(start<rangeEnd&&matched<count&&(until==null||start<=until)) {
const cursor=zoneParts(start,event.timeZone),cursorDay=Date.UTC(cursor.year,cursor.month-1,cursor.day);
const weeks=Math.floor((cursorDay-originDay)/(7*24*60*60*1000));
const matches=rule.FREQ==='DAILY'||(weeks%interval===0&&selected.has(cursor.weekday));
if(matches) {
matched+=1;
if(!excluded.has(start))result.push({start,end:start+duration});
}
start=addCalendarDays(start,rule.FREQ==='DAILY'?interval:1,event.timeZone);
}
(event.rdates||[]).forEach(extra=>{
if(extra<rangeEnd&&!excluded.has(extra)&&!result.some(item=>item.start===extra))result.push({start:extra,end:extra+duration});
});
return result;
}
function dayBoundary(date,minutes) {
const [year,month,day]=date.split('-').map(Number);
return new Date(year,month-1,day,Math.floor(minutes/60),minutes%60).getTime();
}
function localClock(value) {
const date=new Date(value);
return String(date.getHours()).padStart(2,'0')+':'+String(date.getMinutes()).padStart(2,'0');
}
function review(source,{dates,workdayStart='09:00',workdayEnd='17:00'}={}) {
if(!Array.isArray(dates)||dates.length!==7)throw new Error('Week Ahead must contain seven dates.');
const startMinute=clock(workdayStart),endMinute=clock(workdayEnd);
if(startMinute==null||endMinute==null||endMinute<=startMinute)throw new Error('Working hours must end after they start.');
const parsedEvents=events(source),rangeStart=dayBoundary(dates[0],0),rangeEnd=dayBoundary(dates[6],24*60);
const unsupportedRecurrence=parsedEvents.filter(event=>event.rule&&!supportedRecurrence(event.rule)&&
event.start<rangeEnd&&(event.end>rangeStart||event.rule)).length;
const unsupportedTimezone=parsedEvents.filter(event=>event.unsupportedTimezone).length;
const unsupported_count=unsupportedRecurrence+unsupportedTimezone;
const calendarEvents=parsedEvents.filter(event=>!event.unsupportedTimezone).flatMap(event=>occurrences(event,rangeStart,rangeEnd));
const days=dates.map(plan_date=>{
const start=dayBoundary(plan_date,startMinute),end=dayBoundary(plan_date,endMinute);
const ranges=calendarEvents.map(event=>[Math.max(start,event.start),Math.min(end,event.end)])
.filter(range=>range[1]>range[0]).sort((left,right)=>left[0]-right[0]);
const merged=[];
ranges.forEach(range=>{
const previous=merged[merged.length-1];
if(previous&&range[0]<=previous[1])previous[1]=Math.max(previous[1],range[1]);
else merged.push([...range]);
});
const busy_minutes=Math.round(merged.reduce((total,range)=>total+range[1]-range[0],0)/60000);
const free_windows=[];let cursor=start;
merged.forEach(range=>{
if(range[0]>cursor)free_windows.push({start_time:localClock(cursor),end_time:localClock(range[0])});
cursor=Math.max(cursor,range[1]);
});
if(cursor<end)free_windows.push({start_time:localClock(cursor),end_time:localClock(end)});
return {plan_date,busy_minutes,capacity_minutes:endMinute-startMinute-busy_minutes,free_windows};
});
days.unsupported_count=unsupported_count;
days.unsupported_timezone_count=unsupportedTimezone;
return days;
}
function createWorkflow({controller,qs,onApplied=()=>{}}={}) {
let reviewed=null,activeAvailability=null;
const root=()=>qs('#week-capacity-import');
function clear() {
reviewed=null;
qs('#week-capacity-file').value='';
qs('#week-capacity-review').hidden=true;
qs('#week-capacity-days').innerHTML='';
qs('#apply-week-capacities').disabled=false;
}
function open() {
clear();root().hidden=false;qs('#week-capacity-status').textContent='';
qs('#week-capacity-file').focus?.();return true;
}
function cancel() {clear();root().hidden=true;return true;}
function reviewSource(source) {
const display=controller.dates();
reviewed=review(source,{dates:display.map(item=>item.date),workdayStart:qs('#week-capacity-start').value,
workdayEnd:qs('#week-capacity-end').value});
qs('#week-capacity-days').innerHTML=reviewed.map((day,index)=>'<article class="week-capacity-day"><strong>'+
display[index].label+'</strong><span>'+day.capacity_minutes+' min available</span><small>'+day.busy_minutes+
' min busy during working hours</small></article>').join('');
qs('#week-capacity-review').hidden=false;
const unsupported=reviewed.unsupported_count||0;
qs('#apply-week-capacities').disabled=unsupported>0;
const kind=reviewed.unsupported_timezone_count?'calendar event':'recurring event';
qs('#week-capacity-status').textContent=unsupported?
unsupported+' '+kind+(unsupported===1?'':'s')+' could not be counted. Apply is unavailable; export a simpler seven-day calendar and try again.':
'Review seven capacity totals. Calendar details stay on this device.';
return reviewed.map(day=>({...day}));
}
async function apply() {
if(!reviewed||reviewed.unsupported_count||!controller.stageCapacities(reviewed.map(day=>({
plan_date:day.plan_date,capacity_minutes:day.capacity_minutes,
}))))return false;
qs('#apply-week-capacities').disabled=true;
try {await controller.flush();activeAvailability=reviewed.map(day=>({plan_date:day.plan_date,
free_windows:day.free_windows.map(window=>({...window}))}));cancel();onApplied();return true;}
finally {qs('#apply-week-capacities').disabled=false;}
}
qs('#week-capacity-file')?.addEventListener('change',async event=>{
const file=event.currentTarget.files?.[0];if(!file)return;
try {
if(file.size>maxBytes)throw new Error('Calendar files must be 1 MB or smaller.');
reviewSource(await file.text());
} catch(error) {clear();qs('#week-capacity-status').textContent=error.message||'Calendar could not be read.';}
});
qs('#cancel-week-capacity-import')?.addEventListener('click',cancel);
qs('#apply-week-capacities')?.addEventListener('click',()=>apply().catch(error=>{
qs('#week-capacity-status').textContent=(error.message||'Week Ahead sync is unavailable.')+' Capacities remain saved on this phone.';
}));
return {open,cancel,review:reviewSource,apply,state:()=>reviewed?reviewed.map(day=>({...day})):null,
availability:()=>activeAvailability?activeAvailability.map(day=>({plan_date:day.plan_date,
free_windows:day.free_windows.map(window=>({...window}))})):null};
}
function mount(controller,weekWorkflow,qs) {
const workflow=createWorkflow({controller,qs,onApplied:weekWorkflow.renderReview});
StackchainWeekCalendar.setAvailabilityProvider(workflow.availability);
qs('#open-week-capacity-import').addEventListener('click',workflow.open);
return workflow;
}
return {review,createWorkflow,mount};
}
const weekCalendarImport=createWeekCalendarImport();
if(typeof module!=='undefined'&&module.exports)module.exports=weekCalendarImport;
+130
View File
@@ -0,0 +1,130 @@
(function(root){
'use strict';
let availabilityProvider=()=>null;
function escapeText(value){
return String(value||'').replace(/\\/g,'\\\\').replace(/\r?\n/g,'\\n').replace(/,/g,'\\,').replace(/;/g,'\\;');
}
function compact(value){return String(value||'').replace(/[-:]/g,'');}
function addMinutes(value,minutes){
const [hours,mins]=String(value).split(':').map(Number),total=hours*60+mins+Number(minutes);
return String(Math.floor(total/60)%24).padStart(2,'0')+':'+String(total%60).padStart(2,'0');
}
function clockMinutes(value){const [hours,minutes]=String(value).split(':').map(Number);return hours*60+minutes;}
function stableId(value){return String(value||'work').replace(/[^a-z0-9]+/gi,'-').replace(/^-|-$/g,'').toLowerCase();}
function foldLine(line){
const encoder=new TextEncoder(),chunks=[];let chunk='',bytes=0,limit=75;
for(const character of String(line)){
const width=encoder.encode(character).length;
if(chunk&&bytes+width>limit){chunks.push(chunk);chunk=character;bytes=width;limit=74;}
else {chunk+=character;bytes+=width;}
}
chunks.push(chunk);return chunks.join('\r\n ');
}
function buildWeekSchedule(plan,startTimes,getItem,selected,availability){
const blocks=[],blockers=[],availableByDate=new Map((availability||[]).map(day=>[day.plan_date,day.free_windows||[]]));
(plan?.days||[]).slice().sort((a,b)=>a.plan_date.localeCompare(b.plan_date)).forEach(day=>{
let cursor=startTimes?.[day.plan_date]||'09:00';
(day.ids||[]).forEach(id=>{
if(selected&& !selected.has(id))return;
const minutes=Number(day.estimates?.[id]),item=getItem?.(id);
if(!item||!Number.isFinite(minutes)||minutes<=0)return;
const windows=availableByDate.get(day.plan_date);
if(windows){
const fit=windows.find(window=>{
const candidate=Math.max(clockMinutes(cursor),clockMinutes(window.start_time));
if(candidate+minutes>clockMinutes(window.end_time))return false;
cursor=addMinutes('00:00',candidate);return true;
});
if(!fit){blockers.push({id,title:item.title||'Untitled work',plan_date:day.plan_date,minutes});return;}
}
const end=addMinutes(cursor,minutes);
blocks.push({...item,id,plan_date:day.plan_date,start_time:cursor,end_time:end,minutes});
cursor=end;
});
});
return {blocks,blockers};
}
function buildWeekBlocks(plan,startTimes,getItem,selected,availability){
return buildWeekSchedule(plan,startTimes,getItem,selected,availability).blocks;
}
function serializeWeekCalendar(blocks,{timezone='UTC',revision=0,generatedAt}={}){
const stamp=generatedAt||new Date().toISOString().replace(/[-:]/g,'').replace(/\.\d{3}/,'');
const lines=['BEGIN:VCALENDAR','VERSION:2.0','PRODID:-//Stackchain//Week Ahead//EN','CALSCALE:GREGORIAN','METHOD:PUBLISH','X-WR-CALNAME:Stackchain Week Ahead',`X-WR-TIMEZONE:${timezone}`,'BEGIN:VTIMEZONE',`TZID:${timezone}`,'END:VTIMEZONE'];
(blocks||[]).forEach(block=>{
const day=compact(block.plan_date),reference=block.repository+(block.number!=null?' #'+block.number:'');
lines.push('BEGIN:VEVENT',`UID:week-${stableId(block.id)}@stackchain`,`SEQUENCE:${Math.max(0,Math.floor(Number(revision)||0))}`,`DTSTAMP:${stamp}`,
`DTSTART;TZID=${timezone}:${day}T${compact(block.start_time)}00`,`DTEND;TZID=${timezone}:${day}T${compact(block.end_time)}00`,
`SUMMARY:${escapeText(block.title||'Untitled work')}`,`DESCRIPTION:${escapeText(reference+' · Stackchain Week Ahead')}`,
`URL:${String(block.url||'')}`,'TRANSP:OPAQUE','END:VEVENT');
});
lines.push('END:VCALENDAR');return lines.map(foldLine).join('\r\n')+'\r\n';
}
async function deliverWeekCalendar({text,filename,navigator,document,urlApi,FileCtor}){
const file=new FileCtor([text],filename,{type:'text/calendar;charset=utf-8'});
const payload={files:[file],title:'Stackchain Week Ahead',text:'Timed Week Ahead calendar blocks'};
if(typeof navigator?.share==='function'&&typeof navigator?.canShare==='function'&&navigator.canShare(payload)){
await navigator.share(payload);return 'shared';
}
const href=urlApi.createObjectURL(file);
try{const anchor=document.createElement('a');anchor.href=href;anchor.download=filename;anchor.click();}
finally{urlApi.revokeObjectURL(href);}
return 'downloaded';
}
function mountWeekCalendarHandoff({qs,getItem,getAvailability=availabilityProvider,escapeHtml,escapeAttribute,onDone,windowObject=root,navigatorObject=root.navigator,
documentObject=root.document,urlApi=root.URL,FileCtor=root.File}={}){
const handoff=qs('#week-calendar-handoff'),review=qs('#week-review'),daysRoot=qs('#week-calendar-days');
let plan=null;
const selected=()=>new Set(Array.from(daysRoot.querySelectorAll('[data-week-calendar-item]')).filter(input=>input.checked).map(input=>input.value));
const starts=()=>Object.fromEntries(Array.from(daysRoot.querySelectorAll('[data-week-calendar-start]')).map(input=>[input.dataset.weekCalendarStart,input.value]));
const schedule=()=>buildWeekSchedule(plan,starts(),getItem,selected(),getAvailability?.());
const blocks=()=>schedule().blocks;
function update(){
const current=schedule(),byId=new Map(current.blocks.map(block=>[block.id,block])),blockedById=new Map(current.blockers.map(blocker=>[blocker.id,blocker]));
daysRoot.querySelectorAll('[data-week-calendar-preview]').forEach(node=>{
const id=node.dataset.weekCalendarPreview,block=byId.get(id),blocker=blockedById.get(id);
node.textContent=block?block.start_time+'–'+block.end_time+' · '+block.minutes+' min':
(blocker?'Does not fit imported free time':'Excluded from calendar');
});
qs('#share-week-calendar').disabled=!current.blocks.length||current.blockers.length>0;
if(current.blockers.length){
const blocker=current.blockers[0];
qs('#week-calendar-status').textContent=blocker.title+' does not fit free time on '+blocker.plan_date+'. Adjust the start, estimate, or calendar import.';
}else qs('#week-calendar-status').textContent=(getAvailability?.()?'Planning around imported busy time · ':'Manual timing · ')+
current.blocks.length+' calendar block'+(current.blocks.length===1?'':'s')+' selected.';
}
function close({back=false}={}){
handoff.hidden=true;
if(back){review.hidden=false;qs('#confirm-week-plan').focus?.();}
}
function open(value){
plan=value;review.hidden=true;handoff.hidden=false;
const labels=new Map((value.days||[]).map(day=>[day.plan_date,new Intl.DateTimeFormat('en',{weekday:'short',month:'short',day:'numeric',timeZone:'UTC'}).format(new Date(day.plan_date+'T12:00:00Z'))]));
daysRoot.innerHTML=(value.days||[]).filter(day=>day.ids?.length).map(day=>'<article class="week-calendar-day"><header><h3>'+escapeHtml(labels.get(day.plan_date)||day.plan_date)+
'</h3><label>Start <input type="time" value="09:00" data-week-calendar-start="'+escapeAttribute(day.plan_date)+'"></label></header>'+
day.ids.map(id=>{const item=getItem(id),reference=item?(item.repository+' #'+item.number):String(id).slice(0,96);
return '<label class="week-calendar-item"><input type="checkbox" data-week-calendar-item value="'+escapeAttribute(id)+'" checked><span><strong>'+escapeHtml(item?.title||'Work details unavailable')+
'</strong><small>'+escapeHtml(reference)+'</small><small data-week-calendar-preview="'+escapeAttribute(id)+'"></small></span></label>';}).join('')+'</article>').join('');
daysRoot.querySelectorAll('input').forEach(input=>input.addEventListener('change',update));
update();qs('#back-to-week-review-from-calendar').focus?.();return true;
}
qs('#back-to-week-review-from-calendar').addEventListener('click',()=>close({back:true}));
qs('#share-week-calendar').addEventListener('click',async()=>{
const button=qs('#share-week-calendar'),current=blocks();if(!current.length)return;
button.disabled=true;qs('#week-calendar-status').textContent='Preparing calendar blocks…';
const day=new Date().toISOString().slice(0,10);
try{
const text=serializeWeekCalendar(current,{timezone:plan.timezone||Intl.DateTimeFormat().resolvedOptions().timeZone,revision:plan.revision});
const result=await deliverWeekCalendar({text,filename:'stackchain-week-ahead-'+day+'.ics',navigator:navigatorObject,
document:documentObject,urlApi,FileCtor});
close();onDone?.(result);
}catch(error){
qs('#week-calendar-status').textContent=error?.name==='AbortError'?'Share cancelled. Your Week Ahead is still ready.':'Calendar export failed. Retry without leaving Week Ahead.';
button.disabled=false;
}
});
return {open,close,blocks};
}
function setAvailabilityProvider(value){availabilityProvider=typeof value==='function'?value:()=>null;}
const api={buildWeekBlocks,buildWeekSchedule,deliverWeekCalendar,escapeText,foldLine,mountWeekCalendarHandoff,serializeWeekCalendar,setAvailabilityProvider};
if(typeof module!=='undefined'&&module.exports)module.exports=api;else root.StackchainWeekCalendar=api;
})(typeof window!=='undefined'?window:globalThis);
+996 -23
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -19,6 +19,7 @@ RUNTIME_DIRECTORIES = ("docs", "frontend", "src")
RUNTIME_FILES = (
"README.md",
"requirements.txt",
"scripts/rotate_private_state.py",
"scripts/rotate_unfiled_drafts.py",
)
EXCLUDED_PARTS = {"__pycache__", ".pytest_cache"}
+176
View File
@@ -0,0 +1,176 @@
#!/usr/bin/env python3
"""Rewrap shared private-state envelopes under the configured active key."""
from __future__ import annotations
import json
import os
import sqlite3
import sys
from dataclasses import dataclass
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from src.private_state import connect_private_sqlite # noqa: E402
from src.state_encryption import ( # noqa: E402
PrivateStateCipher,
PrivateStateEncryptionError,
private_state_encryption_config,
)
@dataclass(frozen=True)
class Field:
column: str
binding: str
alias: str | None = None
plaintext_string: bool = False
@dataclass(frozen=True)
class Table:
name: str
context_columns: tuple[str, ...]
fields: tuple[Field, ...]
@dataclass(frozen=True)
class Store:
name: str
identity: str
env: str
filename: str
tables: tuple[Table, ...]
STORES = (
Store("today", "today", "STACKCHAIN_TODAY_DB", "today.sqlite3", (
Table("today_plans", ("login",), (Field("ids", "plan:{login}"),)),
Table("tomorrow_plans", ("login",), (Field("payload", "tomorrow:{login}"),)),
Table("tomorrow_promotions", ("login", "promotion_id"), (Field("result", "tomorrow-promotion:{login}:{promotion_id}"),)),
Table("week_plans", ("login",), (Field("payload", "week:{login}"),)),
Table("week_promotions", ("login", "promotion_id"), (Field("result", "week-promotion:{login}:{promotion_id}"),)),
Table("week_reschedules", ("login", "operation_id"), (Field("result", "week-reschedule:{login}:{operation_id}"),)),
Table("today_sessions", ("login",), (Field("device_id", "session:{login}"),)),
Table("today_recaps", ("login",), (
Field("session_id", "recap-id:{login}", "session_id", True),
Field("items", "recap-items:{login}:{session_id}"),
)),
Table("today_time_logs", ("login",), (
Field("session_id", "time-log-session:{login}", "session_id", True),
Field("identity", "time-log-identity:{login}:{session_id}", "identity", True),
Field("actual_minutes", "time-log-payload:{login}:{session_id}:{identity}"),
)),
)),
Store("later", "later", "STACKCHAIN_LATER_DB", "later.sqlite3", (
Table("later_plans", ("login",), (Field("records", "plan:{login}"),)),
Table("later_item_revisions", ("login",), (Field("item_id", "item-revision:{login}", plaintext_string=True),)),
)),
Store("live-snapshot", "live-snapshot", "STACKCHAIN_LIVE_SNAPSHOT_DB", "live-snapshot.sqlite3", (
Table("live_snapshot", ("generation",), (Field("value_json", "{generation}"),)),
)),
Store("available-issue-snapshot", "available-issue-snapshot", "STACKCHAIN_AVAILABLE_ISSUE_SNAPSHOT_DB", "available-issue-snapshot.sqlite3", (
Table("available_issue_snapshot", (), (Field("items_json", "singleton"),)),
)),
Store("saved-searches", "saved-searches", "STACKCHAIN_SAVED_SEARCH_DB", "saved-searches.sqlite3", (
Table("saved_searches", ("login",), (Field("views", "views:{login}"),)),
)),
Store("security-events", "security-events", "STACKCHAIN_SECURITY_EVENT_DB", "security-events.sqlite3", (
Table("security_events", ("id",), (Field("payload", "event:{id}"),)),
)),
Store("idempotency-ledger", "idempotency-ledger", "STACKCHAIN_IDEMPOTENCY_DB", "idempotency.sqlite3", (
Table("idempotency_operations", ("key",), (
Field("fingerprint", "{key}:fingerprint"),
Field("response_json", "{key}:response"),
)),
)),
)
def _tables(connection: sqlite3.Connection) -> set[str]:
return {
row[0]
for row in connection.execute(
"SELECT name FROM sqlite_master WHERE type = 'table'"
)
}
def rotate_store(path: Path, spec: Store, config) -> dict[str, int]:
counts = {"current": 0, "failed": 0, "migrated": 0, "total": 0}
if not path.exists():
return counts
cipher = PrivateStateCipher(config, store=spec.identity)
with connect_private_sqlite(path, timeout=1.0) as connection:
connection.row_factory = sqlite3.Row
available = _tables(connection)
for table in spec.tables:
if table.name not in available:
continue
columns = (*table.context_columns, *(field.column for field in table.fields))
query = f"SELECT rowid AS _rotation_rowid, {', '.join(columns)} FROM {table.name}"
for row in connection.execute(query).fetchall():
context = {name: row[name] for name in table.context_columns}
updates: dict[str, str] = {}
row_failed = False
row_counts = {"current": 0, "migrated": 0, "total": 0}
for field in table.fields:
payload = row[field.column]
if payload is None:
continue
row_counts["total"] += 1
try:
binding = field.binding.format(**context)
if isinstance(payload, str) and not payload.startswith(("v1:", "v2:")) and field.plaintext_string:
value, stale = payload, True
else:
value, stale = cipher.open(str(payload), binding=binding)
if field.alias:
context[field.alias] = value
if stale:
updates[field.column] = cipher.seal(value, binding=binding)
row_counts["migrated"] += 1
else:
row_counts["current"] += 1
except (KeyError, PrivateStateEncryptionError, ValueError):
row_failed = True
break
counts["total"] += row_counts["total"]
if row_failed:
counts["failed"] += 1
continue
if updates:
assignments = ", ".join(f"{name} = ?" for name in updates)
connection.execute(
f"UPDATE {table.name} SET {assignments} WHERE rowid = ?",
(*updates.values(), row["_rotation_rowid"]),
)
counts["migrated"] += row_counts["migrated"]
counts["current"] += row_counts["current"]
return counts
def main() -> int:
try:
config = private_state_encryption_config()
if isinstance(config, bytes):
raise PrivateStateEncryptionError("rotation requires a keyring")
state = Path(os.getenv("STACKCHAIN_STATE_DIR", ".stackchain-state"))
report = {
spec.name: rotate_store(
Path(os.getenv(spec.env, str(state / spec.filename))), spec, config
)
for spec in STORES
}
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
print(json.dumps({"error": "Private-state rotation configuration is unavailable"}, sort_keys=True))
return 2
print(json.dumps(report, sort_keys=True))
return 1 if any(item["failed"] for item in report.values()) else 0
if __name__ == "__main__":
raise SystemExit(main())
+2 -2
View File
@@ -12,7 +12,7 @@ from src.private_state import connect_private_sqlite
from src.state_encryption import (
PrivateStateCipher,
PrivateStateEncryptionError,
private_state_encryption_key,
private_state_encryption_config,
)
@@ -34,7 +34,7 @@ class AvailableIssueSnapshotStore:
self.path = Path(path)
self.clock = clock or time.time
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="available-issue-snapshot",
)
with self._connect() as connection:
+2 -2
View File
@@ -36,7 +36,7 @@ FEATURE_SOURCES = {
"planning": (
"static/plan-today.js", "static/plan-today-readiness.js",
"static/plan-today-preview.js", "static/today-rollover.js", "static/today-readiness.js",
"static/tomorrow-plan.js", "static/week-plan.js", "static/mobile-plan-today-nav.js",
"static/tomorrow-plan.js", "static/week-calendar.js", "static/week-calendar-import.js", "static/week-plan.js", "static/today-week-reschedule.js", "static/search-week-plan.js", "static/search-batch-plan.js", "static/agenda-session-launcher.js", "static/mobile-plan-today-nav.js",
),
"today-timer": (
"static/conversation.js", "static/widgets.js", "static/voice-transcript-store.js", "static/voice-conversation-capture.js", "static/mobile-launch.js", "static/mobile-insights.js", "static/mobile-app-shortcuts.js", "static/mobile-find-work-nav.js", "static/mobile-pull-refresh.js", "static/live-data-status.js",
@@ -45,7 +45,7 @@ FEATURE_SOURCES = {
"static/assign-and-start.js", "static/filed-claim.js", "static/queue-today.js", "static/create-and-start.js",
"static/draft-filing-session.js", "static/draft-capacity-dialog.js", "static/work-selection.js",
"static/today-work.js", "static/today-sync.js", "static/pick-work.js", "static/batch-find-work.js",
"static/search-batch-plan.js", "static/mention-composer.js", "static/issue-evidence-review.js", "static/issue-evidence-editor.js",
"static/mention-composer.js", "static/issue-evidence-review.js", "static/issue-evidence-editor.js",
"static/issue-attachment.js", "static/checklist-conflict.js", "static/issue-outbox.js", "static/authored-outbox.js", "static/issue-sheet.js", "static/mobile-issue-detail-nav.js", "static/issue-filing-review.js", "static/issue-filing-receipt.js",
),
}
+2 -2
View File
@@ -6,7 +6,7 @@ from pathlib import Path
from typing import Any, Callable
from src.private_state import connect_private_sqlite
from src.state_encryption import PrivateStateCipher, private_state_encryption_key
from src.state_encryption import PrivateStateCipher, private_state_encryption_config
@dataclass(frozen=True)
@@ -38,7 +38,7 @@ class IdempotencyLedger:
self.lock_timeout_seconds = lock_timeout_seconds
self.clock = clock
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="idempotency-ledger",
)
self._initialize()
+4 -4
View File
@@ -6,7 +6,7 @@ from datetime import datetime
from pathlib import Path
from src.private_state import connect_private_sqlite
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
class LaterStore:
@@ -26,7 +26,7 @@ class LaterStore:
self.operation_retention_seconds = operation_retention_seconds
self.clock = clock
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="later",
)
self._initialize()
@@ -124,7 +124,7 @@ class LaterStore:
"SELECT item_id, revision FROM later_item_revisions WHERE login = ?",
(login,),
):
if stored_item_id.startswith("v1:"):
if stored_item_id.startswith(("v1:", "v2:")):
item_id, _legacy = self._cipher.open(
stored_item_id, binding=f"item-revision:{login}"
)
@@ -141,7 +141,7 @@ class LaterStore:
) -> dict[str, str]:
migrated = dict(stored_ids)
for item_id, stored_item_id in stored_ids.items():
if stored_item_id.startswith("v1:"):
if stored_item_id.startswith(("v1:", "v2:")):
continue
sealed_item_id = self._cipher.seal(
item_id, binding=f"item-revision:{login}"
+2 -2
View File
@@ -15,7 +15,7 @@ from src.private_state import connect_private_sqlite
from src.state_encryption import (
PrivateStateCipher,
PrivateStateEncryptionError,
private_state_encryption_key,
private_state_encryption_config,
)
SECTIONS = ("context", "events", "notifications")
@@ -63,7 +63,7 @@ class LiveSnapshotStore:
self.path = Path(path)
self.clock = clock or time.time
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="live-snapshot",
)
self._initialize()
+148 -2
View File
@@ -127,7 +127,7 @@ async def _start_day_plan_snapshot() -> dict:
login = user.get("login") if isinstance(user, dict) else None
if not isinstance(login, str) or not login:
return {}
return await asyncio.to_thread(_today_store().get_tomorrow, login)
return await asyncio.to_thread(_today_store().get_start_day_plan, login)
async def _push_poll_loop() -> None:
@@ -747,6 +747,41 @@ class WeekPromotion(BaseModel):
today_revision: int = Field(ge=0)
class WeekReschedule(BaseModel):
operation_id: str = Field(min_length=1, max_length=100)
identity: str = Field(min_length=1, max_length=500)
estimate_minutes: int = Field(ge=5, le=1440)
plan_date: str = Field(min_length=10, max_length=10)
today_revision: int = Field(ge=0)
week_revision: int = Field(ge=0)
allow_over_capacity: bool = False
class WeekItemPull(BaseModel):
operation_id: str = Field(min_length=1, max_length=100)
identity: str = Field(min_length=1, max_length=500)
today_revision: int = Field(ge=0)
week_revision: int = Field(ge=0)
allow_over_capacity: bool = False
class WeekReconciliation(WeekPromotion):
ids: list[str] = Field(max_length=5)
capacity_minutes: int | None = Field(default=None, ge=15, le=1440)
estimates: dict[str, int] = Field(default_factory=dict, max_length=5)
@model_validator(mode="after")
def validate_selection(self):
if len(set(self.ids)) != len(self.ids):
raise ValueError("reconciliation IDs must be unique")
if any(not item_id or len(item_id) > 500 for item_id in self.ids):
raise ValueError("reconciliation IDs must be bounded")
if any(item_id not in self.ids or minutes < 5 or minutes > 1440
for item_id, minutes in self.estimates.items()):
raise ValueError("estimates must match selected IDs and be bounded")
return self
class LaterOperationBatch(BaseModel):
operations: list[LaterOperation] = Field(min_length=1, max_length=50)
@@ -1451,7 +1486,7 @@ async def require_operator_session(request: Request, call_next):
async def prevent_live_api_caching(request, call_next):
response = await call_next(request)
path = dashboard_auth.application_path(request)
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/tomorrow", "/api/v1/tomorrow/promote", "/api/v1/week", "/api/v1/week/promote", "/api/v1/today/session", "/api/v1/later", "/api/v1/saved-searches", "/api/v1/completed-filed-reviews", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
if path in {"/api/v1/context", "/api/v1/background-identity", "/api/v1/events", "/api/v1/live", "/api/v1/available-issues", "/api/v1/search", "/api/v1/work-route", "/api/v1/today", "/api/v1/tomorrow", "/api/v1/tomorrow/promote", "/api/v1/week", "/api/v1/week/promote", "/api/v1/week/start-early", "/api/v1/week/reconcile", "/api/v1/week/reschedule", "/api/v1/week/pull-item", "/api/v1/today/session", "/api/v1/later", "/api/v1/saved-searches", "/api/v1/completed-filed-reviews", "/api/v1/security-events", "/api/v1/push-subscription"} or path.startswith("/api/v1/work/") or (
path.startswith("/api/v1/repos/")
and path.endswith("/review")
) or path.startswith("/api/v1/notifications") or (
@@ -2819,6 +2854,11 @@ async def promote_week_plan(payload: WeekPromotion):
status_code=409, detail={"code": "week_changed", "snapshot": error.snapshot}
)
except TodayPromotionConflict as error:
if error.week is not None:
raise HTTPException(
status_code=409,
detail={"code": "week_today_in_progress", "today": error.today, "week": error.week},
)
raise HTTPException(
status_code=409, detail={"code": "today_changed", "today": error.today}
)
@@ -2835,6 +2875,112 @@ async def promote_week_plan(payload: WeekPromotion):
)
@app.post("/api/v1/week/reschedule")
async def reschedule_today_to_week(payload: WeekReschedule):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().reschedule_today_to_week, login, **payload.model_dump()
)
except WeekPlanConflict as error:
raise HTTPException(
status_code=409, detail={"code": "week_changed", "week": error.snapshot}
)
except TodayPromotionConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "today_changed", "today": error.today, "week": error.week},
)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Week Ahead rescheduling is unavailable",
headers={"Retry-After": "1"},
)
@app.post("/api/v1/week/pull-item")
async def pull_week_item_into_today(payload: WeekItemPull):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().pull_week_item, login, **payload.model_dump()
)
except WeekPlanConflict as error:
raise HTTPException(
status_code=409, detail={"code": "week_changed", "week": error.snapshot}
)
except TodayPromotionConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "today_changed", "today": error.today, "week": error.week},
)
except TodayPlanFull:
raise HTTPException(status_code=409, detail={"code": "today_full"})
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Adding Week Ahead work to Today is unavailable",
headers={"Retry-After": "1"},
)
@app.post("/api/v1/week/start-early")
async def start_week_day_early(payload: WeekPromotion):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().promote_week, login, **payload.model_dump(), allow_future=True
)
except WeekPlanConflict as error:
raise HTTPException(
status_code=409, detail={"code": "week_changed", "snapshot": error.snapshot}
)
except TodayPromotionConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "week_today_in_progress", "today": error.today, "week": error.week},
)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Starting Week Ahead early is unavailable",
headers={"Retry-After": "1"},
)
@app.post("/api/v1/week/reconcile")
async def reconcile_week_plan(payload: WeekReconciliation):
login = await _confirmed_login()
try:
return await asyncio.to_thread(
_today_store().reconcile_week, login, **payload.model_dump()
)
except WeekPlanConflict as error:
raise HTTPException(
status_code=409, detail={"code": "week_changed", "snapshot": error.snapshot}
)
except TodayPromotionConflict as error:
raise HTTPException(
status_code=409,
detail={"code": "week_today_changed", "today": error.today, "week": error.week},
)
except TomorrowPlanNotDue as error:
raise HTTPException(
status_code=409, detail={"code": "week_not_due", "plan_date": error.plan_date}
)
except ValueError as error:
raise HTTPException(status_code=422, detail=str(error))
except (OSError, sqlite3.Error, PrivateStateEncryptionError):
raise HTTPException(
status_code=503, detail="Week Ahead reconciliation is unavailable",
headers={"Retry-After": "1"},
)
@app.get("/api/v1/today/session")
async def get_today_session():
login = await _confirmed_login()
+2 -2
View File
@@ -5,7 +5,7 @@ import sqlite3
from pathlib import Path
from src.private_state import connect_private_sqlite
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
_REPOSITORY = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$")
@@ -33,7 +33,7 @@ class SavedSearchStore:
self.limit = limit
self.timeout = timeout
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="saved-searches",
)
self._initialize()
+2 -2
View File
@@ -10,7 +10,7 @@ from src.private_state import connect_private_sqlite
from src.state_encryption import (
PrivateStateCipher,
PrivateStateEncryptionError,
private_state_encryption_key,
private_state_encryption_config,
)
@@ -53,7 +53,7 @@ class SecurityEventStore:
self.lock_timeout_seconds = lock_timeout_seconds
try:
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="security-events",
)
except PrivateStateEncryptionError as exc:
+136 -18
View File
@@ -6,6 +6,8 @@ import base64
import binascii
import json
import os
import re
from collections.abc import Mapping
from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
@@ -16,7 +18,7 @@ class PrivateStateEncryptionError(RuntimeError):
def decode_private_state_encryption_key(encoded: str) -> bytes:
"""Decode the independently injected 256-bit private-state key."""
"""Decode an independently injected 256-bit private-state key."""
try:
key = base64.b64decode(encoded, validate=True)
except (binascii.Error, ValueError) as error:
@@ -31,38 +33,130 @@ def decode_private_state_encryption_key(encoded: str) -> bytes:
def private_state_encryption_key() -> bytes:
"""Load the legacy single key setting."""
return decode_private_state_encryption_key(
os.getenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY", "")
)
_KEY_ID = re.compile(r"^[A-Za-z0-9_-]{1,32}$")
_MAX_KEYS = 4
def decode_private_state_encryption_keyring(
encoded: str, active_key_id: str
) -> tuple[dict[str, bytes], str]:
"""Decode a bounded key-ID-to-key JSON object and validate its active key."""
try:
raw = json.loads(encoded)
except (TypeError, json.JSONDecodeError) as error:
raise PrivateStateEncryptionError(
"private state encryption keyring is invalid"
) from error
if not isinstance(raw, dict) or not raw:
raise PrivateStateEncryptionError("private state encryption keyring is invalid")
if len(raw) > _MAX_KEYS:
raise PrivateStateEncryptionError(
f"private state encryption keyring supports at most {_MAX_KEYS} keys"
)
keys: dict[str, bytes] = {}
for key_id, value in raw.items():
if not isinstance(key_id, str) or not _KEY_ID.fullmatch(key_id):
raise PrivateStateEncryptionError("private state encryption key ID is invalid")
if not isinstance(value, str):
raise PrivateStateEncryptionError("private state encryption keyring is invalid")
keys[key_id] = decode_private_state_encryption_key(value)
if active_key_id not in keys:
raise PrivateStateEncryptionError(
"private state active key is missing from the keyring"
)
return keys, active_key_id
def private_state_encryption_config() -> bytes | tuple[dict[str, bytes], str]:
"""Load a rotation keyring when configured, otherwise the legacy single key."""
encoded = os.getenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS", "")
active = os.getenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "")
if encoded or active:
return decode_private_state_encryption_keyring(encoded, active)
return private_state_encryption_key()
class PrivateStateCipher:
"""Seal JSON values with store-specific authenticated context."""
def __init__(self, key: bytes, *, store: str):
if not isinstance(key, bytes) or len(key) != 32:
raise PrivateStateEncryptionError(
"private state encryption requires exactly 32 key bytes"
)
def __init__(
self,
key: bytes | Mapping[str, bytes] | tuple[dict[str, bytes], str],
*,
store: str,
active_key_id: str | None = None,
):
if isinstance(key, tuple):
key, active_key_id = key
if isinstance(key, Mapping):
if not key or len(key) > _MAX_KEYS or active_key_id not in key:
raise PrivateStateEncryptionError(
"private state encryption keyring configuration is invalid"
)
ciphers: dict[str, AESGCM] = {}
for key_id, raw_key in key.items():
if not isinstance(key_id, str) or not _KEY_ID.fullmatch(key_id):
raise PrivateStateEncryptionError(
"private state encryption key ID is invalid"
)
if not isinstance(raw_key, bytes) or len(raw_key) != 32:
raise PrivateStateEncryptionError(
"private state encryption requires exactly 32 key bytes"
)
ciphers[key_id] = AESGCM(raw_key)
self._ciphers = ciphers
self._active_key_id = active_key_id
self._legacy_cipher = None
else:
if not isinstance(key, bytes) or len(key) != 32:
raise PrivateStateEncryptionError(
"private state encryption requires exactly 32 key bytes"
)
self._ciphers = {}
self._active_key_id = None
self._legacy_cipher = AESGCM(key)
if not store or "\0" in store:
raise ValueError("private state store identity is invalid")
self._cipher = AESGCM(key)
self._store = store
def _aad(self, binding: str) -> bytes:
return f"stackchain:private-state:v1\0{self._store}\0{binding}".encode()
def _aad(self, binding: str, *, version: str = "v1", key_id: str = "") -> bytes:
prefix = f"stackchain:private-state:{version}\0{self._store}\0{binding}"
if version == "v2":
prefix += f"\0{key_id}"
return prefix.encode()
def seal(self, value: object, *, binding: str = "singleton") -> str:
plaintext = json.dumps(value, separators=(",", ":")).encode()
nonce = os.urandom(12)
sealed = nonce + self._cipher.encrypt(nonce, plaintext, self._aad(binding))
if self._active_key_id is not None:
key_id = self._active_key_id
sealed = nonce + self._ciphers[key_id].encrypt(
nonce, plaintext, self._aad(binding, version="v2", key_id=key_id)
)
return f"v2:{key_id}:" + base64.urlsafe_b64encode(sealed).decode()
sealed = nonce + self._legacy_cipher.encrypt(
nonce, plaintext, self._aad(binding)
)
return "v1:" + base64.urlsafe_b64encode(sealed).decode()
@staticmethod
def _decode_sealed(payload: str) -> bytes:
sealed = base64.b64decode(payload, altchars=b"-_", validate=True)
if len(sealed) < 28:
raise ValueError("encrypted payload is too short")
return sealed
def open(self, payload: str, *, binding: str = "singleton") -> tuple[object, bool]:
"""Return the decoded value and whether plaintext migration is required."""
"""Return the decoded value and whether active-key rewrapping is required."""
if not isinstance(payload, str):
raise PrivateStateEncryptionError("private state could not be decrypted")
if not payload.startswith("v1:"):
if not payload.startswith(("v1:", "v2:")):
try:
return json.loads(payload), True
except (TypeError, json.JSONDecodeError) as error:
@@ -70,13 +164,37 @@ class PrivateStateCipher:
"private state could not be decrypted"
) from error
try:
sealed = base64.b64decode(payload[3:], altchars=b"-_", validate=True)
if len(sealed) < 28:
raise ValueError("encrypted payload is too short")
plaintext = self._cipher.decrypt(
sealed[:12], sealed[12:], self._aad(binding)
if payload.startswith("v2:"):
_, key_id, encoded = payload.split(":", 2)
cipher = self._ciphers.get(key_id)
if cipher is None:
raise ValueError("encrypted payload uses an unavailable key")
sealed = self._decode_sealed(encoded)
plaintext = cipher.decrypt(
sealed[:12],
sealed[12:],
self._aad(binding, version="v2", key_id=key_id),
)
return json.loads(plaintext), key_id != self._active_key_id
sealed = self._decode_sealed(payload[3:])
candidates = (
[self._legacy_cipher]
if self._legacy_cipher is not None
else list(self._ciphers.values())
)
return json.loads(plaintext), False
plaintext = None
for cipher in candidates:
try:
plaintext = cipher.decrypt(
sealed[:12], sealed[12:], self._aad(binding)
)
break
except InvalidTag:
continue
if plaintext is None:
raise InvalidTag
return json.loads(plaintext), self._active_key_id is not None
except (
binascii.Error,
InvalidTag,
+330 -17
View File
@@ -8,7 +8,7 @@ from pathlib import Path
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
from src.private_state import connect_private_sqlite
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_key
from src.state_encryption import PrivateStateCipher, PrivateStateEncryptionError, private_state_encryption_config
class TodayPlanFull(ValueError):
@@ -48,11 +48,12 @@ class WeekPlanConflict(ValueError):
class TodayPromotionConflict(ValueError):
"""Raised when rollover would overwrite a changed Today plan."""
"""Raised when promotion cannot safely replace the current Today plan."""
def __init__(self, today: dict):
super().__init__("Today changed before Tomorrow could be promoted")
def __init__(self, today: dict, week: dict | None = None):
super().__init__("Today must be reviewed before a saved plan can be promoted")
self.today = today
self.week = week
class TodayStore:
@@ -76,14 +77,14 @@ class TodayStore:
self.recap_limit = recap_limit
self.clock = clock
self._cipher = PrivateStateCipher(
encryption_key if encryption_key is not None else private_state_encryption_key(),
encryption_key if encryption_key is not None else private_state_encryption_config(),
store="today",
)
self._initialize()
def _initialize(self) -> None:
connection = connect_private_sqlite(self.path, timeout=self.timeout)
if connection.execute("PRAGMA user_version").fetchone()[0] >= 5:
if connection.execute("PRAGMA user_version").fetchone()[0] >= 7:
connection.close()
return
connection.execute("PRAGMA journal_mode=WAL")
@@ -188,7 +189,17 @@ class TodayStore:
"login TEXT NOT NULL, promotion_id TEXT NOT NULL, result TEXT NOT NULL, "
"created_at REAL NOT NULL, PRIMARY KEY (login, promotion_id))"
)
connection.execute("PRAGMA user_version = 5")
connection.execute(
"CREATE TABLE IF NOT EXISTS week_reschedules ("
"login TEXT NOT NULL, operation_id TEXT NOT NULL, result TEXT NOT NULL, "
"created_at REAL NOT NULL, PRIMARY KEY (login, operation_id))"
)
connection.execute(
"CREATE TABLE IF NOT EXISTS week_item_pulls ("
"login TEXT NOT NULL, operation_id TEXT NOT NULL, result TEXT NOT NULL, "
"created_at REAL NOT NULL, PRIMARY KEY (login, operation_id))"
)
connection.execute("PRAGMA user_version = 7")
connection.commit()
connection.close()
@@ -222,7 +233,7 @@ class TodayStore:
def _snapshot(self, row, login: str) -> tuple[dict, bool]:
if row is None:
return {"revision": 0, "ids": [], "capacity_minutes": None, "estimates": {}}, False
if row[1].startswith("v1:"):
if row[1].startswith(("v1:", "v2:")):
payload, legacy = self._cipher.open(row[1], binding=f"plan:{login}")
if not isinstance(payload, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
@@ -449,6 +460,32 @@ class TodayStore:
raise PrivateStateEncryptionError("private state could not be decrypted")
return {"revision": int(row[0]), **payload}
def get_start_day_plan(self, login: str) -> dict:
"""Return the next private planned day without changing either plan."""
login = self._normalize_login(login)
with self._connect() as connection:
week_row = connection.execute(
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,)
).fetchone()
if week_row is not None:
week = self._week_snapshot(week_row, login)
local_date = datetime.fromtimestamp(
self.clock(), ZoneInfo(week["timezone"])
).date().isoformat()
for day in week["days"]:
if (
isinstance(day, dict)
and isinstance(day.get("ids"), list)
and day["ids"]
and day.get("plan_date", "") <= local_date
):
return {**day, "timezone": week.get("timezone")}
tomorrow_row = connection.execute(
"SELECT revision, payload FROM tomorrow_plans WHERE login = ?", (login,)
).fetchone()
tomorrow = self._tomorrow_snapshot(tomorrow_row, login)
return tomorrow if tomorrow.get("ids") and tomorrow.get("plan_date") else {}
def get_week(self, login: str) -> dict:
login = self._normalize_login(login)
with self._connect() as connection:
@@ -494,6 +531,7 @@ class TodayStore:
raise ValueError("timezone must be a valid IANA timezone") from None
normalized = []
seen_dates = set()
seen_ids = set()
for day in days:
if not isinstance(day, dict):
raise ValueError("each Week Ahead date must be an object")
@@ -510,6 +548,10 @@ class TodayStore:
ids=day.get("ids", []), capacity_minutes=day.get("capacity_minutes"),
estimates=day.get("estimates", {}), plan_date=plan_date, timezone=timezone,
)
duplicate_ids = seen_ids.intersection(plan["ids"])
if duplicate_ids:
raise ValueError("work must be assigned to only one Week Ahead date")
seen_ids.update(plan["ids"])
plan.pop("timezone")
normalized.append(plan)
normalized.sort(key=lambda item: item["plan_date"])
@@ -536,10 +578,270 @@ class TodayStore:
)
return snapshot
def reschedule_today_to_week(
self, login: str, *, operation_id: str, identity: str, estimate_minutes: int,
plan_date: str, today_revision: int, week_revision: int,
allow_over_capacity: bool = False,
) -> dict:
"""Atomically move one current Today item to one Week Ahead date."""
login = self._normalize_login(login)
if not isinstance(operation_id, str) or not operation_id.strip() or len(operation_id) > 100:
raise ValueError("operation_id is required and bounded")
operation_id = operation_id.strip()
if not isinstance(identity, str) or not identity or len(identity) > 500:
raise ValueError("identity is required and bounded")
if (
not isinstance(estimate_minutes, int) or isinstance(estimate_minutes, bool)
or estimate_minutes < 5 or estimate_minutes > 1440
):
raise ValueError("estimate_minutes must be between 5 and 1440")
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
receipt = connection.execute(
"SELECT result FROM week_reschedules WHERE login = ? AND operation_id = ?",
(login, operation_id),
).fetchone()
if receipt:
result, _legacy = self._cipher.open(
receipt[0], binding=f"week-reschedule:{login}:{operation_id}"
)
if not isinstance(result, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
return result
today_row = connection.execute(
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
"FROM today_plans WHERE login = ?", (login,),
).fetchone()
today, _legacy = self._snapshot(today_row, login)
week_row = connection.execute(
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,)
).fetchone()
week = self._week_snapshot(week_row, login)
if today["revision"] != today_revision or identity not in today["ids"]:
raise TodayPromotionConflict(today, week)
if week["revision"] != week_revision:
raise WeekPlanConflict(week)
days = []
for source in week["days"]:
estimates = dict(source.get("estimates", {}))
estimates.pop(identity, None)
days.append({
**source,
"ids": [item_id for item_id in source.get("ids", []) if item_id != identity],
"estimates": estimates,
})
destination = next((day for day in days if day["plan_date"] == plan_date), None)
if destination is None:
destination = {
"plan_date": plan_date, "ids": [],
"capacity_minutes": None, "estimates": {},
}
days.append(destination)
destination["ids"].append(identity)
destination["estimates"][identity] = estimate_minutes
planned_minutes = sum(
int(destination["estimates"].get(item_id, 0)) for item_id in destination["ids"]
)
if (
destination.get("capacity_minutes") is not None
and planned_minutes > destination["capacity_minutes"]
and not allow_over_capacity
):
raise ValueError("explicit overload confirmation is required")
normalized_week = self._normalize_week(days=days, timezone=week["timezone"])
today_ids = [item_id for item_id in today["ids"] if item_id != identity]
today_estimates = {
item_id: minutes for item_id, minutes in today["estimates"].items()
if item_id != identity
}
today_result = {
**today, "revision": today_revision + 1,
"ids": today_ids, "estimates": today_estimates,
}
week_result = {"revision": week_revision + 1, **normalized_week}
connection.execute(
"UPDATE today_plans SET revision = ?, ids = ?, capacity_minutes = NULL, "
"estimates = '{}', plan_date = NULL, timezone = NULL WHERE login = ?",
(today_result["revision"], self._sealed_plan(login, today_result), login),
)
connection.execute(
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
(week_result["revision"], self._cipher.seal(
normalized_week, binding=f"week:{login}"
), login),
)
result = {"today": today_result, "week": week_result}
connection.execute(
"INSERT INTO week_reschedules(login, operation_id, result, created_at) "
"VALUES (?, ?, ?, ?)",
(login, operation_id, self._cipher.seal(
result, binding=f"week-reschedule:{login}:{operation_id}"
), self.clock()),
)
return result
def pull_week_item(
self, login: str, *, operation_id: str, identity: str,
today_revision: int, week_revision: int, allow_over_capacity: bool = False,
) -> dict:
"""Atomically append one Week Ahead item to Today and remove it from Week."""
login = self._normalize_login(login)
if not isinstance(operation_id, str) or not operation_id.strip() or len(operation_id) > 100:
raise ValueError("operation_id is required and bounded")
if not isinstance(identity, str) or not identity or len(identity) > 500:
raise ValueError("identity is required and bounded")
operation_id = operation_id.strip()
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
receipt = connection.execute(
"SELECT result FROM week_item_pulls WHERE login = ? AND operation_id = ?",
(login, operation_id),
).fetchone()
if receipt:
result, _legacy = self._cipher.open(
receipt[0], binding=f"week-item-pull:{login}:{operation_id}"
)
if not isinstance(result, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
return result
today_row = connection.execute(
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
"FROM today_plans WHERE login = ?", (login,),
).fetchone()
today, _legacy = self._snapshot(today_row, login)
week_row = connection.execute(
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,),
).fetchone()
week = self._week_snapshot(week_row, login)
if today["revision"] != today_revision:
raise TodayPromotionConflict(today, week)
if week["revision"] != week_revision:
raise WeekPlanConflict(week)
if identity in today["ids"]:
raise ValueError("work is already in Today")
if len(today["ids"]) >= self.limit:
raise TodayPlanFull("Today plan is full")
source = next((day for day in week["days"] if identity in day["ids"]), None)
if source is None:
raise WeekPlanConflict(week)
estimate = source.get("estimates", {}).get(identity)
planned_minutes = sum(
int(today["estimates"].get(item_id, 0)) for item_id in today["ids"]
) + (int(estimate) if estimate else 0)
if (
today.get("capacity_minutes") is not None
and planned_minutes > today["capacity_minutes"]
and not allow_over_capacity
):
raise ValueError("moving work over Today capacity requires explicit overload confirmation")
today_result = {
**today, "revision": today_revision + 1,
"ids": [*today["ids"], identity],
"estimates": {**today["estimates"], **({identity: estimate} if estimate else {})},
}
remaining_days = []
for day in week["days"]:
estimates = dict(day.get("estimates", {}))
estimates.pop(identity, None)
remaining_days.append({
**day, "ids": [item_id for item_id in day["ids"] if item_id != identity],
"estimates": estimates,
})
week_payload = {"timezone": week["timezone"], "days": remaining_days}
week_result = {"revision": week_revision + 1, **week_payload}
connection.execute(
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
"VALUES (?, ?, ?, NULL, '{}', NULL, NULL) ON CONFLICT(login) DO UPDATE SET "
"revision=excluded.revision, ids=excluded.ids, capacity_minutes=NULL, estimates='{}', "
"plan_date=NULL, timezone=NULL",
(login, today_result["revision"], self._sealed_plan(login, today_result)),
)
connection.execute(
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
(week_result["revision"], self._cipher.seal(week_payload, binding=f"week:{login}"), login),
)
result = {"today": today_result, "week": week_result}
connection.execute(
"INSERT INTO week_item_pulls(login, operation_id, result, created_at) VALUES (?, ?, ?, ?)",
(login, operation_id, self._cipher.seal(
result, binding=f"week-item-pull:{login}:{operation_id}"
), self.clock()),
)
return result
def promote_week(
self, login: str, *, promotion_id: str, week_revision: int,
plan_date: str, today_revision: int,
plan_date: str, today_revision: int, allow_future: bool = False,
) -> dict:
login = self._normalize_login(login)
if not isinstance(promotion_id, str) or not promotion_id.strip() or len(promotion_id) > 100:
raise ValueError("promotion_id is required and bounded")
promotion_id = promotion_id.strip()
with self._connect() as connection:
connection.execute("BEGIN IMMEDIATE")
receipt = connection.execute(
"SELECT result FROM week_promotions WHERE login = ? AND promotion_id = ?",
(login, promotion_id),
).fetchone()
if receipt:
result, _legacy = self._cipher.open(
receipt[0], binding=f"week-promotion:{login}:{promotion_id}"
)
if not isinstance(result, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
return result
row = connection.execute(
"SELECT revision, payload FROM week_plans WHERE login = ?", (login,)
).fetchone()
week = self._week_snapshot(row, login)
if week["revision"] != week_revision:
raise WeekPlanConflict(week)
day = next((item for item in week["days"] if item["plan_date"] == plan_date), None)
if day is None:
raise WeekPlanConflict(week)
local_date = datetime.fromtimestamp(self.clock(), ZoneInfo(week["timezone"])).date().isoformat()
if local_date < plan_date and not allow_future:
raise TomorrowPlanNotDue(plan_date)
today_row = connection.execute(
"SELECT revision, ids, capacity_minutes, estimates, plan_date, timezone "
"FROM today_plans WHERE login = ?", (login,)
).fetchone()
today, _legacy = self._snapshot(today_row, login)
if today["revision"] != today_revision:
raise TodayPromotionConflict(today)
if today["ids"]:
raise TodayPromotionConflict(today, week)
result = {"revision": today_revision + 1, **day, "timezone": week["timezone"]}
connection.execute(
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
"VALUES (?, ?, ?, NULL, '{}', NULL, NULL) ON CONFLICT(login) DO UPDATE SET "
"revision=excluded.revision, ids=excluded.ids, capacity_minutes=NULL, estimates='{}', "
"plan_date=NULL, timezone=NULL",
(login, result["revision"], self._sealed_plan(login, result)),
)
remaining = {"timezone": week["timezone"], "days": [
item for item in week["days"] if item["plan_date"] != plan_date
]}
connection.execute(
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
(week_revision + 1, self._cipher.seal(remaining, binding=f"week:{login}"), login),
)
connection.execute(
"INSERT INTO week_promotions(login, promotion_id, result, created_at) VALUES (?, ?, ?, ?)",
(login, promotion_id, self._cipher.seal(
result, binding=f"week-promotion:{login}:{promotion_id}"
), self.clock()),
)
return result
def reconcile_week(
self, login: str, *, promotion_id: str, week_revision: int,
plan_date: str, today_revision: int, ids: list[str],
capacity_minutes: int | None, estimates: dict[str, int],
) -> dict:
"""Atomically replace Today from preserved Today/due-week work and consume that day."""
login = self._normalize_login(login)
if not isinstance(promotion_id, str) or not promotion_id.strip() or len(promotion_id) > 100:
raise ValueError("promotion_id is required and bounded")
@@ -575,22 +877,33 @@ class TodayStore:
).fetchone()
today, _legacy = self._snapshot(today_row, login)
if today["revision"] != today_revision:
raise TodayPromotionConflict(today)
result = {"revision": today_revision + 1, **day, "timezone": week["timezone"]}
raise TodayPromotionConflict(today, week)
allowed = set(today["ids"]) | set(day["ids"])
if any(item_id not in allowed for item_id in ids):
raise ValueError("selected work must come from Today or the due Week Ahead day")
normalized = self._normalize_tomorrow(
ids=ids, capacity_minutes=capacity_minutes, estimates=estimates,
plan_date=plan_date, timezone=week["timezone"],
)
today_result = {"revision": today_revision + 1, **normalized}
connection.execute(
"INSERT INTO today_plans(login, revision, ids, capacity_minutes, estimates, plan_date, timezone) "
"VALUES (?, ?, ?, NULL, '{}', NULL, NULL) ON CONFLICT(login) DO UPDATE SET "
"revision=excluded.revision, ids=excluded.ids, capacity_minutes=NULL, estimates='{}', "
"plan_date=NULL, timezone=NULL",
(login, result["revision"], self._sealed_plan(login, result)),
(login, today_result["revision"], self._sealed_plan(login, today_result)),
)
remaining = {"timezone": week["timezone"], "days": [
remaining_payload = {"timezone": week["timezone"], "days": [
item for item in week["days"] if item["plan_date"] != plan_date
]}
week_result = {"revision": week_revision + 1, **remaining_payload}
connection.execute(
"UPDATE week_plans SET revision = ?, payload = ? WHERE login = ?",
(week_revision + 1, self._cipher.seal(remaining, binding=f"week:{login}"), login),
(week_result["revision"], self._cipher.seal(
remaining_payload, binding=f"week:{login}"
), login),
)
result = {"today": today_result, "week": week_result}
connection.execute(
"INSERT INTO week_promotions(login, promotion_id, result, created_at) VALUES (?, ?, ?, ?)",
(login, promotion_id, self._cipher.seal(
@@ -609,7 +922,7 @@ class TodayStore:
def _session_snapshot(self, row, login: str) -> tuple[dict, bool]:
if row is None:
return self._empty_session(), False
if row[1].startswith("v1:"):
if row[1].startswith(("v1:", "v2:")):
payload, legacy = self._cipher.open(row[1], binding=f"session:{login}")
if not isinstance(payload, dict):
raise PrivateStateEncryptionError("private state could not be decrypted")
@@ -710,7 +1023,7 @@ class TodayStore:
def _recap_snapshot(
self, login: str, encrypted_session_id: str, created_at: float, serialized: str
) -> tuple[dict, bool]:
if encrypted_session_id.startswith("v1:"):
if encrypted_session_id.startswith(("v1:", "v2:")):
session_id, legacy_session = self._cipher.open(
encrypted_session_id, binding=f"recap-id:{login}"
)
@@ -802,7 +1115,7 @@ class TodayStore:
def _time_log_snapshot(self, login: str, row) -> tuple[dict, bool]:
encrypted_session, encrypted_identity, payload_value, status_value = row
if encrypted_session.startswith("v1:"):
if encrypted_session.startswith(("v1:", "v2:")):
session_id = self._cipher.open(
encrypted_session, binding=f"time-log-session:{login}"
)[0]
+77
View File
@@ -0,0 +1,77 @@
from pathlib import Path
import pytest
sync_api = pytest.importorskip("playwright.sync_api")
FRONTEND = Path(__file__).parents[2] / "frontend"
@pytest.mark.parametrize("width,height", [(320, 568), (390, 844)])
def test_search_week_plan_sheet_fits_small_phones_with_touch_safe_controls(width, height):
html = (FRONTEND / "index.html").read_text()
with sync_api.sync_playwright() as playwright:
try:
browser = playwright.chromium.launch(headless=True)
except Exception as error:
pytest.skip(f"Chromium unavailable: {error}")
page = browser.new_page(viewport={"width": width, "height": height})
page.set_content(html)
page.add_style_tag(path=FRONTEND / "dashboard.css")
page.locator("#search-week-plan-days").evaluate(
"""node => node.innerHTML = Array.from({length:7}, (_, index) =>
`<button type="button" data-search-week-date="2026-08-${21+index}" aria-pressed="${index===0}">
<strong>Day ${index+1}</strong><small>${index*30} of 120 min · ${index} planned</small>
</button>`).join('')"""
)
page.locator("#search-week-plan-sheet").evaluate("node => node.hidden = false")
page.locator("#search-week-plan-estimate").fill("45")
expect = sync_api.expect
expect(page.locator("#search-week-plan-sheet")).to_be_visible()
expect(page.locator("#confirm-search-week-plan")).to_be_visible()
for button in page.locator("#search-week-plan-days button").all():
bounds = button.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.locator("#confirm-search-week-plan").bounding_box()["height"] >= 44
assert page.locator("#cancel-search-week-plan").bounding_box()["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
assert page.locator(".search-week-plan-panel").evaluate(
"node => node.scrollWidth <= node.clientWidth"
)
browser.close()
@pytest.mark.parametrize("width,height", [(320, 568), (390, 844)])
def test_search_week_batch_review_fits_small_phones_without_horizontal_overflow(width, height):
html = (FRONTEND / "index.html").read_text()
with sync_api.sync_playwright() as playwright:
try:
browser = playwright.chromium.launch(headless=True)
except Exception as error:
pytest.skip(f"Chromium unavailable: {error}")
page = browser.new_page(viewport={"width": width, "height": height})
page.set_content(html)
page.add_style_tag(path=FRONTEND / "dashboard.css")
page.locator("#search-week-batch-list").evaluate(
"""node => node.innerHTML = Array.from({length:4}, (_, index) =>
`<div class="search-week-batch-row"><div><span class="small">stackchain/dashboard#${1196+index}</span>
<strong>Substantial mobile planning issue ${index+1}</strong></div>
<div class="search-week-batch-row-controls"><label>Day<select><option>Fri, Aug 21 · 2 planned</option></select></label>
<label>Minutes<input type="number" value="45"></label></div></div>`).join('')"""
)
page.locator("#search-week-batch-review").evaluate("node => node.hidden = false")
page.locator("#cmd-palette").evaluate("node => node.classList.add('open')")
expect = sync_api.expect
expect(page.locator("#search-week-batch-review")).to_be_visible()
expect(page.locator("#confirm-search-week-batch")).to_be_visible()
for control in page.locator("#search-week-batch-review select, #search-week-batch-review input, #search-week-batch-review button").all():
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
assert page.locator("#search-week-batch-review").evaluate(
"node => node.scrollWidth <= node.clientWidth"
)
browser.close()
@@ -0,0 +1,122 @@
from __future__ import annotations
import os
import threading
from datetime import date, timedelta
from pathlib import Path
import pytest
if os.getenv("STACKCHAIN_RUN_RELEASE_E2E") != "1":
pytest.skip("packaged Today to Week Ahead journey runs only in its gated CI job", allow_module_level=True)
pytest.importorskip("playwright.sync_api")
from playwright.sync_api import expect, sync_playwright
from fake_gitea import FakeGiteaServer
from test_mobile_offline_issue_release import ACCESS_TOKEN, ROOT, release_server
@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
def test_release_artifact_reschedules_active_today_into_week_ahead(
tmp_path: Path, width: int, height: int
):
archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
assert len(archives) == 1, "browser job must download exactly one assembled release archive"
fake = FakeGiteaServer(("127.0.0.1", 0))
thread = threading.Thread(target=fake.serve_forever, daemon=True)
thread.start()
try:
with release_server(
archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}"
) as origin, sync_playwright() as playwright:
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
page = browser.new_page(
viewport={"width": width, "height": height}, timezone_id="UTC"
)
page_errors: list[str] = []
page.on("pageerror", lambda error: page_errors.append(str(error)))
page.goto(origin + "/", wait_until="networkidle")
page.locator('input[name="device_label"]').fill("Reschedule release phone")
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
page.locator("#submit-sign-in").click()
page.wait_for_url(origin + "/", wait_until="networkidle")
plan_date = (date.today() + timedelta(days=2)).isoformat()
saved_week = page.evaluate(
"""async ({planDate}) => {
const response=await fetch('api/v1/week',{method:'PUT',headers:{'Content-Type':'application/json'},
body:JSON.stringify({base_revision:0,timezone:'UTC',days:[{
plan_date:planDate,ids:[],capacity_minutes:90,estimates:{}
}]})});
return {status:response.status,body:await response.json()};
}""",
{"planDate": plan_date},
)
assert saved_week["status"] == 200
page.locator('[data-mobile-task="work"]').click()
page.locator("#plan-today-available").fill("90")
page.locator("#plan-today-available").press("Tab")
page.locator("#build-today-plan").click()
missing = page.locator("[data-plan-missing-estimate]")
for _ in range(2):
missing.nth(0).fill("30")
missing.nth(0).press("Tab")
save_and_start = page.locator("#save-and-start-today")
expect(save_and_start).to_be_enabled()
save_and_start.click()
expect(page.locator("#plan-today-sheet")).to_be_hidden(timeout=10_000)
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
if page.locator("#plan-today-sheet").is_visible():
page.locator("#cancel-plan-today").click()
page.locator("#close-issue-sheet").click()
if page.locator("#plan-today-sheet").is_visible():
page.locator("#cancel-plan-today").click()
launcher = page.locator("[data-work-session-reschedule-week]")
page.locator("[data-mobile-today-more]").click()
expect(launcher).to_be_visible()
launcher_bounds = launcher.bounding_box()
assert launcher_bounds and launcher_bounds["height"] >= 44
launcher.click()
dialog = page.locator("#today-week-reschedule")
expect(dialog).to_be_visible()
days = page.locator("#today-week-reschedule-days button")
try:
expect(days).to_have_count(7)
except AssertionError as error:
raise AssertionError({
"status": page.locator("#today-week-reschedule-status").text_content(),
"page_errors": page_errors,
"today": page.evaluate("async()=>await (await fetch('api/v1/today')).json()"),
"week": page.evaluate("async()=>await (await fetch('api/v1/week')).json()"),
}) from error
for control in [*days.all(), page.locator("#cancel-today-week-reschedule"), page.locator("#confirm-today-week-reschedule")]:
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
page.locator("#cancel-today-week-reschedule").click()
expect(dialog).to_be_hidden()
expect(launcher).to_be_focused()
launcher.click()
destination = page.locator(
f'#today-week-reschedule-days button[data-plan-date="{plan_date}"]'
)
destination.click()
page.locator("#confirm-today-week-reschedule").click()
expect(dialog).to_be_hidden()
expect(page.locator("#issue-sheet-title")).to_have_text("Polish desktop filters")
week = page.evaluate("async()=>await (await fetch('api/v1/week')).json()")
today = page.evaluate("async()=>await (await fetch('api/v1/today')).json()")
assert week["days"][0]["plan_date"] == plan_date
assert len(week["days"][0]["ids"]) == 1
assert len(today["ids"]) == 1
assert not page_errors
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
browser.close()
finally:
fake.shutdown()
fake.server_close()
thread.join(timeout=2)
+415 -4
View File
@@ -2,7 +2,9 @@ from __future__ import annotations
import json
import os
import re
import threading
from datetime import date, timedelta
from pathlib import Path
import pytest
@@ -29,9 +31,32 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
try:
with release_server(archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}") as origin, sync_playwright() as playwright:
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
page = browser.new_page(viewport={"width": width, "height": height})
page = browser.new_page(viewport={"width": width, "height": height}, timezone_id="UTC")
page_errors: list[str] = []
page.on("pageerror", lambda error: page_errors.append(str(error)))
pulled: list[dict] = []
page.route("**/api/v1/today", lambda route: route.fulfill(
status=200, content_type="application/json", body=json.dumps({
"revision": 3, "ids": ["issue:acme/mobile:99:"],
"capacity_minutes": 60, "estimates": {"issue:acme/mobile:99:": 30},
}),
))
def pull_item_route(route):
body = json.loads(route.request.post_data or "{}")
pulled.append(body)
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"today": {"revision": 4, "ids": ["issue:acme/mobile:99:", body["identity"]],
"capacity_minutes": 60,
"estimates": {"issue:acme/mobile:99:": 30, body["identity"]: 45}},
"week": {"revision": 99, "timezone": "UTC", "days": [{
"plan_date": (date.today() + timedelta(days=1)).isoformat(),
"ids": [], "capacity_minutes": 60, "estimates": {},
}]},
}))
page.route("**/api/v1/week/pull-item", pull_item_route)
def week_route(route):
if route.request.method == "PUT":
@@ -43,20 +68,111 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
}))
return
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"revision": 0, "timezone": None, "days": [],
"revision": 0, "timezone": None, "days": [{
"plan_date": (date.today() + timedelta(days=1)).isoformat(),
"ids": ["issue:acme/mobile:41:", "issue:acme/mobile:42:"], "capacity_minutes": 60,
"estimates": {"issue:acme/mobile:41:": 45, "issue:acme/mobile:42:": 45},
}],
}))
page.route("**/api/v1/week", week_route)
page.route(
"**/api/v1/repos/acme/mobile/issues/41/close",
lambda route: route.fulfill(
status=200,
content_type="application/json",
body='{"number":41,"state":"closed","updated_at":"2026-08-21T12:00:00Z"}',
),
)
page.goto(origin + "/", wait_until="networkidle")
page.locator('input[name="device_label"]').fill("Week Ahead release phone")
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
page.locator("#submit-sign-in").click()
page.wait_for_url(origin + "/", wait_until="networkidle")
if page.locator("#plan-today-sheet").is_visible():
page.locator("#cancel-plan-today").click()
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="week"]').click()
page.wait_for_timeout(100)
assert not page_errors, f"Week Ahead launch raised: {page_errors}"
expect(page.locator("#plan-today-title")).to_have_text("Week Ahead")
overview = page.locator("#week-review")
expect(overview).to_be_visible()
cards = page.locator("#week-review-days .week-review-day")
expect(cards).to_have_count(7)
expect(cards.first).to_contain_text("Next up")
expect(cards.first).to_contain_text("Ship mobile capture")
expect(page.locator("#week-review-status")).to_have_text(
"Week Ahead overview · no changes made."
)
expect(page.locator("#confirm-week-plan")).to_be_hidden()
edit_week = page.locator("#edit-week-plan")
expect(edit_week).to_be_visible()
remove_actions = cards.first.locator("[data-week-unplan]")
expect(remove_actions).to_have_count(2)
remove_bounds = remove_actions.nth(1).bounding_box()
assert remove_bounds and remove_bounds["height"] >= 44
remove_actions.nth(1).click()
expect(cards.first).not_to_contain_text("Polish desktop filters")
expect(page.locator("#week-unplan-receipt")).to_have_text(
"Polish desktop filters removed from Week Ahead."
)
undo = page.locator("#undo-week-unplan")
expect(undo).to_be_visible()
undo_bounds = undo.bounding_box()
assert undo_bounds and undo_bounds["height"] >= 44
undo.click()
expect(cards.first).to_contain_text("Polish desktop filters")
expect(page.locator("#week-unplan-receipt")).to_be_hidden()
assert saved[-2]["days"][0]["ids"] == ["issue:acme/mobile:41:"]
assert saved[-1]["days"][0]["ids"] == [
"issue:acme/mobile:41:", "issue:acme/mobile:42:"
]
writes_before_reflow = len(saved)
reflow = page.locator("#open-week-reflow")
expect(reflow).to_be_visible()
bounds = reflow.bounding_box()
assert bounds and bounds["height"] >= 44
reflow.click()
preview = page.locator("#week-reflow-review")
expect(preview).to_be_visible()
expect(page.locator("#week-reflow-days")).to_contain_text("1 item · 45 of 60 min")
expect(page.locator("#week-reflow-unscheduled")).to_have_text(
"1 item cannot fit: Polish desktop filters. It will remain in My Work."
)
for control in (page.locator("#cancel-week-reflow"), page.locator("#apply-week-reflow")):
control_bounds = control.bounding_box()
assert control_bounds and control_bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
page.locator("#cancel-week-reflow").click()
expect(preview).to_be_hidden()
assert len(saved) == writes_before_reflow, "cancelling reflow must not write"
reflow.click()
page.locator("#apply-week-reflow").click()
expect(page.locator("#week-review-status")).to_have_text("Week Ahead reflowed and saved.")
expect(preview).to_be_hidden()
assert len(saved) == writes_before_reflow + 1
assert [day["ids"] for day in saved[-1]["days"]][:2] == [["issue:acme/mobile:41:"], []]
planned_item = cards.first.locator("[data-week-open-item]")
expect(planned_item).to_have_count(1)
planned_bounds = planned_item.bounding_box()
assert planned_bounds and planned_bounds["height"] >= 44
planned_item.click()
expect(page.locator("#issue-sheet")).to_have_class(re.compile(r"\bopen\b"))
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
expect(overview).to_be_visible()
page.locator("#close-issue-sheet").click()
expect(page.locator("#issue-sheet")).not_to_have_class(re.compile(r"\bopen\b"))
expect(overview).to_be_visible()
expect(planned_item).to_be_focused()
assert len(saved) == writes_before_reflow + 1, "opening and inspecting Week Ahead must not add a write"
for control in (cards.first.locator("[data-week-edit-day]"), edit_week):
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
edit_week.click()
expect(overview).to_be_hidden()
expect(page.locator("#plan-today-title")).to_have_text("Plan Week Ahead")
dates = page.locator("#week-plan-dates button")
expect(dates).to_have_count(7)
@@ -66,14 +182,309 @@ def test_release_artifact_plans_seven_touch_safe_mobile_dates(
assert bounds and bounds["height"] >= 44
dates.nth(2).click()
expect(dates.nth(2)).to_have_attribute("aria-current", "date")
expect(page.locator("#week-plan-progress")).to_have_text("Day 3 of 7 · 1 planned")
expect(page.locator("#save-today-plan")).to_have_text("Save & next")
page.locator("#save-today-plan").click()
expect(page.locator("#plan-today-sheet")).to_be_visible()
expect(dates.nth(3)).to_have_attribute("aria-current", "date")
expect(page.locator("#week-plan-progress")).to_have_text("Day 4 of 7 · 1 planned")
dates.nth(6).click()
expect(page.locator("#save-today-plan")).to_have_text("Save week")
page.locator("#save-today-plan").click()
expect(page.locator("#plan-today-sheet")).to_be_visible()
expect(page.locator("#week-review")).to_be_visible()
expect(page.locator("#week-review-days .week-review-day")).to_have_count(7)
first_day = page.locator("#week-review-days .week-review-day").first
expect(first_day).to_contain_text("Ship mobile capture")
expect(first_day).to_contain_text("acme/mobile #41 · Issue · 45 min")
expect(first_day.locator("code")).to_have_count(0)
edit = first_day.locator("[data-week-edit-day]")
bounds = edit.bounding_box()
assert bounds and bounds["height"] >= 44
edit.click()
expect(page.locator("#week-review")).to_be_hidden()
expect(page.locator("#back-to-week-review")).to_be_visible()
expect(page.locator("#save-today-plan")).to_have_text("Save & review")
page.locator("#back-to-week-review").click()
expect(page.locator("#week-review")).to_be_visible()
expect(first_day).to_contain_text("Ship mobile capture")
page.locator("#open-week-capacity-import").click()
capacity_import = page.locator("#week-capacity-import")
expect(capacity_import).to_be_visible()
private_title = "Private customer planning"
tomorrow = (date.today() + timedelta(days=1)).strftime("%Y%m%d")
excluded = (date.today() + timedelta(days=2)).strftime("%Y%m%d")
added = (date.today() + timedelta(days=4)).strftime("%Y%m%d")
calendar = (
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\n"
f"SUMMARY:{private_title}\r\nDTSTART;TZID=America/New_York:{tomorrow}T050000\r\n"
f"DTEND;TZID=America/New_York:{tomorrow}T060000\r\nRRULE:FREQ=DAILY;COUNT=3\r\n"
f"EXDATE;TZID=America/New_York:{excluded}T050000\r\n"
f"RDATE;TZID=America/New_York:{added}T050000\r\nEND:VEVENT\r\nEND:VCALENDAR"
)
unsupported_title = "Private monthly board review"
unsupported_calendar = (
"BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\n"
f"SUMMARY:{unsupported_title}\r\nDTSTART:{tomorrow}T100000\r\n"
f"DTEND:{tomorrow}T110000\r\nRRULE:FREQ=MONTHLY;BYDAY=1FR\r\n"
"END:VEVENT\r\nEND:VCALENDAR"
)
page.locator("#week-capacity-file").set_input_files({
"name": "unsupported.ics", "mimeType": "text/calendar", "buffer": unsupported_calendar.encode()
})
expect(page.locator("#week-capacity-status")).to_contain_text(
"1 recurring event could not be counted"
)
expect(page.locator("#apply-week-capacities")).to_be_disabled()
expect(capacity_import).not_to_contain_text(unsupported_title)
page.locator("#week-capacity-file").set_input_files({
"name": "availability.ics", "mimeType": "text/calendar", "buffer": calendar.encode()
})
expect(page.locator("#week-capacity-days .week-capacity-day")).to_have_count(7)
expect(page.locator("#week-capacity-days .week-capacity-day").first).to_contain_text(
"420 min available"
)
expect(page.locator("#week-capacity-days .week-capacity-day").nth(1)).to_contain_text(
"480 min available"
)
expect(page.locator("#week-capacity-days .week-capacity-day").nth(2)).to_contain_text(
"420 min available"
)
expect(page.locator("#week-capacity-days .week-capacity-day").nth(3)).to_contain_text(
"420 min available"
)
expect(capacity_import).not_to_contain_text(private_title)
for control in (
page.locator("#cancel-week-capacity-import"),
page.locator("#week-capacity-file"),
page.locator("#week-capacity-start"),
page.locator("#week-capacity-end"),
page.locator("#apply-week-capacities"),
):
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
page.locator("#apply-week-capacities").click()
expect(capacity_import).to_be_hidden()
expect(page.locator("#week-review")).to_be_visible()
expect(first_day).to_contain_text("45 of 420 min")
page.wait_for_function("() => !document.querySelector('#confirm-week-plan').disabled")
confirm = page.locator("#confirm-week-plan")
bounds = confirm.bounding_box()
assert bounds and bounds["height"] >= 44
confirm.click()
expect(page.locator("#week-calendar-handoff")).to_be_visible()
expect(page.locator("#week-review")).to_be_hidden()
start = page.locator("[data-week-calendar-start]").first
expect(start).to_have_value("09:00")
expect(page.locator('[data-week-calendar-preview="issue:acme/mobile:41:"]')).to_have_text("10:00–10:45 · 45 min")
expect(page.locator("#week-calendar-status")).to_contain_text("Planning around imported busy time")
for control in (start, page.locator("#back-to-week-review-from-calendar"), page.locator("#share-week-calendar")):
bounds = control.bounding_box()
assert bounds and bounds["height"] >= 44
page.locator("#back-to-week-review-from-calendar").click()
expect(page.locator("#week-review")).to_be_visible()
confirm.click()
with page.expect_download() as download_info:
page.locator("#share-week-calendar").click()
assert download_info.value.suggested_filename.startswith("stackchain-week-ahead-")
expect(page.locator("#plan-today-sheet")).to_be_hidden()
page.wait_for_function("() => document.querySelector('#mobile-week-summary').textContent !== 'Loading Week Ahead…'")
assert saved and len(saved[-1]["days"]) == 1
assert saved[-1]["days"][0]["plan_date"]
assert saved and len(saved[-1]["days"]) == 7
assert [day["plan_date"] for day in saved[-1]["days"]] == sorted(
day["plan_date"] for day in saved[-1]["days"]
)
before_retirement = len(saved)
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="week"]').click()
expect(overview).to_be_visible()
planned_item = cards.first.locator(
'[data-week-open-item="issue:acme/mobile:41:"]'
)
planned_item.click()
expect(page.locator("#issue-sheet-title")).to_have_text("Ship mobile capture")
page.once("dialog", lambda dialog: dialog.accept())
page.locator("#close-issue").click()
expect(page.locator("#issue-sheet")).not_to_have_class(re.compile(r"\bopen\b"))
expect(cards.first).not_to_contain_text("Ship mobile capture")
expect(cards.first).to_contain_text("Polish desktop filters")
expect(cards.first).to_contain_text("45 of 60 min")
expect(page.locator("#week-review-status")).to_have_text(
"Ship mobile capture removed and Week Ahead saved."
)
expect(edit_week).to_be_focused()
assert len(saved) == before_retirement + 1
assert saved[-1]["days"][0]["ids"] == ["issue:acme/mobile:42:"]
assert saved[-1]["days"][0]["capacity_minutes"] == 60
pull = cards.first.locator('[data-week-pull-item="issue:acme/mobile:42:"]')
expect(pull).to_have_text("Review Today · 75 of 60 min")
pull_bounds = pull.bounding_box()
assert pull_bounds and pull_bounds["height"] >= 44
page.once("dialog", lambda dialog: dialog.dismiss())
pull.click()
expect(cards.first).to_contain_text("Polish desktop filters")
assert pulled == [], "cancelling the overload review must not submit"
expect(pull).to_have_text("Review Today · 75 of 60 min")
page.once("dialog", lambda dialog: dialog.accept())
pull.click()
expect(cards.first).not_to_contain_text("Polish desktop filters")
expect(page.locator("#week-review-status")).to_have_text(
"Polish desktop filters added to Today."
)
assert pulled and pulled[-1]["identity"] == "issue:acme/mobile:42:"
assert pulled[-1]["today_revision"] == 3
assert pulled[-1]["allow_over_capacity"] is True
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
browser.close()
finally:
fake.shutdown()
fake.server_close()
thread.join(timeout=5)
@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
def test_release_artifact_reconciles_only_the_week_day_changed_on_both_devices(
tmp_path: Path, width: int, height: int
):
archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
assert len(archives) == 1, "browser job must download exactly one assembled release archive"
fake = FakeGiteaServer(("127.0.0.1", 0))
thread = threading.Thread(target=fake.serve_forever, daemon=True)
thread.start()
puts: list[dict] = []
try:
with release_server(archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}") as origin, sync_playwright() as playwright:
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
page = browser.new_page(viewport={"width": width, "height": height})
page_errors: list[str] = []
page.on("pageerror", lambda error: page_errors.append(str(error)))
def week_route(route):
if route.request.method == "PUT":
body = json.loads(route.request.post_data or "{}")
puts.append(body)
if len(puts) == 1:
route.fulfill(status=409, content_type="application/json", body='{"message":"changed"}')
return
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"revision": 6, "timezone": body["timezone"], "days": body["days"],
}))
return
if puts:
changed_date = puts[0]["days"][0]["plan_date"]
following_date = (date.fromisoformat(changed_date) + timedelta(days=1)).isoformat()
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"revision": 5, "timezone": puts[0]["timezone"], "days": [
{"plan_date": changed_date, "ids": [], "capacity_minutes": 90, "estimates": {}},
{"plan_date": following_date, "ids": [], "capacity_minutes": 30, "estimates": {}},
],
}))
return
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"revision": 4, "timezone": None, "days": [],
}))
page.route("**/api/v1/week", week_route)
page.goto(origin + "/", wait_until="networkidle")
page.locator('input[name="device_label"]').fill("Week conflict release phone")
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
page.locator("#submit-sign-in").click()
page.wait_for_url(origin + "/", wait_until="networkidle")
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="week"]').click()
page.locator("#edit-week-plan").click()
page.locator("#plan-today-available").fill("60")
page.locator("#save-today-plan").click()
page.wait_for_function("() => document.querySelector('#mobile-week-summary').textContent.includes('Conflict')")
choices = page.locator("[data-week-conflict-choice]")
expect(choices).to_have_count(2)
for index in range(2):
bounds = choices.nth(index).locator("xpath=..").bounding_box()
assert bounds and bounds["height"] >= 44
page.locator('[data-week-conflict-choice="phone"]').check()
expect(page.locator("#save-merged-week")).to_be_enabled()
page.locator("#save-merged-week").click()
expect(page.locator("#plan-today-sheet")).to_be_hidden()
assert len(puts) == 2
assert [day["capacity_minutes"] for day in puts[-1]["days"]] == [60, 30]
assert not page_errors, f"Week conflict recovery raised: {page_errors}"
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
browser.close()
finally:
fake.shutdown()
fake.server_close()
thread.join(timeout=5)
@pytest.mark.parametrize(("width", "height"), [(320, 568), (390, 844)])
def test_release_artifact_reads_the_confirmed_week_offline_then_retries_live(
tmp_path: Path, width: int, height: int
):
archives = sorted((ROOT / "dist").glob("stackchain-dashboard-*.tar.gz"))
assert len(archives) == 1, "browser job must download exactly one assembled release archive"
fake = FakeGiteaServer(("127.0.0.1", 0))
thread = threading.Thread(target=fake.serve_forever, daemon=True)
thread.start()
online = True
try:
with release_server(archives[0], tmp_path, f"http://127.0.0.1:{fake.server_port}") as origin, sync_playwright() as playwright:
browser = playwright.chromium.launch(args=["--ignore-certificate-errors"])
page = browser.new_page(viewport={"width": width, "height": height}, timezone_id="UTC")
page_errors: list[str] = []
page.on("pageerror", lambda error: page_errors.append(str(error)))
def week_route(route):
if not online:
route.fulfill(status=503, content_type="application/json", body='{"message":"offline"}')
return
route.fulfill(status=200, content_type="application/json", body=json.dumps({
"revision": 7, "timezone": "UTC", "days": [{
"plan_date": (date.today() + timedelta(days=1)).isoformat(),
"ids": ["issue:acme/mobile:41:"], "capacity_minutes": 60,
"estimates": {"issue:acme/mobile:41:": 30},
}],
}))
page.route("**/api/v1/week", week_route)
page.goto(origin + "/", wait_until="networkidle")
page.locator('input[name="device_label"]').fill("Offline Week Ahead phone")
page.locator('input[name="access_token"]').fill(ACCESS_TOKEN)
page.locator("#submit-sign-in").click()
page.wait_for_url(origin + "/", wait_until="networkidle")
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="week"]').click()
expect(page.locator("#week-review-days")).to_contain_text("Ship mobile capture")
page.locator("#cancel-plan-today").click()
online = False
page.locator('[data-mobile-task="queues"]').click()
page.locator('[data-mobile-queue="week"]').click()
notice = page.locator("#week-offline-snapshot")
expect(notice).to_be_visible()
expect(notice).to_contain_text("Offline snapshot")
expect(page.locator("#week-review-days")).to_contain_text("Ship mobile capture")
expect(page.locator("[data-week-edit-day]")).to_have_count(0)
expect(page.locator("#edit-week-plan")).to_be_hidden()
expect(page.locator("#open-week-capacity-import")).to_be_hidden()
retry = page.locator("#retry-week-live")
expect(retry).to_be_visible()
bounds = retry.bounding_box()
assert bounds and bounds["height"] >= 44
assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth")
online = True
retry.click()
expect(notice).to_be_hidden()
expect(page.locator("#edit-week-plan")).to_be_visible()
expect(page.locator("[data-week-edit-day]")).to_have_count(7)
assert not page_errors, f"offline Week Ahead recovery raised: {page_errors}"
browser.close()
finally:
fake.shutdown()
fake.server_close()
thread.join(timeout=5)
+9
View File
@@ -61,6 +61,7 @@ def test_release_promotion_waits_for_packaged_mobile_journeys():
assert (
"python3 -m pytest tests/e2e/test_mobile_offline_issue_release.py "
"tests/e2e/test_mobile_search_preview_navigation.py "
"tests/e2e/test_mobile_search_week_plan.py "
"tests/e2e/test_mobile_find_work_release.py "
"tests/e2e/test_mobile_home_bootstrap_release.py "
"tests/e2e/test_mobile_sign_out_release.py "
@@ -69,6 +70,14 @@ def test_release_promotion_waits_for_packaged_mobile_journeys():
"tests/e2e/test_mobile_today_summary_release.py "
"tests/e2e/test_mobile_tomorrow_conflict_release.py "
"tests/e2e/test_mobile_week_ahead_release.py "
"tests/e2e/test_mobile_today_week_reschedule_release.py "
"tests/e2e/test_mobile_wrap_up_handoff_release.py -q"
) in browser
assert "needs: [lint, build-release, browser-journey]" in release
def test_browser_job_runs_packaged_today_week_reschedule_journey():
text = WORKFLOW.read_text()
browser = text[text.index(" browser-journey:") : text.index(" release-candidate:")]
assert "tests/e2e/test_mobile_today_week_reschedule_release.py" in browser
+1 -1
View File
@@ -303,4 +303,4 @@ async def test_unread_update_offers_reply_mark_read_and_next_independent_of_toda
assert '.update-reply-actions { display:grid; grid-template-columns:repeat(2,minmax(0,1fr));' in html
assert '.update-reply-actions button { min-height:44px;' in html
worker = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
assert "stackchain-dashboard-shell-v126" in worker
assert "stackchain-dashboard-shell-v130" in worker
+1 -1
View File
@@ -435,5 +435,5 @@ async def test_dashboard_syncs_every_later_change_and_exposes_account_status():
def test_later_sync_ships_atomically_in_the_offline_shell():
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/later-sync.js'" in source
+1 -1
View File
@@ -256,4 +256,4 @@ def test_markdown_work_bodies_are_mobile_safe_block_containers():
assert ".markdown-content { min-width:0; max-width:100%; overflow-wrap:anywhere;" in css
assert ".markdown-content pre { max-width:100%; overflow-x:auto;" in css
assert ".markdown-content a { min-height:44px;" in css
assert "stackchain-dashboard-shell-v126" in worker
assert "stackchain-dashboard-shell-v130" in worker
+1 -1
View File
@@ -45,7 +45,7 @@ def test_offline_shell_contains_every_local_dashboard_runtime_asset():
shell_assets = set(re.findall(r"BASE \+ '([^']+)'", worker.split("async function sessionCsrf", 1)[0]))
assert local_assets <= shell_assets, f"Offline shell is missing: {sorted(local_assets - shell_assets)}"
assert "stackchain-dashboard-shell-v126" in worker
assert "stackchain-dashboard-shell-v130" in worker
def test_all_conversation_composers_offer_accessible_mobile_mentions():
+1 -1
View File
@@ -383,7 +383,7 @@ def test_mobile_dashboard_mounts_phone_safe_device_setup_flow():
assert "controller.recoverPermission('deadline')" in dashboard
assert "pushControllerReady.then(ensureDeviceSetup)" in dashboard
assert "BASE + 'static/mobile-device-setup.js'" in worker
assert "stackchain-dashboard-shell-v126" in worker
assert "stackchain-dashboard-shell-v130" in worker
assert ".device-setup-panel" in css
assert ".device-readiness-card" in css
assert "overflow-x:hidden" in css
+1 -1
View File
@@ -243,5 +243,5 @@ async def test_mobile_home_progressively_discloses_secondary_panels_as_insights(
def test_mobile_insights_rolls_into_the_offline_shell():
worker = (CONTROLLER.parent / "service-worker.js").read_text()
assert "stackchain-dashboard-shell-v126" in worker
assert "stackchain-dashboard-shell-v130" in worker
assert "BASE + 'static/mobile-insights.js'" in worker
+1 -1
View File
@@ -358,7 +358,7 @@ async def test_dashboard_wires_thumb_safe_start_day_briefing_into_offline_mobile
assert ".mobile-start-day-finish { min-height:44px;" in html
assert "max-width:100%; overflow-wrap:anywhere;" in html
assert "BASE + 'static/mobile-start-day.js'" in service_worker
assert "stackchain-dashboard-shell-v126" in service_worker
assert "stackchain-dashboard-shell-v130" in service_worker
@pytest.mark.anyio
+9
View File
@@ -129,6 +129,15 @@ process.stdout.write(JSON.stringify(values));
assert result == {"--mobile-today-clearance": "168px"}
def test_visible_mobile_today_hud_reserves_measured_scroll_clearance_without_timer_class():
css = (FRONTEND / "dashboard.css").read_text()
assert (
'body:has(.mobile-today-hud:not([hidden]):not([data-overlay-hidden="true"])) '
"{ padding-bottom:calc(var(--mobile-today-clearance, 166px)"
) in css
def test_mobile_command_bar_keeps_primary_actions_visible_and_secondary_actions_modal():
html = (FRONTEND / "index.html").read_text()
css = (FRONTEND / "dashboard.css").read_text()
+1 -1
View File
@@ -7788,7 +7788,7 @@ async def test_assigned_issues_open_accessible_mobile_action_sheet_with_safe_mut
assert "window.confirm(confirmation)" in html
assert "issueController.close(selectedIssue)" in html
assert "lastMyWork.filter" in html
assert "if (issueTrigger?.isConnected) issueTrigger.focus()" in html
assert "setTimeout(()=>issueTrigger?.focus())" in html
assert "e.key === 'Escape' && selectedIssue" in html
+1 -1
View File
@@ -549,5 +549,5 @@ async def test_offline_today_issue_queues_closure_before_completing_and_advancin
admission = handler.index("await closeOfflineIssue(closing)")
sheet_close = handler.index("closeIssueSheet()")
assert admission < sheet_close
assert "Issue closure queued for reconnect." in handler
assert "Issue close queued." in handler
assert "The issue remains in Today; retry." in handler
+1 -1
View File
@@ -410,7 +410,7 @@ async def test_plan_today_wires_cancel_back_and_success_through_overlay_history(
def test_plan_today_controller_is_available_in_the_offline_shell():
source = SERVICE_WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/plan-today.js'" in source
assert "BASE + 'static/plan-today-readiness.js'" in source
assert "BASE + 'static/plan-today-preview.js'" in source
+3
View File
@@ -20,6 +20,7 @@ def _fixture(root: Path) -> None:
(root / "requirements.txt").write_text("fastapi==1.0\n")
(root / "README.md").write_text("# Stackchain\n")
(root / "scripts" / "rotate_unfiled_drafts.py").write_text("print('rotate')\n")
(root / "scripts" / "rotate_private_state.py").write_text("print('rotate private')\n")
def _commit_fixture(source: Path) -> str:
@@ -87,6 +88,7 @@ def test_release_bundle_is_reproducible_from_declared_commit(tmp_path):
"README.md",
"frontend/index.html",
"requirements.txt",
"scripts/rotate_private_state.py",
"scripts/rotate_unfiled_drafts.py",
"src/main.py",
]
@@ -98,6 +100,7 @@ def test_release_bundle_is_reproducible_from_declared_commit(tmp_path):
"frontend/index.html",
"release-manifest.json",
"requirements.txt",
"scripts/rotate_private_state.py",
"scripts/rotate_unfiled_drafts.py",
"src/main.py",
]
+83
View File
@@ -0,0 +1,83 @@
import base64
import json
import os
import sqlite3
import subprocess
import sys
from pathlib import Path
from src.saved_search_store import SavedSearchStore
ROOT = Path(__file__).resolve().parents[1]
SCRIPT = ROOT / "scripts" / "rotate_private_state.py"
def encoded(value: bytes) -> str:
return base64.b64encode(value * 32).decode()
def run_rotation(state: Path, *, tamper: bool = False):
env = {
**os.environ,
"STACKCHAIN_STATE_DIR": str(state),
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS": json.dumps(
{"old": encoded(b"o"), "next": encoded(b"n")}
),
"STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID": "next",
}
if tamper:
with sqlite3.connect(state / "saved-searches.sqlite3") as connection:
connection.execute(
"UPDATE saved_searches SET views = 'v1:tampered' WHERE login = 'timmy'"
)
return subprocess.run(
[sys.executable, str(SCRIPT)], env=env, text=True, capture_output=True
)
def test_rotation_command_rewraps_shared_store_rows_without_changing_metadata(tmp_path):
state = tmp_path / "state"
path = state / "saved-searches.sqlite3"
store = SavedSearchStore(path, encryption_key=b"o" * 32)
expected = store.replace(
"timmy",
0,
[{"id": "mine", "name": "My private work", "query": "assignee:timmy"}],
)
completed = run_rotation(state)
assert completed.returncode == 0, completed.stderr
report = json.loads(completed.stdout)
assert report["saved-searches"] == {
"current": 0,
"failed": 0,
"migrated": 1,
"total": 1,
}
with sqlite3.connect(path) as connection:
revision, payload = connection.execute(
"SELECT revision, views FROM saved_searches WHERE login = 'timmy'"
).fetchone()
assert revision == expected["revision"]
assert payload.startswith("v2:next:")
assert SavedSearchStore(
path, encryption_key=({"next": b"n" * 32}, "next")
).get("timmy") == expected
def test_rotation_command_fails_closed_and_never_prints_private_content(tmp_path):
state = tmp_path / "state"
secret = "private launch roadmap"
store = SavedSearchStore(state / "saved-searches.sqlite3", encryption_key=b"o" * 32)
store.replace("timmy", 0, [{"id": "secret", "name": secret, "query": "is:open"}])
completed = run_rotation(state, tamper=True)
assert completed.returncode == 1
report = json.loads(completed.stdout)
assert report["saved-searches"]["failed"] == 1
assert secret not in completed.stdout
assert "timmy" not in completed.stdout
assert completed.stderr == ""
+101
View File
@@ -83,6 +83,84 @@ process.stdout.write(JSON.stringify({{one,mixed:flow.releaseRepository()}}));
assert run_node(script) == {"one": "stackchain/dashboard", "mixed": None}
def test_week_batch_validates_every_row_before_claiming_and_flushes_one_staged_week():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const createWeekBatchPlan=createSearchBatchPlan.createWeekBatchPlan;
const calls=[];
const days=[
{{date:'2026-08-21',label:'Fri, Aug 21'}},
{{date:'2026-08-22',label:'Sat, Aug 22'}},
];
const state={{
'2026-08-21':{{ids:['stackchain/dashboard#1'],capacity_minutes:90,estimates:{{'stackchain/dashboard#1':30}}}},
'2026-08-22':{{ids:[],capacity_minutes:60,estimates:{{}}}},
}};
const week={{
load:async()=>{{calls.push('load');}},dates:()=>days,
day:date=>state[date],placement:id=>null,
place:(id,date,estimate,options)=>{{calls.push(['place',id,date,estimate,options.move]);state[date].ids.push(id);state[date].estimates[id]=estimate;return true;}},
flush:async()=>{{calls.push('flush');}},
}};
const items=[
{{kind:'issue',state:'open',repository:'stackchain/dashboard',number:2,title:'Two'}},
{{kind:'issue',state:'open',repository:'stackchain/api',number:3,title:'Three'}},
];
const flow=createWeekBatchPlan({{
week,identity:item=>item.repository+'#'+item.number,
prepare:async item=>{{calls.push(['claim',item.number]);return {{...item,assigned_to_me:true}};}},
}});
(async()=>{{
const invalid=await flow.run(items,{{
'stackchain/dashboard#2':{{date:'2026-08-21',estimate:25}},
'stackchain/api#3':{{date:'2026-08-22',estimate:0}},
}});
const before=calls.slice();
const planned=await flow.run(items,{{
'stackchain/dashboard#2':{{date:'2026-08-21',estimate:25}},
'stackchain/api#3':{{date:'2026-08-22',estimate:20}},
}});
process.stdout.write(JSON.stringify({{invalid,before,planned,calls}}));
}})();
"""
result = run_node(script)
assert result["invalid"]["status"] == "invalid"
assert result["invalid"]["errors"] == [{"id": "stackchain/api#3", "reason": "estimate-required"}]
assert result["before"] == ["load"]
assert result["planned"]["status"] == "planned"
assert result["planned"]["planned"] == 2
assert result["planned"]["failed"] == []
assert result["calls"].count("flush") == 1
assert [call for call in result["calls"] if isinstance(call, list) and call[0] == "claim"] == [
["claim", 2], ["claim", 3],
]
def test_week_batch_stages_details_only_for_successfully_placed_canonical_items():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
const flow=createSearchBatchPlan.createWeekBatchPlan({{
week:{{load:async()=>{{}},dates:()=>[{{date:'2026-08-21'}}],day:()=>({{ids:[],estimates:{{}}}}),
placement:()=>null,place:id=>!id.endsWith('#2'),
rememberPendingItem:(id,item)=>calls.push(['details',id,item.title]),flush:async()=>calls.push(['flush'])}},
prepare:async item=>({{...item,title:'Canonical '+item.number}}),
identity:item=>item.repository+'#'+item.number,
}});
const calls=[];const items=[
{{repository:'r',number:1,title:'Search one'}},{{repository:'r',number:2,title:'Search two'}}];
(async()=>{{const outcome=await flow.run(items,{{'r#1':{{date:'2026-08-21',estimate:20}},'r#2':{{date:'2026-08-21',estimate:30}}}});
process.stdout.write(JSON.stringify({{outcome,calls}}));}})();
"""
result = run_node(script)
assert result["outcome"] == {
"status": "partial", "planned": 1,
"failed": [{"id": "r#2", "reason": "assigned-not-planned"}],
}
assert result["calls"] == [["details", "r#1", "Canonical 1"], ["flush"]]
def test_mobile_search_exposes_touch_safe_durable_batch_planning_controls():
html = HTML.read_text()
dashboard = DASHBOARD.read_text()
@@ -124,6 +202,29 @@ def test_mobile_search_exposes_touch_safe_durable_batch_planning_controls():
assert "BASE + 'static/search-batch-plan.js'" in worker
def test_mobile_search_exposes_batch_week_review_with_per_issue_day_and_estimate_controls():
html = HTML.read_text()
dashboard = DASHBOARD.read_text()
css = CSS.read_text()
controller = SEARCH_BATCH_PLAN.read_text()
assert 'id="week-selected-search-results"' in html
assert 'id="search-week-batch-review" role="dialog" aria-modal="true"' in html
assert 'id="search-week-batch-list"' in html
assert 'id="search-week-batch-summary" aria-live="polite"' in html
assert 'id="cancel-search-week-batch"' in html
assert 'id="confirm-search-week-batch"' in html
assert "createWeekBatchPlan" in controller
assert "data-search-week-batch-date" in controller
assert "data-search-week-batch-estimate" in controller
assert "overload-confirmation-required" in controller
assert "weekPlan, localStorage" in dashboard
assert ".search-week-batch-review" in css
assert "max-height:calc(100dvh - 48px)" in css
assert "min-height:44px" in css
assert "env(safe-area-inset-bottom)" in css
def test_selected_search_issues_choose_one_future_time_before_durable_batch_defer():
script = f"""
const createSearchBatchPlan=require({json.dumps(str(SEARCH_BATCH_PLAN))});
+124
View File
@@ -0,0 +1,124 @@
import json
import subprocess
from pathlib import Path
FRONTEND = Path(__file__).parents[1] / "frontend"
MODULE = FRONTEND / "search-week-plan.js"
def run_planner(scenario: str) -> dict:
harness = f"""
const createSearchWeekPlan = require({json.dumps(str(MODULE))});
(async()=>{{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}});
"""
completed = subprocess.run(["node", "-e", harness], check=True, capture_output=True, text=True)
return json.loads(completed.stdout)
def test_search_week_plan_previews_seven_days_and_requires_explicit_overload_confirmation():
result = run_planner("""
let claims=0,stages=0;
const days=Array.from({length:7},(_,index)=>({date:`2026-08-${21+index}`,label:`Day ${index+1}`}));
const week={load:async()=>({}),dates:()=>days,day:date=>date==='2026-08-21'
? {plan_date:date,ids:['existing'],capacity_minutes:60,estimates:{existing:50}}
: {plan_date:date,ids:[],capacity_minutes:90,estimates:{}},
placement:()=>null,place:()=>{stages+=1;return true;},flush:async()=>({revision:2})};
const planner=createSearchWeekPlan({week,claim:async item=>{claims+=1;return {...item,assigned_to_me:true,claimable:false};},
accept:item=>item,identity:item=>`issue:${item.repository}:${item.number}:`});
const detail={kind:'issue',state:'open',repository:'stackchain/dashboard',number:42,claimable:true};
const preview=await planner.preview(detail);
const invalid=await planner.plan(detail,{date:'2026-08-21',estimate:0});
const overload=await planner.plan(detail,{date:'2026-08-21',estimate:30});
console.log(JSON.stringify({preview,invalid,overload,claims,stages}));
""")
assert len(result["preview"]["days"]) == 7
assert result["preview"]["days"][0]["planned_minutes"] == 50
assert result["preview"]["days"][0]["capacity_minutes"] == 60
assert result["invalid"] == {"status": "estimate-required"}
assert result["overload"]["status"] == "overload-confirmation-required"
assert result["overload"]["planned_minutes"] == 80
assert result["claims"] == 0
assert result["stages"] == 0
def test_search_week_plan_assigns_once_then_durably_places_canonical_issue():
result = run_planner("""
let release,claims=0,places=0,flushes=0;
const week={load:async()=>({}),dates:()=>[{date:'2026-08-22',label:'Sat, Aug 22'}],
day:date=>({plan_date:date,ids:[],capacity_minutes:120,estimates:{}}),placement:()=>null,
place:(id,date,estimate)=>{places+=1;return {id,date,estimate};},flush:async()=>{flushes+=1;return {revision:3};}};
const planner=createSearchWeekPlan({week,
claim:async item=>{claims+=1;await new Promise(resolve=>{release=resolve});return {...item,assigned_to_me:true,claimable:false,title:'Canonical'};},
accept:item=>({...item,accepted:true}),identity:item=>`issue:${item.repository}:${item.number}:`});
const detail={kind:'issue',state:'open',repository:'stackchain/dashboard',number:42,claimable:true};
const first=planner.plan(detail,{date:'2026-08-22',estimate:45});
const second=planner.plan(detail,{date:'2026-08-22',estimate:45});
await Promise.resolve();release();
const outcomes=await Promise.all([first,second]);
console.log(JSON.stringify({outcomes,claims,places,flushes}));
""")
assert result["claims"] == 1
assert result["places"] == 1
assert result["flushes"] == 1
assert result["outcomes"][0] == result["outcomes"][1]
assert result["outcomes"][0]["status"] == "planned"
assert result["outcomes"][0]["item"]["accepted"] is True
def test_search_week_plan_reports_existing_placement_and_partial_assignment_truthfully():
result = run_planner("""
const base={load:async()=>({}),dates:()=>[{date:'2026-08-22',label:'Sat'}],
day:date=>({plan_date:date,ids:[],capacity_minutes:120,estimates:{}}),flush:async()=>({})};
const detail={kind:'issue',state:'open',repository:'stackchain/dashboard',number:42,claimable:true};
const existing=createSearchWeekPlan({week:{...base,placement:()=>({date:'2026-08-23',estimate:30}),place:()=>true},
claim:async item=>item,accept:item=>item,identity:()=> 'work'});
const blocked=await existing.plan(detail,{date:'2026-08-22',estimate:45});
const partial=createSearchWeekPlan({week:{...base,placement:()=>null,place:()=>false},
claim:async item=>({...item,assigned_to_me:true,claimable:false}),accept:item=>item,identity:()=> 'work'});
const failed=await partial.plan(detail,{date:'2026-08-22',estimate:45});
console.log(JSON.stringify({blocked,failed}));
""")
assert result["blocked"] == {"status": "already-planned", "date": "2026-08-23", "estimate": 30}
assert result["failed"]["status"] == "assigned-not-planned"
def test_search_week_plan_moves_without_duplicates_and_keeps_pending_sync_on_network_failure():
result = run_planner("""
const week={load:async()=>({}),dates:()=>[{date:'2026-08-22',label:'Sat'}],
day:date=>({plan_date:date,ids:[],capacity_minutes:120,estimates:{}}),
placement:()=>({date:'2026-08-21',estimate:30}),place:()=>true,
flush:async()=>{throw new Error('offline');}};
const planner=createSearchWeekPlan({week,claim:async item=>item,accept:item=>item,identity:()=> 'work'});
const outcome=await planner.plan({kind:'issue',state:'open',assigned_to_me:true},
{date:'2026-08-22',estimate:45,move:true});
console.log(JSON.stringify(outcome));
""")
assert result == {"status": "planned-pending", "date": "2026-08-22", "estimate": 45}
def test_search_week_plan_stages_canonical_details_before_flushing():
result = run_planner("""
const calls=[];
const week={load:async()=>({}),dates:()=>[{date:'2026-08-22',label:'Sat'}],
day:date=>({plan_date:date,ids:[],capacity_minutes:120,estimates:{}}),placement:()=>null,
place:(id)=>{calls.push(['place',id]);return true;},
rememberPendingItem:(id,item)=>{calls.push(['details',id,item.title,item.repository,item.number]);return true;},
flush:async()=>{calls.push(['flush']);return {revision:3};}};
const planner=createSearchWeekPlan({week,claim:async item=>({...item,title:'Canonical title'}),
accept:item=>({...item,accepted:true}),identity:item=>`issue:${item.repository}:${item.number}:`});
const outcome=await planner.plan({kind:'issue',state:'open',repository:'stackchain/dashboard',number:42,claimable:true},
{date:'2026-08-22',estimate:45});
console.log(JSON.stringify({outcome,calls}));
""")
assert result["outcome"]["status"] == "planned"
assert result["calls"] == [
["place", "issue:stackchain/dashboard:42:"],
["details", "issue:stackchain/dashboard:42:", "Canonical title", "stackchain/dashboard", 42],
["flush"],
]
+51
View File
@@ -0,0 +1,51 @@
from pathlib import Path
from src.frontend_bundle import build_frontend
ROOT = Path(__file__).parents[1]
FRONTEND = ROOT / "frontend"
def test_search_preview_exposes_accessible_plan_ahead_sheet_and_packaged_controller():
html = (FRONTEND / "index.html").read_text()
build = build_frontend(FRONTEND)
assert 'id="plan-search-result"' in html
assert 'id="search-week-plan-sheet" role="dialog" aria-modal="true"' in html
assert 'aria-labelledby="search-week-plan-title"' in html
assert 'id="search-week-plan-days"' in html
assert 'id="search-week-plan-estimate"' in html
assert 'id="confirm-search-week-plan"' in html
assert 'id="cancel-search-week-plan"' in html
assert "static/search-week-plan.js" in build.page_sources
assert b"createSearchWeekPlan" in build.feature_bundles["planning"].runtime_bytes
def test_search_plan_ahead_ui_connects_eligibility_preview_and_truthful_outcomes():
dashboard = (FRONTEND / "dashboard.js").read_text()
source = (FRONTEND / "search-week-plan.js").read_text()
assert "const searchWeekPlan = createSearchWeekPlan" in dashboard
assert "createSearchWeekPlanUI" in dashboard
assert "planButton.hidden = !searchWeekPlan.eligible(detail)" in dashboard
assert "await planner.preview(detail)" in source
assert "overload-confirmation-required" in source
assert "assigned-not-planned" in source
assert "planned-pending" in source
assert "Already planned for" in source
assert "planner.pending()" in source
assert "searchWeekPlan:true" in source
assert "if(!qs('#search-week-plan-sheet').hidden)" in source
assert "window.history.back()" in source
def test_search_plan_ahead_sheet_is_phone_safe_and_touch_sized():
css = (FRONTEND / "dashboard.css").read_text()
assert ".search-week-plan-sheet" in css
assert "padding-bottom:calc(18px + env(safe-area-inset-bottom))" in css
assert ".search-week-plan-days button" in css
assert "min-height:44px" in css
assert "overflow-x:hidden" in css
assert "@media (max-width:359px)" in css
+33 -14
View File
@@ -177,16 +177,31 @@ async function dispatchPush(payload) {{
return json.loads(completed.stdout)
def test_week_unplan_undo_rolls_the_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/week-plan.js'" in source
assert "BASE + 'static/dashboard.css'" in source
def test_private_today_action_mailbox_rolls_the_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
def test_per_day_week_conflict_ui_rolls_the_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/week-plan.js'" in source
def test_resumable_today_session_ships_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/my-work.js'" in source
assert "BASE + 'static/dashboard.js'" in source
assert "BASE + 'static/dashboard.css'" in source
@@ -195,7 +210,7 @@ def test_resumable_today_session_ships_in_a_new_offline_shell():
def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/dashboard.js'" in source
assert "BASE + 'static/authored-outbox.js'" in source
assert "BASE + 'static/background-issue-sync.js'" in source
@@ -204,7 +219,7 @@ def test_mobile_conversation_photo_bundles_roll_the_offline_shell():
def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/issue-evidence-review.js'" in source
assert "BASE + 'static/issue-attachment.js'" in source
@@ -212,14 +227,14 @@ def test_photo_metadata_sanitizer_rolls_the_cached_optimizer_atomically():
def test_ownership_exit_runtime_rolls_the_offline_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/dashboard.js'" in source
def test_offline_review_next_ships_today_completion_atomically():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/today-completion.js'" in source
assert "BASE + 'static/dashboard.js'" in source
@@ -227,7 +242,7 @@ def test_offline_review_next_ships_today_completion_atomically():
def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/create-issue-sheet.js'" in source
assert "BASE + 'static/dashboard.js'" in source
@@ -235,7 +250,7 @@ def test_duplicate_aware_capture_ships_in_a_new_offline_shell():
def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/issue-sheet.js'" in source
assert "BASE + 'static/checklist-conflict.js'" in source
assert "BASE + 'static/dashboard.js'" in source
@@ -245,14 +260,14 @@ def test_inline_checklist_step_flow_rolls_the_offline_shell_atomically():
def test_exact_later_picker_ships_atomically_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/later-picker.js'" in source
def test_navigation_deadline_ships_in_a_new_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/dashboard.css'" in source
assert "BASE + 'static/dashboard.js'" in source
assert "BASE + 'static/install-app.js'" in source
@@ -261,21 +276,21 @@ def test_navigation_deadline_ships_in_a_new_shell_cache():
def test_today_convergence_ships_in_a_new_shell_cache():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/today-sync.js'" in source
def test_mobile_search_viewport_ships_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/mobile-search-viewport.js'" in source
def test_update_ownership_flow_ships_atomically_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/update-ownership.js'" in source
@@ -1245,7 +1260,7 @@ def test_one_session_bound_csrf_proof_is_reused_for_a_background_drain():
def test_queue_today_ships_atomically_in_a_new_offline_shell():
source = WORKER.read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/queue-today.js'" in source
@@ -1321,7 +1336,11 @@ def test_install_precaches_complete_subpath_scoped_app_shell():
"/dashboard/static/plan-today-readiness.js",
"/dashboard/static/plan-today-preview.js",
"/dashboard/static/tomorrow-plan.js",
"/dashboard/static/week-calendar.js",
"/dashboard/static/week-calendar-import.js",
"/dashboard/static/week-plan.js",
"/dashboard/static/today-week-reschedule.js",
"/dashboard/static/search-week-plan.js",
"/dashboard/static/today-sync.js",
"/dashboard/static/today-rollover.js",
"/dashboard/static/update-ownership.js",
+7 -4
View File
@@ -281,15 +281,18 @@ async def test_authenticated_device_can_enable_start_day_reminders(tmp_path, mon
@pytest.mark.anyio
async def test_worker_snapshot_reads_the_confirmed_accounts_tomorrow_plan(monkeypatch):
async def test_worker_snapshot_reads_the_confirmed_accounts_next_planned_day(monkeypatch):
async def current_user():
return {"login": "Timmy"}
class Store:
def get_tomorrow(self, login):
def get_start_day_plan(self, login):
assert login == "Timmy"
return {"ids": ["one"], "plan_date": "2026-08-20"}
def get_tomorrow(self, _login):
raise AssertionError("the worker must use Week Ahead discovery")
monkeypatch.setattr(main, "current_user", current_user)
monkeypatch.setattr(main, "_today_store", lambda: Store())
@@ -308,7 +311,7 @@ def test_mobile_settings_and_launch_route_wire_start_day_into_existing_promotion
assert 'id="device-setup-start-day"' in html
assert "startDayControl:qs('#push-start-day')" in dashboard
assert "startDayHour:qs('#push-start-day-hour')" in dashboard
assert "window.location.hash === '#/my-work/start-day'" in dashboard
assert "weekWorkflow.promote(plan).finally(() =>" in dashboard
assert "window.location.hash !== '#/my-work/start-day'" in dashboard
assert "weekFlow.promote(plan).finally(() =>" in dashboard
assert "onRemotePlan: async plan =>" not in dashboard
assert "openMobileStartDay()" in dashboard
+119
View File
@@ -0,0 +1,119 @@
import base64
import json
import sqlite3
import pytest
from src.today_store import TodayStore
from src.state_encryption import (
PrivateStateCipher,
PrivateStateEncryptionError,
decode_private_state_encryption_keyring,
private_state_encryption_config,
)
def encoded(byte: bytes) -> str:
return base64.b64encode(byte * 32).decode()
def test_keyring_writes_active_versioned_envelope_and_reads_it_current():
keys, active = decode_private_state_encryption_keyring(
json.dumps({"old": encoded(b"o"), "next": encoded(b"n")}), "next"
)
cipher = PrivateStateCipher(keys, active_key_id=active, store="today")
payload = cipher.seal({"ids": [7]}, binding="timmy")
assert payload.startswith("v2:next:")
assert cipher.open(payload, binding="timmy") == ({"ids": [7]}, False)
def test_keyring_reads_legacy_v1_and_marks_it_for_rewrap():
legacy = PrivateStateCipher(b"o" * 32, store="today")
payload = legacy.seal({"ids": [7]}, binding="timmy")
rotating = PrivateStateCipher(
{"old": b"o" * 32, "next": b"n" * 32},
active_key_id="next",
store="today",
)
assert rotating.open(payload, binding="timmy") == ({"ids": [7]}, True)
def test_keyring_reads_inactive_v2_and_marks_it_for_rewrap():
old = PrivateStateCipher(
{"old": b"o" * 32, "next": b"n" * 32},
active_key_id="old",
store="today",
)
payload = old.seal({"ids": [7]}, binding="timmy")
rotating = PrivateStateCipher(
{"old": b"o" * 32, "next": b"n" * 32},
active_key_id="next",
store="today",
)
assert rotating.open(payload, binding="timmy") == ({"ids": [7]}, True)
def test_keyring_fails_closed_for_unknown_key_id():
cipher = PrivateStateCipher(
{"next": b"n" * 32}, active_key_id="next", store="today"
)
with pytest.raises(PrivateStateEncryptionError, match="could not be decrypted"):
cipher.open("v2:retired:AAAA", binding="timmy")
def test_keyring_configuration_is_bounded_and_requires_active_key():
with pytest.raises(PrivateStateEncryptionError, match="active key"):
decode_private_state_encryption_keyring(
json.dumps({"old": encoded(b"o")}), "missing"
)
with pytest.raises(PrivateStateEncryptionError, match="at most 4"):
decode_private_state_encryption_keyring(
json.dumps({str(i): encoded(bytes([65 + i])) for i in range(5)}), "0"
)
def test_environment_prefers_keyring_and_keeps_single_key_rollout(monkeypatch):
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEY", encoded(b"l"))
monkeypatch.delenv("STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS", raising=False)
monkeypatch.delenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", raising=False)
assert private_state_encryption_config() == b"l" * 32
monkeypatch.setenv(
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS",
json.dumps({"legacy": encoded(b"l"), "next": encoded(b"n")}),
)
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "next")
keys, active = private_state_encryption_config()
assert keys == {"legacy": b"l" * 32, "next": b"n" * 32}
assert active == "next"
def test_today_store_reads_and_lazily_rewraps_v2_state_during_rotation(tmp_path, monkeypatch):
path = tmp_path / "today.sqlite3"
legacy = TodayStore(path, encryption_key=b"l" * 32)
legacy.apply("timmy", "seed", "add", "issue:stackchain/dashboard#1237")
monkeypatch.setenv(
"STACKCHAIN_PRIVATE_STATE_ENCRYPTION_KEYS",
json.dumps({"legacy": encoded(b"l"), "next": encoded(b"n")}),
)
monkeypatch.setenv("STACKCHAIN_PRIVATE_STATE_ACTIVE_KEY_ID", "next")
rotating = TodayStore(path)
assert rotating.get("timmy")["ids"] == ["issue:stackchain/dashboard#1237"]
assert rotating.apply(
"timmy", "add-next", "add", "issue:stackchain/dashboard#1238"
)["ids"] == [
"issue:stackchain/dashboard#1237",
"issue:stackchain/dashboard#1238",
]
with sqlite3.connect(path) as connection:
payload = connection.execute(
"SELECT ids FROM today_plans WHERE login = 'timmy'"
).fetchone()[0]
assert payload.startswith("v2:next:")
+79 -5
View File
@@ -185,12 +185,86 @@ process.stdout.write(JSON.stringify({{opened,cancelled,started,expired,final:{{c
}
def test_confirming_the_account_renders_a_persisted_break_immediately():
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
confirmation = dashboard.split("if (activeFlushLogin) {", 1)[1].split("}", 1)[0]
def test_identity_ready_restore_renders_break_again_after_sync_recovery_settles():
script = f"""
const createBreak = require({json.dumps(str(BREAK))});
global.createTodayBreak = createBreak;
global.setInterval = () => 1;
global.clearInterval = () => {{}};
Date.now = () => 100000;
const createTimer = require({json.dumps(str(TIMER))});
const createSync = require({json.dumps(str(ROOT / "frontend" / "today-sync.js"))});
const values = new Map();
const storage = {{
get length(){{return values.size;}},
key:index=>Array.from(values.keys())[index]??null,
getItem:key=>values.get(key)||null,
setItem:(key,value)=>values.set(key,value),
removeItem:key=>values.delete(key),
}};
let login = '';
values.set('stackchain.today-timer.v1.timmy', JSON.stringify({{
version:1, active_identity:'issue:r:42:',
entries:{{'issue:r:42:':{{elapsed_ms:12000,started_at:null,running:false}}}},
away_at:null,pending_interruption:null,attention_interruption:null,capture_interruption:null,
search_interruption:null,detour_interruption:null,
timed_break:{{identity:'issue:r:42:',deadline_at:400000}},
}}));
const status = {{hidden:false,textContent:''}}, resume = {{hidden:false,addEventListener(){{}}}};
const opener = {{hidden:false,addEventListener(){{}}}};
const elements = {{'#today-break-status':[status],'#resume-today-break':[resume],'[data-today-break-open]':[opener]}};
const timer = createTimer({{storage,getLogin:()=>login,now:()=>100000}});
const view = createTimer.createView({{
timer,isActive:()=>true,queryAll:selector=>elements[selector]||[],
formatEstimate:value=>String(value),getItem:()=>({{title:'Ship mobile capture'}}),
}});
login = 'timmy';
values.set('stackchain.today-sync.v1.timmy.operation.broken', '{{not-json');
const statuses = [];
const sync = createSync({{
storage,getLogin:()=>login,now:()=>100000,
fetchJson:async()=>({{revision:1,ids:['issue:r:42:'],capacity_minutes:null,estimates:{{}}}}),
onStatus:(state,detail)=>statuses.push([state,detail.discarded||0]),
}});
const recovery = sync.flush();
const restoring = view.restore(recovery);
const immediate = {{hidden:status.hidden,text:status.textContent,openerHidden:opener.hidden}};
status.hidden = true; status.textContent = ''; opener.hidden = false;
restoring.then(result => {{
const settled = {{hidden:status.hidden,text:status.textContent,openerHidden:opener.hidden}};
status.hidden = true; status.textContent = ''; opener.hidden = false;
return view.restore(Promise.reject(new Error('coordinator unavailable'))).then(rejected =>
process.stdout.write(JSON.stringify({{
immediate, settled, rejectedSettled:{{hidden:status.hidden,text:status.textContent,openerHidden:opener.hidden}},
result,rejected,statuses,
}}))
);
}});
"""
assert "confirmedOwnerLogin = activeFlushLogin;" in confirmation
assert "timerView.render();" in confirmation
assert run_node(script) == {
"immediate": {
"hidden": False,
"text": "On break · resume in 5:00",
"openerHidden": True,
},
"settled": {
"hidden": False,
"text": "On break · resume in 5:00",
"openerHidden": True,
},
"rejectedSettled": {
"hidden": False,
"text": "On break · resume in 5:00",
"openerHidden": True,
},
"result": True,
"rejected": True,
"statuses": [["recovered", 1]],
}
dashboard = (ROOT / "frontend" / "dashboard.js").read_text()
assert "timerView.restore(todaySync.flush());" in dashboard
def test_timed_break_is_packaged_as_an_accessible_mobile_flow():
+1 -1
View File
@@ -221,7 +221,7 @@ async def test_today_blocker_opens_existing_preview_and_preserves_readiness_gate
def test_readiness_runtime_is_available_in_offline_shell():
service_worker = SERVICE_WORKER.read_text()
assert "const CACHE = 'stackchain-dashboard-shell-v126';" in service_worker
assert "const CACHE = 'stackchain-dashboard-shell-v130';" in service_worker
assert "BASE + 'static/today-readiness.js'" in service_worker
+12
View File
@@ -132,6 +132,18 @@ process.stdout.write(JSON.stringify({{date:rollover.localDate(),zone:rollover.ti
assert run_node(script) == {"date": "2026-11-01", "zone": "America/New_York"}
def test_invalid_runtime_timezone_falls_back_to_utc_without_breaking_planners():
script = f"""
const create = require({json.dumps(str(ROLLOVER))});
const rollover = create({{
now:()=>new Date('2026-08-20T23:30:00Z'),
resolvedTimeZone:()=> 'Etc/Unknown'
}});
process.stdout.write(JSON.stringify({{date:rollover.localDate(),zone:rollover.timeZone()}}));
"""
assert run_node(script) == {"date": "2026-08-20", "zone": "UTC"}
def test_rollover_is_one_durable_sync_operation_with_the_server_revision():
script = f"""
const createSync = require({json.dumps(str(SYNC))});
+1 -1
View File
@@ -343,7 +343,7 @@ listeners['stackchain:first-task-complete']();
def test_inflight_today_drain_ships_in_a_new_offline_shell():
source = (Path(__file__).parents[1] / "frontend" / "service-worker.js").read_text()
assert "stackchain-dashboard-shell-v126" in source
assert "stackchain-dashboard-shell-v130" in source
assert "BASE + 'static/today-sync.js'" in source
+281
View File
@@ -0,0 +1,281 @@
import json
import subprocess
from pathlib import Path
CONTROLLER = Path(__file__).parents[1] / "frontend" / "today-week-reschedule.js"
INDEX = CONTROLLER.parent / "index.html"
CSS = CONTROLLER.parent / "dashboard.css"
DASHBOARD = CONTROLLER.parent / "dashboard.js"
BUNDLE = CONTROLLER.parents[1] / "src" / "frontend_bundle.py"
def run_controller(scenario: str) -> dict:
harness = f"""
const createReschedule = require({json.dumps(str(CONTROLLER))});
(async()=>{{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}});
"""
completed = subprocess.run(
["node", "-e", harness], check=True, capture_output=True, text=True
)
return json.loads(completed.stdout)
def test_reschedule_controller_reviews_load_and_atomically_confirms_selected_day():
result = run_controller("""
const requests=[];
const weekState={revision:7,offline_snapshot:false,days:[]};
const review={days:[
{plan_date:'2026-08-24',label:'Mon, Aug 24',ids:['one'],planned_minutes:30,capacity_minutes:60,overloaded:false},
{plan_date:'2026-08-25',label:'Tue, Aug 25',ids:[],planned_minutes:0,capacity_minutes:90,overloaded:false}
]};
const week={load:async()=>weekState,review:()=>review,adopt:value=>{weekState.revision=value.revision;weekState.days=value.days;}};
const api=async(url,options)=>{
if(url==='api/v1/today')return {revision:4,ids:['active','other'],estimates:{active:45}};
requests.push({url,body:JSON.parse(options.body)});return {
today:{revision:5,ids:['other'],capacity_minutes:120,estimates:{other:20}},
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}
};};
let adoptedToday=null;
const controller=createReschedule({week,api,getToday:()=>({revision:4,ids:['active','other'],estimates:{active:45}}),
adoptToday:value=>{adoptedToday=value;},operationId:()=> 'move-active'});
const opened=await controller.open('active');
const confirmed=await controller.confirm('2026-08-25',45);
console.log(JSON.stringify({opened,confirmed,requests,adoptedToday,weekState}));
""")
assert result["opened"]["estimate_minutes"] == 45
assert result["opened"]["days"][0]["load"] == "30 / 60 min"
assert result["opened"]["days"][1]["eligible"] is True
assert result["requests"] == [{
"url": "api/v1/week/reschedule",
"body": {
"operation_id": "move-active",
"identity": "active",
"estimate_minutes": 45,
"plan_date": "2026-08-25",
"today_revision": 4,
"week_revision": 7,
"allow_over_capacity": False,
},
}]
assert result["adoptedToday"]["ids"] == ["other"]
assert result["weekState"]["revision"] == 8
assert result["confirmed"]["today"]["revision"] == 5
def test_reschedule_controller_blocks_offline_full_and_overloaded_days_without_mutation():
result = run_controller("""
let calls=0;
const days=[
{plan_date:'2026-08-24',label:'Mon',ids:['1','2','3','4','5'],planned_minutes:50,capacity_minutes:60},
{plan_date:'2026-08-25',label:'Tue',ids:['1'],planned_minutes:50,capacity_minutes:60}
];
const week={load:async()=>({revision:2,offline_snapshot:false}),review:()=>({days}),adopt:()=>{}};
const api=async url=>{if(url==='api/v1/today')return {revision:3,ids:['active'],estimates:{active:30}};calls++;};
const controller=createReschedule({week,api,getToday:()=>({revision:3,ids:['active'],estimates:{active:30}})});
const opened=await controller.open('active');
let fullError='',overError='';
try{await controller.confirm('2026-08-24',30);}catch(error){fullError=error.message;}
try{await controller.confirm('2026-08-25',30);}catch(error){overError=error.message;}
const offline=createReschedule({week:{load:async()=>({revision:2,offline_snapshot:true,days:[]}),review:()=>({days})},api,getToday:()=>({revision:3,ids:['active'],estimates:{active:30}})});
let offlineOpened=null;try{offlineOpened=await offline.open('active');}catch(_error){}
console.log(JSON.stringify({opened,fullError,overError,offlineOpened,calls}));
""")
assert result["opened"]["days"][0]["eligible"] is False
assert result["fullError"] == "That Week Ahead day already has five items."
assert result["overError"] == "That move exceeds the day's capacity. Confirm overload before rescheduling."
assert result["offlineOpened"]["offline"] is True
assert result["calls"] == 0
def test_reschedule_controller_persists_offline_move_before_optimistic_adoption():
result = run_controller("""
const values=new Map();
const events=[];
const storage={
getItem:key=>values.get(key)||null,
setItem:(key,value)=>{events.push('persist');values.set(key,value);},
removeItem:key=>values.delete(key),
};
const today={revision:4,ids:['active','other'],capacity_minutes:120,estimates:{active:45,other:20}};
const weekState={revision:7,timezone:'UTC',offline_snapshot:true,days:[
{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}
]};
const week={load:async()=>weekState,review:()=>({days:[
{plan_date:'2026-08-25',label:'Tue',ids:[],planned_minutes:0,capacity_minutes:90,estimates:{}}
]}),adopt:value=>events.push(['week',value])};
const api=async()=>{const error=new Error('offline');error.status=0;throw error;};
const controller=createReschedule({week,api,getToday:()=>today,adoptToday:value=>events.push(['today',value]),
storage,getLogin:()=> 'Timmy',operationId:()=> 'move-active',now:()=>123});
const opened=await controller.open('active');
const confirmed=await controller.confirm('2026-08-25',45);
console.log(JSON.stringify({opened,confirmed,events,keys:[...values.keys()],record:JSON.parse([...values.values()][0])}));
""")
assert result["opened"]["offline"] is True
assert result["confirmed"]["sync_pending"] is True
assert result["events"][0] == "persist"
assert result["events"][1][0] == "today"
assert result["events"][1][1]["ids"] == ["other"]
assert result["events"][2][0] == "week"
assert result["events"][2][1]["days"][0]["ids"] == ["active"]
assert result["keys"] == ["stackchain.today-week-reschedule.v1.timmy"]
assert result["record"]["version"] == 2
assert result["record"]["records"][0]["body"]["operation_id"] == "move-active"
assert result["record"]["records"][0]["queued_at"] == 123
def test_reschedule_controller_restores_and_delivers_same_operation_after_reload():
result = run_controller("""
const key='stackchain.today-week-reschedule.v1.timmy';
const record={queued_at:123,body:{operation_id:'move-active',identity:'active',estimate_minutes:45,
plan_date:'2026-08-25',today_revision:4,week_revision:7,allow_over_capacity:false},
today:{revision:4,ids:['other'],estimates:{other:20}},
week:{revision:7,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}};
const values=new Map([[key,JSON.stringify(record)]]);const adopted=[];const requests=[];
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
const api=async(url,options)=>{requests.push({url,body:JSON.parse(options.body)});return {
today:{revision:5,ids:['other'],estimates:{other:20}},
week:{revision:8,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:['active'],capacity_minutes:90,estimates:{active:45}}]}};};
const controller=createReschedule({week:{adopt:value=>adopted.push(['week',value])},api,
getToday:()=>null,adoptToday:value=>adopted.push(['today',value]),storage,getLogin:()=> 'timmy'});
const restored=controller.resume();
const delivered=await controller.flush();
console.log(JSON.stringify({restored,delivered,adopted,requests,remaining:values.size}));
""")
assert result["restored"]["sync_pending"] is True
assert result["adopted"][0][0] == "today"
assert result["adopted"][1][0] == "week"
assert result["requests"][0]["body"]["operation_id"] == "move-active"
assert result["delivered"]["sync_pending"] is False
assert result["remaining"] == 0
def test_reschedule_controller_keeps_admitted_operation_when_connection_drops_on_confirm():
result = run_controller("""
const values=new Map();const events=[];
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>{events.push('persist');values.set(key,value);},removeItem:key=>values.delete(key)};
const weekState={revision:7,timezone:'UTC',days:[{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}]};
const week={load:async()=>weekState,review:()=>({days:[{...weekState.days[0],label:'Tue',planned_minutes:0}]}),
adopt:value=>events.push(['week',value])};
let calls=0;const api=async url=>{if(url==='api/v1/today')return {revision:4,ids:['active'],estimates:{active:45}};
calls++;const error=new Error('connection dropped');error.status=0;throw error;};
const controller=createReschedule({week,api,getToday:()=>null,adoptToday:value=>events.push(['today',value]),
storage,getLogin:()=> 'timmy',operationId:()=> 'stable-operation'});
await controller.open('active');
const result=await controller.confirm('2026-08-25',45);
console.log(JSON.stringify({result,events,calls,pending:controller.pending()}));
""")
assert result["result"]["sync_pending"] is True
assert result["events"][0] == "persist"
assert result["calls"] == 1
assert result["pending"]["body"]["operation_id"] == "stable-operation"
def test_reschedule_controller_queues_two_offline_moves_without_replacing_the_first():
result = run_controller("""
const values=new Map();
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
let today={revision:4,ids:['active','other'],capacity_minutes:120,estimates:{active:45,other:20}};
let weekState={revision:7,timezone:'UTC',offline_snapshot:true,days:[
{plan_date:'2026-08-25',ids:[],capacity_minutes:90,estimates:{}}
]};
const confirmedWeek=JSON.parse(JSON.stringify(weekState));let loads=0;
const week={load:async()=>{loads++;weekState=JSON.parse(JSON.stringify(confirmedWeek));return weekState;},state:()=>weekState,review:()=>({days:[
{...weekState.days[0],label:'Tue',planned_minutes:Object.values(weekState.days[0].estimates).reduce((a,b)=>a+b,0)}
]}),adopt:value=>{weekState={...value,offline_snapshot:true};}};
const api=async()=>{const error=new Error('offline');error.status=0;throw error;};
let n=0;
const controller=createReschedule({week,api,getToday:()=>today,adoptToday:value=>{today=value;},
storage,getLogin:()=> 'timmy',operationId:()=> `move-${++n}`,now:()=>100+n});
await controller.open('active');
await controller.confirm('2026-08-25',45);
await controller.open('other');
const confirmed=await controller.confirm('2026-08-25',20);
const stored=JSON.parse([...values.values()][0]);
console.log(JSON.stringify({confirmed,stored,today,weekState,loads}));
""")
assert [entry["body"]["operation_id"] for entry in result["stored"]["records"]] == [
"move-1",
"move-2",
]
assert result["confirmed"]["pending_count"] == 2
assert result["today"]["ids"] == []
assert result["weekState"]["days"][0]["ids"] == ["active", "other"]
assert result["loads"] == 1
def test_reschedule_controller_drains_fifo_and_rebases_each_next_move():
result = run_controller("""
const key='stackchain.today-week-reschedule.v1.timmy';
const make=(id,identity,today,week)=>({queued_at:1,body:{operation_id:id,identity,estimate_minutes:20,
plan_date:'2026-08-25',today_revision:today,week_revision:week,allow_over_capacity:false},
today:{revision:today,ids:[]},week:{revision:week,days:[]}});
const values=new Map([[key,JSON.stringify({version:2,records:[make('move-1','one',4,7),make('move-2','two',4,7)]})]]);
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
const requests=[];let active=0,maxActive=0;
const api=async(_url,options)=>{active++;maxActive=Math.max(maxActive,active);
const body=JSON.parse(options.body);requests.push(body);await new Promise(resolve=>setTimeout(resolve,1));active--;
const step=requests.length;return {today:{revision:4+step,ids:[]},week:{revision:7+step,days:[]}};};
const controller=createReschedule({week:{adopt:()=>{}},api,adoptToday:()=>{},storage,getLogin:()=> 'timmy'});
const delivered=await controller.flush();
console.log(JSON.stringify({requests,maxActive,delivered,remaining:values.size}));
""")
assert [request["operation_id"] for request in result["requests"]] == ["move-1", "move-2"]
assert result["requests"][1]["today_revision"] == 5
assert result["requests"][1]["week_revision"] == 8
assert result["maxActive"] == 1
assert result["delivered"]["pending_count"] == 0
assert result["remaining"] == 0
def test_reschedule_controller_restores_server_truth_and_keeps_intent_on_conflict():
result = run_controller("""
const key='stackchain.today-week-reschedule.v1.timmy';
const record={queued_at:123,body:{operation_id:'move-active'},today:{revision:4,ids:[]},week:{revision:7,days:[]}};
const values=new Map([[key,JSON.stringify(record)]]);const adopted=[];
const storage={getItem:key=>values.get(key)||null,setItem:(key,value)=>values.set(key,value),removeItem:key=>values.delete(key)};
const api=async url=>{
if(url==='api/v1/week/reschedule'){const error=new Error('conflict');error.status=409;throw error;}
if(url==='api/v1/today')return {revision:9,ids:['active'],estimates:{active:45}};
return {revision:12,timezone:'UTC',days:[]};
};
const controller=createReschedule({week:{adopt:value=>adopted.push(['week',value])},api,
adoptToday:value=>adopted.push(['today',value]),storage,getLogin:()=> 'timmy'});
let message='';try{await controller.flush();}catch(error){message=error.message;}
console.log(JSON.stringify({message,adopted,pending:controller.pending(),remaining:values.size}));
""")
assert result["message"] == "Plans changed on another device. Review and retry this saved move."
assert result["adopted"][0][1]["revision"] == 9
assert result["adopted"][1][1]["revision"] == 12
assert result["pending"]["body"]["operation_id"] == "move-active"
assert result["remaining"] == 1
def test_mobile_active_today_reschedule_dialog_is_touch_safe_and_wired_into_release_bundle():
index = INDEX.read_text()
css = CSS.read_text()
dashboard = DASHBOARD.read_text()
bundle = BUNDLE.read_text()
assert 'data-work-session-reschedule-week' in index
assert 'id="today-week-reschedule"' in index
assert 'id="today-week-reschedule-days"' in index
assert 'id="today-week-reschedule-estimate"' in index
assert 'id="confirm-today-week-reschedule"' in index
assert 'id="cancel-today-week-reschedule"' in index
assert '.today-week-reschedule-days button { min-height:44px;' in css
assert '.today-week-reschedule-panel { width:min(100%,560px);' in css
assert 'x:currentTodayProgressTarget' in dashboard
assert 'restoreWhenOwned()' in CONTROLLER.read_text()
assert "runTodayTransition('next')" in dashboard
assert 'reschedule:()=>({storage,getLogin})' in (CONTROLLER.parent / "week-plan.js").read_text()
assert "addEventListener('online', flushPending)" in CONTROLLER.read_text()
assert '"static/today-week-reschedule.js"' in bundle
+1 -1
View File
@@ -419,5 +419,5 @@ def test_tomorrow_plan_has_a_touch_safe_mobile_entry_and_reuses_the_ordered_plan
assert "qs('#plan-tomorrow').addEventListener('click'" in dashboard
assert "planningTomorrow ? saveTomorrowPlan(plan) : saveTodayPlan(plan)" in dashboard
assert "tomorrowPlan.load()" in dashboard
assert "weekWorkflow.promote(plan)" in dashboard
assert "weekFlow.promote(plan)" in dashboard
assert "tomorrowPlan.startLifecycle" in dashboard
+161
View File
@@ -0,0 +1,161 @@
import json
import subprocess
from pathlib import Path
WEEK_CALENDAR = Path(__file__).parents[1] / "frontend" / "week-calendar.js"
INDEX = Path(__file__).parents[1] / "frontend" / "index.html"
DASHBOARD = Path(__file__).parents[1] / "frontend" / "dashboard.js"
BUNDLE = Path(__file__).parents[1] / "src" / "frontend_bundle.py"
def run_node(source: str):
completed = subprocess.run(["node", "-e", source], capture_output=True, text=True)
assert completed.returncode == 0, completed.stderr
return json.loads(completed.stdout)
def test_week_calendar_builds_ordered_local_time_blocks_and_serializes_opaque_events():
plan = {
"timezone": "America/New_York",
"revision": 7,
"days": [{
"plan_date": "2026-08-21",
"ids": ["issue:stackchain/dashboard:12:", "pull:stackchain/api:7:"],
"capacity_minutes": 120,
"estimates": {
"issue:stackchain/dashboard:12:": 45,
"pull:stackchain/api:7:": 30,
},
}],
}
items = {
"issue:stackchain/dashboard:12:": {
"id": 401,
"title": "Plan, ship; verify",
"repository": "stackchain/dashboard",
"number": 12,
"url": "https://forge.alexanderwhitestone.com/git/stackchain/stackchain-dashboard/issues/12",
},
"pull:stackchain/api:7:": {
"title": "API release",
"repository": "stackchain/api",
"number": 7,
"url": "https://forge.alexanderwhitestone.com/git/stackchain/api/pulls/7",
},
}
source = f"""
const calendar=require({json.dumps(str(WEEK_CALENDAR))});
const plan={json.dumps(plan)}, items={json.dumps(items)};
const blocks=calendar.buildWeekBlocks(plan, {{'2026-08-21':'09:00'}}, id=>items[id]);
const text=calendar.serializeWeekCalendar(blocks, {{timezone:plan.timezone,revision:plan.revision,generatedAt:'20260820T120000Z'}});
console.log(JSON.stringify({{blocks,text}}));
"""
result = run_node(source)
assert [(block["start_time"], block["end_time"]) for block in result["blocks"]] == [
("09:00", "09:45"), ("09:45", "10:15")
]
text = result["text"]
assert "TZID:America/New_York" in text
assert "DTSTART;TZID=America/New_York:20260821T090000" in text
assert "DTEND;TZID=America/New_York:20260821T094500" in text
assert "DTSTART;TZID=America/New_York:20260821T094500" in text
assert "DTEND;TZID=America/New_York:20260821T101500" in text
assert "TRANSP:OPAQUE" in text
assert "UID:week-issue-stackchain-dashboard-12@stackchain" in text
assert "SEQUENCE:7" in text
assert "SUMMARY:Plan\\, ship\\; verify" in text
unfolded = text.replace("\r\n ", "")
assert "URL:https://forge.alexanderwhitestone.com/git/stackchain/stackchain-dashboard/issues/12" in unfolded
def test_week_calendar_reexports_update_stable_distinct_work_events():
source = f"""
const calendar=require({json.dumps(str(WEEK_CALENDAR))});
const issue={{id:'issue:stackchain/dashboard:12:',title:'Ship it',repository:'stackchain/dashboard',number:12,
plan_date:'2026-08-21',start_time:'09:00',end_time:'09:30'}};
const moved={{...issue,plan_date:'2026-08-22',start_time:'14:00',end_time:'14:30'}};
const pull={{...moved,id:'pull:stackchain/dashboard:12:'}};
const first=calendar.serializeWeekCalendar([issue],{{timezone:'UTC',revision:7,generatedAt:'20260820T120000Z'}});
const second=calendar.serializeWeekCalendar([moved,pull],{{timezone:'UTC',revision:8,generatedAt:'20260821T120000Z'}});
const events=text=>text.split('BEGIN:VEVENT').slice(1).map(value=>({{
uid:value.match(/UID:([^\\r]+)/)[1],sequence:Number(value.match(/SEQUENCE:(\\d+)/)[1])
}}));
console.log(JSON.stringify({{first:events(first),second:events(second)}}));
"""
result = run_node(source)
assert result["first"] == [{
"uid": "week-issue-stackchain-dashboard-12@stackchain",
"sequence": 7,
}]
assert result["second"] == [
{"uid": "week-issue-stackchain-dashboard-12@stackchain", "sequence": 8},
{"uid": "week-pull-stackchain-dashboard-12@stackchain", "sequence": 8},
]
def test_week_calendar_places_whole_tasks_in_imported_free_windows_and_reports_unfitted_work():
source = f"""
const calendar=require({json.dumps(str(WEEK_CALENDAR))});
const plan={{days:[{{plan_date:'2026-08-21',ids:['one','two','three'],estimates:{{one:45,two:90,three:400}}}}]}};
const items={{one:{{title:'First',repository:'r',number:1}},two:{{title:'Second',repository:'r',number:2}},
three:{{title:'Too large',repository:'r',number:3}}}};
const availability=[{{plan_date:'2026-08-21',free_windows:[{{start_time:'09:00',end_time:'10:00'}},{{start_time:'11:00',end_time:'17:00'}}]}}];
const result=calendar.buildWeekSchedule(plan,{{'2026-08-21':'09:00'}},id=>items[id],null,availability);
console.log(JSON.stringify(result));
"""
result = run_node(source)
assert [(block["id"], block["start_time"], block["end_time"]) for block in result["blocks"]] == [
("one", "09:00", "09:45"),
("two", "11:00", "12:30"),
]
assert result["blockers"] == [{
"id": "three", "title": "Too large", "plan_date": "2026-08-21", "minutes": 400
}]
def test_week_calendar_excludes_unselected_items_and_downloads_when_native_share_is_unavailable():
source = f"""
const calendar=require({json.dumps(str(WEEK_CALENDAR))});
const plan={{timezone:'UTC',revision:2,days:[{{plan_date:'2026-08-21',ids:['one','two'],capacity_minutes:60,estimates:{{one:20,two:25}}}}]}};
const items={{one:{{title:'Private',repository:'r',number:1,url:'https://forge/r/1'}},two:{{title:'Public',repository:'r',number:2,url:'https://forge/r/2'}}}};
const blocks=calendar.buildWeekBlocks(plan,{{'2026-08-21':'13:00'}},id=>items[id],new Set(['two']));
class FakeFile {{constructor(parts,name,options){{this.parts=parts;this.name=name;this.type=options.type;}}}}
const clicks=[],revoked=[];
(async()=>{{
const result=await calendar.deliverWeekCalendar({{text:'calendar',filename:'week.ics',navigator:{{}},FileCtor:FakeFile,
document:{{createElement:()=>({{click(){{clicks.push([this.download,this.href]);}}}})}},
urlApi:{{createObjectURL:()=> 'blob:week',revokeObjectURL:value=>revoked.push(value)}}}});
console.log(JSON.stringify({{blocks,result,clicks,revoked}}));
}})();
"""
result = run_node(source)
assert [block["id"] for block in result["blocks"]] == ["two"]
assert result["blocks"][0]["start_time"] == "13:00"
assert result["result"] == "downloaded"
assert result["clicks"] == [["week.ics", "blob:week"]]
assert result["revoked"] == ["blob:week"]
def test_week_calendar_handoff_is_wired_into_confirmation_with_mobile_privacy_controls():
index = INDEX.read_text()
dashboard = DASHBOARD.read_text()
bundle = BUNDLE.read_text()
assert '<script src="static/week-calendar.js"></script>' in index
assert 'id="week-calendar-handoff"' in index
assert 'id="week-calendar-days"' in index
assert 'id="share-week-calendar"' in index
assert 'id="back-to-week-review-from-calendar"' in index
assert "Titles, references, dates, and times are included" in index
assert "Imported busy time is used only until this page reloads" in index
assert "mountWeekCalendarHandoff" in WEEK_CALENDAR.read_text()
assert "weekCalendar.open(weekPlan.state())" in dashboard
assert "weekCalendar.close()" in dashboard
assert "StackchainWeekCalendar.setAvailabilityProvider(workflow.availability)" in (WEEK_CALENDAR.parent / "week-calendar-import.js").read_text()
assert "Planning around imported busy time" in WEEK_CALENDAR.read_text()
assert '"static/week-calendar.js", "static/week-calendar-import.js", "static/week-plan.js"' in bundle
+324
View File
@@ -0,0 +1,324 @@
import json
import subprocess
from pathlib import Path
MODULE = Path(__file__).parents[1] / "frontend" / "week-calendar-import.js"
FRONTEND = MODULE.parent
def run_import(scenario: str) -> dict:
harness = f"""
const calendarImport = require({json.dumps(str(MODULE))});
(async() => {{ {scenario} }})().catch(error=>{{console.error(error);process.exit(1);}})
"""
completed = subprocess.run(
["node", "-e", harness], check=True, capture_output=True, text=True
)
return json.loads(completed.stdout)
def test_calendar_import_unions_busy_time_within_working_hours_across_local_days():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:one\r\nSUMMARY:Private planning\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:two\r\nSUMMARY:Secret customer call\r\nATTENDEE:mailto:private@example.com\r\nDTSTART:20260821T103000\r\nDTEND:20260821T120000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:outside\r\nDTSTART:20260821T070000\r\nDTEND:20260821T080000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nUID:overnight\r\nLOCATION:Private office\r\nDTSTART:20260821T163000\r\nDTEND:20260822T100000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({days,serialized:JSON.stringify(days)}));
""")
assert result["days"][0] == {
"plan_date": "2026-08-21", "busy_minutes": 150, "capacity_minutes": 330,
"free_windows": [
{"start_time": "09:00", "end_time": "10:00"},
{"start_time": "12:00", "end_time": "16:30"},
],
}
assert result["days"][1] == {
"plan_date": "2026-08-22", "busy_minutes": 60, "capacity_minutes": 420,
"free_windows": [{"start_time": "10:00", "end_time": "17:00"}],
}
assert [day["capacity_minutes"] for day in result["days"][2:]] == [480] * 5
for private_value in ("Private planning", "Secret customer call", "private@example.com", "Private office"):
assert private_value not in result["serialized"]
def test_calendar_import_converts_iana_tzid_into_the_device_local_workday():
result = run_import("""
process.env.TZ='America/Los_Angeles';
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20260821T120000\r\nDTEND;TZID=America/New_York:20260821T130000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({first:days[0]}));
""")
assert result["first"]["busy_minutes"] == 60
assert result["first"]["free_windows"] == [
{"start_time": "10:00", "end_time": "17:00"},
]
def test_calendar_import_fails_closed_for_unknown_tzid_without_exposing_event_details():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nSUMMARY:Private acquisition\r\nATTENDEE:mailto:secret@example.com\r\nDTSTART;TZID=Private/Boardroom:20260821T120000\r\nDTEND;TZID=Private/Boardroom:20260821T130000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({unsupported:days.unsupported_count,busy:days.map(day=>day.busy_minutes),serialized:JSON.stringify(days)}));
""")
assert result["unsupported"] == 1
assert result["busy"] == [0] * 7
assert "Private acquisition" not in result["serialized"]
assert "secret@example.com" not in result["serialized"]
def test_calendar_import_applies_tzid_to_rdate_and_exdate_values():
result = run_import("""
process.env.TZ='America/Los_Angeles';
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20260821T120000\r\nDTEND;TZID=America/New_York:20260821T130000\r\nRRULE:FREQ=DAILY;COUNT=3\r\nEXDATE;TZID=America/New_York:20260822T120000\r\nRDATE;TZID=America/New_York:20260824T120000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes),fourth:days[3].free_windows}));
""")
assert result["busy"] == [60, 0, 60, 60, 0, 0, 0]
assert result["fourth"] == [{"start_time": "10:00", "end_time": "17:00"}]
def test_calendar_import_keeps_zoned_daily_recurrence_at_wall_time_across_dst():
result = run_import("""
process.env.TZ='UTC';
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20260307T090000\r\nDTEND;TZID=America/New_York:20260307T100000\r\nRRULE:FREQ=DAILY;COUNT=3\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-03-07','2026-03-08','2026-03-09','2026-03-10','2026-03-11','2026-03-12','2026-03-13'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({windows:days.slice(0,3).map(day=>day.free_windows)}));
""")
assert result["windows"] == [
[{"start_time": "09:00", "end_time": "14:00"}, {"start_time": "15:00", "end_time": "17:00"}],
[{"start_time": "09:00", "end_time": "13:00"}, {"start_time": "14:00", "end_time": "17:00"}],
[{"start_time": "09:00", "end_time": "13:00"}, {"start_time": "14:00", "end_time": "17:00"}],
]
def test_calendar_import_interprets_floating_until_in_the_event_timezone():
result = run_import("""
process.env.TZ='UTC';
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20260307T090000\r\nDTEND;TZID=America/New_York:20260307T100000\r\nRRULE:FREQ=DAILY;UNTIL=20260308T090000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-03-07','2026-03-08','2026-03-09','2026-03-10','2026-03-11','2026-03-12','2026-03-13'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60, 60, 0, 0, 0, 0, 0]
def test_calendar_import_fast_forwards_historical_daily_series_to_seven_day_range():
result = run_import("""
process.env.TZ='UTC';
const event=`BEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20000101T090000\r\nDTEND;TZID=America/New_York:20000101T100000\r\nRRULE:FREQ=DAILY\r\nEND:VEVENT\r\n`;
const source='BEGIN:VCALENDAR\\r\\nVERSION:2.0\\r\\n'+event.repeat(80)+'END:VCALENDAR';
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const started=Date.now();const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({elapsed:Date.now()-started,busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60] * 7
assert result["elapsed"] < 1000
def test_calendar_import_fast_forwards_historical_weekly_series_to_seven_day_range():
result = run_import("""
process.env.TZ='UTC';
const event=`BEGIN:VEVENT\r\nDTSTART;TZID=America/New_York:20000101T090000\r\nDTEND;TZID=America/New_York:20000101T100000\r\nRRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR;INTERVAL=2\r\nEND:VEVENT\r\n`;
const source='BEGIN:VCALENDAR\\r\\nVERSION:2.0\\r\\n'+event.repeat(80)+'END:VCALENDAR';
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const started=Date.now();const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({elapsed:Date.now()-started,busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [0, 0, 0, 60, 0, 60, 0]
assert result["elapsed"] < 1000
def test_calendar_import_expands_bounded_daily_recurrence_and_honors_exdate():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nUID:standup\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRRULE:FREQ=DAILY;COUNT=5\r\nEXDATE:20260823T100000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60, 60, 0, 60, 60, 0, 0]
def test_calendar_import_adds_rdates_and_excludes_matching_occurrences():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRDATE:20260823T100000,20260825T100000\r\nEXDATE:20260823T100000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60, 0, 0, 0, 60, 0, 0]
def test_calendar_import_stops_recurrence_at_until_boundary():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRRULE:FREQ=DAILY;UNTIL=20260823T100000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60, 60, 60, 0, 0, 0, 0]
def test_calendar_import_expands_weekly_recurrence_on_selected_weekdays():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRRULE:FREQ=WEEKLY;BYDAY=MO,WE,FR;COUNT=5\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [60, 0, 0, 60, 0, 60, 0]
def test_calendar_import_treats_all_day_events_as_busy_for_working_hours():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART;VALUE=DATE:20260822\r\nDTEND;VALUE=DATE:20260823\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates,workdayStart:'09:00',workdayEnd:'17:00'});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [0, 480, 0, 0, 0, 0, 0]
def test_calendar_import_ignores_cancelled_and_transparent_events():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nSTATUS:CANCELLED\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nEND:VEVENT\r\nBEGIN:VEVENT\r\nTRANSP:TRANSPARENT\r\nDTSTART:20260822T100000\r\nDTEND:20260822T110000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({busy:days.map(day=>day.busy_minutes)}));
""")
assert result["busy"] == [0] * 7
def test_calendar_import_rejects_invalid_and_oversized_files_without_returning_capacity():
result = run_import("""
const errors=[];
for(const source of ['not a calendar','BEGIN:VCALENDAR\\r\\n'+('X'.repeat(1024*1024))+'\\r\\nEND:VCALENDAR']) {
try { calendarImport.review(source,{dates:['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27']}); }
catch(error) { errors.push(error.message); }
}
console.log(JSON.stringify({errors}));
""")
assert result["errors"] == [
"Choose a valid .ics calendar file.",
"Calendar files must be 1 MB or smaller.",
]
def test_calendar_import_blocks_apply_when_recurrence_cannot_be_counted_truthfully():
result = run_import("""
const elements=new Map();
const element=(value='')=>({value,hidden:false,textContent:'',innerHTML:'',disabled:false,files:[],listeners:{},
addEventListener(name,listener){this.listeners[name]=listener;},focus(){}});
for(const selector of ['#week-capacity-import','#week-capacity-review','#week-capacity-days','#week-capacity-status',
'#week-capacity-file','#week-capacity-start','#week-capacity-end','#apply-week-capacities','#cancel-week-capacity-import'])
elements.set(selector,element());
elements.get('#week-capacity-start').value='09:00';elements.get('#week-capacity-end').value='17:00';
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
let staged=0;
const controller={dates:()=>dates.map(date=>({date,label:date})),stageCapacities:()=>{staged+=1;return true;},flush:async()=>{}};
const workflow=calendarImport.createWorkflow({controller,qs:selector=>elements.get(selector)});
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nSUMMARY:Private board review\r\nATTENDEE:mailto:secret@example.com\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRRULE:FREQ=MONTHLY;BYDAY=1FR\r\nEND:VEVENT\r\nEND:VCALENDAR`;
workflow.review(source);const applied=await workflow.apply();
console.log(JSON.stringify({disabled:elements.get('#apply-week-capacities').disabled,status:elements.get('#week-capacity-status').textContent,
markup:elements.get('#week-capacity-days').innerHTML,applied,staged}));
""")
assert result["disabled"] is True
assert result["applied"] is False
assert result["staged"] == 0
assert "1 recurring event could not be counted" in result["status"]
assert "Apply is unavailable" in result["status"]
assert "Private board review" not in json.dumps(result)
assert "secret@example.com" not in json.dumps(result)
def test_calendar_import_marks_unsupported_daily_rule_parts_instead_of_ignoring_them():
result = run_import("""
const source=`BEGIN:VCALENDAR\r\nVERSION:2.0\r\nBEGIN:VEVENT\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nRRULE:FREQ=DAILY;BYHOUR=10\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
const days=calendarImport.review(source,{dates});
console.log(JSON.stringify({unsupported:days.unsupported_count}));
""")
assert result["unsupported"] == 1
def test_calendar_import_workflow_reviews_then_applies_once_without_persisting_calendar_text():
result = run_import("""
const elements=new Map();
const element=(value='')=>({value,hidden:false,textContent:'',innerHTML:'',disabled:false,files:[],listeners:{},
addEventListener(name,listener){this.listeners[name]=listener;},focus(){this.focused=true;}});
for(const selector of ['#week-capacity-import','#week-capacity-review','#week-capacity-days','#week-capacity-status',
'#week-capacity-file','#week-capacity-start','#week-capacity-end','#apply-week-capacities','#cancel-week-capacity-import'])
elements.set(selector,element());
elements.get('#week-capacity-start').value='09:00';elements.get('#week-capacity-end').value='17:00';
const dates=['2026-08-21','2026-08-22','2026-08-23','2026-08-24','2026-08-25','2026-08-26','2026-08-27'];
let staged=[],flushes=0,appliedCalls=0;
const controller={dates:()=>dates.map((date,index)=>({date,label:'Day '+(index+1)})),
stageCapacities:value=>{staged.push(value);return {sync_pending:true};},flush:async()=>{flushes+=1;}};
const workflow=calendarImport.createWorkflow({controller,qs:selector=>elements.get(selector),onApplied:()=>{appliedCalls+=1;}});
workflow.open();
const source=`BEGIN:VCALENDAR\r\nBEGIN:VEVENT\r\nSUMMARY:Do not retain me\r\nDTSTART:20260821T100000\r\nDTEND:20260821T110000\r\nEND:VEVENT\r\nEND:VCALENDAR`;
const reviewed=workflow.review(source);
await workflow.apply();
console.log(JSON.stringify({reviewed,staged,flushes,appliedCalls,rootHidden:elements.get('#week-capacity-import').hidden,
status:elements.get('#week-capacity-status').textContent,markup:elements.get('#week-capacity-days').innerHTML,
fileValue:elements.get('#week-capacity-file').value,workflowState:workflow.state(),availability:workflow.availability()}));
""")
assert result["reviewed"][0]["capacity_minutes"] == 420
assert len(result["staged"]) == 1
assert len(result["staged"][0]) == 7
assert result["flushes"] == 1
assert result["appliedCalls"] == 1
assert result["rootHidden"] is True
assert result["fileValue"] == ""
assert result["workflowState"] is None
assert result["availability"][0] == {
"plan_date": "2026-08-21",
"free_windows": [
{"start_time": "09:00", "end_time": "10:00"},
{"start_time": "11:00", "end_time": "17:00"},
],
}
assert "free_windows" not in json.dumps(result["staged"])
assert "Do not retain me" not in json.dumps(result)
def test_week_ahead_exposes_private_calendar_capacity_import_in_the_packaged_planning_flow():
html = (FRONTEND / "index.html").read_text()
dashboard = (FRONTEND / "dashboard.js").read_text()
css = (FRONTEND / "dashboard.css").read_text()
assert 'id="open-week-capacity-import"' in html
assert 'id="week-capacity-import"' in html
assert 'id="week-capacity-file"' in html and 'accept=".ics,text/calendar"' in html
assert 'id="week-capacity-start"' in html and 'id="week-capacity-end"' in html
assert 'id="week-capacity-review"' in html
assert 'id="apply-week-capacities"' in html
assert '<script src="static/week-calendar-import.js"></script>' in html
assert html.index('static/week-calendar-import.js') < html.index('static/week-plan.js')
week_plan = (FRONTEND / "week-plan.js").read_text()
assert "weekCalendarImport.mount" in week_plan
assert "weekCalendarImport.mount" not in dashboard
assert "open-week-capacity-import" in MODULE.read_text()
assert ".week-capacity-import" in css
assert "overflow-x:hidden" in css
+528 -2
View File
@@ -4,7 +4,7 @@ from datetime import datetime, timezone
import pytest
from src import main
from src.today_store import TodayStore, WeekPlanConflict
from src.today_store import TodayPromotionConflict, TodayStore, WeekPlanConflict
def sample_days():
@@ -51,13 +51,102 @@ def test_week_plan_is_encrypted_account_scoped_revisioned_and_preserves_other_da
assert conflict.value.snapshot == updated
def test_start_day_plan_selects_earliest_nonempty_week_date_without_mutation(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"r" * 32,
clock=lambda: datetime(2026, 8, 21, 13, tzinfo=timezone.utc).timestamp(),
)
days = [
{
"plan_date": "2026-08-20", "ids": [],
"capacity_minutes": 60, "estimates": {},
},
{
"plan_date": "2026-08-21", "ids": ["issue:private/repo:7:"],
"capacity_minutes": 90,
"estimates": {"issue:private/repo:7:": 45},
},
{
"plan_date": "2026-08-22", "ids": ["issue:private/repo:8:"],
"capacity_minutes": 120,
"estimates": {"issue:private/repo:8:": 30},
},
]
week = store.replace_week(
"timmy", base_revision=0, days=days, timezone="America/New_York"
)
assert store.get_start_day_plan("Timmy") == {
**days[1], "timezone": "America/New_York",
}
assert store.get_week("timmy") == week
def test_start_day_plan_falls_back_to_tomorrow_without_migrating_it(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"r" * 32)
tomorrow = store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:private/repo:9:"],
capacity_minutes=75, estimates={"issue:private/repo:9:": 45},
plan_date="2026-08-21", timezone="UTC",
)
assert store.get_start_day_plan("timmy") == tomorrow
assert store.get_tomorrow("timmy") == tomorrow
with store._connect() as connection:
assert connection.execute(
"SELECT COUNT(*) FROM week_plans WHERE login = ?", ("timmy",)
).fetchone()[0] == 0
def test_start_day_plan_uses_due_tomorrow_fallback_before_future_week_day(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"r" * 32,
clock=lambda: datetime(2026, 8, 20, 13, tzinfo=timezone.utc).timestamp(),
)
future = [{
"plan_date": "2026-08-21", "ids": ["issue:private/repo:10:"],
"capacity_minutes": 90, "estimates": {"issue:private/repo:10:": 45},
}]
store.replace_week("timmy", base_revision=0, days=future, timezone="UTC")
tomorrow = store.replace_tomorrow(
"timmy", base_revision=0, ids=["issue:private/repo:9:"],
capacity_minutes=75, estimates={"issue:private/repo:9:": 45},
plan_date="2026-08-20", timezone="UTC",
)
assert store.get_start_day_plan("timmy") == tomorrow
def test_week_plan_rejects_the_same_work_on_multiple_dates_without_advancing_revision(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"w" * 32)
original = store.replace_week(
"timmy", base_revision=0, days=sample_days(), timezone="UTC"
)
duplicated = [
sample_days()[0],
{
"plan_date": "2026-08-22",
"ids": ["issue:secret/repo:3:"],
"capacity_minutes": 60,
"estimates": {"issue:secret/repo:3:": 30},
},
]
with pytest.raises(ValueError, match="work must be assigned to only one Week Ahead date"):
store.replace_week(
"timmy", base_revision=original["revision"], days=duplicated, timezone="UTC"
)
assert store.get_week("timmy") == original
def test_week_promotion_moves_only_due_date_to_today_exactly_once(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"p" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "today", "add", "issue:r:1:")
today = store.get("timmy")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
promoted = store.promote_week(
@@ -76,6 +165,302 @@ def test_week_promotion_moves_only_due_date_to_today_exactly_once(tmp_path):
assert remaining["days"] == [sample_days()[1]]
def test_week_early_start_moves_a_future_day_to_empty_today_exactly_once(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"e" * 32,
clock=lambda: datetime(2026, 8, 20, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.get("timmy")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
promoted = store.promote_week(
"timmy", promotion_id="early-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"], allow_future=True,
)
replay = store.promote_week(
"timmy", promotion_id="early-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"], allow_future=True,
)
assert replay == promoted
assert promoted["ids"] == sample_days()[0]["ids"]
assert promoted["plan_date"] == "2026-08-21"
assert store.get_week("timmy")["days"] == [sample_days()[1]]
def test_pull_week_item_atomically_appends_to_active_today_and_replays_exactly_once(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"i" * 32)
active_id = "issue:stackchain/dashboard:1:"
pulled_id = "issue:secret/repo:3:"
today = store.apply("timmy", "seed-active", "add", active_id)
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
result = store.pull_week_item(
"timmy", operation_id="pull-secret-3", identity=pulled_id,
today_revision=today["revision"], week_revision=week["revision"],
)
replay = store.pull_week_item(
"timmy", operation_id="pull-secret-3", identity=pulled_id,
today_revision=today["revision"], week_revision=week["revision"],
)
assert replay == result
assert result["today"]["ids"] == [active_id, pulled_id]
assert result["today"]["estimates"] == {pulled_id: 60}
assert result["week"]["days"][0]["ids"] == ["issue:secret/repo:2:"]
assert result["week"]["days"][0]["estimates"] == {"issue:secret/repo:2:": 45}
assert result["week"]["days"][1] == sample_days()[1]
assert store.get("timmy") == result["today"]
assert store.get_week("timmy") == result["week"]
def test_pull_week_item_rejects_full_or_changed_today_without_partial_write(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"f" * 32)
today = store.get("timmy")
for index in range(5):
today = store.apply("timmy", f"seed-{index}", "add", f"issue:r:{index + 1}:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
with pytest.raises(main.TodayPlanFull):
store.pull_week_item(
"timmy", operation_id="full", identity="issue:secret/repo:3:",
today_revision=today["revision"], week_revision=week["revision"],
)
with pytest.raises(TodayPromotionConflict):
store.pull_week_item(
"timmy", operation_id="stale", identity="issue:secret/repo:3:",
today_revision=today["revision"] - 1, week_revision=week["revision"],
)
assert store.get("timmy") == today
assert store.get_week("timmy") == week
def test_pull_week_item_requires_explicit_today_capacity_overload_confirmation(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"c" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
active_id = "issue:stackchain/dashboard:1:"
pulled_id = "issue:stackchain/dashboard:2:"
seed = store.replace_week(
"timmy", base_revision=0, timezone="UTC", days=[{
"plan_date": "2026-08-22", "ids": [active_id],
"capacity_minutes": 60, "estimates": {active_id: 45},
}],
)
today = store.promote_week(
"timmy", promotion_id="seed-today", week_revision=seed["revision"],
plan_date="2026-08-22", today_revision=0,
)
week = store.replace_week(
"timmy", base_revision=2, timezone="UTC", days=[{
"plan_date": "2026-08-23", "ids": [pulled_id],
"capacity_minutes": 60, "estimates": {pulled_id: 30},
}],
)
with pytest.raises(ValueError, match="explicit overload confirmation"):
store.pull_week_item(
"timmy", operation_id="unconfirmed", identity=pulled_id,
today_revision=today["revision"], week_revision=week["revision"],
)
assert store.get("timmy") == today
assert store.get_week("timmy") == week
moved = store.pull_week_item(
"timmy", operation_id="confirmed", identity=pulled_id,
today_revision=today["revision"], week_revision=week["revision"],
allow_over_capacity=True,
)
assert moved["today"]["capacity_minutes"] == 60
assert moved["today"]["estimates"] == {active_id: 45, pulled_id: 30}
def test_normal_week_promotion_still_rejects_a_future_day_without_writes(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"e" * 32,
clock=lambda: datetime(2026, 8, 20, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.get("timmy")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
with pytest.raises(main.TomorrowPlanNotDue):
store.promote_week(
"timmy", promotion_id="normal-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
)
assert store.get("timmy") == today
assert store.get_week("timmy") == week
def test_week_promotion_preserves_nonempty_today_and_the_due_week(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"p" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "active", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
with pytest.raises(TodayPromotionConflict) as blocked:
store.promote_week(
"timmy", promotion_id="week-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
)
assert blocked.value.today == today
assert blocked.value.week == week
assert store.get("timmy") == today
assert store.get_week("timmy") == week
def test_week_reconciliation_atomically_combines_today_and_consumes_only_due_day(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"c" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "active", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
result = store.reconcile_week(
"timmy", promotion_id="reconcile-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
ids=["issue:r:active:", "issue:secret/repo:3:"], capacity_minutes=120,
estimates={"issue:r:active:": 30, "issue:secret/repo:3:": 60},
)
replay = store.reconcile_week(
"timmy", promotion_id="reconcile-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
ids=["issue:r:active:", "issue:secret/repo:3:"], capacity_minutes=120,
estimates={"issue:r:active:": 30, "issue:secret/repo:3:": 60},
)
assert replay == result
assert result["today"]["ids"] == ["issue:r:active:", "issue:secret/repo:3:"]
assert result["week"]["days"] == [sample_days()[1]]
assert store.get("timmy") == result["today"]
assert store.get_week("timmy") == result["week"]
def test_week_reconciliation_rejects_work_outside_preserved_plans_without_partial_write(tmp_path):
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"c" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "active", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
with pytest.raises(ValueError, match="selected work must come from Today or the due Week Ahead day"):
store.reconcile_week(
"timmy", promotion_id="bad", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
ids=["issue:other/repo:99:"], capacity_minutes=60,
estimates={"issue:other/repo:99:": 30},
)
assert store.get("timmy") == today
assert store.get_week("timmy") == week
@pytest.mark.anyio
async def test_week_promotion_api_returns_both_preserved_plans_for_review(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(
tmp_path / "today.sqlite3",
encryption_key=b"p" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "active", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
with pytest.raises(main.HTTPException) as blocked:
await main.promote_week_plan(main.WeekPromotion(
promotion_id="week-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
))
assert blocked.value.status_code == 409
assert blocked.value.detail == {
"code": "week_today_in_progress", "today": today, "week": week,
}
@pytest.mark.anyio
async def test_week_early_start_api_promotes_a_future_day(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"a" * 32,
clock=lambda: datetime(2026, 8, 20, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.get("timmy")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
result = await main.start_week_day_early(main.WeekPromotion(
promotion_id="early-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
))
assert result["ids"] == sample_days()[0]["ids"]
assert store.get_week("timmy")["days"] == [sample_days()[1]]
@pytest.mark.anyio
async def test_pull_week_item_api_returns_both_atomic_plans(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"u" * 32)
today = store.apply("timmy", "seed", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
result = await main.pull_week_item_into_today(main.WeekItemPull(
operation_id="pull-api", identity="issue:secret/repo:3:",
week_revision=week["revision"], today_revision=today["revision"],
))
assert result["today"]["ids"] == ["issue:r:active:", "issue:secret/repo:3:"]
assert result["week"]["days"][0]["ids"] == ["issue:secret/repo:2:"]
@pytest.mark.anyio
async def test_week_reconciliation_api_returns_atomic_today_and_remaining_week(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(
tmp_path / "today.sqlite3", encryption_key=b"a" * 32,
clock=lambda: datetime(2026, 8, 22, 8, tzinfo=timezone.utc).timestamp(),
)
today = store.apply("timmy", "active", "add", "issue:r:active:")
week = store.replace_week("timmy", base_revision=0, days=sample_days(), timezone="UTC")
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
result = await main.reconcile_week_plan(main.WeekReconciliation(
promotion_id="reconcile-2026-08-21-r1", week_revision=week["revision"],
plan_date="2026-08-21", today_revision=today["revision"],
ids=["issue:r:active:", "issue:secret/repo:3:"], capacity_minutes=120,
estimates={"issue:r:active:": 30, "issue:secret/repo:3:": 60},
))
assert result["today"]["ids"] == ["issue:r:active:", "issue:secret/repo:3:"]
assert result["week"]["days"] == [sample_days()[1]]
def test_existing_tomorrow_plan_migrates_into_week_without_losing_planning_data(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"m" * 32)
tomorrow = store.replace_tomorrow(
@@ -110,3 +495,144 @@ async def test_week_api_round_trip_and_conflict_contract(monkeypatch, tmp_path):
await main.replace_week_plan(payload)
assert raised.value.status_code == 409
assert raised.value.detail == {"code": "week_changed", "snapshot": saved}
def test_reschedule_today_item_atomically_moves_it_into_selected_week_day(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"s" * 32)
active_id = "issue:stackchain/dashboard:1228:"
other_id = "issue:stackchain/dashboard:1229:"
today = store.apply("timmy", "add-active", "add", active_id)
today = store.apply("timmy", "add-other", "add", other_id)
week = store.replace_week(
"timmy",
base_revision=0,
timezone="UTC",
days=[{
"plan_date": "2026-08-24",
"ids": [active_id],
"capacity_minutes": 120,
"estimates": {active_id: 30},
}, {
"plan_date": "2026-08-25",
"ids": [],
"capacity_minutes": 90,
"estimates": {},
}],
)
result = store.reschedule_today_to_week(
"timmy",
operation_id="reschedule-active-2026-08-25",
identity=active_id,
estimate_minutes=45,
plan_date="2026-08-25",
today_revision=today["revision"],
week_revision=week["revision"],
)
assert result["today"]["ids"] == [other_id]
assert result["week"]["days"] == [{
"plan_date": "2026-08-24", "ids": [], "capacity_minutes": 120, "estimates": {},
}, {
"plan_date": "2026-08-25", "ids": [active_id], "capacity_minutes": 90,
"estimates": {active_id: 45},
}]
assert store.get("timmy") == result["today"]
assert store.get_week("timmy") == result["week"]
def test_reschedule_today_item_is_idempotent_and_rejects_stale_plans_without_partial_write(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"i" * 32)
identity = "issue:stackchain/dashboard:1228:"
today = store.apply("timmy", "add-active", "add", identity)
week = store.replace_week(
"timmy", base_revision=0, timezone="UTC",
days=[{
"plan_date": "2026-08-25", "ids": [],
"capacity_minutes": 60, "estimates": {},
}],
)
arguments = {
"operation_id": "same-operation", "identity": identity,
"estimate_minutes": 30, "plan_date": "2026-08-25",
"today_revision": today["revision"], "week_revision": week["revision"],
}
moved = store.reschedule_today_to_week("timmy", **arguments)
assert store.reschedule_today_to_week("timmy", **arguments) == moved
another = store.apply("timmy", "add-another", "add", "issue:stackchain/dashboard:1230:")
with pytest.raises(TodayPromotionConflict) as conflict:
store.reschedule_today_to_week(
"timmy", **{**arguments, "operation_id": "stale-operation", "identity": another["ids"][-1]}
)
assert conflict.value.today == another
assert store.get_week("timmy") == moved["week"]
def test_reschedule_today_item_requires_explicit_capacity_overload_confirmation(tmp_path):
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"o" * 32)
identity = "issue:stackchain/dashboard:1228:"
today = store.apply("timmy", "add-active", "add", identity)
week = store.replace_week(
"timmy", base_revision=0, timezone="UTC",
days=[{
"plan_date": "2026-08-25", "ids": ["issue:stackchain/dashboard:1:"],
"capacity_minutes": 60, "estimates": {"issue:stackchain/dashboard:1:": 45},
}],
)
arguments = {
"identity": identity, "estimate_minutes": 30, "plan_date": "2026-08-25",
"today_revision": today["revision"], "week_revision": week["revision"],
}
with pytest.raises(ValueError, match="explicit overload confirmation"):
store.reschedule_today_to_week(
"timmy", operation_id="unconfirmed", allow_over_capacity=False, **arguments
)
assert store.get("timmy") == today
assert store.get_week("timmy") == week
moved = store.reschedule_today_to_week(
"timmy", operation_id="confirmed", allow_over_capacity=True, **arguments
)
assert moved["week"]["days"][0]["ids"][-1] == identity
@pytest.mark.anyio
async def test_week_reschedule_api_returns_atomic_snapshots_and_conflict_recovery(monkeypatch, tmp_path):
async def user():
return {"login": "timmy"}
store = TodayStore(tmp_path / "today.sqlite3", encryption_key=b"a" * 32)
identity = "issue:stackchain/dashboard:1228:"
today = store.apply("timmy", "add-active", "add", identity)
week = store.replace_week(
"timmy", base_revision=0, timezone="UTC",
days=[{
"plan_date": "2026-08-25", "ids": [],
"capacity_minutes": 60, "estimates": {},
}],
)
monkeypatch.setattr(main, "current_user", user)
monkeypatch.setattr(main, "_today_store", lambda: store)
payload = main.WeekReschedule(
operation_id="move-active", identity=identity, estimate_minutes=30,
plan_date="2026-08-25", today_revision=today["revision"],
week_revision=week["revision"],
)
moved = await main.reschedule_today_to_week(payload)
assert moved["today"]["ids"] == []
assert moved["week"]["days"][0]["ids"] == [identity]
stale = main.WeekReschedule(
operation_id="stale", identity="issue:stackchain/dashboard:1229:", estimate_minutes=30,
plan_date="2026-08-25", today_revision=today["revision"], week_revision=week["revision"],
)
with pytest.raises(main.HTTPException) as raised:
await main.reschedule_today_to_week(stale)
assert raised.value.status_code == 409
assert raised.value.detail["code"] == "today_changed"
assert raised.value.detail["today"] == moved["today"]
assert raised.value.detail["week"] == moved["week"]
File diff suppressed because it is too large. Load diff