From 0f40d899b095e74ab5bf31cdfadf81a0f3c52e78 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:26:05 +1100 Subject: [PATCH 01/11] docs(openspec): propose the 1.5.2 cleanup, QA and guidance follow-ups (#160) * docs(openspec): propose the 1.5.2 cleanup, QA and guidance follow-ups * docs(openspec): tighten the 1.5.2 change after review * docs(openspec): fix a support scenario and pin the archive steps * docs(openspec): apply the second review round and keep the system prompt section stable * docs(openspec): deliver request notes in a carrier valid for the latest message --- openspec/changes/release-1-5-2/design.md | 137 ++++++++ openspec/changes/release-1-5-2/proposal.md | 54 ++++ .../specs/closed-plan-tidy/spec.md | 292 ++++++++++++++++++ .../delegation-intent-visibility/spec.md | 33 ++ .../large-library-responsiveness/spec.md | 67 ++++ .../specs/plan-mirroring-guidance/spec.md | 50 +++ .../specs/plan-selection-actions/spec.md | 91 ++++++ openspec/changes/release-1-5-2/tasks.md | 79 +++++ 8 files changed, 803 insertions(+) create mode 100644 openspec/changes/release-1-5-2/design.md create mode 100644 openspec/changes/release-1-5-2/proposal.md create mode 100644 openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md create mode 100644 openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md create mode 100644 openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md create mode 100644 openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md create mode 100644 openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md create mode 100644 openspec/changes/release-1-5-2/tasks.md diff --git a/openspec/changes/release-1-5-2/design.md b/openspec/changes/release-1-5-2/design.md new file mode 100644 index 0000000..e775376 --- /dev/null +++ b/openspec/changes/release-1-5-2/design.md @@ -0,0 +1,137 @@ +# Design + +## 1. Existing owners and constraints + +- **The ordinary list read pages by offset.** A refresh reads up to ten pages of 50 plans. The read is complete when the last page had no continuation. Offsets are not a snapshot: a plan that leaves the list behind the cursor between two pages moves the next unseen plan behind the cursor, and the list envelope carries no change token. +- **A complete list supplies bulk targets without a read.** Tidy and Select all count from the loaded rows when the list is complete. Otherwise a bounded scan reads the scope; each later page of that scan re-reads the previous page's last plan, the count fails when that plan is not there, and a count that crossed any page boundary already says that plans may have been missed. +- **Search keeps two result pages.** Each poll, a freshness read checks the plans of the page shown and the opened plan by point lookup. A plan that is gone leaves every retained page. The first page of a search starts checked, because the search has just read its hits, and a retained page shown again counts as checked once a reply covered it. The board treats only a checked page as evidence of which plans are in view. +- **A Select all rule holds two kinds of absence.** Plans the person deselected, and plans a cleanup receipt took out of view. Both are merged when an action captures the rule. +- **A single-plan cleanup is bound to its account and store.** If either changed when its reply arrives, it clears its own state and touches nothing else. The bulk run stops sending on such a change, but its completion still resets caches and applies its receipts to the board shown then. +- **How a frame learns of a switch.** The host announces an account change. A store or binding change arrives with a list reply. List reads pause while a bulk run is in flight and its panel is kept, and continue during a single-plan request. A change of the board's filters or search during the run ends that panel, so list reads resume while the request in flight is still held. Every cleanup request names the store it was counted in, and the service refuses one that names another store. +- **Each remembered list scope keeps the health reply it arrived with.** Showing a remembered scope while its new read is pending adopts that health reply, including its cleanup facts, in place of the current one. A refresh reads health before its list pages, and the controller accepts that health reply when the refresh settles. +- **Two paint lanes.** An explicit action repaints at once, replacing even a held control. Background data waits while a control is held or a picker is open. A cleanup focus request is queued and applied at the next paint that contains its target. +- **The bulk run engine keeps receipts only.** The per-plan request already classifies its failure; the run drops that and reports every plan without a receipt as skipped. The single-plan path already says "could not be confirmed" for an uncertain failure. +- **The large-library gate** compares idle traffic per complete refresh, using requests in the order they were sent, and falls back to wall-clock counts for older artifacts. The driver's request log records every request with its frame, method, path, query and time, and nothing about what caused it. Its reply log holds the same routes but records a request only when it is answered, so it cannot order or bound traffic by when it was sent. +- **A structural plan revision keeps an explicit blocked status.** Removing a prerequisite does not unblock the task that waited on it. + +## 2. Counts and selection while plans change + +**Decisions.** + +1. **A count taken from a list read in more than one page is qualified.** The list read records that it crossed a page boundary. A Tidy or Select all confirmation built from such a list carries the existing line that some plans may have been missed, on the first step and on the deletion step. A list read in a single page is one answer from the service and stays exact. Rows explicitly chosen from the loaded list stay exact: they name their plans and are not a census. A Try again recount names its plans too, but on a complete list it is taken by looking those plans up among the loaded rows. It stays exact when it found every plan it names, or when the list was read in one page, where a plan that is not there has left. When the list was read in several pages and a named plan is not among the rows, the read cannot show whether that plan left or was missed, and the recount carries the same line. Where chosen rows or a recount are counted by a scan instead (a searched or truncated scope), the scan's existing qualification and Check more rules apply unchanged. That includes an older service, whose scan pages the list by offset and cannot vouch for what crossed its cursor. The qualification is on the confirmation line only. The selection bar keeps the 1.5.1 plus rule: under Select all its count is the number of selected plans the frame has loaded, with a plus only while matching plans are known not to be loaded. It is not a verified total, and it is the confirmation that says so before any request. No read is added and the ordinary list read is unchanged. +2. **A freshness reply certifies only the page it was asked about.** The page's identity is its number in the run, not its position among the retained pages. When Load more drops the oldest retained page, a reply still in flight is never credited to the page that took that position. Whether it still certifies its own page, if that page is retained and shown again, follows the existing retirement rules; this change adds a prohibition, not a new way to be credited. A reply certifies a page only when it covered every plan the page shows when the reply arrives: a search still running can append hits to the page a reply was asked about, and those plans were not covered. The rule runs one way. Hits the search reads into a page after a reply certified it leave the page checked: they were read from the service at that moment, which is what the first page of every search rests on, since it starts checked and is filled only by such reads. A reply is needed for hits that were carried over: a retained page shown again, or hits held back from an earlier read and placed on a new page. The frame does not record which hits of an unchecked page were carried over, so a reply certifies such a page only when it covered all of its plans. Recording coverage per hit would make the two orders equal and is listed as a follow-up. The next poll covers the plans read since. +3. **A cleanup in this frame retires freshness checks in flight.** Retiring the search after a cleanup action in this frame also retires any freshness read the frame already sent, so a reply from before that cleanup cannot mark a page checked or undo what a receipt established. The boundary is this frame's own invalidation. A cleanup made in another frame retires nothing here: a freshness reply that shows its effect is the evidence decision 4 acts on. +4. **Removal is a fact about a plan, not about a page.** When a freshness reply shows a plan missing, deleted or on the other side of the archive boundary, its hits leave every retained page, as today, and the selection forgets it, whether or not the page shown was the one the reply certified. +5. **Deselection and departure are separate.** A deselection lasts until the person changes it or the selection ends. A departure ends when an Undo receipt returns the plan, when a verified read lists it, when the person clicks its row, or when a fresh count finds the plan in the view at a newer cleanup generation than the one that took it out. A plan archived here and restored elsewhere is therefore counted by the next action. A return by receipt, read or count ends the departure only. If the person had also deselected that plan, it stays out as a deselected plan until the person clicks its row. Of the events that return a plan, that click is the only one that also ends a deselection. Pressing Select all again is a different thing: it replaces the selection, and so clears deselections and departures alike, as it does today. The generation that took a plan out is the one its receipt returned. The run hands it to the selection together with the receipt, as a map from plan to cleanup generation where it handed over a set of plans before. It is not read from a loaded row, because Select all can archive a plan the page never loaded. A cached, unchecked page is still no evidence. +6. **A newly opened result page starts unchecked**, whatever the state of the page shown before it, and becomes checked when a freshness reply covers its own plans. Visible consequence: the note that results are being checked can show on a new page until such a reply succeeds. No time limit is promised: the poll backs off after a failure and pauses while the frame is hidden. A failed freshness read leaves the page unchecked and is reported by the existing stale indication. A page that shows no plan has nothing to check: when Load more ends without a hit for the new page, no freshness read is added for it and the checking note is not shown. + +**Consequence of decision 1.** Where the scope's list spans more than one page (more than 50 plans), the Tidy and Select all count line always says that some plans may have been missed. The line is honest and the wording exists in three languages; it is also more visible than before. The maintainer accepted it as the usual line above one list page. Removing it needs a list read the service can vouch for as a snapshot, which is out of scope. + +**Alternatives rejected.** Re-reading the previous page's last plan in the ordinary list read: ten pages would then load 491 plans instead of 500, changing the documented bound and the reference library's measurements. Running the bounded scan for every multi-page list: it adds up to eleven reads to each opening and still ends with the same qualified line. Treating two identical consecutive list reads as verification: strong evidence, not proof, and a new rule for a patch release. + +## 3. Account, store and capability + +**Decisions.** + +1. **A bulk run completes only into the account and store it ran in.** The run captures the integration account and the store and binding identity when it starts. If the frame observed a change of either since the run started, the run drops its own state when it finishes and changes nothing on the board shown: no cache reset, no selection change, no closed plan, no result line. The test is whether a change was observed, not whether the identity is equal at the end: after a switch away and back the board shown was loaded anew, and the person may have opened or selected a plan on it. The result line is not what changes: the 1.5.1 scenario said the result reports what completed after any context change, but the interface shipped, and is tested, without a result line after an account change or a change of board scope. The confirmation requirement is modified to state that outcome. What changes in behaviour is the rest of the list: today such a run still resets caches and applies its receipts to the board shown then. A change of board scope inside the same account and store keeps the outcome the 1.5.1 interface has: the run stops, shows no result line and sends its one reconciliation read when it ends. Changing the filters or the search is itself the next action, which ends a result. No behaviour changes for that case. One effect of a run is device-side and survives the change: a validated Delete receipt removes the review marker stored for its plan under the account and store the run started in, also when the receipt arrives after the change, as it does today and as the single-plan path does. That marker is keyed by account, store, binding, source and plan. It can therefore reach a review open on the board shown only when that board is the same account and store again and shows that same plan, which the receipt has just proved deleted; ending that review is correct, and no further guard is added for it. +2. **Cleanup support is what the service last said, whichever list is shown.** The controller keeps the cleanup facts of the latest health reply it accepted apart from the remembered lists. Adopting a remembered scope changes the list shown and never those facts, in either direction: it does not bring back support, or in-progress support, that a later health reply withdrew, and it does not hide support that a later health reply granted. Support returns only with a newer health reply that offers it. A health reply is accepted when the refresh that read it settles, complete or failed, as today. One that arrived inside a refresh still reading its list pages takes effect when that refresh settles; until then a request is checked when it is sent and by the service. Applying it earlier would change the list read itself and is not part of this change. +3. **An account or store switch releases the busy state.** Cleanup controls on the new board are usable without waiting for a request sent before the switch, and that request's late completion can neither complete nor release a newer run. The busy state and the stale-answer cleanup are bound to the request that set them, in the single-plan path as well as in the bulk run: both share one busy state today, and a late single-plan answer clears it and resets the cleanup panel whatever is running by then. Comparing the account and store alone is not enough, because it reads a switch away and back as no change. + +**What counts as a switch.** Decisions 1 and 3 act on a change the frame has observed. An account change is observed when the host announces it, during any request. A store or binding change is observed with a list reply. Those continue during a single-plan request, so a store change is observed while that request is held. They pause during a bulk run for as long as its panel is kept, so a store change with no account change is then observed by the list read that follows the run. Until then the board shown is still the one the run started on, the run ends there, and that read then adopts the new store and clears the board, as today. The requests of such a run name the old store, and the service refuses them. Observing a store change while list reads are paused needs a read the run does not send today and is listed as a follow-up. The pause ends early when the person changes the board's filters or search during the run: that ends the run's panel, list reads resume while the request in flight is still held, and a store change one of them shows is an observed change, to which decisions 1 and 3 apply. + +**Not covered: support withdrawn while an action is open.** Decision 2 governs what the controls offer. A count, confirmation or run that is already open when in-progress support is withdrawn is not re-checked by this change. A bulk run decides whether it may send in-progress plans when it starts and leaves them unsent otherwise; a single-plan deletion attaches the in-progress acknowledgement only if the service still offers it when the request is sent; and the service's own check refuses the rest. Losing cleanup support altogether already retires an open confirmation. Re-checking open counts and confirmations on a downgrade is listed as a follow-up. + +**Mixed versions and rollback.** Interface only. Nothing is stored, and no request changes. + +## 4. Background updates and focus + +**Decisions.** + +1. **A count that finishes by itself is background data.** The end of a scan, its failure and the end of a Check more continuation repaint through the background lane, so they wait for a held control or an open picker like any refresh. Opening the panel, Cancel, the confirm buttons and pressing Check more are explicit actions and still repaint at once. +2. **A run's own updates are background data too.** That covers each progress update and the repaint at the end of the run, with its result line and the selection changes its receipts cause: like a count, a run finishes by itself. A press on Stop is not lost to a progress update, and neither update replaces a held control. The progress line and the result line can lag while a control is held or a picker is open. Nothing else waits: the run, the release of its busy state, the cache invalidation and the reconciliation read happen when the last reply arrives. Starting a run, Stop, Undo and Try again are explicit actions and still repaint at once. Two limits follow from what does not wait. First, the cache invalidation at the end of a run retires the controls of the board whose data it invalidated, as every cache reset does: a Filters button held at that moment stays in place, so focus and the pointer are not disturbed, but it ignores that click. Keeping such a control valid across the reset is listed as a follow-up. Second, a result has to be shown before a refresh can expire it: a refresh does not expire a result that has not been painted yet, so a hold that lasts past the next refresh loses neither the result line, nor its unconfirmed warning, nor Undo. Once painted, the result expires with the next refresh and that expiry repaints at once, as in 1.5.1; and an action of the person that changes the view ends a result whether or not it was painted. Both are listed as follow-ups. +3. **A deferred focus move is decided when it is applied.** The move to the Tidy button after a run that ended with focus on Stop, and the move to Cancel after a count, are applied only if focus is still on the control the move was queued from, or is on no control because that control was removed. Being inside the cleanup panel is not enough: once Stop is gone the result line can offer Undo while the Tidy button is still absent, and a person who has moved to Undo keeps focus there. If the person has focused anything else meanwhile, in the panel or outside it, the request is dropped, not kept for a later paint. A request denied because another frame has focus stays dropped, as in 1.5.1. + +No timer is added and no freshness is deferred beyond the existing press and picker rules. + +## 5. Unconfirmed results + +Each target of a run ends in exactly one of three states. + +| State | When | Result line | +|---|---|---| +| Done | its receipt was validated | archived, restored or deleted | +| Skipped | the service answered and refused it (changed, closed, reused operation, not found, store busy); or the view left it out right before sending; or the run stopped before sending it | skipped | +| Unconfirmed | the request was attempted and no valid answer came back: a lost or timed-out reply, a connection or host failure, or an answer that is not a valid receipt or one of the refusals above | could not be confirmed and may have been archived, restored or deleted | + +The split follows the classification the single-plan messages already use, so one failure never reads as "changed" on one surface and "possibly applied" on the other. A failure that fits neither refusal class counts as unconfirmed: over-warning is safe, under-warning is the defect. A target the run did not attempt, because the view left it out or the run stopped first, is never unconfirmed. An attempt that fails before the service could receive it, while the request is prepared or handed over, counts as unconfirmed too: the run engine cannot tell it from a lost reply, it does not happen in normal operation, and telling the two apart would need a second failure channel for a case that only over-warns. + +**Result line.** Still one sentence, announced once. English reference strings: + +| Case | Text | +|---|---| +| All done | 128 plans archived. | +| Some skipped | 126 of 128 plans archived; 2 skipped. | +| Some unconfirmed | 126 of 128 plans archived; 2 could not be confirmed and may have been archived. | +| Both | 125 of 128 plans archived; 1 skipped; 2 could not be confirmed and may have been archived. | + +Delete and restore use "may have been deleted" and "may have been restored". Russian and Simplified Chinese ship in the same pull request, as whole strings with plural rules, and are checked by reading. + +**Undo and Try again.** Undo restores exactly the plans with a validated archive receipt, each bound to the generation its receipt returned. An unconfirmed plan has no receipt and no generation, so it is never part of Undo. If its archive was applied, it can be restored on its own once an Archived plans list or search shows it. The reconciliation read is not promised to show it: that read uses the scope shown, which leaves archives out during an ordinary archive run, and an Archived plans list has the ordinary page limit. After an archive, a deletion or a restore of selected plans, Try again recounts skipped and unconfirmed plans together under the existing retry rules, which leaves out the ones that have left the view. After a partial Undo it does not recount: a plan whose restore did not arrive is still archived and would not be in the view shown, so Try again sends the same restore request again for exactly the remaining plans, each still bound to the revision and cleanup generation its archive receipt returned, as it does today. The service answers a repeated request from the receipt it saved for that request, before it compares generations: a plan whose earlier restore was in fact applied is therefore confirmed as restored, and is not restored twice. A plan that another cleanup changed since is refused, because its generation has moved, and is reported as skipped. Nothing is retried automatically, and the one reconciliation read after the run is unchanged. + +**QA driver.** The selection driver proxies the frame's requests through the cleanup fixture's request helper, whose three-second limit turned a slow reply into exactly this unconfirmed case and let the driver continue to Undo with fewer plans than it believed. The helper's limit for service calls becomes 30 seconds, its readiness probe keeps a short bound so a hung start still fails fast, and the driver asserts that the archive result reports every plan archived before it uses Undo. + +## 6. Large-library gate + +QA only. Nothing shipped changes. + +1. **Exact window, counted by requests sent.** The request and reply offsets that bound a timed window are captured in the same browser evaluations that start and stop its timer. A request logged after the stop is not counted, and it does not close a refresh that was still open. Every count the comparison uses, the cadence counts and both inbox forms included, is taken from the request log inside those bounds, so a request counts by when it was sent: one sent before the window and answered inside it is out, one sent inside and answered after it is in. The reply log stays for what only a reply can show: status, size and timing. +2. **Run reads are counted per window, and their per-refresh budget is unverified.** A refresh can cause a run read after the next refresh has started: the automatic follow-up of a run reconciliation is sent without waiting for the next poll. In the request log that read looks like any other run read, so the gate cannot say which refresh caused it, and it does not try. Run reads are taken out of the per-refresh figures and counted once per window: every run read sent inside the window, whichever refresh preceded it, including one sent before the window's first list start and one sent after the last. Late traffic then cannot be charged to the wrong refresh, be lost with the final open refresh or be dropped at the start of the window. A window count does not show how many run reads one refresh sent: five reads over five list starts and five over four give the same count. The gate therefore shows each window's run-read count beside its list starts as an informational row and judges neither. Because the cause is the log, not a particular baseline, this is a standing limit rather than the unverified state of decision 7: the row never changes the exit status, so the gate can still pass. Tying each read back to the refresh that caused it would remove the state. It needs the shipped interface to label its requests, which these QA-only checks must not ask for, and is listed as a follow-up. +3. **The artifact says how it attributed.** An artifact records its attribution method. The gate does not treat an older artifact that bucketed replies as equivalent to one that buckets requests. +4. **The wall-clock inbox split is saved** beside the complete-refresh counts, so a window with a single list start still has a split to compare. +5. **The bundled inbox form is compared on its own** as well as in the combined figure, so an extra standalone request at a window edge cannot pay for an added first window on the list read. The form carried by the list read is counted per list start. A list start either carried it or did not, so that figure has no error at the window edge and is comparable in any window. The standalone form is judged in the combined figure over complete refreshes. A standalone request sent in the refresh still open when the window ends is counted in the window's split and changes no per-refresh verdict, like that refresh's list pages: a refresh the window cut is on neither side of a ratio. +6. **Health is outside per-refresh traffic.** The health read precedes its refresh's first list page, so it cannot be tied to a bucket; the cadence check already covers it. +7. **No comparable baseline means unverified.** When the baseline or too few candidates carry the inbox split, the combined inbox budget is reported as unverified. The same holds for any per-refresh budget whose baseline and candidate figures do not rest on the same denominator, even when both artifacts are in the current format. A window that completed no refresh has only wall-clock counts over a single list start, where the traffic of a refresh that began before the window changes the figure by itself: nineteen list pages over one list start would let a candidate reading eleven pages per refresh pass a ten-page contract. Such a figure is not compared with complete-refresh figures. The gate then reports neither a pass nor a failed budget and exits non-zero with that state named. The other comparisons still run. A baseline recorded with the current driver whose idle window completed at least one refresh removes the state for those budgets. Its summary names which budgets are unverified and which failed. The run-read row of decision 2 is informational and is neither. +8. **The tests tell the paths apart.** The attribution fixtures fail if requests were bucketed in reply order, and the gate fixtures use counts that differ per denominator and mix an older candidate, a current candidate and one without a split. They include a baseline with a single list start against candidates with complete refreshes, a run read on each side of the window's first and last list start, with the run-read budget reported as unverified whatever those counts are, and an inbox request sent across each window edge, with the window's split and the unchanged complete-refresh figures both asserted. + +The driver is not part of portable CI. Decisions 1 to 7 put their logic in the attribution helper and the gate, which the unit tests cover; the browser-side capture of offsets is shown by one rendered run. + +## 7. Guidance, receipt evidence and documentation + +1. **A dependency block follows the plan's current prerequisites.** The moved-back sentence in the skill, the tool description and the inline guidance says to read the current plan before a handoff: once every prerequisite the task still has is done, the task blocked this way goes back to working or pending. A prerequisite the plan no longer lists no longer holds it. A skipped prerequisite that is still listed counts as unfinished. The rule stays limited to the task the agent blocked this way; a decision, review, external or other blocker is never touched. The store is unchanged: a structural revision still keeps an explicit blocked status, which is why the guidance has to say this. The tool description stays within its tested limits. +2. **Refusal guidance checks a receipt before reading meaning into it.** Before the coordinator refusal reader infers that cleanup retired a waiting delegation, it checks that the receipt's state agrees with its dispatch and its declared tasks, as the per-plan reader does: a pending declaration names no dispatch, a reserved one does, and both name at least one task. The check applies to pending and reserved receipts only. A cancellation is stored as retired and comes in two shapes, both read as before: the empty declaration that cancelled, and the earlier declaration it retired, which keeps its tasks. A receipt that fails the check makes the guidance incomplete, the existing explicit limitation, instead of producing a `closed` refusal. A well-formed receipt still yields no refusal once the plan's current assignment shows that its declared tasks were explicitly linked since; the check runs before that existing step and does not replace it. No receipt or store change. +3. **Point lookups are documented where they apply.** `docs/ui.md` says that chosen rows are validated by point lookup in a searched or truncated scope on a service that advertises task search, that a complete browse list uses the loaded rows, that an older service counts a truncated browse scope by list scan, and that the point lookup skips, and does not adopt, a plan whose revision moved where search or session criteria apply. That skip belongs to the point lookup only; item 4 says what the other two paths do. +4. **The retry baseline is named, for the reader that compares.** `docs/contracts.md` and `docs/ui.md` say that where the point lookup validates named plans, each is compared with the revision supplied to the count, which on Try again is the original target's revision, instead of "since the count began". The other two paths compare nothing against that revision and the guides say so: a complete list takes a named plan as its loaded row shows it, and an older service's list scan takes it as the scan's row shows it. In every path the service still checks the revision each request carries. + +Items 3 and 4 change documentation only. + +## 8. Stable system prompt section + +1. **The system section holds only text that does not change within a session.** The companion's context hook adds one section to the system prompt on every eligible request. Today that section also carries the one-request hint after a dispatch, a plan-file write or a tracker save, the resume capsule of a sub-agent session, which names the plan's current revision and can drop out for one request when its bounded lookup times out, and the delegation refusal note. Each of these changes the system prompt between requests, and a provider prompt cache misses from the first changed byte, which takes the whole message history with it. After this change the system section is the fixed activation guidance only, byte-identical on every request where it is present. +2. **Changing text goes after the cacheable prefix, in a carrier valid for the latest message's role.** The hint, capsule and refusal note are added for that request only, after the content of the latest message the request carries, so the stored conversation is unchanged and the prefix up to the previous request stays identical. The carrier depends on that message's role. On a user message they are a text part after its content. On a tool message, which is the latest message of a continuation after a tool call such as a plan-file write, a separate text part is not valid, so they are appended to the output of its last tool result, the same carrier the existing note on a completed tool result already uses and the native driver already checks. Any other role gets nothing on that request: the text waits for the next request whose latest message has a valid carrier and is never dropped. The text and its eligibility rules are unchanged; only its position moves. Providers that drop plugin system sections now also receive these notes; the checklist they rely on is already in the tool description and does not change. +3. **What stays as it is.** The tool set, the tool description, the skill text and the note added once to a completed tool result already stay identical after their first send. The section is still removed when capture is off, the report tool is unavailable or the source is unverified, so turning those on or off still changes the prefix once. Compaction already rebuilds the prompt. +4. **Tests.** A context-hook test runs consecutive requests across a hint trigger, a capsule revision, a capsule lookup timeout and a refusal appearing and clearing, and asserts that the system array is identical each time and that the varying text arrives once, on the latest message, for that request only. The native activation driver also checks the outgoing request of a real plan-file write continuation: the hint arrives inside the last tool result, the system section is unchanged, and the provider accepts the request. Prompt-cache hit rates are not measured: that needs a live provider. + +## 9. Delivery, verification and rollback + +Each numbered task group is one pull request into the development branch with its documentation, its three-language copy where copy changes and its tests, and passes portable CI alone. Every defect gets a regression test that fails before its fix. No generated output and no version change is committed in these pull requests. + +Group 8 touches only the companion's context hook, its tests and the guides' statements about where the section goes, and is independent of every other group. Groups 2, 4 and 6 touch disjoint source and test files, and different lines of the guides, and can start together. Group 5 touches only the large-library driver, gate and their tests and is independent of every other group. Group 3 follows group 2, because both change the end of the bulk run in the shared controller and extend the same controller test file; it also follows group 4, which rewrites the same line of the Tidy result statement in `docs/ui.md`. Group 1 follows groups 2, 3, 4 and 6 and merges last: it shares the controller with group 2, the cleanup model with group 4 and the bulk-count paragraphs of the two guides with group 6, and it changes how the end of a run hands its receipts to the selection, in the lines groups 2 and 3 change before it, and extends the same controller test harness as group 3. + +Interface checks use the controller, search and selection unit harnesses, and source-built disposable guests with real browser input for the result line in three languages and the keyboard pass. Service-facing checks use the disposable cleanup fixture. They are synthetic-host evidence, not native-host or physical-phone acceptance. + +Rollback is by reverting pull requests in reverse order. Nothing is stored and no contract with the service or with older guests changes. + +**Archiving.** This change's requirement deltas modify capabilities introduced by the 1.5.0 and 1.5.1 changes, and neither is archived yet. The 1.5.2 release pull request archives the 1.5.0 change, then the 1.5.1 change, then this one, in that order; each archive builds the base spec the next one's deltas apply to. The pull requests of groups 1 to 6 archive nothing. Before each archive, that change's task list is reconciled: a task whose work shipped is ticked, and a task that did not happen stays unticked with a note saying whether it is deferred, superseded or out of scope. An archive that refuses a delta is a finding to resolve in the delta, not a reason to skip the spec update or the validation. + +The chain was rehearsed on a disposable copy of the specs, and three rules follow from it. A modified requirement must keep every scenario name the spec already holds under that requirement, or the archive refuses the whole change; this change keeps them, which is why the confirmation requirement retains its "Context changes mid-run" scenario and adds the account and store case beside it, and why the result requirement keeps its six scenarios and moves the unconfirmed rules into a requirement of their own. A capability that an archive creates gets a placeholder purpose, which strict validation of the specs reports until a purpose is written. And a requirement text longer than 500 characters passes in a change's modified block but is reported once it is in a spec, so this change keeps its two modified texts below that. In the rehearsal the 1.5.0 change archived as it is. The 1.5.1 change was refused for two modified requirements that each dropped a scenario name the 1.5.0 specs hold, and it left four requirement texts above the limit. The two scenario names and all four texts are corrected in the 1.5.1 change inside the release pull request, before its archive, so that strict validation passes after each archive and not only after the last; this change's result requirement then replaces one of the four. With the two names restored and the four texts shortened in the copy, and a purpose written for each capability an archive created, the 1.5.1 change and then this one archived without a refusal, and strict validation of the specs reported nothing after each of the three archives. + +Promotion to the distribution branch follows the release pull request, so it is listed after the archive in the task list. + +## 10. Open questions + +None. The maintainer decided the points this design had left open: + +1. The three adjacent defects (decisions 2.6, 3.3 and 4.2) are in scope. +2. The qualified count line is the usual line wherever the scope's list spans more than one page, until a snapshot read exists (section 2). +3. A budget the gate cannot compare is reported as unverified and exits unsuccessfully (decision 6.7). +4. The release pull request archives the 1.5.0, 1.5.1 and 1.5.2 changes in that order (section 9). diff --git a/openspec/changes/release-1-5-2/proposal.md b/openspec/changes/release-1-5-2/proposal.md new file mode 100644 index 0000000..735ff86 --- /dev/null +++ b/openspec/changes/release-1-5-2/proposal.md @@ -0,0 +1,54 @@ +# Agent Progress 1.5.2: Cleanup follow-ups from the 1.5.1 review + +## Why + +1.5.1 added Tidy and multi-select. Review of that release accepted a set of follow-ups and deferred them, because none lets an archive or a deletion reach a plan the person did not choose: every request still carries the plan's revision and the service checks it. They do leave a count, a selection, a focus position, a result line or a QA result less precise than the interface says. + +- **A count can be stated as exact when it may be low.** A plan list read in several pages is not a snapshot, yet Tidy and Select all count from it as if it were. While searching, a freshness check can be credited to a result page it never asked about, a check started before a cleanup can still act after it, a plan confirmed gone can stay counted as selected, and a plan the person never deselected can be left out of the next action. +- **Cleanup state can cross an account or store switch.** A bulk run that finishes after the switch clears caches and selection on the new board. A remembered list can bring back cleanup controls after the service stopped offering cleanup. +- **Background cleanup updates interrupt the person.** A count that finishes while a button is held replaces that button, so its click is lost. A focus move queued for the Tidy button is applied after the person has moved on to another control. +- **A lost reply is reported as "skipped".** A request whose answer never arrived may have been applied, but the result line files it with the plans the service refused. +- **The large-library gate attributes idle traffic imprecisely** at window and refresh boundaries, and can report a pass for a comparison it could not make. +- **The companion's system prompt section changes between requests.** It carries a one-request hint, the sub-agent resume capsule with the plan's revision, and refusal notes. Each change alters the system prompt, so a provider's prompt cache misses from that point on, which a user reported as a lower cache hit rate. +- **Four small inaccuracies.** Guidance for work that moves back to a prerequisite keeps a task blocked on a prerequisite the plan no longer has. A malformed delegation receipt can produce a confident refusal in coordinator guidance. Two documentation statements about bulk counts say more than the code does. + +## What Changes + +- Tidy and Select all say that plans may have been missed when their count comes from a list read in more than one page. A single-page list and rows explicitly chosen from the loaded list stay exact, and so does a Try again recount that found every plan it names. No read is added. +- A search freshness reply certifies only the result page it was asked about, a cleanup in the same frame retires freshness checks already in flight, a plan confirmed gone leaves the selection whichever page is shown, and a plan a cleanup receipt took out of a Select all rule is kept apart from plans the person deselected, so a plan that returned to the view is counted again. +- A bulk run that finishes after the frame observed an account or store change changes nothing on the new board: it resets no cache, changes no selection and closes no opened plan there. It shows no result line either, and neither does a run stopped by a change of filters or search alone. The 1.5.1 interface already shows none after any such change, so the 1.5.1 scenario that said the result reports what completed is corrected to match. Cleanup controls follow the latest health reply the frame accepted: a remembered list neither brings back support that a later reply withdrew nor hides support that a later reply granted. +- A count that finishes in the background, a run's progress and its end, and the deferred focus move after a run wait for the person: none replaces a held control or takes focus from a control the person has since chosen. +- **Visible copy change:** the bulk result line separates plans that were skipped from plans whose request could not be confirmed and may have been applied, in English, Russian and Simplified Chinese. Undo still restores only plans with a validated receipt. +- The selection QA driver waits longer for the fixture service and asserts that every plan was archived before it uses Undo. +- The large-library gate bounds its idle window exactly, counts by the requests sent inside it, counts run reads per window and shows them as an informational row, because the request log cannot tie a run read to the refresh that caused it, records how an artifact attributed its traffic, compares both inbox request forms separately and reports a comparison it could not make, including one across different denominators, as unverified instead of passed. QA only. +- Guidance tells an agent to clear a dependency block against the plan's current prerequisites. Coordinator refusal guidance validates a receipt's state against its dispatch before inferring that cleanup retired it. `docs/ui.md` and `docs/contracts.md` state when chosen plans are checked by point lookup and which revision a retry compares against. +- The companion's section of the system prompt stays identical from one request to the next, so it no longer defeats a provider's prompt cache. The text that changes between requests, which is the one-request hint after a dispatch or plan write, the sub-agent resume capsule and the delegation refusal note, is delivered after the cacheable prefix, with the latest message of that request, instead of inside the system prompt. +- Three adjacent defects are fixed with the follow-ups they sit beside: a newly opened search result page no longer inherits the previous page's checked state; a run's progress and its end no longer replace a held control; and cleanup controls on the new board no longer stay pending after an account or store switch until the earlier request settles. + +## Capabilities + +### New Capabilities + +None. + +### Modified Capabilities + +- `closed-plan-tidy`: count exactness for a multi-page list, the result line for unconfirmed requests, results and cleanup support bound to the current account, store and service answer, and background updates that do not interrupt. +- `plan-selection-actions`: how a selection follows confirmed changes during a search, and departures kept apart from deselection. +- `large-library-responsiveness`: precision of the idle-traffic check that guards the no-larger-reads requirement. +- `plan-mirroring-guidance`: clearing a dependency block against the plan's current prerequisites, and a system prompt section that stays identical across requests. +- `delegation-intent-visibility`: refusal guidance rests on validated receipt evidence. + +## Impact + +Affected owners: the shared view controller (cleanup run, count and focus paths, remembered list scopes), the search controller's freshness and paging, the cleanup model (selection rule, run engine, result copy) and its view, the full page entry's selection reconciliation, the list read, the delegation refusal reader, the companion guidance text and its per-request context hook, browser and backend tests, the cleanup service test fixture, the selection QA driver and the large-library driver and gate. `docs/ui.md` and `docs/contracts.md` change with each behaviour. + +Protocol and schema stay at 2. No route, request field, receipt, capability fact, store format, migration, permission, host floor or SDK change. No refresh sends more or larger reads. + +## IN / OUT / Must NOT have + +IN: the follow-ups above; English, Russian and Simplified Chinese together where copy changes; a regression test that fails first for every defect; documentation in the same pull request as each behaviour; release preparation for 1.5.2, whose pull request also archives the 1.5.0 change, the 1.5.1 change and this one, in that order. + +OUT: repairing the stale rendered QA drivers that predate 1.5.1 (tracked separately); a list read the service can vouch for as a snapshot, which is what would let a multi-page count be exact again; changing how the ordinary list read pages; retrying an unconfirmed request automatically; an Undo for plans without a receipt; a bulk route; any change to the service's cleanup contract; re-checking a count, confirmation or run that is already open when the service withdraws in-progress cleanup support; observing a store change while a bulk run has the list reads paused; applying a health reply before its refresh settles; attributing a run read to the refresh that caused it in the gate; keeping a held board control valid across the cache invalidation at the end of a run; changing how a painted result expires; recording freshness coverage per search hit. + +The release MUST NOT relax a documented safety contract: the service's per-plan revision and generation check stays the final safeguard, and every rule of the 1.5.1 change still holds, with one stated correction of its wording. The 1.5.1 scenario in which a run stopped by a change of the store, account, binding or board reading reports what completed is corrected to what the interface does, which is to show no result line after such a change. No behaviour changes there; the behaviour that changes is that a run ending after an account or store change no longer resets caches, the selection or the opened plan of the board shown. It MUST NOT report a plan as archived, restored or deleted without its validated receipt, call a request that may have been applied "skipped", or call a plan the run never attempted "possibly applied". It MUST NOT present a possibly low count as exact, or mark a selection count with a plus where the 1.5.1 rule does not. It MUST NOT apply one account's or store's receipts, cache resets or selection changes to another. It MUST NOT add a timer, polling loop, route or read, defer a repaint the person asked for, or defer freshness without bound. It MUST NOT let the gate pass a budget it could not compare, and it MUST NOT commit measurements, stores or logs taken from a real library. diff --git a/openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md b/openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md new file mode 100644 index 0000000..935c415 --- /dev/null +++ b/openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md @@ -0,0 +1,292 @@ +## ADDED Requirements + +### Requirement: A bulk count is exact only when its read can show it + +A Tidy or Select all count taken from the loaded plan list SHALL be stated as exact only when that list was read in a single page. Otherwise the confirmation SHALL say that some plans may have been missed, on its first step and on the deletion step. A count of rows explicitly chosen from that list SHALL stay exact. A Try again recount from a list read in several pages SHALL stay exact only when it found every plan it names. The qualification MUST NOT add a read. + +#### Scenario: List read in several pages +- **WHEN** Tidy is opened on a complete list of 120 plans that was read in three pages +- **THEN** the count line states the number found and that some plans may have been missed +- **AND** no request is sent to produce the count + +#### Scenario: List read in one page +- **WHEN** Tidy is opened on a complete list of 30 plans that was read in one page +- **THEN** the count line states the number without qualification + +#### Scenario: Select all on a multi-page list +- **WHEN** Select all is active on a complete list read in several pages and an action is opened +- **THEN** the confirmation says that some plans may have been missed + +#### Scenario: Explicitly chosen rows +- **WHEN** three rows are chosen one by one on a complete list read in several pages and an action is opened +- **THEN** the confirmation states three plans without qualification + +#### Scenario: Chosen rows counted by a scan +- **WHEN** rows are chosen in a searched or truncated scope, where the count runs through a scan +- **THEN** the scan's existing qualification and Check more rules apply unchanged, also on an older service, whose list scan cannot vouch for what crossed its cursor + +#### Scenario: Try again finds every named plan +- **WHEN** Try again is chosen after a partial run on a complete list that was read in several pages, and every remaining plan is among the loaded rows +- **THEN** the recount states those plans without qualification + +#### Scenario: Try again does not find a named plan +- **WHEN** Try again is chosen on a complete list that was read in several pages, and a remaining plan is not among the loaded rows +- **THEN** the recount states the plans it found and that some plans may have been missed, because that read cannot show whether the plan left the view or was missed +- **AND** no request is sent to look for it + +#### Scenario: Try again on a list read in one page +- **WHEN** Try again is chosen on a complete list that was read in one page, and a remaining plan is not among its rows +- **THEN** the recount states the plans it found without qualification + +#### Scenario: Deletion step +- **WHEN** Delete permanently is chosen from a qualified count +- **THEN** the deletion step repeats that some plans may have been missed + +### Requirement: A bulk run completes only into the account and store it ran in + +A bulk run SHALL capture the integration account and the store and binding identity when it starts. When it finishes after the frame observed a change of either, even one that has since changed back, it SHALL drop its own state and MUST NOT reset caches, change the selection, close the opened plan or show a result on the board shown then. A validated Delete receipt SHALL still remove the device review marker captured for its plan in the account and store the run started in. + +#### Scenario: Account switched while a request is held +- **WHEN** the integration account changes while a bulk archive request is held, a plan is opened and selected on the new board, and the held request then answers +- **THEN** the new board keeps its opened plan, its selection and its loaded list, and shows no result line +- **AND** the plans of the earlier run that were never sent stay unsent + +#### Scenario: Same identifiers in the new store +- **WHEN** the board shown after the change holds a selected plan with the same source and plan identifier as a target of the earlier run +- **THEN** that plan stays selected and is not treated as archived, restored or deleted + +#### Scenario: Account switched away and back while a request is held +- **WHEN** the integration account changes and changes back while a bulk archive request is held, a plan is opened on the board shown, no newer run is started, and the held request then answers +- **THEN** that board keeps its opened plan, its selection and its loaded list, and shows no result line + +#### Scenario: Delete receipt arrives after the switch +- **WHEN** the integration account changes while a bulk delete request is held, and the request then answers with a valid receipt +- **THEN** the review marker stored for that plan under the account and store the run started in is removed +- **AND** the markers of other plans, and of the same plan identifier under another account, stay + +#### Scenario: Board scope changed in the same account and store +- **WHEN** only the board's filters or search changed while the run was in flight +- **THEN** the run stops after the request in flight, shows no result line and sends its one reconciliation read when it ends, as the interface did before this change + +#### Scenario: Store changed during a run without the frame observing it +- **WHEN** the store changes with no account change while a bulk run has the list reads paused +- **THEN** the run ends on the board it started on, and the list read that follows it adopts the new store and clears that board, as before this change + +#### Scenario: Store change observed after a board change resumed list reads +- **WHEN** the board's filters change while a bulk request is held, so list reads resume, a list reply then shows that the store changed, and the held request answers +- **THEN** the board shown keeps its loaded list and its selection, and shows no result of that run + +### Requirement: Cleanup support follows the service's latest answer + +Cleanup controls SHALL follow the cleanup facts of the latest health reply the frame accepted, whichever list is shown. Showing a remembered list scope MUST NOT bring back cleanup support, or in-progress cleanup support, that a later health reply withdrew, and MUST NOT hide support that a later health reply granted. A health reply is accepted when the refresh that read it settles, whether its list read completed or failed. + +#### Scenario: Switching back to a remembered view +- **WHEN** Current plans was read with cleanup support, Archived plans then observes a service without it, and the person switches back to Current plans while its new read is pending +- **THEN** Tidy and Select stay absent while the remembered list is shown + +#### Scenario: Loss observed on a failed read +- **WHEN** a refresh receives a health reply without cleanup support and then fails to read the plans, and the person changes to a scope the frame remembers +- **THEN** the remembered list is shown without cleanup controls + +#### Scenario: Support returns +- **WHEN** a later health reply offers cleanup again +- **THEN** the controls return with that reply, not earlier + +#### Scenario: Support granted after a view was remembered +- **WHEN** one view of Current plans was last read while the service offered no cleanup, a later refresh in another view of Current plans, such as the same list under a session filter, accepts a health reply that offers it, and the person switches back to the first view while its new read is pending +- **THEN** Tidy and Select are offered while the remembered list of the first view is shown + +### Requirement: Background cleanup updates do not interrupt the person + +A count that finishes by itself, including its failure and the end of a Check more continuation, SHALL repaint as background data, so it waits while a control is held or a picker is open. Explicit actions SHALL still repaint at once, and the change MUST NOT add a timer or defer freshness beyond the existing held-control and open-picker rules. + +#### Scenario: Count finishes during a press +- **WHEN** a count finishes between pointer down and pointer up on an unrelated control such as Filters +- **THEN** the control is not replaced before its click, the click takes effect and the count line appears on the next paint + +#### Scenario: Explicit action during a count +- **WHEN** the person presses Cancel or Check more while a count is running +- **THEN** the panel repaints at once, as before this change + +### Requirement: A deferred cleanup focus move is decided when it is applied + +A focus move that cleanup deferred SHALL be applied only if, at the paint that applies it, focus is still on the control the move was queued from, or is on no control because that control was removed. If the person has focused anything else, inside the cleanup panel or outside it, the move SHALL be dropped and MUST NOT be kept for a later paint. A move denied because another frame has focus SHALL stay dropped. + +#### Scenario: Focus moved before Tidy returns +- **WHEN** a run ends while Stop has focus, the Tidy button is absent during the reconciliation read, and the person focuses Search before that read finishes +- **THEN** focus stays in Search when the Tidy button reappears, and on every later paint + +#### Scenario: Focus moved to Undo before Tidy returns +- **WHEN** a run ends while Stop has focus, the result line offers Undo while the Tidy button is absent during the reconciliation read, and the person focuses Undo before that read finishes +- **THEN** focus stays on Undo for as long as Undo is shown, also when the Tidy button reappears +- **AND** the dropped move to the Tidy button is not applied later, also after the result expires and Undo is removed + +#### Scenario: Focus lost with the removed control +- **WHEN** a run ends while Stop has focus and the person focuses nothing else +- **THEN** focus moves to the Tidy button when it reappears + +#### Scenario: Count finishes after focus moved +- **WHEN** a count finishes after the person moved focus from Cancel to Search, and its repaint was delayed by a held control +- **THEN** focus stays in Search + +### Requirement: An account or store switch releases pending cleanup controls + +After the frame observes a change of the integration account or of the store and binding, cleanup controls on the board shown SHALL be usable without waiting for a cleanup request sent before the change. That request's late answer MUST NOT complete, release or otherwise change a cleanup action started after the change. This SHALL hold for a single-plan request as for a bulk run, and when the account or store changed and changed back before the answer. + +#### Scenario: Tidy after a switch +- **WHEN** the account changes while a cleanup request is held, and the person opens Tidy on the new board before that request answers +- **THEN** Tidy opens and counts + +#### Scenario: Store change observed during a single-plan request +- **WHEN** a single-plan cleanup request is held and a list reply shows that the store changed +- **THEN** cleanup controls on the board shown after that reply are usable before the held request answers + +#### Scenario: Late answer during a newer run +- **WHEN** the earlier request answers while a run started on the new board is in flight +- **THEN** the newer run stays pending until its own requests finish and cannot be confirmed a second time + +#### Scenario: Single-plan request held across a switch +- **WHEN** a single-plan cleanup request is held, the account changes, a Tidy run is started on the new board, and the held request then answers +- **THEN** the Tidy run completes and shows its own result +- **AND** the late answer shows no message and resets nothing on the new board + +#### Scenario: Switched away and back +- **WHEN** the account changes and changes back while a cleanup request is held, a new run is started, and the held request then answers +- **THEN** the late answer neither completes nor releases the new run + +### Requirement: A run's own updates do not replace a held control + +A progress update of a bulk run, and the repaint at its end with the result line and the selection changes its receipts cause, SHALL repaint as background data, so they wait while a control is held or a picker is open. The run itself, the release of its busy state, its cache invalidation and its reconciliation read MUST NOT wait for the repaint. A refresh MUST NOT expire a result that has not been painted yet. + +#### Scenario: Stop pressed while a plan is confirmed +- **WHEN** a plan's receipt arrives between pointer down and pointer up on Stop, and requests remain +- **THEN** Stop is not replaced before its click, and the run stops after the request in flight + +#### Scenario: Last reply arrives during a press +- **WHEN** the run's last reply arrives between pointer down and pointer up on an unrelated control +- **THEN** that control is not replaced while it is held, and the result line appears on the next paint +- **AND** the reconciliation read is sent without waiting for that paint +- **AND** a held control of the board whose data the run invalidated, such as Filters, stays in place and ignores that click, as after any cache reset + +#### Scenario: Hold lasts past the next refresh +- **WHEN** the run's last reply arrives while a control is held or a picker is open, and the hold lasts past the next refresh +- **THEN** that refresh does not expire the result, and the result line, with Undo after an archive, appears on the paint after the hold ends +- **AND** the refresh after that paint expires it, as before this change + +#### Scenario: Progress still advances +- **WHEN** no control is held and no picker is open during a run +- **THEN** the progress line follows the completed count, and the result line appears when the run ends, as before this change + +### Requirement: The result separates skipped plans from unconfirmed ones + +The result line SHALL state how many plans were archived, restored or deleted, how many were skipped and, separately, how many could not be confirmed and may have been applied. A plan whose request was attempted and received no valid answer SHALL be reported as unconfirmed, never as skipped. A plan the run did not attempt MUST NOT be reported as unconfirmed. Undo SHALL restore only plans with a validated archive receipt. + +#### Scenario: Reply lost +- **WHEN** the reply to one of 128 archive requests is lost or times out and the other 127 are archived +- **THEN** the line says 127 of 128 were archived and that one could not be confirmed and may have been archived +- **AND** that plan is not reported as skipped, is not reported as archived and is not retried automatically + +#### Scenario: Skipped and unconfirmed together +- **WHEN** one plan was refused as changed and the replies for two others were lost +- **THEN** the line states the archived count, one skipped and two that could not be confirmed, in one sentence + +#### Scenario: Stopped before sending +- **WHEN** the run is stopped with plans not yet sent +- **THEN** those plans count as skipped, never as unconfirmed + +#### Scenario: Attempt that failed before reaching the service +- **WHEN** the run attempts a plan's request and it fails while being prepared or handed over, before the service could receive it +- **THEN** the plan is reported as unconfirmed, because the run cannot tell this failure from a lost reply + +#### Scenario: Unconfirmed plans and Undo +- **WHEN** Undo is chosen after a run with unconfirmed plans +- **THEN** only the plans with a validated archive receipt are restored +- **AND** an unconfirmed plan that was in fact archived is not restored by Undo; it can be restored on its own once an Archived plans list or search shows it + +#### Scenario: Try again after unconfirmed plans +- **WHEN** Try again is chosen after an archive, a deletion or a restore of selected plans that left skipped and unconfirmed plans +- **THEN** both are recounted under the existing retry rules before a new confirmation, and a plan that has left the view is left out + +#### Scenario: Try again after a partial Undo +- **WHEN** Undo restored some plans, others were skipped or could not be confirmed, and Try again is chosen +- **THEN** the restore is sent again for exactly those remaining plans, each still bound to the revision and cleanup generation its archive receipt returned, without a recount in the view shown +- **AND** a plan whose earlier restore was in fact applied is confirmed as restored from the receipt the service saved for that same request, and is not restored twice +- **AND** a plan that another cleanup changed since is refused, left as it is and reported as skipped + +#### Scenario: Three languages +- **WHEN** the result line is shown in English, Russian or Simplified Chinese +- **THEN** it distinguishes skipped from unconfirmed plans in that language, as whole sentences with its plural forms + +## MODIFIED Requirements + +### Requirement: Explicit confirmation before any request + +Opening Tidy SHALL show an inline panel, not a modal, whose one short line states how many plans are in scope and whose buttons name the action and the count. It MUST NOT list plan titles. Cancel SHALL have initial focus, Enter MUST NOT confirm by default and Escape SHALL cancel. No archive, restore or delete request SHALL be sent on opening or cancelling. The deletion step SHALL keep what deletion removes and keeps reachable in one collapsed disclosure. + +#### Scenario: Cancel +- **WHEN** the user opens the panel and presses Escape or Cancel +- **THEN** no cleanup request is sent and focus returns to the Tidy button + +#### Scenario: Confirm +- **WHEN** the user activates the archive button +- **THEN** each plan in scope is archived through the existing per-plan archive route, bound to the progress revision and cleanup generation captured for it, one request at a time + +#### Scenario: Counting plans that are not loaded +- **WHEN** the scope reaches beyond the loaded list +- **THEN** the panel shows that it is counting, sends only reads, and can be cancelled before the count arrives + +#### Scenario: More than one run covers +- **WHEN** at least 1,000 matching plans are collected and more remain +- **THEN** the line says it covers the first 1,000 of more, and the rest can be done by using Tidy again + +#### Scenario: Scan limit reached first +- **WHEN** the scan reaches its 2,000-plan limit having collected fewer than 1,000 matching plans +- **THEN** the line states the number actually found and that more plans weren't checked, without claiming more matches exist, and offers Check more + +#### Scenario: Check more continues past checked plans +- **WHEN** the user chooses Check more after the scan limit +- **THEN** the scan continues from where it stopped in the same reading, reading up to 2,000 further plans and adding their matches to the count, never re-reading plans it already checked +- **AND** a change of store, account, binding, view, search or filters discards the continuation, so the next scan starts from the beginning + +#### Scenario: Deletion details +- **WHEN** the user expands the disclosure in the deletion step +- **THEN** it states that stored tasks, history and the document copy are removed, the original file is kept, and deletion is not secure erasure + +#### Scenario: Context changes mid-run +- **WHEN** the frame observes a change of the store, account, binding or board reading while requests remain +- **THEN** no further request is sent and no plan is reported as done without its validated receipt +- **AND** after a change of board reading in the same account, store and binding the run shows no result line and sends its one reconciliation read when it ends + +#### Scenario: Account, store or binding changes mid-run +- **WHEN** the frame observes a change of the account, store or binding while requests remain +- **THEN** the board shown after the change shows no result of that run and is not changed by it + +### Requirement: Honest result with undo + +A run SHALL show one progress line with how many of the total are done, and Stop. Its result SHALL be one line, kept until the next action or refresh, not a timer. After Archive it SHALL offer Undo, which restores each plan this run archived through the restore route; a deletion result MUST NOT offer Undo. Archive and Undo MUST NOT change a plan's lifecycle, counts or history. A plan SHALL be reported as done only when its receipt was validated, and no plan SHALL be retried automatically. + +#### Scenario: All archived +- **WHEN** 128 plans are archived +- **THEN** one line says 128 plans were archived and offers Undo, and the plans leave the current list after one authoritative re-read + +#### Scenario: Partial failure +- **WHEN** two of 128 plans were refused as changed +- **THEN** the line says 126 of 128 were archived and two were skipped, with a way to try again for the plans that remain +- **AND** the skipped plans are not retried automatically and are not reported as archived + +#### Scenario: Stop +- **WHEN** the user chooses Stop during a run +- **THEN** no further request is sent after the one in flight, and the result states how many were done before stopping + +#### Scenario: Undo +- **WHEN** the user chooses Undo +- **THEN** each plan this run archived is restored with its lifecycle unchanged, bound to the cleanup generation its archive returned +- **AND** a plan that changed since is left as it is and reported + +#### Scenario: Deleted +- **WHEN** 128 plans are deleted +- **THEN** one line says 128 plans were deleted and no Undo is offered + +#### Scenario: Keyboard and announcement +- **WHEN** a run starts and completes +- **THEN** its start and its result are each announced once, individual plans are not announced, and Stop and Undo are reachable by keyboard without moving focus unexpectedly diff --git a/openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md b/openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md new file mode 100644 index 0000000..525769c --- /dev/null +++ b/openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md @@ -0,0 +1,33 @@ +## ADDED Requirements + +### Requirement: Refusal guidance rests on validated receipt evidence + +Before coordinator guidance infers from a delegation receipt that cleanup retired a waiting delegation, a pending or reserved receipt SHALL be checked as the per-plan reader checks it: pending names no dispatch, reserved names one, and both name at least one task. A receipt that fails MUST NOT produce a refusal; it SHALL make the guidance incomplete, as other unreadable evidence does. Other receipts SHALL be read as before. The check MUST NOT change a receipt, the store or any reply. + +#### Scenario: Reserved without a dispatch +- **WHEN** a restored plan's latest delegation receipt says reserved and names no dispatch, and its intent is gone +- **THEN** coordinator guidance reports no `closed` refusal for it and is marked incomplete + +#### Scenario: Pending with a dispatch +- **WHEN** a restored plan's latest delegation receipt says pending and names a dispatch +- **THEN** coordinator guidance reports no refusal for it and is marked incomplete + +#### Scenario: Pending or reserved with no tasks +- **WHEN** a restored plan's latest delegation receipt says pending or reserved and declares no task, and its intent is gone +- **THEN** coordinator guidance reports no refusal for it and is marked incomplete + +#### Scenario: Cancellation receipts are read as before +- **WHEN** a plan's latest delegation receipt is a cancellation, either the empty declaration that cancelled or the earlier declaration it retired, which keeps its tasks +- **THEN** coordinator guidance reads it as before this change: it reports no refusal for it and is not marked incomplete because of it + +#### Scenario: Well-formed receipt after restore +- **WHEN** a restored plan's latest delegation receipt is pending without a dispatch, or reserved with one, names at least one task, its intent was retired by cleanup, and its declared tasks have not been verifiably recovered since +- **THEN** coordinator guidance reports the `closed` refusal as before + +#### Scenario: Well-formed receipt whose tasks were recovered +- **WHEN** that same well-formed receipt is still the latest, and the plan's current assignment shows its declared tasks were explicitly linked since +- **THEN** coordinator guidance reports no refusal for it, as before this change + +#### Scenario: Both readers agree +- **WHEN** the per-plan reader rejects a pending or reserved receipt because its dispatch disagrees with its state +- **THEN** coordinator guidance does not present that same receipt as complete evidence diff --git a/openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md b/openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md new file mode 100644 index 0000000..4baf1b3 --- /dev/null +++ b/openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md @@ -0,0 +1,67 @@ +## ADDED Requirements + +### Requirement: Idle traffic is counted by when and in what order it was sent + +The release gate's idle-traffic comparison SHALL count only requests sent inside the timed window, taken from the request log in the order they were sent. List pages and inbox requests SHALL be kept with the refresh whose first list page precedes them. Run reads SHALL be counted per window and shown as not compared per refresh, because the log cannot show which refresh caused one. Health reads SHALL be judged by cadence only. These checks change no shipped behaviour. + +#### Scenario: Request logged after the window ends +- **WHEN** a first-page list request is logged after the timed window stopped and before the driver read its logs +- **THEN** it is not counted as a list start of that window and does not close the refresh that was still open + +#### Scenario: Run read sent after the next refresh started +- **WHEN** a run read is sent after the next refresh's first list page, as the automatic follow-up of a run reconciliation can be +- **THEN** it is counted in the window's run-read count, which the artifact records +- **AND** it adds nothing to either refresh's per-refresh figures and is not lost with the final open refresh + +#### Scenario: Run read before the window's first list start +- **WHEN** a run read is sent inside the window before the window's first list page, because the refreshes around it started before the window +- **THEN** it is counted in the window's run-read count and is not dropped + +#### Scenario: Health read before its list page +- **WHEN** a refresh reads health before its first list page +- **THEN** that health read is not added to the previous refresh's traffic + +#### Scenario: Inbox request across a window edge +- **WHEN** a standalone inbox request is sent before the window and answered inside it, and another is sent inside the window and answered after it +- **THEN** only the second is counted in the window's inbox split, by when it was sent +- **AND** per-refresh verdicts still rest on complete refreshes: a request of the refresh left open at the window's end changes no per-refresh verdict, like that refresh's list pages + +#### Scenario: Reply-ordered attribution is caught +- **WHEN** attribution is changed to follow the order replies arrived +- **THEN** a unit test fails + +### Requirement: The gate reports what it cannot compare + +An artifact SHALL record how it attributed traffic and SHALL keep the wall-clock split of both inbox request forms. The gate SHALL compare the inbox form carried by the list read on its own as well as in the combined figure. A budget the gate cannot compare SHALL be reported as unverified and MUST NOT be reported as passed. That includes a per-refresh budget whose baseline and candidate figures do not rest on the same denominator. + +#### Scenario: Older artifact that bucketed replies +- **WHEN** the baseline artifact was produced by a driver that attributed replies instead of requests +- **THEN** the gate names the difference and does not treat the two as equivalent complete samples + +#### Scenario: Window with one list start +- **WHEN** an idle window holds a single list start, so no refresh completed inside it +- **THEN** the artifact still carries the wall-clock split of both inbox forms, and the form carried by the list read is still compared per list start +- **AND** no per-refresh budget is compared between that artifact's wall-clock figure and another artifact's complete refreshes + +#### Scenario: Extra boundary request on the standalone form +- **WHEN** a baseline counts one more standalone inbox request than list starts, and a candidate adds one inbox window carried by the list read +- **THEN** the comparison of the form carried by the list read fails + +#### Scenario: No comparable baseline +- **WHEN** the baseline, or all but one candidate, lacks the inbox split +- **THEN** the combined inbox budget is reported as unverified, the gate reports neither a pass nor a failed budget for it, and it exits unsuccessfully naming that state +- **AND** the comparisons that can be made still run + +#### Scenario: Mixed denominators +- **WHEN** the baseline completed no refresh inside its window, so its list-page figure rests on wall-clock counts, and the candidates' figures rest on complete refreshes +- **THEN** the per-refresh budgets are reported as unverified and the gate exits unsuccessfully naming that state +- **AND** a candidate that reads eleven list pages per refresh is not passed against a wall-clock baseline figure of nineteen + +#### Scenario: Per-refresh run-read budget +- **WHEN** the gate compares a baseline and candidates in the current artifact format +- **THEN** it shows each window's run-read count beside its list starts as a row that is not compared, and that row alone does not change the exit status +- **AND** it does not judge those counts as a budget + +#### Scenario: Wrong denominator is caught +- **WHEN** the gate divides by health replies where it should divide by list starts +- **THEN** a unit test fails diff --git a/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md b/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md new file mode 100644 index 0000000..97426bc --- /dev/null +++ b/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md @@ -0,0 +1,50 @@ +## ADDED Requirements + +### Requirement: Guidance clears a dependency block against the plan's current prerequisites + +The skill, the tool description and the inline guidance SHALL tell an agent that blocked a task because work moved back to its prerequisites to read the current plan before a handoff, and to unblock that task once every prerequisite it still has is done. A prerequisite the plan no longer lists MUST NOT keep it blocked; a skipped prerequisite that is still listed SHALL count as unfinished. The guidance SHALL stay advisory and MUST NOT change any tool input, validation, reply or size limit. + +#### Scenario: A revision removes one of two prerequisites +- **WHEN** an agent holding only the companion's text blocked a task on prerequisites A and B, an approved plan revision removes B as a prerequisite, and A finishes +- **THEN** the guidance leads it to set the task back to working or pending without waiting for B + +#### Scenario: A listed prerequisite was skipped +- **WHEN** a prerequisite the task still lists is skipped instead of done +- **THEN** the guidance does not lead the agent to clear the block for that reason + +#### Scenario: Before a handoff +- **WHEN** the agent is about to hand off with a task it blocked this way +- **THEN** the guidance leads it to read the current plan first and to clear the block if no listed prerequisite is unfinished + +#### Scenario: Another kind of blocker +- **WHEN** a task is blocked with a decision, review, external or other blocker +- **THEN** the guidance leaves that task and its blocker as they are + +#### Scenario: Description limits +- **WHEN** the companion's texts are built +- **THEN** the tool description stays within its existing total limit, with the checklist and start example inside its first part + +### Requirement: The companion's system prompt section stays identical across requests + +The companion's section of the system prompt SHALL contain only text that does not change within a session, and SHALL be byte-identical on every request where it is present. The one-request hint, the sub-agent resume capsule and the delegation refusal note SHALL be added for that request only after the content of its latest message, in a carrier valid for that message's role, with their text and eligibility unchanged, and MUST NOT be dropped. The stored conversation MUST NOT change. + +#### Scenario: A hint is due +- **WHEN** a dispatch or a plan-file write makes the one-request hint due and the next request is built +- **THEN** the system section is identical to the previous request's, and the hint is added after the latest message's content for that request only + +#### Scenario: Continuation after a plan-file write +- **WHEN** a plan-file write succeeds and the next request continues the tool call, so its latest message is a tool message +- **THEN** the system section is unchanged, and the hint is appended to the output of that message's last tool result for that request only, so the request stays valid for the provider + +#### Scenario: A sub-agent's plan moved on +- **WHEN** a sub-agent session sends two requests and the plan's revision changed between them, or the capsule lookup timed out for one of them +- **THEN** the system section is identical on both requests, and each request carries its own capsule, or none, after its latest message + +#### Scenario: A refusal appears and clears +- **WHEN** a delegation refusal note applies to one request and not to the next +- **THEN** the system section is identical on both, and only the first carries the note after its latest message + +#### Scenario: Section removed +- **WHEN** capture is off, the report tool is unavailable or the source is unverified +- **THEN** the section is absent as before, and no note is added to the message + diff --git a/openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md b/openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md new file mode 100644 index 0000000..e47a405 --- /dev/null +++ b/openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md @@ -0,0 +1,91 @@ +## ADDED Requirements + +### Requirement: A selection follows confirmed changes during a search + +While searching, a freshness reply SHALL certify only the result page it was asked about, identified by its number in the search and not by its position among the retained pages, and only when it covered every plan that page shows when the reply arrives. Hits the search reads into a page after it was checked SHALL leave it checked. A plan that a freshness reply shows missing, deleted or moved across the archive boundary SHALL leave the selection whichever page is shown. + +#### Scenario: Load more replaces the page a reply was asked about +- **WHEN** a freshness reply for result page 2 is held, Load more drops page 1 from the retained pages and shows page 3, and the reply then arrives +- **THEN** page 3 is not treated as checked by that reply +- **AND** page 3 is checked only by a reply that covered its own plans + +#### Scenario: Hits appended while a reply is held +- **WHEN** a freshness reply for an unchecked result page is held, the search appends further hits to that same page, and the reply then arrives with every covered plan unchanged +- **THEN** the page is not counted as checked by that reply +- **AND** it counts as checked once a reply has covered the plans it then shows + +#### Scenario: Hits read after a page was checked +- **WHEN** a freshness reply has certified a result page and the running search then reads further hits into that page +- **THEN** the page stays checked: those hits were read from the service at that moment, as the hits on the first page of a search are +- **AND** the next freshness read covers the plans the page then shows + +#### Scenario: Plan confirmed gone while another page is shown +- **WHEN** a selected plan has hits on two retained pages, a freshness reply for page 2 is held, the person goes back to page 1, and the reply shows that another frame archived the plan +- **THEN** the plan's hits leave both pages and the selected count drops by one +- **AND** page 1 stays unchecked until a reply covers it + +#### Scenario: Unchanged poll +- **WHEN** a freshness reply covered every plan shown on the page it was asked about and shows them unchanged +- **THEN** the selection and the focused row are kept and the page counts as checked + +### Requirement: A cleanup in this frame retires freshness reads in flight + +When a cleanup action in this frame invalidates the search, the freshness reads the frame already sent SHALL be retired: their replies MUST NOT certify a page or change the selection. A cleanup made elsewhere that this frame has not observed retires nothing; a freshness reply that shows its effect is evidence like any other. + +#### Scenario: Reply from before a cleanup +- **WHEN** a freshness reply is held on an unchecked result page under Select all, a matching plan is archived from this frame, and the reply arrives after the run reconciled +- **THEN** the reply changes nothing: the page is not marked checked and the archived plan is not selected again + +#### Scenario: Archive made in another frame +- **WHEN** a freshness read is in flight while another frame archives a selected plan, and its reply shows the plan archived +- **THEN** the plan leaves the selection and the retained pages, as for any plan a reply shows gone + +### Requirement: Deselection and departure are kept apart + +Under Select all, a plan the person deselected and a plan a cleanup receipt took out of view SHALL be tracked separately. Both SHALL last until the person clicks the plan's row, replaces the selection with Select all or ends it. A departure SHALL also end when an Undo receipt returns the plan, a verified read lists it, or a fresh count finds it in the view at a newer cleanup generation; none of these SHALL end a deselection. A cached, unchecked page MUST NOT end a departure. + +#### Scenario: Restored elsewhere, then counted again +- **WHEN** a plan is archived from this frame under Select all, the retained search drops it, another frame restores it, and the person opens the next action +- **THEN** the count includes that plan at its current revision and cleanup generation + +#### Scenario: Deselected plan stays out +- **WHEN** the person deselected a plan under Select all and a fresh count finds that plan in the view +- **THEN** the plan is left out of the action + +#### Scenario: Deselected and departed +- **WHEN** a plan was both deselected by the person and taken out by a receipt, and an Undo receipt, a verified read or a fresh count returns it to the view +- **THEN** its departure ends and it stays out of the action as a deselected plan, until the person clicks its row or replaces the selection with Select all + +#### Scenario: Select all pressed again +- **WHEN** the person presses Select all again after deselecting plans +- **THEN** the selection is replaced and those plans are selected again, as before this change + +#### Scenario: Still archived +- **WHEN** a departed plan is still archived when the next action in Current plans is counted +- **THEN** it is not in the count + +### Requirement: A new search result page starts unchecked + +A result page opened by Load more SHALL start unchecked, whatever the state of the page shown before it, and SHALL count as checked only after a freshness reply covered its own plans. A page that shows no plan has nothing to check and MUST NOT show the checking note. + +#### Scenario: New page after a checked page +- **WHEN** Load more opens a new result page while the page shown before it was checked +- **THEN** the new page is not treated as checked until a freshness reply has covered its plans +- **AND** the note that results are being checked can show until then, with no time limit; a failed freshness read leaves the page unchecked and is reported by the existing stale indication + +#### Scenario: Load more finds nothing +- **WHEN** Load more opens a new result page and the search ends without a hit for it +- **THEN** the page shows no checking note, and no freshness read is added for it + +### Requirement: A Select all count states the plans the frame has loaded + +Under Select all, the selection bar's count SHALL be the number of selected plans the frame has loaded. It SHALL carry a plus mark only while matching plans are known not to be loaded, as before this change, and MUST NOT gain one because the list was read in several pages. The count is not a verified total of matching plans: where a list read in several pages may have missed a plan, the confirmation SHALL say so before any request. + +#### Scenario: Complete list read in several pages +- **WHEN** Select all is active on a complete list that was read in several pages +- **THEN** the selection bar states the number of selected plans the frame has loaded, without a plus +- **AND** an action opened from it says that some plans may have been missed + +#### Scenario: Matching plans not loaded +- **WHEN** Select all is active while matching plans are not loaded +- **THEN** the selected count carries a plus mark, as before this change diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md new file mode 100644 index 0000000..e763f28 --- /dev/null +++ b/openspec/changes/release-1-5-2/tasks.md @@ -0,0 +1,79 @@ +# Tasks + +Each numbered group is one pull request into the development branch. It carries its own documentation, English/Russian/Simplified Chinese copy where copy changes, and a regression test that fails before each fix. It passes portable CI alone, commits no generated output and changes no version. Groups 2, 4 and 6 touch disjoint source and test files and can be worked in parallel; group 5 is independent of every other group. Group 3 starts after group 2 has merged, because both change the end of the bulk run in the shared view controller, and after group 4, which rewrites the same line of the Tidy result statement in `docs/ui.md`. Group 1 starts after groups 2, 3, 4 and 6 have merged and merges last: it shares the controller with group 2, the cleanup model with group 4 and the bulk-count paragraphs of `docs/ui.md` and `docs/contracts.md` with group 6, and it changes how the end of a run hands its receipts to the selection, in lines groups 2 and 3 change before it. Groups 1 to 6 archive no OpenSpec change; the release pull request of group 7 does. + +## 1. Counts and selection while plans change + +- [ ] 1.1 Record on the list read that it crossed a page boundary, and carry that into Tidy and Select all confirmations built from the loaded list: the count line and the deletion step say that some plans may have been missed. Keep a single-page list, and rows explicitly chosen from the loaded list, exact; a count that runs through a scan keeps the scan's own rules. Keep a Try again recount exact when it found every plan it names, and qualify it when the list was read in several pages and a named plan is not among the loaded rows. Add no read, and leave the selection bar's plus rule as it is: under Select all its count is the number of selected plans the frame has loaded, not a verified total. Test the controller with a multi-page and a single-page list, for Tidy, Select all, chosen rows, and Try again with every named plan found and with one not found. +- [ ] 1.2 Make a search freshness reply certify the result page it was asked about by that page's number in the search, never another page, and only when it covered every plan the page shows when it arrives. Keep a checked page checked when the search reads further hits into it. Test with a held reply across a Load more that drops the oldest retained page, with a held reply while the search appends hits to the same page, and with hits read after the reply, which leave the page checked. +- [ ] 1.3 Retire freshness reads in flight when a cleanup action in this frame retires the search; a cleanup made in another frame retires nothing. Test with a reply held across an archive under Select all: it marks nothing checked and does not select the archived plan again. Keep the case of a plan archived from another frame, whose reply still removes it. +- [ ] 1.4 Pass the plans a freshness reply showed gone to the selection separately from the page's checked state, so they leave the selection whichever page is shown. Test with a selected plan whose hits span two retained pages. +- [ ] 1.5 Keep receipt departures apart from deselections when an action captures a Select all rule, and let a fresh count include a departed plan it finds in the view at a newer cleanup generation than its receipt returned. Hand that generation from the run to the selection with each receipt, as a map from plan to cleanup generation, for the bulk run and the single-plan action alike; do not read it from a loaded row. A return by receipt, verified read or fresh count ends the departure only; a deselection of the same plan ends when the person clicks its row, or replaces the selection with Select all, which clears deselections and departures as it does today. Test: restored elsewhere and counted again; a departed plan the page never loaded, restored elsewhere and counted again; deselected stays out; deselected and departed stays out; still archived stays out; Select all pressed again selects a deselected plan again. +- [ ] 1.6 Start a result page opened by Load more unchecked, whatever the previous page's state, and keep it unchecked until a freshness reply covers it, with no time limit. A page that shows no plan shows no checking note and adds no freshness read. Test after a checked page, with a failed freshness read, which leaves the page unchecked, and with a Load more that ends without a hit. +- [ ] 1.7 Update the counting, Select and selection-context statements of `docs/ui.md` and the bulk-count paragraph of `docs/contracts.md`, including the consequence for lists longer than one page. Run the root and interface typechecks and the browser logic tests. + +## 2. Account, store and capability + +- [ ] 2.1 Capture the integration account and the store and binding identity when a bulk run starts, and when the frame observed a change of either since the run started, also one that has changed back, drop the run's own state at its end without resetting caches, changing the selection, closing the opened plan or showing a result. An observed change is an account change the host announced, or a store or binding change a list reply showed; do not decide by comparing the identity at the end. Keep the device-side effect of a validated Delete receipt: it still removes the review marker stored for its plan under the account and store the run started in, also when it arrives after the change. Test with a held request across an account switch, with equal identifiers in the new store, with a switch away and back and no newer run, and with a store change shown by a list reply after a change of filters resumed list reads during the run. Keep the scope-change-only case as it is, where the run stops and shows no result line, keep the existing marker tests passing, and pin the case the frame cannot observe: a store change while the run has the list reads paused is adopted by the list read that follows the run. +- [ ] 2.2 Take the cleanup facts the controls follow from the latest health reply the controller accepted, whichever remembered scope is adopted, so that adopting one neither restores support a later reply withdrew nor hides support a later reply granted. A health reply is accepted when its refresh settles, as today. Test: a switch between Current and Archived plans after support was withdrawn; a failed list read after a health reply without cleanup; support that returns with an unchanged list; and support granted after one view of Current plans was remembered without it and accepted in another view of Current plans, followed by a switch back to the first. +- [ ] 2.3 Release the busy state when the frame observes an account or store change, and bind it and the stale-answer cleanup to the request that set them, in the single-plan action as well as the bulk run, so the new board's cleanup controls work at once and a late answer can neither complete, release nor reset a newer run, also after a switch away and back. Test: Tidy opens after a switch with a request still held; a late answer during a newer run leaves that run pending; a held single-plan request, an account switch, a new Tidy run, then the old reply: the new run completes and shows its result; a held request, a switch away and back, a new run, then the old reply: the new run keeps its state and result; a store change shown by a list reply while a single-plan request is held: the controls are usable before that request answers. +- [ ] 2.4 Update the binding, failure and invalidation statements of the closed-plan cleanup section of `docs/ui.md`. Run the root and interface typechecks and the browser logic tests. + +## 3. Background updates and focus + +- [ ] 3.1 Repaint a count that finishes by itself, its failure and the end of a Check more continuation through the background lane; keep explicit actions on the immediate lane. Test: a count finishing during a press on an unrelated control leaves that control in place until its click. +- [ ] 3.2 Repaint run progress, and the end of a run with its result line, through the background lane, without delaying the release of the busy state, the cache invalidation or the reconciliation read. Do not let a refresh expire a result that has not been painted yet. Test: a receipt arriving during a press on Stop leaves Stop in place, and the run stops after the request in flight; the run's last reply arriving during a press on an unrelated control leaves that control in place while it is held, while the reconciliation read is sent; a hold that lasts past the next refresh still ends with the result line and Undo painted. Do not assert that a held board control such as Filters acts on that click: the cache invalidation retires it. +- [ ] 3.3 Decide a deferred cleanup focus move when it is applied: apply it only if focus is still on the control the move was queued from, or is on no control because that control was removed, and drop it otherwise, also when focus moved to another control of the cleanup panel. Test: focus moved to Search before the Tidy button reappears stays in Search; focus moved to Undo before the Tidy button reappears stays on Undo while Undo is shown, and the dropped move is not applied after the result expires; focus left on Stop moves to Tidy; a count delayed by a held control does not take focus back. +- [ ] 3.4 Update the result, focus and controller repaint statements of `docs/ui.md`. Run the cleanup rendered driver's keyboard pass at desktop width and 390 px, the root and interface typechecks and the browser logic tests. + +## 4. Unconfirmed results + +- [ ] 4.1 Keep the failure class of each bulk request in the run engine and report unconfirmed plans apart from skipped ones, using the classes the single-plan messages already use. A plan the run did not attempt is never unconfirmed. Test each class against the cleanup fixture and with a held or failed transport: refused as changed, store busy, lost reply, unreadable receipt, an attempt rejected before it reached the service, left out before sending, stopped before sending. +- [ ] 4.2 Reword the result line in English, Russian and Simplified Chinese as the design tables it, as whole strings with plural rules, for archive, restore and delete; keep one sentence and one announcement. Test the strings and the view for skipped only, unconfirmed only and both; review Russian and Chinese by reading. +- [ ] 4.3 Keep Undo to validated receipts and Try again to a recount of skipped and unconfirmed plans together. After a partial Undo, keep Try again as it is: the restore sent again for the remaining plans, bound to their archive receipts, without a recount. Test all three after a run with unconfirmed plans, and both outcomes of the repeated restore: a plan whose earlier restore was applied is confirmed from the receipt the service saved and is not restored twice, and a plan another cleanup changed since is refused and reported as skipped. +- [ ] 4.4 Update the Tidy result statement of `docs/ui.md` and the bulk run paragraph of `docs/contracts.md`. +- [ ] 4.5 Raise the cleanup fixture's request limit for service calls to 30 seconds while its readiness probe keeps a short bound, check the fixture's other users still pass, and make the selection driver assert that the archive result reports every plan archived before it uses Undo. Run the selection driver and the backend cleanup suites that use the fixture, then the root and interface typechecks and the browser logic tests. + +## 5. Large-library gate precision + +- [ ] 5.1 Capture the request and reply offsets of a timed window in the browser evaluations that start and stop its timer, and slice between them, in a helper the unit tests can call. Take the cadence counts and both inbox forms from the request log inside those bounds, and keep the reply log for status, size and timing. +- [ ] 5.2 Count run reads per window, outside the per-refresh figures: every run read sent inside the window, whichever refresh preceded it. Record that count beside the window's list starts as an informational row that does not affect the exit status, and judge neither. Keep health reads out of per-refresh traffic. Test a run read sent after the next refresh's first list page, one sent inside the window before the window's first list start, and that the row leaves a passing run passing whatever the counts are. +- [ ] 5.3 Record the attribution method and the wall-clock split of both inbox forms in the artifact; make the gate distinguish artifacts that bucketed replies, and compare the inbox form carried by the list read on its own as well as combined. +- [ ] 5.4 Report the combined inbox budget as unverified when the baseline or too few candidates carry the split, with its own summary state and an unsuccessful exit, while the other comparisons still run. Report a per-refresh budget the same way when its baseline and candidate figures do not rest on the same denominator, and keep comparing the inbox form carried by the list read per list start. Make the summary name each unverified budget and each failed one. +- [ ] 5.5 Strengthen the tests so they fail for reply-ordered attribution and for the wrong denominator: a reply landing after the final first-page reply, one start with two health replies and ten plan replies, a mix of an older candidate, a current candidate and one without a split, a baseline with a single list start against candidates with complete refreshes, and an inbox request sent across each window edge, asserting the window's split and that a request in the refresh left open at the window's end changes no complete-refresh figure. +- [ ] 5.6 Update the large-library paragraph of `docs/ui.md`, including how a baseline is recorded for the current artifact format: the current driver run against an interface build from before the 1.5.1 responsiveness change, the last one that shows the stall a baseline must show. Rehearse that procedure once, check that the recorded baseline completed at least one refresh inside its idle window, and report the completed baseline run in the pull request as local synthetic-host evidence without committing a measurement. Run the gate and attribution tests, and one rendered run of the driver to show the offset capture. + +## 6. Guidance, receipt evidence and documentation + +- [ ] 6.1 Reword the moved-back sentence in the skill, the tool description and the inline guidance so the block is cleared against the plan's current prerequisites, read before a handoff, with a still-listed skipped prerequisite counting as unfinished. Keep the tool description within its tested limits and update the active-tool statement of `docs/contracts.md`. Judge it by reading, not phrase search: given only the companion's text, record what an agent does after a revision removes one of two prerequisites. +- [ ] 6.2 Check a delegation receipt's state against its dispatch and its declared tasks in the coordinator refusal reader before inferring a cleanup retirement, and mark the guidance incomplete when the check fails. Apply the check to pending and reserved receipts only, before the existing recovery step. Test reserved without a dispatch, pending with one, pending or reserved with no tasks, both shapes of a cancellation read as before (the empty declaration that cancelled, and the earlier declaration it retired, which keeps its tasks), the well-formed cases after a restore, each naming at least one task, and a well-formed receipt whose tasks were explicitly linked since, which still yields no refusal. +- [ ] 6.3 State in `docs/ui.md` when chosen plans are validated by point lookup, when the loaded rows or a list scan are used instead, and that it is the point lookup that skips a moved revision where search or session criteria apply. +- [ ] 6.4 Name the retry baseline in `docs/contracts.md` and `docs/ui.md` for the reader that compares: where the point lookup validates named plans, the revision supplied to the count, which on Try again is the original target's revision. Say that a complete list and an older service's list scan take a named plan as their row shows it. Run the root typecheck and the affected backend tests. + +## 8. Stable system prompt section + +- [ ] 8.1 Keep the companion's system prompt section to the fixed activation guidance only, identical on every request where it is present, and add the one-request hint, the sub-agent resume capsule and the delegation refusal note for that request only after the content of its latest message, in a carrier valid for its role: a text part on a user message, the output of the last tool result on a tool message, and otherwise the next request with a valid carrier, never dropped. Their text and eligibility stay unchanged. Test consecutive requests across a hint trigger, a capsule revision, a capsule lookup timeout and a refusal appearing and clearing: the system array is identical each time, and the varying text arrives once, on the latest message, for that request only. Extend the native activation driver to check the outgoing request of a real plan-file write continuation: the hint is inside the last tool result and the system section is unchanged. +- [ ] 8.2 Update the statements in `docs/contracts.md`, `docs/backend.md` and `docs/compatibility.md` about where the section and its notes are delivered, including what providers that drop plugin system sections now receive, and say that the section stays identical across requests so it does not defeat a provider's prompt cache. + +## 7. Joined verification and release + +- [ ] 7.1 After groups 1 to 6 and 8 have merged, run one rendered journey on the development branch at desktop width and 390 px: Tidy and a mixed selection with archive, Undo and delete; a search selection across two result pages with a plan archived from another frame; the result line with skipped and unconfirmed plans in three languages; and a keyboard-only pass through count, run, Stop and result. +- [ ] 7.2 Run the measuring driver on the joined branch and the gate against a baseline recorded with the same driver. Report every row, including any reported as unverified and the informational run-read row. The gate passes. Commit no measurement. +- [ ] 7.3 Run portable CI in a fresh full-history disposable checkout with a cleared environment, and review every public diff for private data. +- [ ] 7.4 Prepare the release in one pull request into the development branch: version 1.5.2 in the package and the release constant, the changelog entry and curated release notes. This pull request is not documentation-only for CI: release notes and the changelog feed the release scripts, and tests read `openspec/changes/archive/`. +- [ ] 7.5 In the same pull request, reconcile the task lists of the 1.5.0 change, the 1.5.1 change and this one: tick each task whose work shipped, and leave a task that did not happen unticked with a note saying whether it is deferred, superseded or out of scope. +- [ ] 7.6 In the same pull request, archive the 1.5.0 change, then the 1.5.1 change, then this one, in that order, because each later change modifies capabilities the earlier ones introduced. Never use `--skip-specs` or `--no-validate`. A rehearsal showed what this pull request must correct in the 1.5.1 change's deltas before archiving that change. First, restore the two scenario names that the 1.5.0 specs hold and two of its modified requirements dropped, either by putting the old name on the new content or by keeping the old scenario beside the renamed one. Second, shorten or split the four requirement texts that would exceed 500 characters once in the specs, keeping their meaning and their scenarios. That includes the result requirement at 628 characters, although this change replaces it in the third archive: strict validation runs after the second archive too. After each archive, write the purpose of every capability it created, ten in all, and validate the specs strictly. That validation reports nothing after each of the three archives. If an archive refuses any other delta, correct the delta. + +## Deferred acceptance and out-of-scope follow-up + +- [ ] Promotion to the distribution branch and its host gates, as the contributor guide describes. It follows the release pull request, and so the archive of this change. The nine generated outputs are built and committed by the promotion only. +- [ ] Repairing the rendered QA drivers that were already stale before 1.5.1. Tracked separately. +- [ ] A list read the service can vouch for as a snapshot, so a multi-page count can be exact again. +- [ ] Physical-phone and native-host acceptance of the changed surfaces. Emulated and synthetic-host evidence does not establish them. +- [ ] Re-checking a count, a confirmation or a run that is already open when the service withdraws in-progress cleanup support. Today a run decides when it starts, a single-plan request when it is sent, and the service's own check refuses the rest. +- [ ] Observing a store or binding change while a bulk run has the list reads paused. Today the list read that follows the run observes it. +- [ ] Applying a health reply before the refresh that read it settles. +- [ ] Attributing a run read to the refresh that caused it in the large-library gate, which needs the request log to record a cause. Until then the gate shows run reads per window as an informational row. +- [ ] Keeping a board control that is held when a bulk run ends valid as well as in place. Today the run's cache invalidation retires it, so it ignores that click. +- [ ] Result expiry: repainting the expiry of a painted result as background data, and keeping a result the person has not seen through their own next action. +- [ ] Recording per search hit whether a freshness reply covered it, so a page's checked state no longer depends on whether a reply or a search read came first. From 30f2d657d830fbb1f12ce5fe2d7d4917470629df Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:46:43 +1100 Subject: [PATCH 02/11] fix(companion): clear dependency blocks against current prerequisites and validate receipts (#162) * fix(companion): clear dependency blocks against current prerequisites and validate receipts before refusing The moved-back guidance in the skill, tool description and inline guidance now unblocks against the plan's current prerequisites: a prerequisite the plan no longer lists no longer holds the task, and a still-listed skipped one counts as unfinished. Coordinator refusal guidance validates pending and reserved receipts as the per-plan reader does and reports incomplete evidence instead of a closed refusal. The retry baseline and point-lookup applicability are documented. * docs: describe how malformed delegation receipts affect coordinator guidance --- docs/backend.md | 4 +- docs/contracts.md | 20 +++-- docs/ui.md | 4 +- openspec/changes/release-1-5-2/tasks.md | 8 +- plugin/SKILL.md | 2 +- plugin/index.ts | 4 +- shared/subagent-runs.ts | 5 ++ tests/backend/plan-cleanup-delegation.test.ts | 73 +++++++++++++++++++ tests/backend/progress-invocation.test.ts | 2 +- 9 files changed, 104 insertions(+), 18 deletions(-) diff --git a/docs/backend.md b/docs/backend.md index e4775b3..c2ce74e 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -1512,7 +1512,9 @@ at most three current-per-plan refusals and marks incomplete evidence. Newer declaration evidence suppresses old refusals, as do bounded current assignments covering all refused tasks through linked children at a later revision; archived/deleted plans and -disabled/unverified contexts expose none. +disabled/unverified contexts expose none. A pending or reserved receipt whose +state disagrees with its dispatch, or that names no task, marks evidence +incomplete instead of yielding a refusal. The refreshed coordinator context section is capped at 4 KiB, uses fixed reasons and explicitly marks omissions, including an empty incomplete result. It is advisory and read-only: recovery requires diff --git a/docs/contracts.md b/docs/contracts.md index 44491bb..9893236 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1159,14 +1159,18 @@ service's 16 KiB encoded-query limit each, pinned to the expected store and binding). This applies to scans that use the named reader: a truncated or searched scope on a service that advertises `planTaskSearch`. A complete non-search list counts from the displayed metadata without a lookup, and an older service still -counts a truncated browse scope with the list scan. In the named reader, where the -view's scope depends on content the client cannot evaluate (a search, a session -scope) a plan whose revision moved since the count began (the revision captured -when the count was requested, not necessarily when the rows were chosen) is +counts a truncated browse scope with the list scan. Only the point lookup +compares a named plan with a baseline: the revision supplied to the count, which +is the revision the chosen plan carried and, on Try again, the original target's +revision (not the revision at which the count began). A complete list takes a +named plan as its loaded row shows it, and the older service's list scan takes it +as the scan's row shows it; neither compares it with a supplied revision. In the +point lookup, where the view's scope depends on content the client cannot evaluate +(a search, a session scope) a plan whose revision differs from the supplied one is skipped as changed; elsewhere it is re-read with one `/v1/plan` head read, verified against the expected store and binding, and a missing plan is dropped only after the pinned lookup confirms its absence. Every request carries the -captured revision and the service enforces it. Each lookup and each head read is one request of the +captured revision and the service enforces it, in every path. Each lookup and each head read is one request of the per-action budget; unfinished plans wait for Check more. The count distinguishes a target ceiling with a confirmed further match (**more remain**) from unchecked plans that may or may not match: a full set keeps scanning @@ -1327,7 +1331,9 @@ replay, `/v1/plan?delegationIntent=1` and coordinator guidance all show it as `retired`/`closed` (a refusal to redeclare or link), never as waiting or invalid; a fresh declaration works. Only the explicit restore record explains a missing intent: a plan never archived whose pending receipt lost its intent is not reported -as closed; the view is unavailable and guidance incomplete. A new unlinked dispatch ignores archived plans when it +as closed; the view is unavailable and guidance incomplete. A pending or reserved +receipt whose state disagrees with its dispatch, or that names no task, is +unreadable evidence: guidance is incomplete and reports no refusal for it. A new unlinked dispatch ignores archived plans when it looks for its one visible active plan. Older writers may return generic storage errors; their old readers can show @@ -1921,7 +1927,7 @@ prerequisites; `delegate`/`link` sub-agent tasks; `change` actual work to workin to load the skill when writing, receiving or coordinating plans and before dispatching sub-agents. The description is at most 4,096 characters, with the checklist and executable prerequisite start example inside the first 2,048. -Operation details remain in the skill. The skill and the inline guidance also say that when work moves back to the prerequisites of a task that is working, that task is marked blocked with a `blocker:{category:"dependency",reason}` payload (an Also blocked entry, never Needs you; the map shows beads into it from working prerequisites), or set back to pending if none of its own work was done; that a task that is already blocked is left as it is, so its decision, review, external or other blocker is never replaced; and that once every prerequisite it was blocked on is done again the task blocked this way is set back to working or pending, including before a handoff, because an explicit blocked task never becomes Ready. The following conditional rule still applies: +Operation details remain in the skill. The skill and the inline guidance also say that when work moves back to the prerequisites of a task that is working, that task is marked blocked with a `blocker:{category:"dependency",reason}` payload (an Also blocked entry, never Needs you; the map shows beads into it from working prerequisites), or set back to pending if none of its own work was done; that a task that is already blocked is left as it is, so its decision, review, external or other blocker is never replaced; and that the block is cleared against the plan's current prerequisites: before a handoff, and when a prerequisite finishes, the agent reads the current plan, and once every prerequisite the task still lists is done the task blocked this way is set back to working or pending, because an explicit blocked task never becomes Ready. A prerequisite the plan no longer lists no longer holds the task, and a skipped prerequisite that is still listed counts as unfinished. This guidance is advisory; the store is unchanged and a structural revision keeps an explicit blocked status. The following conditional rule still applies: tracker updates are not Agent Progress reports; explicitly mirror meaningful unreported canonical state at PLAN_READY handoff, review approval, owner approval and actual work start, not again when already current. These are diff --git a/docs/ui.md b/docs/ui.md index 06615b8..c4d3cf4 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -1016,9 +1016,9 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Counting and confirmation.** A complete loaded scope supplies targets without a read. Otherwise a separate bounded list/search traversal counts them, applying the same effective filters as the displayed board (including normalized project/worktree choices) and, when browsing, the board's own placement of a plan by its recorded directory (the search-only check that a chosen location is currently discoverable applies to searches alone) without populating ordinary list/search caches or changing refresh budgets. Each explicit scan stops at 2,000 plan slots or 40 request windows, whichever comes first. Forty windows match the ordinary 50-plan list-page budget and prevent task-heavy search continuations from causing thousands of round trips. **Check more** continues from its last cursor with fresh per-action budgets, adding matches without repeating windows. The cursor is discarded on a store, account, binding, view, search or filter change. At most 1,000 targets belong to a confirmation. **First 1000 closed plans; more remain.** appears only once a further match has been found (a full set keeps counting within the scan budget to prove it); a cursor that merely remains, including after exactly 1,000 matches, says that more plans weren’t checked, never that more match. Each browse page after the first starts one row early and must open with the plan that ended the previous page; if another frame archived or deleted a plan behind the cursor, the count fails (**Could not count plans. Try again.**) instead of skipping plans and claiming completeness. The final **Delete permanently…** step repeats the same one-line subset qualification when the count is limited or unchecked. Cancel gets initial focus, Enter never defaults to a destructive action, and Escape cancels and returns focus to Tidy. Opening/cancelling sends no cleanup request. **Archive N plans** confirms Archive; **Delete permanently…** opens its own second step, whose count line says it cannot be undone. One collapsed disclosure keeps the stored tasks/history/document-copy removal, original-file preservation and non-erasure details reachable. - **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests, which are skipped. - **Effective selection scope.** Ownership includes the board's normalized location filters. If the last plan in a project or worktree leaves and the board falls back to all locations, Select all is retired; selecting those other locations requires a new gesture. Old action callbacks cannot open a broader confirmation before repaint. Search counts update when hits are appended to the same result-page array and still count each plan only once. -- **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view; a chosen plan whose revision moved after the count began is skipped as changed. This is the named-plan count used for a truncated or searched scope; a complete browse list counts from the displayed rows. A count that read every page of an offset-paged list says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. A plan a cleanup receipt took out of a Select all rule is selected again when an Undo receipt puts it back or a verified read lists it again (a cached, unchecked search page is not evidence), and a click on such an unpressed row selects it; a plan the user deselected stays deselected. +- **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view. Where a chosen plan is validated by point lookup (a truncated or searched scope, only when the service offers `planTaskSearch:1`), the baseline it is compared with is the revision supplied to the count: the revision the selection carried and, on Try again, the original target's revision, not the revision when the count began. Where search or session criteria apply, the point lookup skips a plan whose revision moved as changed and does not adopt the new one; that skip belongs to the point lookup only. A complete browse list counts a chosen plan from the displayed rows and an older service's list scan takes it as the scan's row shows it; neither compares it with the supplied revision. A count that read every page of an offset-paged list says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. A plan a cleanup receipt took out of a Select all rule is selected again when an Undo receipt puts it back or a verified read lists it again (a cached, unchecked search page is not evidence), and a click on such an unpressed row selects it; a plan the user deselected stays deselected. - **Keyboard order.** Tidy precedes the selection bar, which precedes confirmation/result actions. Outside Select mode this gives Tidy → Select → Undo when an archive result is shown. In Select mode, Done and Select all come first; when plans remain selected, Archive/Restore, Delete permanently… and Clear follow, then Undo. The count is a live status, not a Tab stop. -- **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. +- **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: in a searched or truncated scope, on a service that offers `planTaskSearch:1`, their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle, except where search or session criteria apply, where the point lookup skips it as changed. A complete browse list uses the loaded rows instead, and an older service counts a truncated browse scope by list scan. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. - **Unsupported in-progress plans.** Archive/Delete counting excludes these plans before applying the 1,000-target ceiling, in loaded selections and scans alike. Their distinct-plan warning count is separate from eligible targets; they still consume scan slots/windows, so a scan that has not reached eligible plans offers Check more rather than an empty terminal target ceiling. - **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A changed, refused or unconfirmed plan is skipped without retry; Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures. The result states completed and skipped counts, with Undo for precisely the successful archive receipts and Try again recounting only the plans the run left, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; changed plans stay untouched and unsuccessful restores are reported. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. - **Archived plans** is a page-level view above filters, including when ordinary results are empty. It uses the existing list/detail/document/history views. **Restore** preserves the plan's lifecycle and history, including an archived in-progress plan, which accepts reports again after restoration. More offers Restore and Delete permanently for archived plans of any lifecycle (in-progress deletion requires the service capability). Switching Current/Archived plans resets filters and selection so archived work is discoverable. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index e763f28..818ca6c 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -45,10 +45,10 @@ Each numbered group is one pull request into the development branch. It carries ## 6. Guidance, receipt evidence and documentation -- [ ] 6.1 Reword the moved-back sentence in the skill, the tool description and the inline guidance so the block is cleared against the plan's current prerequisites, read before a handoff, with a still-listed skipped prerequisite counting as unfinished. Keep the tool description within its tested limits and update the active-tool statement of `docs/contracts.md`. Judge it by reading, not phrase search: given only the companion's text, record what an agent does after a revision removes one of two prerequisites. -- [ ] 6.2 Check a delegation receipt's state against its dispatch and its declared tasks in the coordinator refusal reader before inferring a cleanup retirement, and mark the guidance incomplete when the check fails. Apply the check to pending and reserved receipts only, before the existing recovery step. Test reserved without a dispatch, pending with one, pending or reserved with no tasks, both shapes of a cancellation read as before (the empty declaration that cancelled, and the earlier declaration it retired, which keeps its tasks), the well-formed cases after a restore, each naming at least one task, and a well-formed receipt whose tasks were explicitly linked since, which still yields no refusal. -- [ ] 6.3 State in `docs/ui.md` when chosen plans are validated by point lookup, when the loaded rows or a list scan are used instead, and that it is the point lookup that skips a moved revision where search or session criteria apply. -- [ ] 6.4 Name the retry baseline in `docs/contracts.md` and `docs/ui.md` for the reader that compares: where the point lookup validates named plans, the revision supplied to the count, which on Try again is the original target's revision. Say that a complete list and an older service's list scan take a named plan as their row shows it. Run the root typecheck and the affected backend tests. +- [x] 6.1 Reword the moved-back sentence in the skill, the tool description and the inline guidance so the block is cleared against the plan's current prerequisites, read before a handoff, with a still-listed skipped prerequisite counting as unfinished. Keep the tool description within its tested limits and update the active-tool statement of `docs/contracts.md`. Judge it by reading, not phrase search: given only the companion's text, record what an agent does after a revision removes one of two prerequisites. +- [x] 6.2 Check a delegation receipt's state against its dispatch and its declared tasks in the coordinator refusal reader before inferring a cleanup retirement, and mark the guidance incomplete when the check fails. Apply the check to pending and reserved receipts only, before the existing recovery step. Test reserved without a dispatch, pending with one, pending or reserved with no tasks, both shapes of a cancellation read as before (the empty declaration that cancelled, and the earlier declaration it retired, which keeps its tasks), the well-formed cases after a restore, each naming at least one task, and a well-formed receipt whose tasks were explicitly linked since, which still yields no refusal. +- [x] 6.3 State in `docs/ui.md` when chosen plans are validated by point lookup, when the loaded rows or a list scan are used instead, and that it is the point lookup that skips a moved revision where search or session criteria apply. +- [x] 6.4 Name the retry baseline in `docs/contracts.md` and `docs/ui.md` for the reader that compares: where the point lookup validates named plans, the revision supplied to the count, which on Try again is the original target's revision. Say that a complete list and an older service's list scan take a named plan as their row shows it. Run the root typecheck and the affected backend tests. ## 8. Stable system prompt section diff --git a/plugin/SKILL.md b/plugin/SKILL.md index 64b9803..7c4be03 100644 --- a/plugin/SKILL.md +++ b/plugin/SKILL.md @@ -46,7 +46,7 @@ it is not evidence of a host outage. Empty/all-skipped plans cannot finish successfully. Denied document access still commits valid checklist changes with diagnostics; `source` is optional and never a reason to manufacture a file. -If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. When every prerequisite it was blocked on is done again, set the task you blocked this way back to working or pending, including before a handoff, since an explicit blocked task never becomes Ready. +If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. Before a handoff, and when a prerequisite finishes, read the current plan: once every prerequisite the task still lists is done, set the task you blocked this way back to working or pending, since an explicit blocked task never becomes Ready. A prerequisite the plan no longer lists no longer holds it; a still-listed skipped prerequisite counts as unfinished. Inline guidance documents the other operations. Routine requests use `op=change`, `plan`, fresh `oid`, expected `rev`, and changed items. diff --git a/plugin/index.ts b/plugin/index.ts index 96ec10f..bcf63e2 100644 --- a/plugin/index.ts +++ b/plugin/index.ts @@ -177,7 +177,7 @@ Valid start (replace synthetic values with the real plan; task-2 requires task-1 Load the agent-progress skill when writing, receiving or coordinating plans and before dispatching sub-agents: it has delegation, staging, handoff and blocker rules. Tracker updates are not Agent Progress reports. Mirror actionable structure at PLAN_READY handoff; review approval and owner approval are separate, existing canonical gates only. A write is not readiness, dispatch is not work start, and worker completion is not accepted handoff. Repeated guidance or already-current state needs no report. Never invent review tasks, infer progress or report automatically per turn. Read uses only op=read, one concrete plan ID and optional 0-based page; no oid/rev. Read current revision before updating and after compaction/conflict. Batch changes. Report only real same-plan prerequisites; omit dependencies when none are known, and retain still-needed links in full structural replacements. Source is optional; never manufacture a file; document capture still needs read permission. -For parallel sub-agents, dispatch first then op=link each verified returned child, or op=delegate one at a time and wait for binding. A declaration is not assignment. Children report only explicitly assigned tasks after verified binding, on naturally occurring eligible contexts; restricted tools stay restricted. Needs-input keeps actual work pending/blocked. If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. When every prerequisite it was blocked on is done again, set the task you blocked this way back to working or pending, including before a handoff, since an explicit blocked task never becomes Ready. Finish successfully only when all actionable work is resolved.`; +For parallel sub-agents, dispatch first then op=link each verified returned child, or op=delegate one at a time and wait for binding. A declaration is not assignment. Children report only explicitly assigned tasks after verified binding, on naturally occurring eligible contexts; restricted tools stay restricted. Needs-input keeps actual work pending/blocked. If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. Before a handoff, and when a prerequisite finishes, read the current plan: once every prerequisite the task still lists is done, set the task you blocked this way back to working or pending, since an explicit blocked task never becomes Ready. A prerequisite the plan no longer lists no longer holds it; a still-listed skipped prerequisite counts as unfinished. Finish successfully only when all actionable work is resolved.`; const GUIDANCE = `${REPORT_CHECKLIST} Keep using your canonical planner/task workflow. This tool mirrors it, never replaces it. If not already reported, report at meaningful start/change/delegation/finish boundaries, not on a timer. Repeated guidance alone is not a reason to report again. Activity/idle/age never means completion. Structured/conversation-only plans need no source; never manufacture a file. Document-backed plans may explicitly name their canonical source, subject to report-time read permissions. Authored/Ready is not reviewed/accepted; worker completion is not accepted handoff. Needs-input keeps actual work pending/blocked. Never invent review work or infer progress from file writes. @@ -185,6 +185,6 @@ Tracker updates are not Agent Progress reports. For tracked plan work, explicitl Conditional native dispatch/tracker hints ask only whether meaningful canonical state remains unreported. They are not report receipts, assignments or evidence of work start, review, approval or completion; already-current state needs no mutation. ${START_HELP} Blocked tasks may optionally include blocker:{category?,reason?,nextAction?}; categories are decision/dependency/review/external/other. Prose must be nonblank, at most 512 JS code units each, without NUL. Supply purpose-written safe summaries, never private prompts, transcripts or raw tool output; bounds do not redact secrets. Missing parts are unknown. An object completely replaces details; null clears details without resolving status. Omission retains only verified-current details on a continuously blocked task. Groups reject blocker; non-null objects require blocked status. A metadata-only change repeats status:"blocked". Start/revise/staged task entries also accept blocker; staging publishes nothing before commit. Leaving blocked or closing clears details; re-entry/reopen without an explicit object is unknown. Older writers can invalidate optional details: deliberately re-report rather than resurrecting text. Do not send unsupported fields automatically to older tools. Waiting durations are derived from reported status history, not caller input, actual model activity or approval. -Start unrelated objectives as separate plan IDs. Mirror the complete structure once with stable item IDs; groups are not work. Start with op=start, plan/title/items, oid and rev=0. Routine changes send only changes:[{id,status}] with the latest rev and a fresh oid. Batch changes. Status: pending, working, blocked, done, skipped. If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. When every prerequisite it was blocked on is done again, set the task you blocked this way back to working or pending, including before a handoff, since an explicit blocked task never becomes Ready. Read after compaction/conflict before writing. Retry identical input with the same oid only; altered reuse refuses. Every call needs op, including change; if the host rejects a call with "op: Missing key", resend the same call with op added and the same oid. +Start unrelated objectives as separate plan IDs. Mirror the complete structure once with stable item IDs; groups are not work. Start with op=start, plan/title/items, oid and rev=0. Routine changes send only changes:[{id,status}] with the latest rev and a fresh oid. Batch changes. Status: pending, working, blocked, done, skipped. If work moves back to the prerequisites of a task that is working, mark it blocked with changes:[{id,status:"blocked",blocker:{category:"dependency",reason}}], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is. Before a handoff, and when a prerequisite finishes, read the current plan: once every prerequisite the task still lists is done, set the task you blocked this way back to working or pending, since an explicit blocked task never becomes Ready. A prerequisite the plan no longer lists no longer holds it; a still-listed skipped prerequisite counts as unfinished. Read after compaction/conflict before writing. Retry identical input with the same oid only; altered reuse refuses. Every call needs op, including change; if the host rejects a call with "op: Missing key", resend the same call with op added and the same oid. Large structures: op=stage with upload/chunk/items (max50/chunk and16KiB/request; at most32 chunks/1000 items), then op=commit with upload/chunks/title and expected rev. Chunks are not a committed plan. Explicitly report limits rather than dropping work. Never truncate a plan or call staging complete. Revise retains item statuses unless explicitly changed. Bind a canonical file using op=bind/source; confirm=true only when its checklist is mirrored. The original document remains authoritative; permission/read failure still commits valid checklist changes with diagnostics. Coordinator explicitly links a verified child session with op=link, child and assign IDs; pass plan/item IDs in the assignment. Children report assigned items only. Unlinked/unknown children stay independent. Restricted children may be relayed explicitly using attributed child ID after valid linking; this labels the parent reporter honestly, never impersonates a child. Do not loosen child restrictions. Finish is explicit: outcome finished only with actionable work all resolved; cancelled/failed retain unfinished work. Closed plans require explicit coordinator revise/commit with reopen=true. If a plan you were reporting returns closed while in progress or on a reopen, or a plan you started returns not-found, the user archived or deleted it; stop reporting to it, do not retry, and don't recreate it unless the user specifically asks for it. A reopen refused with conflict or stage-incomplete is recoverable: read the plan and retry at its current revision. For a staged commit, if every chunk already staged is valid for the current revision and intended layout, stage only the missing chunks under that same upload ID; otherwise stage the whole intended set under a fresh upload ID, because chunks stay pinned to the revision they were staged at. Keep reopen=true on every stage and the commit. No inference, passive scraping, document rewriting or hidden assignments.`; diff --git a/shared/subagent-runs.ts b/shared/subagent-runs.ts index e145cee..0e2e498 100644 --- a/shared/subagent-runs.ts +++ b/shared/subagent-runs.ts @@ -406,6 +406,11 @@ export function delegationRefusals(db:DatabaseSync,binding:RunBinding,sourceId:s // declaration must not resurrect an older refusal in coordinator guidance. const cleanup=cleanupInstalled(db)?String(cleanupState(db,sourceId,r.plan)?.state??''):''; if(['archived','deleted'].includes(cleanup))continue; + // Read a pending/reserved receipt as the per-plan reader does (ui/shared/adapter.ts + // intentDeclaration): pending names no dispatch, reserved names one, both declare a task. + // A failing receipt is unreadable evidence, never a `closed` refusal. Retired (both + // cancellation shapes) and bound receipts are not checked here and read as before. + if(['pending','reserved'].includes(d.state)&&((d.state==='reserved')!==(a.dispatch!==null)||!a.taskIds.length)){result.complete=false;continue;} // Cleanup retires an intent without rewriting its guarded receipt. Only a // restored plan (explicit visible cleanup record, as replay requires) explains // a pending/reserved receipt with no active intent; otherwise it is incomplete. diff --git a/tests/backend/plan-cleanup-delegation.test.ts b/tests/backend/plan-cleanup-delegation.test.ts index 3e14432..945a6d1 100644 --- a/tests/backend/plan-cleanup-delegation.test.ts +++ b/tests/backend/plan-cleanup-delegation.test.ts @@ -128,3 +128,76 @@ test('an unlinked dispatch keeps its visible plan when other active plans are ar assert.equal(JSON.parse(String(row.payload)).planContext?.plan,'P-active-c'); }finally{f.cleanup();} }); + +// Receipt evidence: coordinator guidance validates a pending or reserved receipt as the per-plan +// reader does (adapter intentDeclaration) before it reads a cleanup retirement into it. +function restoredReceipt(state:'pending'|'reserved',edit:(receipt:any)=>void,after?:(f:ReturnType)=>void) { + const f=cleanupFixture(); + try{ + f.store.bindReads(f.source.id,true);f.store.installSubagentRuns();f.store.installDelegationControl(); + f.store.declareDelegation({op:'delegate',plan:'P-active',rev:1,oid:'declare',assign:['A']},f.actor); + if(state==='reserved')f.store.beforeRun({source:f.source.id,parent:'M',message:'message',call:'call'},f.actor,'subagent',{},1000); + f.store.cleanup('archive',{...f.body('P-active',0,'cleanup',1),active:true}); + f.store.cleanup('restore',f.body('P-active',1,'restore',1)); + const row=f.store.db.prepare("SELECT receipt FROM receipts WHERE plan='P-active' AND oid='declare'").get()!; + const receipt=JSON.parse(String(row.receipt));edit(receipt); + f.store.db.prepare("UPDATE receipts SET receipt=? WHERE plan='P-active' AND oid='declare'").run(JSON.stringify(receipt)); + const before=f.store.db.prepare("SELECT receipt FROM receipts WHERE plan='P-active' AND oid='declare'").get()!.receipt; + after?.(f); + const guidance=f.store.delegationRefusals(f.source.id,'M'); + assert.equal(f.store.db.prepare("SELECT receipt FROM receipts WHERE plan='P-active' AND oid='declare'").get()!.receipt,before,'the receipt is never rewritten'); + return guidance; + }finally{f.cleanup();} +} +const dispatchOf={tool:'subagent',messageId:'message',callId:'call'}; + +for(const [state,edit,label] of [ + ['reserved',(r:any)=>{r.delegation.declaration.dispatch=null;},'reserved without a dispatch'], + ['pending',(r:any)=>{r.delegation.declaration.dispatch=dispatchOf;},'pending with a dispatch'], +] as const) +test(`a ${label} receipt makes restored guidance incomplete instead of closed`,()=>{ + const guidance=restoredReceipt(state,edit); + assert.deepEqual(guidance.refusals,[]);assert.equal(guidance.complete,false); +}); + +for(const state of ['pending','reserved'] as const) +test(`a ${state} receipt that declares no task makes restored guidance incomplete`,()=>{ + const guidance=restoredReceipt(state,r=>{r.delegation.declaration.taskIds=[];}); + assert.deepEqual(guidance.refusals,[]);assert.equal(guidance.complete,false); +}); + +for(const state of ['pending','reserved'] as const) +test(`a well-formed ${state} receipt after restore still reports closed and declares a task`,()=>{ + const guidance=restoredReceipt(state,r=>{assert.ok(r.delegation.declaration.taskIds.length>=1);assert.equal(r.delegation.declaration.dispatch!==null,state==='reserved');}); + assert.equal(guidance.complete,true);assert.deepEqual(guidance.refusals.map(r=>[r.plan,r.reason,r.declaration.oid]),[['P-active','closed','declare']]); +}); + +test('a well-formed restored receipt whose tasks were explicitly linked since yields no refusal',()=>{ + const guidance=restoredReceipt('pending',()=>{},f=>{ + f.store.apply({op:'link',plan:'P-active',oid:'link',rev:f.store.get(f.source.id,'P-active')!.revision,child:'C1',assign:['A']},f.actor,f.capture(),f.child); + }); + assert.equal(guidance.complete,true);assert.deepEqual(guidance.refusals,[]); +}); + +test('a bound receipt without a dispatch is skipped without marking guidance incomplete',()=>{ + const guidance=restoredReceipt('pending',r=>{r.delegation.state='bound';r.delegation.declaration.dispatch=null;}); + assert.deepEqual(guidance.refusals,[]);assert.equal(guidance.complete,true); +}); + +for(const shape of ['empty cancelling declaration','earlier declaration it retired'] as const) +test(`cancellation read as before: the ${shape}`,()=>{ + const f=cleanupFixture(); + try{ + f.store.bindReads(f.source.id,true);f.store.installSubagentRuns();f.store.installDelegationControl(); + f.store.declareDelegation({op:'delegate',plan:'P-active',rev:1,oid:'declare',assign:['A']},f.actor); + const cancel=f.store.declareDelegation({op:'delegate',plan:'P-active',rev:1,oid:'cancel',assign:[]},f.actor); + assert.equal(cancel.delegation.state,'retired');assert.equal(cancel.delegation.reason,'cancelled'); + if(shape==='earlier declaration it retired'){ + f.store.db.prepare("DELETE FROM receipts WHERE plan='P-active' AND oid='cancel'").run(); + const earlier=JSON.parse(String(f.store.db.prepare("SELECT receipt FROM receipts WHERE plan='P-active' AND oid='declare'").get()!.receipt)); + assert.equal(earlier.delegation.state,'retired');assert.deepEqual(earlier.delegation.declaration.taskIds,['A'],'the retired declaration keeps its tasks'); + } + const guidance=f.store.delegationRefusals(f.source.id,'M'); + assert.equal(guidance.complete,true);assert.deepEqual(guidance.refusals,[]); + }finally{f.cleanup();} +}); diff --git a/tests/backend/progress-invocation.test.ts b/tests/backend/progress-invocation.test.ts index 3a3d41f..14c5954 100644 --- a/tests/backend/progress-invocation.test.ts +++ b/tests/backend/progress-invocation.test.ts @@ -80,7 +80,7 @@ test('registered report provides safe recovery hints and executable start help w for(const text of [tool.description,skill.content,fs.readFileSync('plugin/SKILL.md','utf8')]){ const examples=[...text.matchAll(/```json\s*([\s\S]*?)```/g)].map(m=>JSON.parse(m[1])); assert.ok(examples.length>0,'direct tool and both guidance surfaces include JSON start example'); - assert.match(text,/work moves back to the prerequisites of a task that is working, mark it blocked with changes:\[\{id,status:"blocked",blocker:\{category:"dependency",reason\}\}\], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is\. When every prerequisite it was blocked on is done again, set the task you blocked this way back to working or pending, including before a handoff, since an explicit blocked task never becomes Ready\./,'status guidance for moved-back work'); + assert.match(text,/work moves back to the prerequisites of a task that is working, mark it blocked with changes:\[\{id,status:"blocked",blocker:\{category:"dependency",reason\}\}\], or set it back to pending if none of its own work was done; leave a task that is already blocked as it is\. Before a handoff, and when a prerequisite finishes, read the current plan: once every prerequisite the task still lists is done, set the task you blocked this way back to working or pending, since an explicit blocked task never becomes Ready\. A prerequisite the plan no longer lists no longer holds it; a still-listed skipped prerequisite counts as unfinished\./,'status guidance for moved-back work'); for(const example of examples){assert.equal(parseRequest(example).op,'start');assert.equal(example.rev,0);assert.equal(example.items[0].kind,'task'); const reply=await call(example);assert.equal(reply.rev,1); const page=await call({op:'read',plan:example.plan,page:0}); From 50348477204d4cae6c84b5c401a97b6dad27baef Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:00:49 +1100 Subject: [PATCH 03/11] fix(ui): report unconfirmed cleanup results apart from skipped plans (#163) * fix(ui): report unconfirmed cleanup results apart from skipped plans A bulk Tidy or selection run now keeps the failure class of each request. A plan the service refused, left out before sending, or never sent after Stop is skipped; an attempted request with no valid answer is reported as unconfirmed and may have been applied. The result line says so in English, Russian and Simplified Chinese. Undo still restores validated receipts only and Try again keeps its behaviour. The cleanup fixture's service calls wait 30 seconds while its readiness probe stays short, and the selection driver asserts that every plan was archived before it uses Undo. * fix(ui): agree Russian unconfirmed wording and share the refusal check Pick the Russian pronoun and participle by the exact count of one, so 21, 31 and 101 read as plural. Export cleanupRefused from the refusal codes cleanupError already uses, and use it in the run engine. Reword the Select bullet about a withdrawn store and the fixture probe comment. * docs(openspec): mark the fixture check done; the failing drivers predate this change --- docs/contracts.md | 8 +- docs/ui.md | 4 +- openspec/changes/release-1-5-2/tasks.md | 10 +-- tests/browser/cleanup-result-copy.test.ts | 88 ++++++++++++++++++++ tests/browser/cleanup-selection-qa.ts | 4 +- tests/browser/cleanup-selection-view.test.ts | 42 +++++++++- tests/browser/cleanup-tidy-scan.test.ts | 80 +++++++++++++++++- tests/browser/cleanup-tidy.test.ts | 75 +++++++++++++++++ tests/fixtures/cleanup-service.ts | 10 ++- ui/shared/cleanup-view.ts | 2 +- ui/shared/cleanup.ts | 33 ++++++-- 11 files changed, 335 insertions(+), 21 deletions(-) create mode 100644 tests/browser/cleanup-result-copy.test.ts diff --git a/docs/contracts.md b/docs/contracts.md index 9893236..26fb58c 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1188,7 +1188,13 @@ automatically. Stop and a change of account, store/binding or board reading end the run after the in-flight request. One progress line shows completed/total counts; start and result are announced once, not per plan. One final invalidation/re-read reconciles the result, including uncertain failures. Only -validated receipts count as completed; all other targets are reported as skipped. +validated receipts count as completed. A plan the service refused (changed, +closed, reused operation, not found, store busy) and a plan the run did not send +(left out of the view before sending, or after Stop) are reported as skipped. A +plan whose attempted request got no valid answer (a lost reply, a connection or +host failure, an unreadable receipt, or an attempt that failed before the service +could receive it) is reported separately as unconfirmed: it may have been +applied. Undo covers validated receipts only. Undo restores exactly the successful archive receipts of that action through the restore route, each bound to the generation returned by its receipt and a diff --git a/docs/ui.md b/docs/ui.md index c4d3cf4..8e7e4a6 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -1014,13 +1014,13 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Archive** is the ordinary per-plan action for a closed plan (Finished, Cancelled or Failed) in the rail/page. It hides the plan from ordinary lists and featured choices, retaining tasks, counts, report age, document and history. Archived plans cannot receive further reports until restored. Visible in-progress plans have no per-plan cleanup action; they can be acted on only through full-page selection. There is no automatic cleanup. - **Tidy.** The full-page bar always offers **Tidy** beside search and Filters when a library and `planCleanup:1` are available, including during search/filtering and when nothing is eligible. Neither the rail nor More offers bulk cleanup. Tidy covers Finished, Cancelled and Failed plans matching the current search and filters, or all closed plans in the current view without narrowing. It includes plans not loaded into the list and never targets in-progress plans or sends their acknowledgement. In Current plans it offers Archive and Delete permanently; in Archived plans only Delete permanently. An inline panel has one short count/scope line, no plan titles, named action buttons and Cancel. With no targets it says **No closed plans here.** and offers no cleanup action. - **Counting and confirmation.** A complete loaded scope supplies targets without a read. Otherwise a separate bounded list/search traversal counts them, applying the same effective filters as the displayed board (including normalized project/worktree choices) and, when browsing, the board's own placement of a plan by its recorded directory (the search-only check that a chosen location is currently discoverable applies to searches alone) without populating ordinary list/search caches or changing refresh budgets. Each explicit scan stops at 2,000 plan slots or 40 request windows, whichever comes first. Forty windows match the ordinary 50-plan list-page budget and prevent task-heavy search continuations from causing thousands of round trips. **Check more** continues from its last cursor with fresh per-action budgets, adding matches without repeating windows. The cursor is discarded on a store, account, binding, view, search or filter change. At most 1,000 targets belong to a confirmation. **First 1000 closed plans; more remain.** appears only once a further match has been found (a full set keeps counting within the scan budget to prove it); a cursor that merely remains, including after exactly 1,000 matches, says that more plans weren’t checked, never that more match. Each browse page after the first starts one row early and must open with the plan that ended the previous page; if another frame archived or deleted a plan behind the cursor, the count fails (**Could not count plans. Try again.**) instead of skipping plans and claiming completeness. The final **Delete permanently…** step repeats the same one-line subset qualification when the count is limited or unchecked. Cancel gets initial focus, Enter never defaults to a destructive action, and Escape cancels and returns focus to Tidy. Opening/cancelling sends no cleanup request. **Archive N plans** confirms Archive; **Delete permanently…** opens its own second step, whose count line says it cannot be undone. One collapsed disclosure keeps the stored tasks/history/document-copy removal, original-file preservation and non-erasure details reachable. -- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests, which are skipped. +- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests. A refusal as changed, closed, reused operation, not found or store busy is skipped; any other refusal is reported as unconfirmed, for example the 503 `storage` answer of a withdrawn store. - **Effective selection scope.** Ownership includes the board's normalized location filters. If the last plan in a project or worktree leaves and the board falls back to all locations, Select all is retired; selecting those other locations requires a new gesture. Old action callbacks cannot open a broader confirmation before repaint. Search counts update when hits are appended to the same result-page array and still count each plan only once. - **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view. Where a chosen plan is validated by point lookup (a truncated or searched scope, only when the service offers `planTaskSearch:1`), the baseline it is compared with is the revision supplied to the count: the revision the selection carried and, on Try again, the original target's revision, not the revision when the count began. Where search or session criteria apply, the point lookup skips a plan whose revision moved as changed and does not adopt the new one; that skip belongs to the point lookup only. A complete browse list counts a chosen plan from the displayed rows and an older service's list scan takes it as the scan's row shows it; neither compares it with the supplied revision. A count that read every page of an offset-paged list says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. A plan a cleanup receipt took out of a Select all rule is selected again when an Undo receipt puts it back or a verified read lists it again (a cached, unchecked search page is not evidence), and a click on such an unpressed row selects it; a plan the user deselected stays deselected. - **Keyboard order.** Tidy precedes the selection bar, which precedes confirmation/result actions. Outside Select mode this gives Tidy → Select → Undo when an archive result is shown. In Select mode, Done and Select all come first; when plans remain selected, Archive/Restore, Delete permanently… and Clear follow, then Undo. The count is a live status, not a Tab stop. - **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: in a searched or truncated scope, on a service that offers `planTaskSearch:1`, their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle, except where search or session criteria apply, where the point lookup skips it as changed. A complete browse list uses the loaded rows instead, and an older service counts a truncated browse scope by list scan. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. - **Unsupported in-progress plans.** Archive/Delete counting excludes these plans before applying the 1,000-target ceiling, in loaded selections and scans alike. Their distinct-plan warning count is separate from eligible targets; they still consume scan slots/windows, so a scan that has not reached eligible plans offers Check more rather than an empty terminal target ceiling. -- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A changed, refused or unconfirmed plan is skipped without retry; Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures. The result states completed and skipped counts, with Undo for precisely the successful archive receipts and Try again recounting only the plans the run left, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; changed plans stay untouched and unsuccessful restores are reported. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. +- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A plan the service refuses (changed, closed, reused operation, not found, store busy) is skipped; a plan whose attempted request gets no valid answer is unconfirmed; neither is retried automatically. Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures. The result is one sentence stating completed, skipped and unconfirmed counts apart: an unconfirmed plan "could not be confirmed and may have been" archived, restored or deleted, and a plan the run did not send (left out of the view before sending, or after Stop) is skipped, never unconfirmed. It offers Undo for precisely the successful archive receipts, and Try again recounting the skipped and unconfirmed plans together, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; an unconfirmed plan has no receipt and is not restored by it, and if its archive was applied it can be restored on its own once an Archived plans list or search shows it (the reconciliation read is not promised to). After a partial Undo, Try again does not recount: it sends the restore again for exactly the remaining plans, each bound to its archive receipt, so a restore that was in fact applied is confirmed from the receipt the service saved and not repeated, and a plan another cleanup changed since is refused and reported as skipped; unsuccessful restores are reported and changed plans stay untouched. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. - **Archived plans** is a page-level view above filters, including when ordinary results are empty. It uses the existing list/detail/document/history views. **Restore** preserves the plan's lifecycle and history, including an archived in-progress plan, which accepts reports again after restoration. More offers Restore and Delete permanently for archived plans of any lifecycle (in-progress deletion requires the service capability). Switching Current/Archived plans resets filters and selection so archived work is discoverable. - **Delete permanently…** is a separate per-plan action for a visible closed plan or any archived plan (in-progress deletion requires `planCleanupActive:1`). It opens an inline confirmation (not a modal) naming the plan and explaining deletion of stored tasks/history/copied document, preservation of the original file, irreversibility, the minimal replay guard and non-secure-erasure/recovery-backup limits. Nothing is sent on open or Cancel. The confirmation opens below the plan and is scrolled into view once; Cancel receives focus; Enter there cancels, Escape cancels, and focus returns to the opener (the ⋯ trigger, or the Delete permanently… button where the buttons are shown). The destructive button requires its own activation. Pending controls are disabled and the controller rejects duplicate submissions. - **Binding.** The confirmation captures store/source/plan, current progress revision and cleanup generation. Context, integration account/store, selection or revision changes invalidate it. A retired confirmation callback cannot act on a newer dialog. The controller checks eligibility and binding again before the POST; the server remains authoritative. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index 818ca6c..cf67a0a 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -28,11 +28,11 @@ Each numbered group is one pull request into the development branch. It carries ## 4. Unconfirmed results -- [ ] 4.1 Keep the failure class of each bulk request in the run engine and report unconfirmed plans apart from skipped ones, using the classes the single-plan messages already use. A plan the run did not attempt is never unconfirmed. Test each class against the cleanup fixture and with a held or failed transport: refused as changed, store busy, lost reply, unreadable receipt, an attempt rejected before it reached the service, left out before sending, stopped before sending. -- [ ] 4.2 Reword the result line in English, Russian and Simplified Chinese as the design tables it, as whole strings with plural rules, for archive, restore and delete; keep one sentence and one announcement. Test the strings and the view for skipped only, unconfirmed only and both; review Russian and Chinese by reading. -- [ ] 4.3 Keep Undo to validated receipts and Try again to a recount of skipped and unconfirmed plans together. After a partial Undo, keep Try again as it is: the restore sent again for the remaining plans, bound to their archive receipts, without a recount. Test all three after a run with unconfirmed plans, and both outcomes of the repeated restore: a plan whose earlier restore was applied is confirmed from the receipt the service saved and is not restored twice, and a plan another cleanup changed since is refused and reported as skipped. -- [ ] 4.4 Update the Tidy result statement of `docs/ui.md` and the bulk run paragraph of `docs/contracts.md`. -- [ ] 4.5 Raise the cleanup fixture's request limit for service calls to 30 seconds while its readiness probe keeps a short bound, check the fixture's other users still pass, and make the selection driver assert that the archive result reports every plan archived before it uses Undo. Run the selection driver and the backend cleanup suites that use the fixture, then the root and interface typechecks and the browser logic tests. +- [x] 4.1 Keep the failure class of each bulk request in the run engine and report unconfirmed plans apart from skipped ones, using the classes the single-plan messages already use. A plan the run did not attempt is never unconfirmed. Test each class against the cleanup fixture and with a held or failed transport: refused as changed, store busy, lost reply, unreadable receipt, an attempt rejected before it reached the service, left out before sending, stopped before sending. +- [x] 4.2 Reword the result line in English, Russian and Simplified Chinese as the design tables it, as whole strings with plural rules, for archive, restore and delete; keep one sentence and one announcement. Test the strings and the view for skipped only, unconfirmed only and both; review Russian and Chinese by reading. +- [x] 4.3 Keep Undo to validated receipts and Try again to a recount of skipped and unconfirmed plans together. After a partial Undo, keep Try again as it is: the restore sent again for the remaining plans, bound to their archive receipts, without a recount. Test all three after a run with unconfirmed plans, and both outcomes of the repeated restore: a plan whose earlier restore was applied is confirmed from the receipt the service saved and is not restored twice, and a plan another cleanup changed since is refused and reported as skipped. +- [x] 4.4 Update the Tidy result statement of `docs/ui.md` and the bulk run paragraph of `docs/contracts.md`. +- [x] 4.5 Raise the cleanup fixture's request limit for service calls to 30 seconds while its readiness probe keeps a short bound, check the fixture's other users still pass, and make the selection driver assert that the archive result reports every plan archived before it uses Undo. Run the selection driver and the backend cleanup suites that use the fixture, then the root and interface typechecks and the browser logic tests. ## 5. Large-library gate precision diff --git a/tests/browser/cleanup-result-copy.test.ts b/tests/browser/cleanup-result-copy.test.ts new file mode 100644 index 0000000..a53cca1 --- /dev/null +++ b/tests/browser/cleanup-result-copy.test.ts @@ -0,0 +1,88 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { tidyCopy } from '../../ui/shared/cleanup.ts'; + +/** Skipped only, unconfirmed only, both, and nothing refused: what the run result line says, per language and action. */ +type Row = [n: number, total: number, unconfirmed: number | undefined, text: string]; +const rows: Record> = { + en: { + archive: [ + [128, 128, undefined, '128 plans archived.'], + [126, 128, undefined, '126 of 128 plans archived; 2 skipped.'], + [126, 128, 0, '126 of 128 plans archived; 2 skipped.'], + [126, 128, 2, '126 of 128 plans archived; 2 could not be confirmed and may have been archived.'], + [127, 128, 1, '127 of 128 plans archived; 1 could not be confirmed and may have been archived.'], + [125, 128, 2, '125 of 128 plans archived; 1 skipped; 2 could not be confirmed and may have been archived.'], + ], + restore: [ + [3, 4, 1, '3 of 4 plans restored; 1 could not be confirmed and may have been restored.'], + [1, 4, 2, '1 of 4 plans restored; 1 skipped; 2 could not be confirmed and may have been restored.'], + [2, 4, undefined, '2 of 4 plans restored; 2 skipped.'], + ], + delete: [ + [3, 4, 1, '3 of 4 plans deleted; 1 could not be confirmed and may have been deleted.'], + [0, 4, 3, '0 of 4 plans deleted; 1 skipped; 3 could not be confirmed and may have been deleted.'], + ], + }, + ru: { + archive: [ + [128, 128, undefined, 'Архивировано 128 из 128.'], + [126, 128, undefined, 'Архивировано 126 из 128; пропущено: 2.'], + [126, 128, 2, 'Архивировано 126 из 128; 2 плана не удалось подтвердить: возможно, они архивированы.'], + [127, 128, 1, 'Архивировано 127 из 128; 1 план не удалось подтвердить: возможно, он архивирован.'], + [120, 128, 5, 'Архивировано 120 из 128; пропущено: 3; 5 планов не удалось подтвердить: возможно, они архивированы.'], + [100, 128, 21, 'Архивировано 100 из 128; пропущено: 7; 21 план не удалось подтвердить: возможно, они архивированы.'], + [100, 128, 11, 'Архивировано 100 из 128; пропущено: 17; 11 планов не удалось подтвердить: возможно, они архивированы.'], + ], + restore: [ + [3, 4, 1, 'Восстановлено 3 из 4; 1 план не удалось подтвердить: возможно, он восстановлен.'], + [1, 4, 2, 'Восстановлено 1 из 4; пропущено: 1; 2 плана не удалось подтвердить: возможно, они восстановлены.'], + [0, 31, 31, 'Восстановлено 0 из 31; 31 план не удалось подтвердить: возможно, они восстановлены.'], + ], + delete: [ + [3, 4, 1, 'Удалено 3 из 4; 1 план не удалось подтвердить: возможно, он удалён.'], + [0, 131, 101, 'Удалено 0 из 131; пропущено: 30; 101 план не удалось подтвердить: возможно, они удалены.'], + [0, 26, 21, 'Удалено 0 из 26; пропущено: 5; 21 план не удалось подтвердить: возможно, они удалены.'], + [0, 14, 11, 'Удалено 0 из 14; пропущено: 3; 11 планов не удалось подтвердить: возможно, они удалены.'], + ], + }, + 'zh-CN': { + archive: [ + [128, 128, undefined, '已归档 128 / 128 个计划。'], + [126, 128, undefined, '已归档 126 / 128 个计划;跳过 2 个。'], + [126, 128, 2, '已归档 126 / 128 个计划;2 个无法确认,可能已归档。'], + [125, 128, 2, '已归档 125 / 128 个计划;跳过 1 个;2 个无法确认,可能已归档。'], + ], + restore: [ + [3, 4, 1, '已恢复 3 / 4 个计划;1 个无法确认,可能已恢复。'], + [1, 4, 2, '已恢复 1 / 4 个计划;跳过 1 个;2 个无法确认,可能已恢复。'], + ], + delete: [ + [3, 4, 1, '已删除 3 / 4 个计划;1 个无法确认,可能已删除。'], + ], + }, +}; + +for (const [locale, actions] of Object.entries(rows)) for (const [action, list] of Object.entries(actions) as [keyof typeof actions, Row[]][]) { + test(`result line: ${action} in ${locale} says skipped and unconfirmed plans apart, in one sentence`, () => { + const t = tidyCopy(locale); + for (const [n, total, unconfirmed, text] of list) { + assert.equal(t.result(n, total, action, unconfirmed), text); + assert.equal(text.match(/[.。]/g)?.length, 1, 'one sentence, so one announcement'); + } + }); +} + +test('result line: the three-argument call and the restore flag keep their meaning', () => { + const t = tidyCopy('en'); + assert.equal(t.result(4, 4, false), '4 plans archived.'); + assert.equal(t.result(3, 4, true), '3 of 4 plans restored; 1 skipped.'); + assert.equal(t.result(3, 4, true, 1), '3 of 4 plans restored; 1 could not be confirmed and may have been restored.'); + assert.match(t.result(0, 4, false), /0 of 4.*4 skipped/); + // Stop leaves plans unsent: they read as skipped, which the rendered driver waits for. + assert.match(t.result(2, 4, 'archive', 0), /skipped/); +}); + +test('result line: a count that cannot add up never reports a negative skipped count', () => { + for (const locale of ['en', 'ru', 'zh-CN']) assert.doesNotMatch(tidyCopy(locale).result(1, 2, 'archive', 5), /-\d/); +}); diff --git a/tests/browser/cleanup-selection-qa.ts b/tests/browser/cleanup-selection-qa.ts index eb48608..f9b6be0 100644 --- a/tests/browser/cleanup-selection-qa.ts +++ b/tests/browser/cleanup-selection-qa.ts @@ -6,7 +6,7 @@ import { javascriptLiteral as js } from '../../shared/javascript-literal.ts'; import { launchCleanupService } from '../fixtures/cleanup-service.ts'; import { startLanguageFixture } from './interface-language-fixture.ts'; import { chromiumPath, launchChromium } from './phone-cdp.ts'; -import { selectionCopy } from '../../ui/shared/cleanup.ts'; +import { selectionCopy, tidyCopy } from '../../ui/shared/cleanup.ts'; const arg = (name: string) => { const i = process.argv.indexOf(name); return i > 0 ? process.argv[i + 1] : undefined; }; const artifacts = arg('--artifacts'); @@ -203,6 +203,8 @@ try { check('all-includes-closed-folds', await count() === '6 selected'); await click('selection-archive'); await click('tidy-confirm-archive'); await wait(`!!d.querySelector('[data-testid="tidy-undo"]')`); + // Undo restores only receipts: a slow reply must not let the run go on with fewer plans than it believes were archived. + check('archive-result-reports-all-archived', await guest(`return d.querySelector('[data-testid="tidy-result"]')?.textContent===${js(tidyCopy('en').result(6, 6, 'archive'))}`)); const archived = await posts(); check('mixed-archive-ack-only-active', archived.length === 6 && archived.every(q => q.body.plan === 'P-active' ? q.body.active === true : !('active' in q.body))); const report = (oid: string) => ({ op: 'change', plan: 'P-active', rev: service.store.get(service.source.id, 'P-active')?.revision ?? 2, oid, changes: [{ id: 'A', status: 'working' }] }); diff --git a/tests/browser/cleanup-selection-view.test.ts b/tests/browser/cleanup-selection-view.test.ts index 2597d3e..4f8cd42 100644 --- a/tests/browser/cleanup-selection-view.test.ts +++ b/tests/browser/cleanup-selection-view.test.ts @@ -11,14 +11,15 @@ const code = ts.transpileModule(readFileSync(new URL('../../ui/shared/cleanup-vi function panel() { const buttons: { id: string; run: () => void }[] = []; const texts: string[] = []; + const byId: Record = {}; const node = () => ({ dataset: {}, textContent: '', setAttribute() {}, append() {}, addEventListener() {} }); const exports: any = {}; runInNewContext(code, { exports, requestAnimationFrame() {}, require: (name: string) => ({ './cleanup.ts': cleanup, './i18n.ts': { resolveLanguage }, - './components.ts': { el: (_tag: string, _cls?: string, text?: string) => { if (text !== undefined) texts.push(text); return node(); }, testid: (n: any, id: string) => { n.dataset.testid = id; return n; }, + './components.ts': { el: (_tag: string, _cls?: string, text?: string) => { if (text !== undefined) texts.push(text); return node(); }, testid: (n: any, id: string) => { n.dataset.testid = id; byId[id] = n; return n; }, button: (_parent: any, id: string, _text: string, run: () => void) => buttons.push({ id, run }) }, } as Record)[name] }); - return { render: exports.tidyPanel as (state: cleanup.TidyState, locale: string, controls: any) => void, buttons, texts }; + return { render: exports.tidyPanel as (state: cleanup.TidyState, locale: string, controls: any) => void, buttons, texts, byId }; } test('a bounded selection Delete confirmation can Check more before its explicit final action', () => { @@ -72,3 +73,40 @@ for (const locale of ['en', 'ru', 'zh-CN']) test(`a fully read but unverifiable } assert.notEqual(t.missed(1, false), t.unchecked(1, false)); }); + +const target = (id: string) => ({ key: `fixture/${id}`, title: id, lifecycle: 'completed', context: 'scope', request: { storeId: 'store', source: 'fixture', plan: id, rev: 1, cleanupRev: 0, oid: id } }) as cleanup.CleanupTarget; +const [a, b, c] = ['a', 'b', 'c'].map(target); +const resultState = (result: Partial, selection?: 'restore') => { + const ok = a, skipped = b, lost = c; + return { context: 'scope', ...(selection ? { selection } : {}), result: { action: 'archive', attempted: 3, total: 3, succeeded: [ok], remaining: [skipped, lost], ...result } } as cleanup.TidyState; +}; +const expected = { + en: { both: '1 of 3 plans archived; 1 skipped; 1 could not be confirmed and may have been archived.', unconfirmed: '2 of 3 plans archived; 1 could not be confirmed and may have been archived.', skipped: '2 of 3 plans archived; 1 skipped.' }, + ru: { both: 'Архивировано 1 из 3; пропущено: 1; 1 план не удалось подтвердить: возможно, он архивирован.', unconfirmed: 'Архивировано 2 из 3; 1 план не удалось подтвердить: возможно, он архивирован.', skipped: 'Архивировано 2 из 3; пропущено: 1.' }, + 'zh-CN': { both: '已归档 1 / 3 个计划;跳过 1 个;1 个无法确认,可能已归档。', unconfirmed: '已归档 2 / 3 个计划;1 个无法确认,可能已归档。', skipped: '已归档 2 / 3 个计划;跳过 1 个。' }, +} as const; +for (const locale of ['en', 'ru', 'zh-CN'] as const) test(`the result line separates skipped from unconfirmed plans, with Undo and Try again offered (${locale})`, () => { + const show = (s: cleanup.TidyState) => { const h = panel(); let called = ''; h.render(s, locale, { undo: () => { called = 'undo'; }, retry: () => { called = 'retry'; } }); return { h, called: () => called }; }; + const both = show(resultState({ unconfirmed: 1 })); + assert.equal(both.h.byId['tidy-result'].textContent, expected[locale].both); + assert.deepEqual(both.h.buttons.map(b => b.id), ['tidy-undo', 'tidy-retry'], 'Undo and Try again are both offered'); + both.h.buttons.find(b => b.id === 'tidy-retry')!.run(); + assert.equal(both.called(), 'retry', 'after an archive Try again recounts'); + both.h.buttons.find(b => b.id === 'tidy-undo')!.run(); + assert.equal(both.called(), 'undo'); + const unconfirmedOnly = show(resultState({ succeeded: [a, b], remaining: [c], unconfirmed: 1 })); + assert.equal(unconfirmedOnly.h.byId['tidy-result'].textContent, expected[locale].unconfirmed); + const skippedOnly = show(resultState({ succeeded: [a, b], remaining: [c] })); + assert.equal(skippedOnly.h.byId['tidy-result'].textContent, expected[locale].skipped); +}); + +test('after a partial Undo, Try again is the receipt-bound restore, whether the remaining plans were skipped or unconfirmed', () => { + for (const selection of [undefined, 'restore' as const]) { + const h = panel(); let called = ''; + h.render(resultState({ action: 'restore', unconfirmed: 1, returned: true }, selection), 'en', { undo: () => { called = 'undo'; }, retry: () => { called = 'retry'; } }); + assert.match(h.byId['tidy-result'].textContent, /could not be confirmed and may have been restored/); + assert.equal(h.buttons.some(b => b.id === 'tidy-undo'), false, 'a restore result offers no Undo'); + h.buttons.find(b => b.id === 'tidy-retry')!.run(); + assert.equal(called, selection === 'restore' ? 'retry' : 'undo', 'Undo\'s retry resends the restore bound to the receipts; a selection Restore recounts'); + } +}); diff --git a/tests/browser/cleanup-tidy-scan.test.ts b/tests/browser/cleanup-tidy-scan.test.ts index 588fdfd..4be3ae3 100644 --- a/tests/browser/cleanup-tidy-scan.test.ts +++ b/tests/browser/cleanup-tidy-scan.test.ts @@ -1,6 +1,6 @@ import test from 'node:test'; import assert from 'node:assert/strict'; -import { CleanupScan, TIDY_LIMIT, tidyConfirmation, runTidy } from '../../ui/shared/cleanup.ts'; +import { CleanupScan, TIDY_LIMIT, tidyConfirmation, runTidy, cleanupRefused, cleanupError } from '../../ui/shared/cleanup.ts'; import { parsePlansPage } from '../../ui/shared/adapter.ts'; import { plansPage, summary } from './fixtures.ts'; @@ -98,3 +98,81 @@ test('shared run engine strips acknowledgement for closed targets, skips active assert.equal(result.remaining.length, 2); assert.equal(bodies[0].active, undefined); }); + +type Reply = { ok: true } | { status: number; body: string } | { throws: Error }; +const lost = Object.assign(new Error('host timed out'), { code: 'HOST_TIMEOUT' }); +/** One scripted reply per plan id; an id with no entry is archived. */ +function fakeHost(replies: Record, onRequest?: (plan: string) => void) { + const asked: string[] = []; + return { asked, host: { serviceRequest: async (q: { body?: string }) => { + const body = JSON.parse(q.body!); asked.push(body.plan); onRequest?.(body.plan); + const reply = replies[body.plan] ?? { ok: true }; + if ('throws' in reply) throw reply.throws; + if ('status' in reply) return { status: reply.status, body: reply.body }; + return { status: 200, body: JSON.stringify({ ...body, cleanup: { state: 'archived', revision: body.cleanupRev + 1 } }) }; + } } }; +} +const refusal = (status: number, error: string): Reply => ({ status, body: JSON.stringify({ error }) }); + +const attemptedFailures: [name: string, reply: Reply, unconfirmed: number][] = [ + ['refused as changed', refusal(409, 'conflict'), 0], + ['refused as closed', refusal(409, 'closed'), 0], + ['refused as a reused operation', refusal(409, 'operation-reused'), 0], + ['refused as not found', refusal(404, 'not-found'), 0], + ['store busy', refusal(503, 'busy'), 0], + ['lost reply', { throws: lost }, 1], + ['unreadable receipt', { status: 200, body: 'not a receipt' }, 1], + ['receipt for another plan', { status: 200, body: JSON.stringify({ storeId: 'store', source: 'other', plan: 'p-1', oid: 'x', cleanup: { state: 'archived', revision: 1 } }) }, 1], + ['service failure with no known refusal code', refusal(500, 'internal'), 1], + ['withdrawn store (503 storage)', refusal(503, 'storage'), 1], + // The fake host's plain rejection stands for an attempt that fails before the service could receive it + // (a refusal by the frame's own guard): the engine cannot tell it from a lost reply, so it is unconfirmed. + ['attempt that failed before reaching the service', { throws: new Error('The frame refused the request.') }, 1], +]; +for (const [name, reply, unconfirmed] of attemptedFailures) test(`run engine: ${name} is ${unconfirmed ? 'unconfirmed' : 'skipped'}`, async () => { + const targets = tidyConfirmation(plans(2), 'store', 'reading').targets; + const result = await runTidy(fakeHost({ 'p-1': reply }).host, 'archive', targets, () => true); + assert.equal(result.attempted, 2); + assert.equal(result.succeeded.length, 1); + assert.equal(result.unconfirmed ?? 0, unconfirmed); + assert.deepEqual(result.remaining.map(t => t.key), [targets[1].key], 'the plan with no receipt stays in remaining, for Try again'); +}); + +test('refusal classes: only a refusal the service answered is skipped; every other code, a withdrawn store and a lost reply are unconfirmed', () => { + for (const code of ['conflict', 'closed', 'operation-reused', 'not-found', 'busy']) assert.equal(cleanupRefused(code), true, code); + for (const code of ['storage', 'internal', 'http-500', 'HOST_TIMEOUT', 'CONTRACT', 'UNKNOWN', '']) assert.equal(cleanupRefused(code), false, code); + // The single-plan message agrees: a refusal never reads as "may have reached the service". + for (const code of ['conflict', 'closed', 'operation-reused', 'not-found', 'busy', 'storage', 'HOST_TIMEOUT']) { + assert.equal(cleanupRefused(code), cleanupError(code) !== cleanupError(''), code); + } +}); + +test('run engine: a plan left out before sending or after Stop is skipped, never unconfirmed', async () => { + const targets = tidyConfirmation(plans(4), 'store', 'reading').targets; + let current = true; + const { host, asked } = fakeHost({}, plan => { if (plan === 'p-2') current = false; }); + const result = await runTidy(host, 'archive', targets, () => current, undefined, false, target => target.request.plan !== 'p-1'); + assert.deepEqual(asked, ['p-0', 'p-2'], 'p-1 was left out before sending and p-3 was not sent after Stop'); + assert.equal(result.attempted, 2); + assert.equal(result.succeeded.length, 2); + assert.equal(result.unconfirmed ?? 0, 0); + assert.deepEqual(result.remaining.map(t => t.request.plan), ['p-1', 'p-3']); + // An in-progress plan that Tidy does not attempt is skipped as well. + const idle = fakeHost({}); + const skipped = await runTidy(idle.host, 'archive', [{ ...targets[0], lifecycle: 'active' as const }], () => true); + assert.deepEqual([idle.asked.length, skipped.unconfirmed ?? 0, skipped.remaining.length], [0, 0, 1]); +}); + +test('run engine: skipped and unconfirmed plans stay in remaining with the generation they were given, and succeeded holds neither', async () => { + const targets = tidyConfirmation(plans(6), 'store', 'reading').targets; + let current = true; + const { host } = fakeHost({ 'p-1': refusal(409, 'conflict'), 'p-2': { throws: lost }, 'p-3': { throws: new Error('x') } }, plan => { if (plan === 'p-3') current = false; }); + const result = await runTidy(host, 'archive', targets, () => current); + assert.equal(result.total, 6); + assert.equal(result.attempted, 4); + assert.deepEqual(result.succeeded.map(t => t.request.plan), ['p-0']); + assert.equal(result.unconfirmed, 2); + assert.deepEqual(result.remaining.map(t => t.request.plan), ['p-1', 'p-2', 'p-3', 'p-4', 'p-5']); + for (const kept of result.remaining) assert.deepEqual(kept.request, targets.find(t => t.key === kept.key)!.request, 'same revision, generation and operation id: nothing is rebound'); + assert.equal(result.succeeded[0].request.cleanupRev, targets[0].request.cleanupRev + 1, 'only a receipt moves the generation'); +}); diff --git a/tests/browser/cleanup-tidy.test.ts b/tests/browser/cleanup-tidy.test.ts index a9d2d8f..f1b2dc9 100644 --- a/tests/browser/cleanup-tidy.test.ts +++ b/tests/browser/cleanup-tidy.test.ts @@ -208,3 +208,78 @@ test('a counted plan reopened by its agent is skipped without acknowledgement or assert.equal(f.store.get('source-fixture', 'P-other')?.lifecycle, 'active'); } finally { await f.stop(); } }); + +/** A host that lets chosen plans' requests reach the service, then loses the reply. */ +function lossyHost(f: Awaited>, loseReplyFor: Set): ServiceHost { + return { serviceRequest: async q => { + const r = await f.request(q.path + (q.query ? '?' + new URLSearchParams(q.query) : ''), q.body ? JSON.parse(q.body) : undefined); + const body = await r.text(); + if (q.body && loseReplyFor.has(JSON.parse(q.body).plan)) throw Object.assign(new Error('host timed out'), { code: 'HOST_TIMEOUT' }); + return { status: r.status, body }; + } }; +} +async function closedTargets(f: Awaited>, ids: string[]) { + const read = await readList(lossyHost(f, new Set()), { archived: 'exclude' }); + assert.ok(read.ok && read.read); + const targets = tidyConfirmation(read.read.plans.filter(p => p.sourceId === 'source-fixture' && ids.includes(p.id)), read.read.storeId, 'board').targets; + assert.deepEqual(targets.map(t => t.request.plan).sort(), [...ids].sort()); + return targets; +} + +test('against the cleanup service: a refusal is skipped, a lost reply is unconfirmed and applied, and Undo takes receipts only', async () => { + const f = await launchCleanupService(false); + try { + const targets = await closedTargets(f, ['P-done', 'P-other', 'P-cancelled', 'P-failed']); + const [, changed] = targets; + assert.ok((await cleanupCall(lossyHost(f, new Set()), 'archive', { ...changed.request, oid: crypto.randomUUID() })).ok, 'another cleanup moves this plan first'); + const lostPlan = targets[2].request.plan; + const result = await runTidy(lossyHost(f, new Set([lostPlan])), 'archive', targets, () => true); + assert.equal(result.succeeded.length, 2); + assert.equal(result.unconfirmed, 1, 'the refusal as changed is skipped; only the lost reply is unconfirmed'); + assert.deepEqual(result.remaining.map(t => t.request.plan).sort(), [changed.request.plan, lostPlan].sort()); + assert.equal(f.store.detail('source-fixture', lostPlan).plan.cleanup?.state, 'archived', 'the unconfirmed plan was in fact archived'); + const undo = await runTidy(lossyHost(f, new Set()), 'restore', result.succeeded, () => true); + assert.equal(undo.succeeded.length, 2); + assert.equal(f.store.detail('source-fixture', lostPlan).plan.cleanup?.state, 'archived', 'Undo never restores a plan it holds no receipt for'); + } finally { await f.stop(); } +}); + +test('a restore whose reply was lost, sent again with the same request, returns the saved receipt and restores once', async () => { + const f = await launchCleanupService(false); + try { + const targets = await closedTargets(f, ['P-done', 'P-failed']); + const archived = await runTidy(lossyHost(f, new Set()), 'archive', targets, () => true); + assert.equal(archived.succeeded.length, 2); + const lostPlan = archived.succeeded[1].request.plan; + const first = await runTidy(lossyHost(f, new Set([lostPlan])), 'restore', archived.succeeded, () => true); + assert.equal(first.succeeded.length, 1); + assert.equal(first.unconfirmed, 1); + assert.deepEqual(first.remaining.map(t => t.request), [archived.succeeded[1].request], 'the remaining restore keeps its request and receipt generation'); + const generation = f.store.detail('source-fixture', lostPlan).plan.cleanup?.revision; + const again = await runTidy(lossyHost(f, new Set()), 'restore', first.remaining, () => true); + assert.equal(again.succeeded.length, 1, 'the applied restore is confirmed, not refused'); + assert.equal(again.unconfirmed ?? 0, 0); + assert.equal(f.store.detail('source-fixture', lostPlan).plan.cleanup?.state, 'visible'); + assert.equal(f.store.detail('source-fixture', lostPlan).plan.cleanup?.revision, generation, 'restored once: the generation did not move again'); + } finally { await f.stop(); } +}); + +test('a repeated restore after another cleanup of the plan is a conflict and counts as skipped', async () => { + const f = await launchCleanupService(false); + try { + const targets = await closedTargets(f, ['P-done']); + const archived = await runTidy(lossyHost(f, new Set()), 'archive', targets, () => true); + const [receipt] = archived.succeeded; + const first = await runTidy(lossyHost(f, new Set([receipt.request.plan])), 'restore', archived.succeeded, () => true); + assert.equal(first.unconfirmed, 1); + // The restore was applied; another cleanup archives the plan again before the repeat. + const host = lossyHost(f, new Set()); + const moved = await cleanupCall(host, 'archive', { ...receipt.request, cleanupRev: receipt.request.cleanupRev + 1, oid: crypto.randomUUID() }); + assert.ok(moved.ok); + const again = await runTidy(host, 'restore', first.remaining, () => true); + assert.equal(again.succeeded.length, 0); + assert.equal(again.unconfirmed ?? 0, 0, 'refused because the generation moved: skipped'); + assert.equal(again.remaining.length, 1); + assert.equal(f.store.detail('source-fixture', receipt.request.plan).plan.cleanup?.state, 'archived', 'left as the other cleanup made it'); + } finally { await f.stop(); } +}); diff --git a/tests/fixtures/cleanup-service.ts b/tests/fixtures/cleanup-service.ts index e1a8b42..1351768 100644 --- a/tests/fixtures/cleanup-service.ts +++ b/tests/fixtures/cleanup-service.ts @@ -10,6 +10,10 @@ import { RELEASE } from '../../shared/release.ts'; import { cleanupFixture } from './cleanup.ts'; import { isolatedEnvironment, publishFixtureBinding } from './managed.ts'; +/** A slow reply to a service call must not read as a lost one (it did in the selection driver), so calls wait this long. */ +const REQUEST_LIMIT=30000; +/** Readiness probes: short, so a hung start fails in seconds rather than after a service-call wait. The 7 s deadline is checked between probes, so one pass can overrun it by up to two probe limits. */ +const PROBE_LIMIT=3000; /** All roots, history and bindings are disposable. No installation or real user config. */ export async function launchCleanupService(built=false,pages=true) { const f=cleanupFixture(pages);f.store.bindReads(f.source.id,true); @@ -37,11 +41,13 @@ export async function launchCleanupService(built=false,pages=true) { server=createProgressServer(f.store,'fixture-only');server.listen(0,'127.0.0.1');await once(server,'listening');port=(server.address()as {port:number}).port; } const url=`http://127.0.0.1:${port}`; - const request=(route:string,body?:unknown,options:RequestInit={})=>fetch(`${url}${route}`,{method:body===undefined?'GET':'POST',headers:{authorization:'Bearer fixture-only','content-type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(3000),...options}); + const request=(route:string,body?:unknown,options:RequestInit={})=>fetch(`${url}${route}`,{method:body===undefined?'GET':'POST',headers:{authorization:'Bearer fixture-only','content-type':'application/json'},...(body===undefined?{}:{body:JSON.stringify(body)}),signal:AbortSignal.timeout(REQUEST_LIMIT),...options}); + // Readiness probes keep a short bound so a hung start fails fast; service calls get the long one. + const probe=(route:string)=>request(route,undefined,{signal:AbortSignal.timeout(PROBE_LIMIT)}); async function waitReady(){const deadline=Date.now()+7000;let ready=false; while(Date.now() CHANGED_CODES.includes(code) || code === 'busy'; export function cleanupError(code: string, locale = 'en') { const language = resolveLanguage('auto', locale); const text = language === 'ru' ? ru : language === 'zh-CN' ? zh : en; - if (['conflict', 'closed', 'operation-reused', 'not-found'].includes(code)) return text.changed; + if (CHANGED_CODES.includes(code)) return text.changed; if (code === 'busy') return text.busy; return text.uncertain; } @@ -94,6 +97,8 @@ export interface TidyResult { total: number; succeeded: CleanupTarget[]; remaining: CleanupTarget[]; + /** Attempted plans that got no valid answer and may have been applied. Absent when none; they are in `remaining`, never in `succeeded`. */ + unconfirmed?: number; /** An Undo: its receipts put plans back in the view they left (also when retried after a partial Undo). */ returned?: boolean; } @@ -310,7 +315,7 @@ export function selectionConfirmation(plans: CleanupPlan[], storeId: string, con export async function runTidy(host: ServiceHost, action: CleanupAction, targets: CleanupTarget[], current: () => boolean, progress?: (done: number, total: number, confirmed?: CleanupTarget) => void, allowActive = false, admit?: (target: CleanupTarget) => boolean): Promise { const succeeded: CleanupTarget[] = []; - let attempted = 0; + let attempted = 0, unconfirmed = 0; for (const target of targets.slice(0, TIDY_LIMIT)) { if (!current()) break; if (!cleanupClosed(target) && !allowActive) continue; @@ -323,11 +328,14 @@ export async function runTidy(host: ServiceHost, action: CleanupAction, targets: ...target, request: { ...target.request, cleanupRev: result.cleanup.revision, oid: crypto.randomUUID() }, }); + // A refusal is skipped. Any other failure of an attempted request, including one raised before the + // service could receive it, may have been applied: unconfirmed. + if (!result.ok && !cleanupRefused(result.failure.code)) unconfirmed++; // Receipt-dependent side effects belong to this validated target, even if context moved. progress?.(succeeded.length, targets.length, result.ok ? succeeded.at(-1) : undefined); } const keys = new Set(succeeded.map(t => t.key)); - return { action, attempted, total: targets.length, succeeded, remaining: targets.filter(t => !keys.has(t.key)) }; + return { action, attempted, total: targets.length, succeeded, remaining: targets.filter(t => !keys.has(t.key)), ...(unconfirmed ? { unconfirmed } : {}) }; } const tidyEn = { @@ -344,7 +352,11 @@ const tidyEn = { cancel: 'Cancel', confirm: (n: number) => `Archive ${plural(n, 'plan', 'plans')}`, pending: 'Archiving…', undo: 'Undo', retry: 'Try again', restoring: 'Restoring…', progress: (n: number, total: number, action: CleanupAction) => `${action === 'archive' ? 'Archiving' : action === 'restore' ? 'Restoring' : 'Deleting'}: ${n} of ${total}.`, count: (n: number, total: number) => `${n} of ${total} closed plans.`, - result: (n: number, total: number, action: CleanupAction | boolean) => `${n < total ? `${n} of ${total} plans` : plural(n, 'plan', 'plans')} ${action === true || action === 'restore' ? 'restored' : action === 'delete' ? 'deleted' : 'archived'}${n < total ? `; ${total - n} skipped` : ''}.`, + result: (n: number, total: number, action: CleanupAction | boolean, unconfirmed = 0) => { + const done = action === true || action === 'restore' ? 'restored' : action === 'delete' ? 'deleted' : 'archived'; + const skipped = Math.max(0, total - n - unconfirmed); + return `${n < total ? `${n} of ${total} plans` : plural(n, 'plan', 'plans')} ${done}${skipped ? `; ${skipped} skipped` : ''}${unconfirmed > 0 ? `; ${unconfirmed} could not be confirmed and may have been ${done}` : ''}.`; + }, }; const russianPlans = (n: number, closed = false) => { const form = new Intl.PluralRules('ru').select(n); @@ -365,7 +377,12 @@ const tidyRu: typeof tidyEn = { cancel: 'Отмена', confirm: n => `Архивировать ${formatCount(n, 'ru')} ${russianPlans(n)}`, pending: 'Архивируем…', undo: 'Отменить', retry: 'Повторить', restoring: 'Восстанавливаем…', progress: (n, total, action) => `${action === 'archive' ? 'Архивируем' : action === 'restore' ? 'Восстанавливаем' : 'Удаляем'}: ${formatCount(n, 'ru')} из ${formatCount(total, 'ru')}.`, count: (n, total) => `${formatCount(n, 'ru')} из ${formatCount(total, 'ru')} закрытых планов.`, - result: (n, total, action) => `${action === true || action === 'restore' ? 'Восстановлено' : action === 'delete' ? 'Удалено' : 'Архивировано'} ${formatCount(n, 'ru')} из ${formatCount(total, 'ru')}${n < total ? `; пропущено: ${formatCount(total - n, 'ru')}` : ''}.`, + result: (n, total, action, unconfirmed = 0) => { + const restore = action === true || action === 'restore', deleting = action === 'delete'; + const skipped = Math.max(0, total - n - unconfirmed), one = unconfirmed === 1; + const done = restore ? one ? 'восстановлен' : 'восстановлены' : deleting ? one ? 'удалён' : 'удалены' : one ? 'архивирован' : 'архивированы'; + return `${restore ? 'Восстановлено' : deleting ? 'Удалено' : 'Архивировано'} ${formatCount(n, 'ru')} из ${formatCount(total, 'ru')}${skipped ? `; пропущено: ${formatCount(skipped, 'ru')}` : ''}${unconfirmed > 0 ? `; ${formatCount(unconfirmed, 'ru')} ${russianPlans(unconfirmed)} не удалось подтвердить: возможно, ${one ? 'он' : 'они'} ${done}` : ''}.`; + }, }; const tidyZh: typeof tidyEn = { menu: '整理', heading: n => `此处有 ${formatCount(n, 'zh-CN')} 个已关闭的计划。`, @@ -381,7 +398,11 @@ const tidyZh: typeof tidyEn = { cancel: '取消', confirm: n => `归档 ${formatCount(n, 'zh-CN')} 个计划`, pending: '正在归档…', undo: '撤销', retry: '重试', restoring: '正在恢复…', progress: (n, total, action) => `正在${action === 'archive' ? '归档' : action === 'restore' ? '恢复' : '删除'}:${formatCount(n, 'zh-CN')} / ${formatCount(total, 'zh-CN')}。`, count: (n, total) => `${formatCount(total, 'zh-CN')} 个已关闭计划中的 ${formatCount(n, 'zh-CN')} 个。`, - result: (n, total, action) => `已${action === true || action === 'restore' ? '恢复' : action === 'delete' ? '删除' : '归档'} ${formatCount(n, 'zh-CN')} / ${formatCount(total, 'zh-CN')} 个计划${n < total ? `;跳过 ${formatCount(total - n, 'zh-CN')} 个` : ''}。`, + result: (n, total, action, unconfirmed = 0) => { + const done = action === true || action === 'restore' ? '恢复' : action === 'delete' ? '删除' : '归档'; + const skipped = Math.max(0, total - n - unconfirmed); + return `已${done} ${formatCount(n, 'zh-CN')} / ${formatCount(total, 'zh-CN')} 个计划${skipped ? `;跳过 ${formatCount(skipped, 'zh-CN')} 个` : ''}${unconfirmed > 0 ? `;${formatCount(unconfirmed, 'zh-CN')} 个无法确认,可能已${done}` : ''}。`; + }, }; export function tidyCopy(locale = 'en') { const language = resolveLanguage('auto', locale); From 0da126c5496ed51dfdadd25877db6873a9bf86fe Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:14:53 +1100 Subject: [PATCH 04/11] fix(ui): keep cleanup correct across account and store switches (#164) * fix(ui): bind cleanup busy state to its request, keep capability from the latest health * fix(ui): drop stale health on announced account change and guard retired Try again --- docs/ui.md | 10 +- openspec/changes/release-1-5-2/tasks.md | 8 +- tests/browser/cleanup-tidy-controller.test.ts | 389 +++++++++++++++++- ui/shared/app.ts | 80 +++- 4 files changed, 451 insertions(+), 36 deletions(-) diff --git a/docs/ui.md b/docs/ui.md index 8e7e4a6..45f8820 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -1014,18 +1014,18 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Archive** is the ordinary per-plan action for a closed plan (Finished, Cancelled or Failed) in the rail/page. It hides the plan from ordinary lists and featured choices, retaining tasks, counts, report age, document and history. Archived plans cannot receive further reports until restored. Visible in-progress plans have no per-plan cleanup action; they can be acted on only through full-page selection. There is no automatic cleanup. - **Tidy.** The full-page bar always offers **Tidy** beside search and Filters when a library and `planCleanup:1` are available, including during search/filtering and when nothing is eligible. Neither the rail nor More offers bulk cleanup. Tidy covers Finished, Cancelled and Failed plans matching the current search and filters, or all closed plans in the current view without narrowing. It includes plans not loaded into the list and never targets in-progress plans or sends their acknowledgement. In Current plans it offers Archive and Delete permanently; in Archived plans only Delete permanently. An inline panel has one short count/scope line, no plan titles, named action buttons and Cancel. With no targets it says **No closed plans here.** and offers no cleanup action. - **Counting and confirmation.** A complete loaded scope supplies targets without a read. Otherwise a separate bounded list/search traversal counts them, applying the same effective filters as the displayed board (including normalized project/worktree choices) and, when browsing, the board's own placement of a plan by its recorded directory (the search-only check that a chosen location is currently discoverable applies to searches alone) without populating ordinary list/search caches or changing refresh budgets. Each explicit scan stops at 2,000 plan slots or 40 request windows, whichever comes first. Forty windows match the ordinary 50-plan list-page budget and prevent task-heavy search continuations from causing thousands of round trips. **Check more** continues from its last cursor with fresh per-action budgets, adding matches without repeating windows. The cursor is discarded on a store, account, binding, view, search or filter change. At most 1,000 targets belong to a confirmation. **First 1000 closed plans; more remain.** appears only once a further match has been found (a full set keeps counting within the scan budget to prove it); a cursor that merely remains, including after exactly 1,000 matches, says that more plans weren’t checked, never that more match. Each browse page after the first starts one row early and must open with the plan that ended the previous page; if another frame archived or deleted a plan behind the cursor, the count fails (**Could not count plans. Try again.**) instead of skipping plans and claiming completeness. The final **Delete permanently…** step repeats the same one-line subset qualification when the count is limited or unchecked. Cancel gets initial focus, Enter never defaults to a destructive action, and Escape cancels and returns focus to Tidy. Opening/cancelling sends no cleanup request. **Archive N plans** confirms Archive; **Delete permanently…** opens its own second step, whose count line says it cannot be undone. One collapsed disclosure keeps the stored tasks/history/document-copy removal, original-file preservation and non-erasure details reachable. -- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests. A refusal as changed, closed, reused operation, not found or store busy is skipped; any other refusal is reported as unconfirmed, for example the 503 `storage` answer of a withdrawn store. +- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests. A refusal as changed, closed, reused operation, not found or store busy is skipped; any other refusal is reported as unconfirmed, for example the 503 `storage` answer of a withdrawn store. Tidy, Select and the other cleanup controls follow what the latest health reply the frame accepted said, whichever remembered list is shown: switching to a remembered Current or Archived list neither brings back support (or in-progress support) a later reply withdrew nor hides support a later reply granted, and support returns only with a newer reply that offers it, even when its list is unchanged. A health reply is accepted when the refresh that read it settles, complete or failed; one that arrived inside a refresh still reading its list pages takes effect then, and until then a request is checked when it is sent and by the service. A count, confirmation or run already open is not re-checked when only in-progress support is withdrawn. - **Effective selection scope.** Ownership includes the board's normalized location filters. If the last plan in a project or worktree leaves and the board falls back to all locations, Select all is retired; selecting those other locations requires a new gesture. Old action callbacks cannot open a broader confirmation before repaint. Search counts update when hits are appended to the same result-page array and still count each plan only once. - **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view. Where a chosen plan is validated by point lookup (a truncated or searched scope, only when the service offers `planTaskSearch:1`), the baseline it is compared with is the revision supplied to the count: the revision the selection carried and, on Try again, the original target's revision, not the revision when the count began. Where search or session criteria apply, the point lookup skips a plan whose revision moved as changed and does not adopt the new one; that skip belongs to the point lookup only. A complete browse list counts a chosen plan from the displayed rows and an older service's list scan takes it as the scan's row shows it; neither compares it with the supplied revision. A count that read every page of an offset-paged list says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. A plan a cleanup receipt took out of a Select all rule is selected again when an Undo receipt puts it back or a verified read lists it again (a cached, unchecked search page is not evidence), and a click on such an unpressed row selects it; a plan the user deselected stays deselected. - **Keyboard order.** Tidy precedes the selection bar, which precedes confirmation/result actions. Outside Select mode this gives Tidy → Select → Undo when an archive result is shown. In Select mode, Done and Select all come first; when plans remain selected, Archive/Restore, Delete permanently… and Clear follow, then Undo. The count is a live status, not a Tab stop. - **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: in a searched or truncated scope, on a service that offers `planTaskSearch:1`, their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle, except where search or session criteria apply, where the point lookup skips it as changed. A complete browse list uses the loaded rows instead, and an older service counts a truncated browse scope by list scan. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. - **Unsupported in-progress plans.** Archive/Delete counting excludes these plans before applying the 1,000-target ceiling, in loaded selections and scans alike. Their distinct-plan warning count is separate from eligible targets; they still consume scan slots/windows, so a scan that has not reached eligible plans offers Check more rather than an empty terminal target ceiling. -- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A plan the service refuses (changed, closed, reused operation, not found, store busy) is skipped; a plan whose attempted request gets no valid answer is unconfirmed; neither is retried automatically. Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures. The result is one sentence stating completed, skipped and unconfirmed counts apart: an unconfirmed plan "could not be confirmed and may have been" archived, restored or deleted, and a plan the run did not send (left out of the view before sending, or after Stop) is skipped, never unconfirmed. It offers Undo for precisely the successful archive receipts, and Try again recounting the skipped and unconfirmed plans together, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; an unconfirmed plan has no receipt and is not restored by it, and if its archive was applied it can be restored on its own once an Archived plans list or search shows it (the reconciliation read is not promised to). After a partial Undo, Try again does not recount: it sends the restore again for exactly the remaining plans, each bound to its archive receipt, so a restore that was in fact applied is confirmed from the receipt the service saved and not repeated, and a plan another cleanup changed since is refused and reported as skipped; unsuccessful restores are reported and changed plans stay untouched. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. +- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A plan the service refuses (changed, closed, reused operation, not found, store busy) is skipped; a plan whose attempted request gets no valid answer is unconfirmed; neither is retried automatically. Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures, unless an account, store or binding change was observed during the run: then the run touches nothing on the board shown and shows no result. The result is one sentence stating completed, skipped and unconfirmed counts apart: an unconfirmed plan "could not be confirmed and may have been" archived, restored or deleted, and a plan the run did not send (left out of the view before sending, or after Stop) is skipped, never unconfirmed. It offers Undo for precisely the successful archive receipts, and Try again recounting the skipped and unconfirmed plans together, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; an unconfirmed plan has no receipt and is not restored by it, and if its archive was applied it can be restored on its own once an Archived plans list or search shows it (the reconciliation read is not promised to). After a partial Undo, Try again does not recount: it sends the restore again for exactly the remaining plans, each bound to its archive receipt, so a restore that was in fact applied is confirmed from the receipt the service saved and not repeated, and a plan another cleanup changed since is refused and reported as skipped; unsuccessful restores are reported and changed plans stay untouched. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. - **Archived plans** is a page-level view above filters, including when ordinary results are empty. It uses the existing list/detail/document/history views. **Restore** preserves the plan's lifecycle and history, including an archived in-progress plan, which accepts reports again after restoration. More offers Restore and Delete permanently for archived plans of any lifecycle (in-progress deletion requires the service capability). Switching Current/Archived plans resets filters and selection so archived work is discoverable. - **Delete permanently…** is a separate per-plan action for a visible closed plan or any archived plan (in-progress deletion requires `planCleanupActive:1`). It opens an inline confirmation (not a modal) naming the plan and explaining deletion of stored tasks/history/copied document, preservation of the original file, irreversibility, the minimal replay guard and non-secure-erasure/recovery-backup limits. Nothing is sent on open or Cancel. The confirmation opens below the plan and is scrolled into view once; Cancel receives focus; Enter there cancels, Escape cancels, and focus returns to the opener (the ⋯ trigger, or the Delete permanently… button where the buttons are shown). The destructive button requires its own activation. Pending controls are disabled and the controller rejects duplicate submissions. -- **Binding.** The confirmation captures store/source/plan, current progress revision and cleanup generation. Context, integration account/store, selection or revision changes invalidate it. A retired confirmation callback cannot act on a newer dialog. The controller checks eligibility and binding again before the POST; the server remains authoritative. -- **Failure.** Conflict/busy/unavailable responses have plain feedback and an authoritative re-read; ambiguous requests are never silently retried or claimed successful. Cleanup is disabled while a read is stale/failed. Failed archived lookup is an error or explicitly stale prior data, never an authoritative empty archive. Capture-off does not disable explicit cleanup. -- **Invalidation.** On success or ambiguous failure, retire list and part-read generations, clear list/detail/document/history memories and the affected selections, then refetch. Late replies cannot refill retired caches. Cleanup generation changes invalidate content even if the agent revision is unchanged. Every other mounted surface converges on its existing successful poll; a complete refreshed scope that loses a key evicts remembered scopes/parts and that key's recent choices too. No new bus or polling cadence. Known persisted rail choices are cleared when their removed keys are observed. +- **Binding.** The confirmation captures store/source/plan, current progress revision and cleanup generation. Context, integration account/store, selection or revision changes invalidate it. A retired confirmation callback cannot act on a newer dialog. The controller checks eligibility and binding again before the POST; the server remains authoritative. The busy state belongs to the request that set it, in a bulk run and in a single-plan action alike. An integration account change the host announced, or a store or binding change a list reply showed, releases it, so the new board's cleanup controls work at once while an earlier request is still held; the late answer of that request can neither complete, release nor reset a newer one, also after a switch away and back to the same account and store, which comparing the two identities would read as no change. A store change with no account change is observed with a list reply; list reads pause while a bulk run keeps its panel, so one is then first observed by the read after the run, and they resume when a filter or search change ends that panel. +- **Failure.** Conflict/busy/unavailable responses have plain feedback and an authoritative re-read; ambiguous requests are never silently retried or claimed successful. Cleanup is disabled while a read is stale/failed. Failed archived lookup is an error or explicitly stale prior data, never an authoritative empty archive. Capture-off does not disable explicit cleanup. A request answered after an observed account, store or binding change reports nothing on the board shown then: no message and no re-read. +- **Invalidation.** On success or ambiguous failure, retire list and part-read generations, clear list/detail/document/history memories and the affected selections, then refetch. Late replies cannot refill retired caches. Cleanup generation changes invalidate content even if the agent revision is unchanged. Every other mounted surface converges on its existing successful poll; a complete refreshed scope that loses a key evicts remembered scopes/parts and that key's recent choices too. No new bus or polling cadence. Known persisted rail choices are cleared when their removed keys are observed. A bulk run that ends after an account, store or binding change the frame observed since it started, also one that changed back, drops its own state and does none of this on the board shown then: no cache is reset, the selection and the opened plan stay, and no result is shown. A validated Delete receipt still removes the review marker stored for its plan under the account and store the run started in, also when it arrives later. A change of board scope alone (filters or search) ends the run as before: it stops, shows no result line and sends its one reconciliation read. - Setup's capture removal still retains history; only this separately confirmed plan deletion removes stored plan content. SQLite recovery files/backups are not erased or automatically restored. ![Archived synthetic plan with preserved history, Restore and separate Delete permanently action](images/archived-plan-actions.png) diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index cf67a0a..436850b 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -14,10 +14,10 @@ Each numbered group is one pull request into the development branch. It carries ## 2. Account, store and capability -- [ ] 2.1 Capture the integration account and the store and binding identity when a bulk run starts, and when the frame observed a change of either since the run started, also one that has changed back, drop the run's own state at its end without resetting caches, changing the selection, closing the opened plan or showing a result. An observed change is an account change the host announced, or a store or binding change a list reply showed; do not decide by comparing the identity at the end. Keep the device-side effect of a validated Delete receipt: it still removes the review marker stored for its plan under the account and store the run started in, also when it arrives after the change. Test with a held request across an account switch, with equal identifiers in the new store, with a switch away and back and no newer run, and with a store change shown by a list reply after a change of filters resumed list reads during the run. Keep the scope-change-only case as it is, where the run stops and shows no result line, keep the existing marker tests passing, and pin the case the frame cannot observe: a store change while the run has the list reads paused is adopted by the list read that follows the run. -- [ ] 2.2 Take the cleanup facts the controls follow from the latest health reply the controller accepted, whichever remembered scope is adopted, so that adopting one neither restores support a later reply withdrew nor hides support a later reply granted. A health reply is accepted when its refresh settles, as today. Test: a switch between Current and Archived plans after support was withdrawn; a failed list read after a health reply without cleanup; support that returns with an unchanged list; and support granted after one view of Current plans was remembered without it and accepted in another view of Current plans, followed by a switch back to the first. -- [ ] 2.3 Release the busy state when the frame observes an account or store change, and bind it and the stale-answer cleanup to the request that set them, in the single-plan action as well as the bulk run, so the new board's cleanup controls work at once and a late answer can neither complete, release nor reset a newer run, also after a switch away and back. Test: Tidy opens after a switch with a request still held; a late answer during a newer run leaves that run pending; a held single-plan request, an account switch, a new Tidy run, then the old reply: the new run completes and shows its result; a held request, a switch away and back, a new run, then the old reply: the new run keeps its state and result; a store change shown by a list reply while a single-plan request is held: the controls are usable before that request answers. -- [ ] 2.4 Update the binding, failure and invalidation statements of the closed-plan cleanup section of `docs/ui.md`. Run the root and interface typechecks and the browser logic tests. +- [x] 2.1 Capture the integration account and the store and binding identity when a bulk run starts, and when the frame observed a change of either since the run started, also one that has changed back, drop the run's own state at its end without resetting caches, changing the selection, closing the opened plan or showing a result. An observed change is an account change the host announced, or a store or binding change a list reply showed; do not decide by comparing the identity at the end. Keep the device-side effect of a validated Delete receipt: it still removes the review marker stored for its plan under the account and store the run started in, also when it arrives after the change. Test with a held request across an account switch, with equal identifiers in the new store, with a switch away and back and no newer run, and with a store change shown by a list reply after a change of filters resumed list reads during the run. Keep the scope-change-only case as it is, where the run stops and shows no result line, keep the existing marker tests passing, and pin the case the frame cannot observe: a store change while the run has the list reads paused is adopted by the list read that follows the run. +- [x] 2.2 Take the cleanup facts the controls follow from the latest health reply the controller accepted, whichever remembered scope is adopted, so that adopting one neither restores support a later reply withdrew nor hides support a later reply granted. A health reply is accepted when its refresh settles, as today. Test: a switch between Current and Archived plans after support was withdrawn; a failed list read after a health reply without cleanup; support that returns with an unchanged list; and support granted after one view of Current plans was remembered without it and accepted in another view of Current plans, followed by a switch back to the first. +- [x] 2.3 Release the busy state when the frame observes an account or store change, and bind it and the stale-answer cleanup to the request that set them, in the single-plan action as well as the bulk run, so the new board's cleanup controls work at once and a late answer can neither complete, release nor reset a newer run, also after a switch away and back. Test: Tidy opens after a switch with a request still held; a late answer during a newer run leaves that run pending; a held single-plan request, an account switch, a new Tidy run, then the old reply: the new run completes and shows its result; a held request, a switch away and back, a new run, then the old reply: the new run keeps its state and result; a store change shown by a list reply while a single-plan request is held: the controls are usable before that request answers. +- [x] 2.4 Update the binding, failure and invalidation statements of the closed-plan cleanup section of `docs/ui.md`. Run the root and interface typechecks and the browser logic tests. ## 3. Background updates and focus diff --git a/tests/browser/cleanup-tidy-controller.test.ts b/tests/browser/cleanup-tidy-controller.test.ts index 4281e71..cf201ff 100644 --- a/tests/browser/cleanup-tidy-controller.test.ts +++ b/tests/browser/cleanup-tidy-controller.test.ts @@ -46,7 +46,7 @@ function liveFeed(config: { projects: LiveProject[]; sessions: LiveSession[]; wo }; } const liveSession = (id: string, projectId = 'proj', directory = '/fixture/proj'): LiveSession => ({ id, title: id, projectId, directory, parentId: null, archivedAt: null, worktree: null, activity: 'idle', outcome: null }); -type Opts = { plans?: PlanSummary[]; live?: { projects: LiveProject[]; sessions: LiveSession[]; worktrees?: { directory: string; name: string; branch: string; status: 'ready' }[] } }; +type Opts = { plans?: PlanSummary[]; item?: unknown; live?: { projects: LiveProject[]; sessions: LiveSession[]; worktrees?: { directory: string; name: string; branch: string; status: 'ready' }[] } }; function frame(surface: 'page' | 'panel', scan = false, active = false, activeCapability = true, extra: Partial> = {}, opts: Opts = {}) { const listeners: Record void> = {}; const focusables = new Map(); @@ -71,22 +71,32 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa const docListeners: Record void> = {}; const posts: string[] = []; const bodies: any[] = []; - let release: (() => void) | undefined; - let hold = false; + // Held cleanup requests answer in the order they are released; a held health reply waits for `releaseHealth`. + const waiting: (() => void)[] = []; + let holds = 0; + const healthWaiting: (() => void)[] = []; + let healthHolds = 0; + let storeId: string | null = null; + let lists = 0; let refused: string | null = null; const markers = new Map(); let effectiveScope = 'initial'; let vc!: ViewContext<{ filter: string }>; const host = { async serviceRequest(q: { path: string; body?: string }) { - if (q.path === '/health') return { status: 200, body: JSON.stringify({ ...HEALTH, ...(setupLost ? { ready: false } : {}), ...(capability && !setupLost ? { planCleanup: 1 } : {}), ...(activeCapability ? { planCleanupActive: 1 } : {}) }) }; - if (q.path === '/v1/plans') return plansFail ? { status: 500, body: '{"error":"storage"}' } : { status: 200, body: JSON.stringify(plansPage(plans)) }; + if (q.path === '/health') { + // The reply is decided when the request arrives, as at a real service. + const body = JSON.stringify({ ...HEALTH, ...(setupLost ? { ready: false } : {}), ...(capability && !setupLost ? { planCleanup: 1 } : {}), ...(activeCapability ? { planCleanupActive: 1 } : {}) }); + if (healthHolds > 0) { healthHolds--; await new Promise(r => { healthWaiting.push(r); }); } + return { status: 200, body }; + } + if (q.path === '/v1/plans') { lists++; return plansFail ? { status: 500, body: '{"error":"storage"}' } : { status: 200, body: JSON.stringify(plansPage(plans, null, storeId ? { storeId } : {})) }; } if (['/v1/plan/archive', '/v1/plan/restore', '/v1/plan/delete'].includes(q.path)) { posts.push(q.path); const request = JSON.parse(q.body!); bodies.push(request); if (request.plan === refused) return { status: 409, body: '{"error":"conflict"}' }; - if (hold) { hold = false; await new Promise(r => { release = r; }); } + if (holds > 0) { holds--; await new Promise(r => { waiting.push(r); }); } return { status: 200, body: JSON.stringify({ ...request, cleanup: { state: q.path.endsWith('archive') ? 'archived' : q.path.endsWith('delete') ? 'deleted' : 'visible', revision: request.cleanupRev + 1 } }) }; } return { status: 404, body: '{"error":"not-found"}' }; @@ -94,7 +104,7 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa storage: { get: async (key: string) => markers.get(key), set: async (key: string, value: unknown) => { markers.set(key, value); }, keys: async () => [...markers.keys()], delete: async (key: string) => { markers.delete(key); } }, onReady(fn: any) { listeners.ready = fn; }, onSession(fn: any) { listeners.session = fn; }, - onDirectory(fn: any) { listeners.directory = fn; }, onItem() {}, onConnection() {}, ...feed?.host, + onDirectory(fn: any) { listeners.directory = fn; }, onItem() {}, onConnection(fn: any) { listeners.connection = fn; }, ...feed?.host, }; const exports: any = {}; runInNewContext(APP, { @@ -125,7 +135,7 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa wantProjects: () => [], wantDetails: () => [], ...extra, paint: (root, c) => { vc = c; (extra as any).paint?.(root, c); }, }; exports.startView(spec); - listeners.ready({ session: { id: S.M }, directory: '/fixture', connection: { connected: true, account: 'example' }, features: { deviceStorage: true }, locale: 'en', surface, settings: {}, item: null, theme: {} }); + listeners.ready({ session: { id: S.M }, directory: '/fixture', connection: { connected: true, account: 'example' }, features: { deviceStorage: true }, locale: 'en', surface, settings: {}, item: opts.item ?? null, theme: {} }); return { get vc() { return vc; }, posts, markers, bodies, live: feed, capability(on: boolean) { capability = on; }, @@ -142,9 +152,17 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa focusAt(element: unknown) { focused = element; }, ownsFocus(on: boolean) { ownsFrame = on; }, normalizeScope(value: string) { effectiveScope = value; }, - hold() { hold = true; }, release() { assert.ok(release); release(); }, + hold() { holds++; }, + release(index = 0) { const answer = waiting.splice(index, 1)[0]; assert.ok(answer, 'a held request is waiting'); answer(); }, + holdHealth() { healthHolds++; }, + releaseHealth() { const answer = healthWaiting.shift(); assert.ok(answer, 'a health reply is held'); answer(); }, + /** The store the service reports from the next list reply on. */ + store(id: string) { storeId = id; }, + get lists() { return lists; }, session(id: string) { listeners.session({ id }); }, - account() { listeners.ready({ ...vc.ctx, connection: { connected: true, account: 'other-account' } }); }, + account(name = 'other-account') { listeners.ready({ ...vc.ctx, connection: { connected: true, account: name } }); }, + /** The host announces another integration account (action panes only). */ + connection(name: string) { listeners.connection({ connected: true, account: name }); }, stop() { listeners.pagehide(); }, }; } @@ -168,7 +186,7 @@ for (const switchAccount of [false, true]) test(`Tidy delete retires only confir await until(() => f.posts.length === 1); f.account(); await drain(); f.release(); } - await until(() => !f.vc.cleanup.pending); + await until(() => !f.markers.has(keys[0])); await drain(); assert.equal(f.markers.has(keys[0]), false, 'validated deletion retires the original account marker'); assert.ok(keys.slice(1).every(key => f.markers.has(key)), 'refused/unsent plans and other contexts keep their markers'); @@ -230,7 +248,7 @@ for (const switchAccount of [false, true]) test(`selection delete retires only r await until(() => f.posts.length === 1); f.account(); await drain(); f.release(); } - await until(() => !f.vc.cleanup.pending); + await until(() => !f.markers.has(keys[0])); await drain(); assert.equal(f.bodies[0].active, true); assert.equal(f.markers.has(keys[0]), false); @@ -844,3 +862,350 @@ test('retrying a partial Undo returns the restored plans to the Select all rule' assert.equal(selection.has(plans[1].key), true, 'restored by the retry: back under the rule'); } finally { f.stop(); } }); + +// Account, store and capability: what a request answered late may touch, and what the controls follow. +type Held = ReturnType; +/** A board whose selection and cache retirements are observable: a late run must leave them alone. */ +function boardSpy() { + const forgotten: string[][] = []; + const retires: string[] = []; + const extra = { + initialUi: () => ({ filter: 'all', selected: [] as string[], open: null as string | null }), + forgetPlans: (keys: Set, ui: { selected: string[]; open: string | null }) => { forgotten.push([...keys]); return { selected: ui.selected.filter(k => !keys.has(k)), ...(ui.open && keys.has(ui.open) ? { open: null } : {}) }; }, + retire: (reason: string) => { retires.push(reason); }, + // Single-plan actions run on the closed plan the board shows. + actionPlan: (c: ViewContext) => c.read?.plans.find(p => p.id === 'two') ?? null, + } as Partial>; + return { forgotten, retires, extra }; +} +/** Hold the first request of a bulk run, then let the test observe an account or store switch. */ +async function heldBulkRun(f: Held) { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 1); +} +/** Run `change`, then wait until the board it caused has been read and painted. */ +async function boardReloaded(f: Held, change: () => void) { + const before = f.lists; + change(); + await until(() => f.lists > before && !!f.vc.read); + await drain(); +} +/** The board shown must be exactly what it was: the late answer reached nothing on it. */ +function untouched(f: Held, spy: ReturnType, board: unknown, selected: string[], lists: number, retires: number) { + assert.equal((f.vc.ui as { open?: string | null }).open, selected[0], 'the plan opened on the board shown stays open'); + assert.equal(f.vc.read, board, 'the loaded list is the one that was shown'); + assert.deepEqual((f.vc.ui as { selected?: string[] }).selected, selected, 'the selection on the board shown is unchanged'); + assert.deepEqual(spy.forgotten, [], 'no plan of the late run is forgotten on the board shown'); + assert.equal(spy.retires.length, retires, 'no cache is reset on the board shown'); + assert.equal(f.lists, lists, 'no reconciliation read is sent'); + assert.equal(f.vc.cleanup.tidy, undefined, 'no result line'); + assert.equal(f.vc.cleanup.pending, false); +} + +test('a bulk run ending after an account switch touches nothing on the board shown then', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await heldBulkRun(f); + await boardReloaded(f, () => f.account()); + const board = f.vc.read!; + // The new board has a plan with the same key; the person selects it. + (f.vc as ViewContext).setUi({ selected: [board.plans[0].key], open: board.plans[0].key }); await drain(); + const retires = spy.retires.length, lists = f.lists; + f.release(); await drain(); + assert.equal(f.posts.length, 1, 'the retired run sends nothing more'); + untouched(f, spy, board, [board.plans[0].key], lists, retires); + } finally { f.stop(); } +}); + +test('a bulk run ending after a switch away and back, with no newer run, touches nothing on the reloaded board', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await heldBulkRun(f); + await boardReloaded(f, () => f.account()); + await boardReloaded(f, () => f.account('example')); + const board = f.vc.read!; + (f.vc as ViewContext).setUi({ selected: [board.plans[0].key], open: board.plans[0].key }); await drain(); + const retires = spy.retires.length, lists = f.lists; + f.release(); await drain(); + assert.equal(f.posts.length, 1); + untouched(f, spy, board, [board.plans[0].key], lists, retires); + } finally { f.stop(); } +}); + +test('a bulk run ending after a store change that a list reply showed during a filter change touches nothing', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await heldBulkRun(f); + // The filter change ends the run's panel, so list reads resume while its request is still held. + f.vc.setUi({ filter: 'other' }); + f.store('store-b'); + await boardReloaded(f, () => f.vc.retry()); + assert.equal(f.vc.read!.storeId, 'store-b'); + const board = f.vc.read!; + (f.vc as ViewContext).setUi({ selected: [board.plans[0].key], open: board.plans[0].key }); await drain(); + const retires = spy.retires.length, lists = f.lists; + f.release(); await drain(); + untouched(f, spy, board, [board.plans[0].key], lists, retires); + } finally { f.stop(); } +}); + +test('a bulk run ending after a filter change alone keeps no result and sends its one reconciliation read', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await heldBulkRun(f); + f.vc.setUi({ filter: 'other' }); + const lists = f.lists; + f.release(); await until(() => f.lists > lists); await drain(); + assert.equal(f.vc.cleanup.tidy, undefined, 'the shipped outcome: no result line'); + assert.equal(f.lists, lists + 1, 'one reconciliation read'); + assert.equal(spy.forgotten.length, 1, 'the run reconciled the board it ended on'); + } finally { f.stop(); } +}); + +test('a store change that no list read shows before the run ends is adopted by the read that follows the run', async () => { + const f = frame('page'); + try { + await heldBulkRun(f); + f.store('store-b'); + f.release(); + await until(() => f.vc.read?.storeId === 'store-b'); + await drain(); + assert.equal(f.vc.cleanup.tidy, undefined, 'the new board starts clean'); + assert.equal(f.vc.cleanup.pending, false); + } finally { f.stop(); } +}); + +test('Tidy opens on the new board while a request sent before an account switch is still held', async () => { + const f = frame('page'); + try { + await heldBulkRun(f); + await boardReloaded(f, () => f.account()); + assert.equal(f.vc.cleanup.pending, false, 'the switch released the busy state'); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + } finally { f.stop(); } +}); + +test('the late answer of a bulk run cannot complete, release or reset a newer run', async () => { + const f = frame('page'); + try { + await heldBulkRun(f); + await boardReloaded(f, () => f.account()); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 2); + const newer = f.vc.cleanup.tidy; + f.release(0); await drain(); + assert.equal(f.vc.cleanup.pending, true, 'the newer run is still pending'); + assert.equal(f.vc.cleanup.tidy, newer, 'and keeps its state'); + f.release(0); + await until(() => !!f.vc.cleanup.tidy?.result); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2, 'the newer run completes and shows its result'); + } finally { f.stop(); } +}); + +test('the late answer of a bulk run cannot reset a newer run after a switch away and back', async () => { + const f = frame('page'); + try { + await heldBulkRun(f); + await boardReloaded(f, () => f.account()); + await boardReloaded(f, () => f.account('example')); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 2); + const newer = f.vc.cleanup.tidy; + f.release(0); await drain(); + assert.equal(f.vc.cleanup.pending, true); + assert.equal(f.vc.cleanup.tidy, newer, 'the same account and store again: only the request identity tells the runs apart'); + f.release(0); + await until(() => !!f.vc.cleanup.tidy?.result); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2); + } finally { f.stop(); } +}); + +for (const away of [false, true]) test(`the late answer of a single-plan action cannot wipe a newer Tidy run (switch away and back: ${away})`, async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await until(() => !!f.vc?.read); + f.vc.requestDelete(f.vc.read!.plans[1]); await until(() => !!f.vc.cleanup.target); + f.hold(); f.vc.confirmDelete(); + await until(() => f.posts.length === 1); + await boardReloaded(f, () => f.account()); + if (away) await boardReloaded(f, () => f.account('example')); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 2); + const newer = f.vc.cleanup.tidy; + f.release(0); await drain(); + assert.equal(f.vc.cleanup.pending, true, 'the single-plan answer does not release the run'); + assert.equal(f.vc.cleanup.tidy, newer); + f.release(0); + await until(() => !!f.vc.cleanup.tidy?.result); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2, 'the run completes and shows its result'); + } finally { f.stop(); } +}); + +test('a store change shown by a list reply frees the cleanup controls before a held single-plan request answers', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await until(() => !!f.vc?.read); + f.vc.requestDelete(f.vc.read!.plans[1]); await until(() => !!f.vc.cleanup.target); + f.hold(); f.vc.confirmDelete(); + await until(() => f.posts.length === 1); + f.store('store-b'); + await boardReloaded(f, () => f.vc.retry()); + assert.equal(f.vc.read!.storeId, 'store-b'); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + const opened = f.vc.cleanup.tidy; + f.release(); await drain(); + assert.equal(f.vc.cleanup.tidy, opened, 'the old answer leaves the new board\'s panel alone'); + } finally { f.stop(); } +}); + +test('a Try again callback captured before a switch away and back does nothing', async () => { + const f = frame('page'); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await until(() => !!f.vc.cleanup.tidy?.confirmation); + f.refuse('two'); f.vc.confirmTidy(); + await until(() => (f.vc.cleanup.tidy?.result?.remaining.length ?? 0) === 1); + const stale = f.vc; + await boardReloaded(f, () => f.account()); + await boardReloaded(f, () => f.account('example')); + assert.equal(f.vc.cleanup.tidy, undefined, 'the result belonged to the earlier board'); + stale.retryTidy(); await drain(); + assert.equal(f.vc.cleanup.tidy, undefined, 'the retired callback opens nothing on the reloaded board'); + } finally { f.stop(); } +}); + +const TARGET = { kind: 'session', action: 'open-progress', sessionId: S.M, directory: '/fixture' }; +test('an announced account change drops the old account\'s health until the new one is read', async () => { + const f = frame('panel', false, false, true, {}, { item: TARGET, live: { projects: [], sessions: [] } }); + try { + await until(() => !!f.vc?.health); + assert.equal(f.vc.health?.planCleanup, 1); + f.holdHealth(); + f.connection('other-account'); await drain(); + assert.equal(f.vc.health, null, 'no flag of the earlier account shows while the new account loads'); + f.releaseHealth(); await drain(); + } finally { f.stop(); } +}); + +// Cleanup facts of the latest accepted health reply, whichever remembered list is shown. +const factScopes = { scope: (_context: unknown, ui: { filter: string }) => ui.filter === 'archived' ? { archived: 'only' as const } : ui.filter === 'session' ? { session: S.U } : {} } as Partial>; +const offered = (f: Held) => f.vc.health?.planCleanup === 1; +/** Neither Tidy nor Select may open: the press is a no-op. */ +async function refusesCleanup(f: Held) { + f.vc.requestTidy(); await drain(); + if (f.vc.cleanup.tidy) return false; + f.vc.requestSelection('archive', { all: true, plans: f.vc.read?.plans ?? [], includes: () => true }); await drain(); + return f.vc.cleanup.tidy === undefined; +} + +test('Current plans remembered with support do not bring it back after an Archived read observed none, and the next read restores it', async () => { + const f = frame('page', false, false, true, factScopes); + try { + await until(() => !!f.vc?.read); + f.capability(false); f.vc.setUi({ filter: 'archived' }); + await until(() => !offered(f)); await drain(); + f.capability(true); f.holdHealth(); + f.vc.setUi({ filter: 'all' }); await drain(); + assert.ok(f.vc.read, 'the remembered list is shown'); + assert.equal(offered(f), false, 'the withdrawn support does not return with the remembered list'); + assert.equal(await refusesCleanup(f), true); + f.releaseHealth(); + await until(() => offered(f)); + f.vc.requestTidy(); await drain(); + assert.ok(f.vc.cleanup.tidy, 'an unchanged list with newly offered support brings the controls back'); + } finally { f.stop(); } +}); + +test('Current plans remembered with support stay without it after a failed list read saw none', async () => { + const f = frame('page', false, false, true, factScopes); + try { + await until(() => !!f.vc?.read); + f.capability(false); f.failPlans(true); f.vc.setUi({ filter: 'session' }); + await until(() => !!f.vc.failure); await drain(); + assert.equal(offered(f), false); + f.failPlans(false); f.holdHealth(); + f.vc.setUi({ filter: 'all' }); await drain(); + assert.ok(f.vc.read); + assert.equal(offered(f), false, 'the remembered list does not restore the withdrawn support'); + assert.equal(await refusesCleanup(f), true); + } finally { f.stop(); } +}); + +/** Current plans read with no support (remembered so), a session filter accepted with support, the filter cleared with its read held. */ +async function grantedElsewhere(f: Held) { + await until(() => !!f.vc?.read); + f.capability(false); f.vc.retry(); + await until(() => !offered(f)); await drain(); + f.capability(true); f.vc.setUi({ filter: 'session' }); + await until(() => offered(f)); await drain(); + f.capability(false); f.holdHealth(); + f.vc.setUi({ filter: 'all' }); await drain(); +} + +test('support granted since a remembered view of Current plans was kept is not hidden by switching back to it', async () => { + const f = frame('page', false, false, true, factScopes); + try { + await grantedElsewhere(f); + assert.ok(f.vc.read); + assert.equal(offered(f), true, 'the latest accepted health reply granted it'); + f.vc.requestTidy(); await drain(); + assert.ok(f.vc.cleanup.tidy, 'Tidy opens'); + } finally { f.stop(); } +}); + +test('a held read equal to the remembered one, without support, takes the controls away again', async () => { + const f = frame('page', false, false, true, factScopes); + try { + await grantedElsewhere(f); + assert.equal(offered(f), true); + f.releaseHealth(); + await until(() => !offered(f)); + assert.equal(await refusesCleanup(f), true); + } finally { f.stop(); } +}); + +/** Current plans read without support (remembered so), then a failed read whose health grants it. */ +async function grantedByFailedRead(f: Held) { + await until(() => !!f.vc?.read); + f.capability(false); f.vc.retry(); + await until(() => !offered(f)); await drain(); + f.capability(true); f.failPlans(true); f.vc.retry(); + await until(() => !!f.vc.failure && offered(f)); await drain(); +} + +test('while a read has failed, no cleanup action opens even though the failed read\'s health granted support', async () => { + const spy = boardSpy(); + const f = frame('page', false, false, true, spy.extra); + try { + await grantedByFailedRead(f); + assert.equal(await refusesCleanup(f), true, 'Tidy and Select are refused'); + f.vc.requestDelete(f.vc.read!.plans[1]); await drain(); + assert.ok(!f.vc.cleanup.target, 'the per-plan action is refused'); + } finally { f.stop(); } +}); + +test('a later equal list read replaces the facts a failed read granted, after a freshness read cleared the failure', async () => { + let freshness = false; + const fresh = async () => ({ state: 'fresh' as const, captureEnabled: true }); + const f = frame('page', false, false, true, { freshness: () => freshness ? fresh : null } as Partial>); + try { + await grantedByFailedRead(f); + // The board search's own read clears the failure without a list read. + freshness = true; f.failPlans(false); f.vc.retry(); + await until(() => !f.vc.failure); await drain(); + assert.equal(offered(f), true, 'the failed read\'s health is the latest accepted one'); + freshness = false; f.capability(false); f.vc.retry(); + await until(() => !offered(f)); + assert.equal(await refusesCleanup(f), true); + } finally { f.stop(); } +}); diff --git a/ui/shared/app.ts b/ui/shared/app.ts index f274d9a..d711f7f 100644 --- a/ui/shared/app.ts +++ b/ui/shared/app.ts @@ -564,6 +564,23 @@ export function startView(spec: ViewSpec) { let cacheGeneration = 0; let cleanup = initialCleanup(); let cleanupBusy = false; + /** + * The request that holds the busy state; 0 when none. A cleanup request, bulk or single-plan, completes + * only while it still holds it: an account, store or binding change the frame observed releases it (and + * clears it for good, also after a switch away and back), so a late answer can neither release nor wipe + * a newer request. + */ + let cleanupToken = 0; + let cleanupSeq = 0; + const claimCleanup = () => { cleanupBusy = true; return cleanupToken = ++cleanupSeq; }; + /** True when `token` still held the busy state, which is released with it. */ + const releaseCleanup = (token: number) => { + if (cleanupToken !== token) return false; + cleanupBusy = false; cleanupToken = 0; + return true; + }; + /** An account change the host announced, or a store or binding change a list reply showed. */ + const observeSwitch = () => { cleanupBusy = false; cleanupToken = 0; }; let cleanupFocus: string | null = null; let tidyReconcile = false; let handoff: (Handoff & { from: FocusKey }) | null = null; @@ -776,12 +793,38 @@ export function startView(spec: ViewSpec) { if (keys.size && spec.forgetPlans) { ui = { ...ui, ...spec.forgetPlans(keys, ui, context(), confirmed, returned) }; versions.ui++; } }; + /** + * Cleanup support is what the service last said, whichever list is shown: `latest` (the health reply + * accepted last) decides both facts, in either direction. `base` is returned itself when they agree. + */ + const AFTER_CLEANUP_FACTS = new Set(['planChangeDigests', 'planTaskSearch', 'documentCaptureComparison', 'subagentRuns', 'needsYouInbox', 'delegationIntent']); + const withCleanupFacts = (base: HealthView, latest: HealthView | null): HealthView => { + if (!latest || base.planCleanup === latest.planCleanup && base.planCleanupActive === latest.planCleanupActive) return base; + const { planCleanup: _support, planCleanupActive: _active, ...rest } = base; + // Same key order as a parsed reply (adapter.ts), so the signature of this health equals that of the next identical reply. + const merged: Record = {}; + let placed = false; + const place = () => { + if (placed) return; + placed = true; + if (latest.planCleanup === 1) merged.planCleanup = 1; + if (latest.planCleanupActive === 1) merged.planCleanupActive = 1; + }; + for (const [name, value] of Object.entries(rest)) { if (AFTER_CLEANUP_FACTS.has(name)) place(); merged[name] = value; } + place(); + return merged as unknown as HealthView; + }; + /** The list scope changed: show its remembered validated read (if any) until the new read lands. */ function adoptScope(key: string) { if (key === readScope || !identity) return; const hit = memory.get(memoryKey(key)); if (!hit) return; // unknown scope: loading, never another scope's data - read = hit.read; readScope = key; readSig = hit.sig; health = hit.health; lastGoodAt = hit.at; + // The remembered list is shown; the cleanup facts stay those of the latest accepted health reply. + const shown = withCleanupFacts(hit.health, health); + // The remembered signature describes the remembered health. With other facts it is recomputed, so a + // read equal to the remembered one still replaces them when the service says something else. + read = hit.read; readScope = key; readSig = shown === hit.health ? hit.sig : JSON.stringify([key, shown, hit.read]); health = shown; lastGoodAt = hit.at; versions.data++; } @@ -937,7 +980,7 @@ export function startView(spec: ViewSpec) { authorityChanged = nextIdentity !== identity; if (authorityChanged) { setup = null; setupSerial++; } // A hand-off belongs to the old store/binding: it never focuses or announces in the new one. - if (identity && authorityChanged) { ui = spec.initialUi(); versions.ui++; resetCaches(); clearReading(); cleanup = { ...initialCleanup(), pending: cleanupBusy }; handoff = null; handoffNote = null; live.restart(); } + if (identity && authorityChanged) { ui = spec.initialUi(); versions.ui++; resetCaches(); clearReading(); observeSwitch(); cleanup = initialCleanup(); handoff = null; handoffNote = null; live.restart(); } // A complete refreshed scope is authoritative about keys formerly in that scope. // Evict all remembered scopes/parts so another session cannot resurrect removed data. const previous = memory.get(memoryKey(key))?.read; @@ -978,7 +1021,11 @@ export function startView(spec: ViewSpec) { failure = result.failure; // The health reply read before the failure still says what the service offers: the page learns a loss too. if (result.health) { - if (result.health.planCleanup !== 1 && health?.planCleanup === 1) { const { planCleanup: _lost, planCleanupActive: _active, ...kept } = health; health = kept; versions.data++; } + if (health) { + const next = withCleanupFacts(health, result.health); + // The signature of the list read no longer describes this health: an equal later read must still replace it. + if (next !== health) { health = next; readSig = ''; versions.data++; } + } retirePendingTidy(result.health); } } @@ -1092,7 +1139,8 @@ export function startView(spec: ViewSpec) { state.scan?.cancel(); state.confirmation = undefined; state.progress = { action, done: 0, total: targets.length }; cleanupFocus = 'tidy-stop'; - cleanupBusy = true; cleanup = { ...cleanup, pending: true }; versions.ui++; gate.retire(); schedule(); + const token = claimCleanup(); + cleanup = { ...cleanup, pending: true }; versions.ui++; gate.retire(); schedule(); const result = await runTidy(guardedHost(current), action, targets, current, (done, total, confirmed) => { const checkpoint = confirmed && deleted.get(confirmed.key); if (checkpoint) { if (digests) digests.forget(checkpoint); else void new CheckpointStore(host.storage, () => ctx?.features?.deviceStorage === true).forget(checkpoint); } @@ -1100,8 +1148,12 @@ export function startView(spec: ViewSpec) { }, !!state.selection && (action === 'restore' || health?.planCleanupActive === 1) || undo, // Undo restores exactly the receipts; everything else must still be in the displayed scope when sent. undo || !spec.tidyMember ? undefined : t => spec.tidyMember!(context(), t)); - cleanupBusy = false; + const mine = releaseCleanup(token); if (disposed) return; + // An observed account, store or binding change released the busy state and dropped this run's panel: + // what is shown now belongs to a board this run never saw, so nothing of it is touched, also after a + // switch away and back (its Delete receipts already retired their review markers above). + if (!mine) return; const same = cleanup.tidy === state && state.context === tidyContext(); if (same && document.activeElement?.closest('[data-testid="tidy-stop"]')) cleanupFocus = 'tidy-open'; // Reconcile once, including uncertain requests; never retry a refused plan automatically. @@ -1132,19 +1184,17 @@ export function startView(spec: ViewSpec) { if (cleanupBusy || !validTarget(target)) { if (!cleanupBusy) cancelCleanup(); return; } const selected = spec.actionPlan?.(context()); if (!selected || !cleanupEligible(action, selected)) return; - const actionIdentity = identity; - const actionIntegrationAccount = ctx?.connection?.account; const deleted = action === 'delete' && read ? digestIdentity({ sourceId: target.request.source, id: target.request.plan }, { storeId: target.request.storeId, binding: read.binding }) : null; - cleanupBusy = true; cleanup = { ...cleanup, pending: true, message: null }; versions.ui++; schedule(); + const token = claimCleanup(); + cleanup = { ...cleanup, pending: true, message: null }; versions.ui++; schedule(); const result = await cleanupCall(host, action, { ...target.request, ...(!cleanupClosed(target) && action === 'delete' && health?.planCleanupActive === 1 ? { active: true as const } : {}) }); - cleanupBusy = false; + const mine = releaseCleanup(token); // A confirmed deletion is authoritative for its captured context: retire its review markers. if (result.ok && deleted) { if (digests) digests.forget(deleted); else void new CheckpointStore(host.storage, () => ctx?.features?.deviceStorage === true).forget(deleted); } if (disposed) return; - if (identity !== actionIdentity || ctx?.connection?.account !== actionIntegrationAccount) { - cleanup = initialCleanup(); versions.ui++; schedule(); return; - } + // An observed switch already released the busy state and reset the panel; a newer request owns both now. + if (!mine) return; const sameContext = target.context === cleanupContext(); // Also reconcile ambiguous failures. Never replay an action automatically or retain // pre-action data as a fresh success; every part/list reply from before this is retired. @@ -1421,7 +1471,7 @@ export function startView(spec: ViewSpec) { tidyPlans: () => spec.tidyPlans?.(context()) ?? [], requestTidy: () => { if (actionContext === cleanupContext()) requestTidy(); }, retryTidy: () => { - if (actionContext !== cleanupContext()) return; + if (actionContext !== cleanupContext() || tidyState !== cleanup.tidy) return; if (tidyState?.selection && tidyState.selectionRequest) { const remaining = tidyState.result?.remaining; const keys = new Set(remaining?.map(t => t.key)); @@ -1842,7 +1892,7 @@ export function startView(spec: ViewSpec) { host.onConnection((next) => { if (!ctx || disposed || item.kind === 'ordinary' || next.account === ctx.connection?.account) return; ctx = { ...ctx, connection: next }; - identity = ''; ui = spec.initialUi(); revalidateAction(); spec.onContext?.(context()); + identity = ''; ui = spec.initialUi(); health = null; observeSwitch(); cleanup = initialCleanup(); revalidateAction(); spec.onContext?.(context()); }); host.onReady((next) => { @@ -1876,7 +1926,7 @@ export function startView(spec: ViewSpec) { contextGeneration++; gate.retire(); resetCaches(); clearReading(); ui = spec.initialUi(); identity = ''; read = null; readScope = ''; readSig = ''; health = null; failure = null; lastGoodAt = null; - cleanup = { ...initialCleanup(), pending: cleanupBusy }; cleanupFocus = null; handoff = null; handoffNote = null; + observeSwitch(); cleanup = initialCleanup(); cleanupFocus = null; handoff = null; handoffNote = null; session = nextSession; directory = nextDirectory; requestedScope = scopeKey(currentScope()); versions.ctx++; live.restart(); spec.onContext?.(context()); gate.request(); From 19439fd9767c7a2f32547bb2ef530e2495a3e205 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:15:55 +1100 Subject: [PATCH 05/11] fix(companion): keep the system prompt section identical across requests (#165) * fix(companion): keep the system prompt section identical across requests The companion's system section carried the one-request hint, the sub-agent resume capsule (with its plan revision) and the delegation refusal note, so it changed between requests and defeated provider prompt caching. The section is now the fixed activation guidance only, byte-identical on every request where it is present. The hint, capsule and refusal note are added for one request after the content of its latest message, on a copy so the stored conversation never carries them: a text part on a user message, the output of the last tool result on a tool message (not the Code Mode wrapper result), and nothing on any other role, where the text waits for the next request with a valid carrier. Providers that drop plugin system sections now receive these notes too. Fixes #161 * docs(openspec): keep delivered context notes in place on later requests * docs(openspec): pin re-delivery, cleared line, keys and memory for context notes --- docs/backend.md | 16 ++- docs/compatibility.md | 22 +++-- docs/contracts.md | 47 +++++++-- openspec/changes/release-1-5-2/design.md | 11 ++- .../specs/plan-mirroring-guidance/spec.md | 39 ++++++-- openspec/changes/release-1-5-2/tasks.md | 6 +- plugin/activation.ts | 87 ++++++++++++++--- tests/backend/progress-activation.test.ts | 97 +++++++++++++++++-- tests/backend/progress-provider-view.test.ts | 10 +- .../progress-resume-activation.test.ts | 89 ++++++++++++++--- tests/fixtures/activation-native-driver.ts | 24 ++++- tests/fixtures/activation-production.ts | 18 +++- tests/fixtures/latest-message-text.ts | 16 +++ tests/fixtures/progress-resume-observer.ts | 4 +- tests/fixtures/proxy-shape-probe.ts | 17 +++- tests/fixtures/subagent-activity-observer.ts | 6 +- 16 files changed, 425 insertions(+), 84 deletions(-) create mode 100644 tests/fixtures/latest-message-text.ts diff --git a/docs/backend.md b/docs/backend.md index c2ce74e..3abeb33 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -1062,6 +1062,17 @@ for the parent's next observed qualifying call, not an inserted message or turn. No hook performs a missing-plan query, document read or progress mutation. Both system-forwarding and system-dropping providers get the checklist via the short report description; result notes do not depend on plugin system text. +The owned system section is the fixed guidance only and stays byte-identical across +requests, so it does not defeat a provider's prompt cache. The context hook adds +the one-request hint, the resume capsule and the refusal note after the content +of the request's latest message instead, on a copy of that message so the stored +conversation is unchanged: a text part on a user message, the output of the last +tool result on a tool message (native-proven string or content-array shapes, as for +result notes; the Code Mode wrapper result stays the script's exact value, so a hint +raised by an inner call waits for the next valid carrier), and nothing on any other +role or shape, where the hint stays pending, an armed capsule stays armed and the +refusal is read again on the next request. +Providers that drop plugin system sections therefore receive these notes too. The context section and inline/packaged skill share that checklist. The listing line names the plan/dispatch load boundary; detailed operation help stays in the skill. Description budgets are 4,096 overall and 2,048 through the first example. @@ -1136,7 +1147,7 @@ bun run typecheck The separately selected native `progress resume` case on OpenCode **2.2.2** loads the real production plugin with direct synthetic Store seeding, not an installer. It captures actual -outgoing recovery from system parts with a credential-free scripted AISDK provider, +outgoing recovery from the latest message with a credential-free scripted AISDK provider, fresh HOME/XDG and a rootless loopback-only network namespace. Source and built commands are in [compatibility](compatibility.md#progress-resume-capsule-verification). Proof includes a changed current revision, unconfirmed candidates, assigned child, @@ -1515,7 +1526,8 @@ linked children at a later revision; archived/deleted plans and disabled/unverified contexts expose none. A pending or reserved receipt whose state disagrees with its dispatch, or that names no task, marks evidence incomplete instead of yielding a refusal. -The refreshed coordinator context section is capped at 4 KiB, uses fixed reasons +The refreshed coordinator note, carried on the latest message and not in the +system section, is capped at 4 KiB, uses fixed reasons and explicitly marks omissions, including an empty incomplete result. It is advisory and read-only: recovery requires an intentional fresh declaration or verified explicit link, never an automatic diff --git a/docs/compatibility.md b/docs/compatibility.md index 02b4d16..a467ce3 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -693,8 +693,9 @@ node --experimental-strip-types --test tests/backend/progress-activation-runtime The separately named `progress resume` native case verifies production activation and Store lookup on OpenCode **2.x >= 2.2.2** at the actual outgoing scripted-provider boundary. It uses direct synthetic Store construction and local plugin loading, -not installation. The observer records metadata and the synthetic recovery section -from actual outgoing system parts; it never manufactures recovery in regression +not installation. The observer records metadata and the synthetic recovery text +from the latest outgoing message, where the capsule rides for one request while +the system section stays fixed; it never manufactures recovery in regression mode or retains conversation/summary text. No real model or provider credentials are used. Node 24.19.0 and OpenCode 2.2.2 are the tested baselines; later 24.x/2.x releases are accepted but not separately certified. The test requires Node 24.x @@ -782,14 +783,23 @@ tool check is not the cause: host tool names are checked before proxy renaming. Tool descriptions and results survive under host-prefixed names. The companion therefore puts its checklist and start example inside the first 2,048 description characters (4,096 overall), and appends conditional fixed notes to qualifying -completed direct calls. Its existing system section remains for providers that -forward it; no provider identifier or custom instructions are required. +completed direct calls. The one-request hint, the resume capsule and the +delegation refusal note ride the latest message of their request (a text part on +a user message, the last tool result's output on a tool message), so providers +that drop plugin system sections now receive them too. The system section remains +for providers that forward it and is the fixed guidance only, identical on every +request, so it does not defeat a provider's prompt cache. No provider identifier +or custom instructions are required. Credential-free native 2.2.2 probes establish result-content delivery for dispatch, write, edit and typed tracker results, with original content first and unchanged structured output. Code Mode inner result content does not reach the model: -those calls retain context hints but get no result note. Adapter checks cover -both run-observer orders and the provider view that drops system text. These +those calls retain context hints but get no result note, and their hint waits for the +next request whose latest message can carry it, since the wrapper result stays the +script's exact value. Adapter checks cover +both run-observer orders and the provider view that drops system text. The native +activation case checks the outgoing request of a real plan-file write continuation: +the hint ends the last tool result and the system section is unchanged. These checks establish delivery, not that a real model will mirror a plan unprompted. That live workflow remains an owner-only check, never a paid-model test. diff --git a/docs/contracts.md b/docs/contracts.md index 26fb58c..128fb7e 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -549,7 +549,12 @@ no protocol/schema version, persisted field, read behavior or permission change. ## Advisory activation does not change the protocol The companion can add one owned section to an eligible outgoing primary context -and one conditional possible-plan-file hint. Neither is a report receipt, plan, +and one conditional possible-plan-file hint. The section is the fixed activation +guidance only: its text never changes within a session and is byte-identical on +every request where it is present, so it does not defeat a provider's prompt +cache. Everything that varies per request (the one-request hint, the sub-agent +resume capsule and the delegation refusal note) is carried on the latest message +of that request instead, as described below. Neither is a report receipt, plan, assignment, review/acceptance, capture, or completion event. Existing explicit `agent_progress_report` operations, source-optional inputs, transactional control, authorization and outputs remain unchanged. Hidden/restricted tools are never @@ -574,8 +579,8 @@ checks are repeated after awaited lookups; recipient flags publish synchronously The same process-local bounded state may coalesce three advisory reasons: possible plan write, native dispatch and tracker mutation. At most one conditional hint is -added to the recipient's owned context section, consumed on eligible delivery, -not a receipt. Proxy reasons are actor-only: no child/parent/ancestor fan-out. +added after the content of the latest message of the recipient's next eligible +request, consumed on delivery, not a receipt. Proxy reasons are actor-only: no child/parent/ancestor fan-out. Only plan writes retain the verified-direct-parent relay. Existing 128 pending recipient and 256 recent call caps remain; no new queues, per-tool history, plan lookup, source read, report or automatic progress mutation is introduced. @@ -588,6 +593,24 @@ Only lexical path and host metadata are used: no file, folder or repository metadata is read. A missing, failing, malformed or timed-out worktree list declines cross-directory observation and relay. +Request-only text (the one-request hint, the resume capsule and the delegation +refusal note, with their text and eligibility unchanged) is added for that request +only, after the content of the request's latest message, in a carrier valid for +that message's role. On a user message it is a text part after the content. On a +tool message, the continuation after a tool call such as a plan-file write, a +separate part is not valid, so it is appended to the output of the message's last +tool result: the carrier the completed-result note below uses, with the same +shape limits (a native-proven string or content-array result). The Code Mode +wrapper (`execute`) result is the exact value its script returned and never +carries the text. Any other role or shape has no valid carrier, and the text +waits for the next request that has one; the hint stays pending, an armed capsule +stays armed and the refusal is read again then, never dropped. The standing +assigned-child brief and refusal note are read again on every request, so they +ride any ordinary tool continuation, not only the tools that receive result notes. The message and part are copied: the stored conversation never +carries the text, so a request rebuilt from history is identical up to its latest +message and a reused host array loses a stale note. The text is therefore +delivered even to providers that drop plugin system sections. + Hints also travel in completed tool results, independently of forwarded system text. The latest verified eligible context must expose both the report tool and the observed tool directly. Unknown eligibility, hidden report tools, disabled @@ -601,7 +624,10 @@ parent on the parent's next qualifying call, including the returning dispatch. No plan-presence lookup suppresses notes on already-mirrored work. Code Mode inner calls still raise context hints, but receive no result note: they are absent from the direct tool inventory, and native proof shows their -content note is lost on the way back to the script/model. Structured-only +content note is lost on the way back to the script/model. Their hint cannot ride +the wrapper's own result either, so it is delivered on the next request whose +latest message is a valid carrier, usually the next user message, not on the +continuation of that call. Structured-only results likewise stay unchanged. Neither carrier reports or grants authority. The dispatch hint conditionally asks coordinators of planned or multi-step work @@ -640,7 +666,8 @@ than broaden history. Hints conditionally ask about unreported canonical state, never assert work start, review/owner approval, assignment or completion, and never map issue state to plan status. No receipt correlation or compliance promise exists. -Recovery is an optional addition inside that same owned section, only after a +Recovery is an optional request-only addition on the latest message, never part +of the owned section, only after a host compaction observed during the loaded plugin lifetime: a live start, an observe-only compaction hook and an increasing, matching-reason successful end must pair for the same session/source. Hook/start callback delivery order is not @@ -654,7 +681,9 @@ precomputation or arbitrarily inverted durable streams. A start or hook alone is Accepted terminals retire open evidence; failure clears pending recovery. The first following primary context attempt consumes pending and incomplete evidence before awaits, retaining a creation-time fence against delayed backfill even if -delivery safely declines. Ordinary turns and uncompacted resumes do no recovery +delivery safely declines. The one exception is a request whose latest message has no +valid carrier: it performs no lookup and leaves the pending completion armed for the +next request that has one. Ordinary turns and uncompacted resumes do no recovery lookup and retain today's eligible generic guidance. Failed compactions retire pending recovery; title/generate and summarization requests receive no capsule. Observation never reads summary text or changes compaction inputs or `result`. @@ -1942,8 +1971,10 @@ structure, not implementation completion or approval. Review and owner approval are separate; reflect only existing canonical gate/work items, never invent review tasks. Dispatch is not work start. No file or automatic per-turn report is required. No custom instructions or provider-specific branch is needed. System-dropping -providers retain tool definitions and result notes; providers forwarding system -text retain the owned section too. Clients can still omit/truncate descriptions +providers retain tool definitions, result notes and the request-only hint, +capsule and refusal note on the latest message; providers forwarding system +text retain the owned section too, which stays identical across requests so it +does not defeat a provider's prompt cache. Clients can still omit/truncate descriptions below the supported budget; delivery does not guarantee reporting or model compliance. diff --git a/openspec/changes/release-1-5-2/design.md b/openspec/changes/release-1-5-2/design.md index e775376..935b04a 100644 --- a/openspec/changes/release-1-5-2/design.md +++ b/openspec/changes/release-1-5-2/design.md @@ -107,9 +107,14 @@ Items 3 and 4 change documentation only. ## 8. Stable system prompt section 1. **The system section holds only text that does not change within a session.** The companion's context hook adds one section to the system prompt on every eligible request. Today that section also carries the one-request hint after a dispatch, a plan-file write or a tracker save, the resume capsule of a sub-agent session, which names the plan's current revision and can drop out for one request when its bounded lookup times out, and the delegation refusal note. Each of these changes the system prompt between requests, and a provider prompt cache misses from the first changed byte, which takes the whole message history with it. After this change the system section is the fixed activation guidance only, byte-identical on every request where it is present. -2. **Changing text goes after the cacheable prefix, in a carrier valid for the latest message's role.** The hint, capsule and refusal note are added for that request only, after the content of the latest message the request carries, so the stored conversation is unchanged and the prefix up to the previous request stays identical. The carrier depends on that message's role. On a user message they are a text part after its content. On a tool message, which is the latest message of a continuation after a tool call such as a plan-file write, a separate text part is not valid, so they are appended to the output of its last tool result, the same carrier the existing note on a completed tool result already uses and the native driver already checks. Any other role gets nothing on that request: the text waits for the next request whose latest message has a valid carrier and is never dropped. The text and its eligibility rules are unchanged; only its position moves. Providers that drop plugin system sections now also receive these notes; the checklist they rely on is already in the tool description and does not change. -3. **What stays as it is.** The tool set, the tool description, the skill text and the note added once to a completed tool result already stay identical after their first send. The section is still removed when capture is off, the report tool is unavailable or the source is unverified, so turning those on or off still changes the prefix once. Compaction already rebuilds the prompt. -4. **Tests.** A context-hook test runs consecutive requests across a hint trigger, a capsule revision, a capsule lookup timeout and a refusal appearing and clearing, and asserts that the system array is identical each time and that the varying text arrives once, on the latest message, for that request only. The native activation driver also checks the outgoing request of a real plan-file write continuation: the hint arrives inside the last tool result, the system section is unchanged, and the provider accepts the request. Prompt-cache hit rates are not measured: that needs a live provider. +2. **Changing text goes after the cacheable prefix, in a carrier valid for the latest message's role.** The hint, capsule and refusal note are added after the content of the latest message the request carries; the stored conversation is unchanged. The carrier depends on that message's role. On a user message they are a text part after its content. On a tool message, which is the latest message of a continuation after a tool call such as a plan-file write, a separate text part is not valid, so they are appended to the output of its last tool result, the same carrier the existing note on a completed tool result already uses and the native driver already checks. A tool message whose last result is not a string or text content, or is the Code Mode `execute` wrapper's exact script value, has no valid carrier, and neither has any other role: the text waits for the next request whose latest message has a valid carrier and is never dropped. The text and its eligibility rules are unchanged; only its position moves. Providers that drop plugin system sections now also receive these notes; the checklist they rely on is already in the tool description and does not change. +3. **A delivered note stays where it was put.** A provider writes its cache at the end of the latest message, which is where the note sits, and reads it only when a later request repeats that prefix byte for byte; with extended thinking, the reply's thinking is also bound to that prefix. So a note added to one request and absent from the next would cost the cache and the thinking of every request it was on. The companion therefore remembers, per session, each note it delivered with its carrier: a tool carrier by its call identifier together with its position and a digest of its original output, because providers do not keep call identifiers unique across turns; a user carrier by the message's identifier when it has one, or else by its position and a digest of its original content. On every later request whose messages still hold that carrier, it adds the same text in the same place, so each request's messages are the previous request's messages followed by new ones, and the stored conversation still never changes. + - **Notes due together are one note**: hint, then capsule, then refusal note or cleared line, joined by a blank line. It is stored and added back exactly as delivered. A later note on the same carrier, for example on a retry, follows the earlier ones and never rewrites them. The comparison with the last delivery and the memory update happen in one synchronous step after the request's last wait, so two concurrent requests each record their own carrier. + - **Standing text.** A resume capsule or refusal note is delivered again when its text differs from the last one delivered in the session, or when the carrier of that last delivery is not in this request with its note, which covers compaction, a reverted message, an evicted carrier, a restart and a fork. A capsule lookup that times out adds nothing. A capsule or refusal left out as unchanged counts as delivered, and an armed capsule is consumed. + - **Cleared refusal.** A delivered refusal stays in history after it stops applying, so one fixed line is delivered in the same way: `Agent Progress note (delegation): the earlier delegation refusal no longer applies; read the current plan before you declare or link.` It is the one text this change adds. It is delivered only after a successful, complete refusal read that finds no refusal, while the last refusal delivered is still in this request with its note; a read that fails or is incomplete adds nothing. The cleared line counts as the last refusal delivered, so the same refusal returning is delivered again. A resume capsule that becomes empty after a successful lookup gets no cleared line: the capsule already says to read the current state first, and the earlier capsule staying in history is accepted. + - **Memory bound.** At most 128 sessions, least recently used first, and per session at most 64 carriers and 64 KiB of note text. Entries whose carrier is absent from the latest request are evicted first, then the oldest. A carrier evicted from the memory, a restart or a fork loses its note once, which changes the prefix once from that message on, and is accepted; the standing-text rule then delivers the current capsule or refusal again. +4. **What stays as it is.** The tool set, the tool description, the skill text and the note added once to a completed tool result already stay identical after their first send. On every path that removes the section (capture off, report tool unavailable, source unverified, caller lookup failed, an epoch change, disposal, or a failure in the hook), every note the companion added is removed from that request too, so a disabled or unverified context exposes none. The session's memory is cleared only when capture is turned off, the source binding changes or the companion is disposed; a transient failure, or a request without the report tool, keeps it, and the notes come back with the section. Turning those on or off still changes the prefix once. Compaction already rebuilds the prompt. +5. **Tests.** A context-hook test runs consecutive requests built from a growing stored history across a hint trigger, a capsule revision, a capsule lookup timeout, and a refusal appearing, clearing and appearing again, on a user carrier with and without an identifier and on a tool carrier. It asserts that the system array is identical each time and that each request's messages, including every note, are a byte-identical prefix of the next request's. Further cases: removal followed by the section coming back, a missing carrier or compaction causing the standing note to be delivered again, a failed refusal read adding no cleared line, and a reused tool call identifier in a later turn not receiving the earlier note. The native activation driver also checks the outgoing requests of a real plan-file write continuation: the hint arrives inside the last tool result, the system section is unchanged, the next outgoing request repeats that tool result with the hint, and the stored conversation does not contain it; it records whether the host's user messages carry an identifier. Prompt-cache hit rates are not measured: that needs a live provider. ## 9. Delivery, verification and rollback diff --git a/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md b/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md index 97426bc..809feea 100644 --- a/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md +++ b/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md @@ -26,25 +26,44 @@ The skill, the tool description and the inline guidance SHALL tell an agent that ### Requirement: The companion's system prompt section stays identical across requests -The companion's section of the system prompt SHALL contain only text that does not change within a session, and SHALL be byte-identical on every request where it is present. The one-request hint, the sub-agent resume capsule and the delegation refusal note SHALL be added for that request only after the content of its latest message, in a carrier valid for that message's role, with their text and eligibility unchanged, and MUST NOT be dropped. The stored conversation MUST NOT change. +The companion's section of the system prompt SHALL contain only text that does not change within a session, and SHALL be byte-identical on every request where it is present. The one-request hint, the sub-agent resume capsule and the delegation refusal note SHALL be added after the content of the latest message, in a carrier valid for its role, with their text unchanged. A due note MUST NOT be dropped for lack of a carrier, and the stored conversation MUST NOT change. #### Scenario: A hint is due - **WHEN** a dispatch or a plan-file write makes the one-request hint due and the next request is built -- **THEN** the system section is identical to the previous request's, and the hint is added after the latest message's content for that request only +- **THEN** the system section is identical to the previous request's, and the hint is added after the latest message's content #### Scenario: Continuation after a plan-file write - **WHEN** a plan-file write succeeds and the next request continues the tool call, so its latest message is a tool message -- **THEN** the system section is unchanged, and the hint is appended to the output of that message's last tool result for that request only, so the request stays valid for the provider +- **THEN** the system section is unchanged, and the hint is appended to the output of that message's last tool result, so the request stays valid for the provider + +#### Scenario: No valid carrier +- **WHEN** a note is due and the latest message has no valid carrier, such as an assistant message or the Code Mode `execute` wrapper's result +- **THEN** nothing is added on that request, and the note is added on the next request whose latest message has a valid carrier + +### Requirement: Delivered context notes stay in place on later requests + +Each note the companion delivered SHALL be added again, unchanged and in the same place, on every later request whose messages still hold its carrier while the companion remembers it. A capsule or refusal SHALL be delivered again only when its text differs from the last one delivered or that delivery's carrier is absent from the request. When a delivered refusal clears on a complete read, one fixed cleared line SHALL be delivered. Where the section is removed, every added note MUST be removed. + +#### Scenario: Later requests keep earlier notes +- **WHEN** a request carried a note and the next request is built from the same stored history with new messages after it +- **THEN** the next request repeats that message with the same note in the same place, so its messages begin with the previous request's messages byte for byte, and the stored conversation does not contain the note #### Scenario: A sub-agent's plan moved on -- **WHEN** a sub-agent session sends two requests and the plan's revision changed between them, or the capsule lookup timed out for one of them -- **THEN** the system section is identical on both requests, and each request carries its own capsule, or none, after its latest message +- **WHEN** a sub-agent session sends two requests and the plan's revision changed between them, or the capsule lookup timed out for the second +- **THEN** the system section is identical on both requests; after a revision change the second request carries the new capsule after its latest message, and after a timeout it adds nothing, while the earlier capsule stays where it was #### Scenario: A refusal appears and clears -- **WHEN** a delegation refusal note applies to one request and not to the next -- **THEN** the system section is identical on both, and only the first carries the note after its latest message +- **WHEN** a delegation refusal note applies to one request and not to a later one +- **THEN** the system section is identical on both, the note stays where it was delivered, and after a successful, complete read with no refusal the fixed cleared line is added after the later request's latest message; a failed read adds nothing -#### Scenario: Section removed -- **WHEN** capture is off, the report tool is unavailable or the source is unverified -- **THEN** the section is absent as before, and no note is added to the message +#### Scenario: Standing note after its carrier is gone +- **WHEN** a capsule or refusal note was delivered and a later request no longer holds that carrier, after compaction, a reverted message or an evicted carrier, and the text is unchanged +- **THEN** the current capsule or refusal is delivered again after that request's latest message + +#### Scenario: Reused tool call identifier +- **WHEN** a later turn's tool result reuses the call identifier of a tool result that carried a note +- **THEN** the newer tool result does not receive the earlier note +#### Scenario: Section removed +- **WHEN** any path removes the section, such as capture off, the report tool unavailable, the source unverified or a failure in the hook +- **THEN** the section is absent as before, every note the companion added is removed from the request, and no new note is added diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index 436850b..d377688 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -52,8 +52,8 @@ Each numbered group is one pull request into the development branch. It carries ## 8. Stable system prompt section -- [ ] 8.1 Keep the companion's system prompt section to the fixed activation guidance only, identical on every request where it is present, and add the one-request hint, the sub-agent resume capsule and the delegation refusal note for that request only after the content of its latest message, in a carrier valid for its role: a text part on a user message, the output of the last tool result on a tool message, and otherwise the next request with a valid carrier, never dropped. Their text and eligibility stay unchanged. Test consecutive requests across a hint trigger, a capsule revision, a capsule lookup timeout and a refusal appearing and clearing: the system array is identical each time, and the varying text arrives once, on the latest message, for that request only. Extend the native activation driver to check the outgoing request of a real plan-file write continuation: the hint is inside the last tool result and the system section is unchanged. -- [ ] 8.2 Update the statements in `docs/contracts.md`, `docs/backend.md` and `docs/compatibility.md` about where the section and its notes are delivered, including what providers that drop plugin system sections now receive, and say that the section stays identical across requests so it does not defeat a provider's prompt cache. +- [ ] 8.1 Keep the companion's system prompt section to the fixed activation guidance only, identical on every request where it is present, and add the one-request hint, the sub-agent resume capsule and the delegation refusal note after the content of its latest message, in a carrier valid for its role: a text part on a user message, the output of the last tool result on a tool message (not the Code Mode `execute` wrapper's result or a non-text result), and otherwise the next request with a valid carrier, never dropped. Their text and eligibility stay unchanged. Keep each delivered note in the same place on later requests built from the same history, keyed as design 8.3 says and bounded as it says; join notes due together in its order; deliver a capsule or refusal again when its text changed or its last carrier is gone; deliver the fixed cleared line under design 8.3's gates; remove every added note on every path that removes the section, and clear the memory only on the paths design 8.4 names. Test the cases design 8.5 lists: the system array is identical each time, and each request's messages are a byte-identical prefix of the next request's. Extend the native activation driver as design 8.5 says. +- [ ] 8.2 Update the statements in `docs/contracts.md`, `docs/backend.md` and `docs/compatibility.md` about where the section and its notes are delivered, including what providers that drop plugin system sections now receive, that delivered notes stay in place on later requests, when standing notes are delivered again, the fixed cleared line, and that the section stays identical across requests so it does not defeat a provider's prompt cache. Replace the statements that notes are added for that request only and that standing notes are read again on every request (`docs/contracts.md` around 596-612, `docs/backend.md` around 1013 and 1092). ## 7. Joined verification and release @@ -77,3 +77,5 @@ Each numbered group is one pull request into the development branch. It carries - [ ] Keeping a board control that is held when a bulk run ends valid as well as in place. Today the run's cache invalidation retires it, so it ignores that click. - [ ] Result expiry: repainting the expiry of a painted result as background data, and keeping a result the person has not seen through their own next action. - [ ] Recording per search hit whether a freshness reply covered it, so a page's checked state no longer depends on whether a reply or a search read came first. +- [ ] A source label on the one-request hint, which now sits in a user turn or a tool result. Its text is unchanged in this release. +- [ ] Releasing the cleanup busy state when a bulk run throws before it finishes, for example from a failed member check. This was present before 1.5.2. diff --git a/plugin/activation.ts b/plugin/activation.ts index 7811651..06d39a9 100644 --- a/plugin/activation.ts +++ b/plugin/activation.ts @@ -33,19 +33,60 @@ function noteText(reasons: number) { ? 'Agent Progress note (agent_progress_report): If you coordinate planned work without a mirror, start one with op=start; declare op=delegate before the next dispatch, or op=link for verified returned children. Already-current state needs no report; dispatch is not work start or assignment.' : 'Agent Progress note (agent_progress_report): If this is tracked plan work with meaningful unreported canonical state, mirror only work you own or are authorized to coordinate. A tracker update is not a progress report or evidence of work start, approval or completion.'; } +/** Native-proven content carriers only: a string, or text/file parts. Anything else is left untouched. */ +function appended(content: unknown, text: string): string | any[] | undefined { + if (typeof content === 'string') return `${content}\n\n${text}`; + if (Array.isArray(content) && content.every(part => record(part) && (part.type === 'text' && typeof part.text === 'string' || part.type === 'file' && typeof part.uri === 'string' && typeof part.mime === 'string'))) { + return [...content, { type: 'text' as const, text }]; + } +} function notedResult(result: Extract['result'], text: string) { // Only native-proven content carriers. Structured-only and unknown shapes // stay untouched: content can otherwise replace the host's output projection. - const content = result.content; - if (typeof content === 'string') return { ...result, content: `${content}\n\n${text}` }; - if (Array.isArray(content) && content.every(part => record(part) && (part.type === 'text' && typeof part.text === 'string' || part.type === 'file' && typeof part.uri === 'string' && typeof part.mime === 'string'))) { - return { ...result, content: [...content, { type: 'text' as const, text }] }; - } + const content = appended(result.content, text); + if (content !== undefined) return { ...result, content }; } function hintText(reasons: number) { return [reasons & PLAN ? PLAN_OBSERVATION : '', reasons & DISPATCH ? `${DISPATCH_OBSERVATION} ${DISPATCH_HINT}` : '', reasons & TRACKER ? TRACKER_OBSERVATION : '', HINT_CONDITION].filter(Boolean).join(' '); } +/** + * Where request-only text can ride on the latest message of a request, chosen + * by its role. A user message takes a text part after its content. A tool + * message, the continuation after a tool call, takes the text on the output of + * its last tool result: a separate part is not valid there, and this is the + * carrier the completed-result note already uses, so it has the same shape + * limits (a string, or text/file parts). The Code Mode wrapper's result is the + * exact structured value its script returned and never carries a note. Any + * other role, shape or result has no valid carrier. The stored message is never + * changed; the returned copy remembers its original so a reused host array can + * be restored. + */ +const CODE_MODE_TOOL = 'execute'; +const restored = Symbol('agent-progress-note'); +function carrier(messages: unknown): { index: number; apply: (text: string) => Record } | undefined { + if (!Array.isArray(messages) || !messages.length) return; + const index = messages.length - 1, message = messages[index]; + if (!record(message) || !Array.isArray(message.content)) return; + const copy = (content: unknown[]) => { + const value = Object.assign(Object.create(Object.getPrototypeOf(message)), message, { content }); + Object.defineProperty(value, restored, { value: message }); + return value; + }; + if (message.role === 'user') return { index, apply: text => copy([...message.content, { type: 'text', text }]) }; + if (message.role !== 'tool') return; + const at = message.content.findLastIndex((part: unknown) => record(part) && part.type === 'tool-result'); + const part = message.content[at], output = part?.result; + if (part?.name === CODE_MODE_TOOL || !record(output) || !(output.type === 'text' ? typeof output.value === 'string' : output.type === 'content' && Array.isArray(output.value))) return; + if (appended(output.value, '') === undefined) return; + return { index, apply: text => copy(message.content.map((entry: unknown, i: number) => i === at ? { ...part, result: { ...output, value: appended(output.value, text) } } : entry)) }; +} +/** Put back every message this owner replaced on a reused host array. */ +function restoreNotes(messages: unknown) { + if (!Array.isArray(messages)) return; + for (let i = 0; i < messages.length; i++) if (record(messages[i]) && Object.prototype.hasOwnProperty.call(messages[i], restored)) messages[i] = messages[i][restored]; +} + const record = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const boundedID = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 512; const uuid = (value: unknown) => typeof value === 'string' && /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(value); @@ -199,9 +240,12 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri const eligibility = new Map>(); // latest context, max128 sessions const noted = new Set(); // max256 source/session/model-message IDs const owned = Symbol('agent-progress-section'); - function section(hint: number, capsule = '', refusal = '') { - const part = { type: 'text' as const, text: ACTIVATION_GUIDANCE + (hint ? `\n\n${hintText(hint)}` : '') + (capsule ? `\n\n${capsule}` : '') + (refusal ? `\n\n${refusal}` : '') }; - Object.defineProperty(part, owned, { value: { hint } }); + // The section is fixed text: it must be byte-identical on every request, or + // a provider's prompt cache misses from this point on. Anything that varies + // per request rides the latest message instead (see `carrier`). + function section() { + const part = { type: 'text' as const, text: ACTIVATION_GUIDANCE }; + Object.defineProperty(part, owned, { value: true }); return part; } const registrations: Array<{ dispose(): Promise }> = []; @@ -320,12 +364,13 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri const context = async (event:SessionHooks['context']) => { const removeOwned = () => { for (let i = event.system.length - 1; i >= 0; i--) if (Object.prototype.hasOwnProperty.call(event.system[i], owned)) event.system.splice(i, 1); + restoreNotes(event.messages); }; try { - // A reused host array may carry old text, but never a reusable recovery payload. - for (let i = 0; i < event.system.length; i++) if (Object.prototype.hasOwnProperty.call(event.system[i], owned)) { - event.system[i] = section((event.system[i] as any)[owned].hint); - } + // A reused host array may carry an old section or note, never a reusable + // payload: drop both and rebuild from this request alone. + restoreNotes(event.messages); + for (let i = 0; i < event.system.length; i++) if (Object.prototype.hasOwnProperty.call(event.system[i], owned)) event.system[i] = section(); if (disposed) { removeOwned(); return; } if (!boundedID(event.sessionID)) return; const sessionKey = key(event.sessionID); @@ -349,10 +394,16 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri if (disposed || epoch !== disableEpoch) { removeOwned(); return; } if (!caller || !control()) { pending.delete(sessionKey); removeOwned(); return; } let capsule = ''; + // Request-only text needs a carrier valid for the latest message's role. + // Without one nothing is computed or consumed: the hint stays pending and + // an armed capsule stays armed for the next request that has a carrier. + const carried = carrier(event.messages) !== undefined; + const rearm = () => { if (armed && compactions.get(sessionKey) === attempt) attempt.pending = true; }; + if (!carried) rearm(); // Ordinary coordinators do not scan plans. Children reuse the bounded, // read-only identity/projection owner on naturally occurring contexts. const assignedOnly = !armed && !!caller.parentID; - if ((armed && recoveryAvailable || assignedOnly) && recovery && !lookupBusy && compactions.get(sessionKey) === attempt) { + if (carried && (armed && recoveryAvailable || assignedOnly) && recovery && !lookupBusy && compactions.get(sessionKey) === attempt) { const controller = new AbortController(); held = controller; const now = recovery.now ?? (() => performance.now()); const deadline = now() + 1000; @@ -382,17 +433,21 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri if (disposed || !control() || epoch !== disableEpoch || !source.verified || !Object.prototype.hasOwnProperty.call(event.tools, REPORT_TOOL)) { removeOwned(); return; } let refusal=''; try { - const selection=recovery?.refusals?.(event.sessionID); + const selection=carried?recovery?.refusals?.(event.sessionID):undefined; if(selection?.sourceId===source.id&&selection.sessionId===event.sessionID)refusal=delegationRefusalText(selection); } catch { /* Optional bounded receipt read never enables a report or blocks guidance. */ } if(disposed||!control()||epoch!==disableEpoch||!source.verified||!Object.prototype.hasOwnProperty.call(event.tools,REPORT_TOOL)){removeOwned();return;} if (eligibility.get(sessionKey) === effective) for (const tool of NOTE_TOOLS) { if (Object.prototype.hasOwnProperty.call(event.tools, tool)) effective.add(tool); } + // The section is the fixed guidance and nothing else, whatever this request carries. const existing = event.system.findIndex(part => Object.prototype.hasOwnProperty.call(part, owned)); - if (existing !== -1) { event.system[existing] = section((event.system[existing] as any)[owned].hint, capsule, refusal); return; } + if (existing !== -1) event.system[existing] = section(); else event.system.push(section()); const hint = (pending.get(sessionKey) ?? 0) & 7; - event.system.push(section(hint, capsule, refusal)); + const target = carrier(event.messages); + if (!target) { rearm(); return; } // the hint stays pending; capsule and refusal are read again next request + const text = [hint ? hintText(hint) : '', capsule, refusal].filter(Boolean).join('\n\n'); + if (text) event.messages[target.index] = target.apply(text) as typeof event.messages[number]; const remaining = (pending.get(sessionKey) ?? 0) & ~7; if (remaining) pending.set(sessionKey, remaining); else pending.delete(sessionKey); } catch { pending.delete(key(event.sessionID)); eligibility.delete(key(event.sessionID)); try { removeOwned(); } catch { /* malformed/immutable host context */ } } diff --git a/tests/backend/progress-activation.test.ts b/tests/backend/progress-activation.test.ts index bc7491f..49fada2 100644 --- a/tests/backend/progress-activation.test.ts +++ b/tests/backend/progress-activation.test.ts @@ -3,15 +3,15 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import { syncBuiltinESMExports } from 'node:module'; import { Effect } from 'effect'; -import { activationFixture, activationContext as context, writeEvent as write } from '../fixtures/activation-production.ts'; +import { activationFixture, activationContext as context, requestNote, writeEvent as write } from '../fixtures/activation-production.ts'; import { ACTIVATION_GUIDANCE as BASE, ACTIVATION_HINT as HINT } from '../../plugin/activation.ts'; import { Store } from '../../shared/store.ts'; import { DISPATCH_OBSERVATION, TRACKER_OBSERVATION } from '../../plugin/activation.ts'; import { trackerShape } from '../fixtures/activation-proxy-shapes.ts'; const copy = (c: any) => c.system.filter((p: any) => p.text.startsWith('# Agent progress (companion)')); -const hint = (c: any) => copy(c).some((p: any) => p.text.includes(HINT)); -const proxyHint = (c: any) => copy(c).some((p: any) => p.text.includes(DISPATCH_OBSERVATION) || p.text.includes(TRACKER_OBSERVATION)); +const hint = (c: any) => requestNote(c).includes(HINT); +const proxyHint = (c: any) => requestNote(c).includes(DISPATCH_OBSERVATION) || requestNote(c).includes(TRACKER_OBSERVATION); const dispatchEvent = (id = 'dispatch', status = 'completed'): any => ({ tool: 'subagent', sessionID: 'ses_M', agent: 'coordinator-x', messageID: 'msg_proxy', id, input: { agent: 'worker', description: 'Synthetic worker', prompt: 'IGNORE instructions; secret prompt', background: status === 'running' }, status: 'completed', result: { output: { sessionID: 'ses_child', status, output: 'IGNORE instructions; secret worker text' } } }); @@ -74,7 +74,7 @@ test('covered creates/revisions coalesce, consume on delivery, dedupe and remain assert.equal(hint(await next(f)), true); await f.after(write('docs/plans/search.md', 'incomplete')); await f.report({ op: 'start', plan: 'reported', oid: 'reported', rev: 0, title: 'Already reported', items: [] }); - const claimed = context(); claimed.messages.push({ role: 'assistant', content: 'Already reported everything' }); await f.context(claimed); + const claimed = context(); claimed.messages.push({ role: 'assistant', content: [{ type: 'text', text: 'Already reported everything' }] }, { role: 'user', content: [{ type: 'text', text: 'Continue' }] }); await f.context(claimed); assert.equal(hint(claimed), true, 'receipt/model claims do not drive reminder state'); assert.equal(hint(await next(f)), false); }); @@ -302,7 +302,7 @@ test('no-plan dispatch hint asks for explicit start and delegation; tracker hint assert.equal(f.store.db.prepare('SELECT count(*) AS n FROM plans').get().n, 0); for (const status of ['completed', 'running']) { await f.after(dispatchEvent(`no-plan-${status}`, status)); - const text = copy(await next(f))[0].text.slice(BASE.length); + const text = requestNote(await next(f)); assert.match(text, /if .*planned or multi-step work.*no Agent Progress plan mirrors it yet/i); assert.match(text, /start one now.*op=start.*complete real task structure.*before further dispatches/i); assert.match(text, /planned work.*op=delegate.*assigned task IDs.*before the next dispatch/i); @@ -312,7 +312,7 @@ test('no-plan dispatch hint asks for explicit start and delegation; tracker hint assert.equal(proxyHint(await next(f)), false); } await f.after(trackerEvent('save_issue')); - assert.doesNotMatch(copy(await next(f))[0].text.slice(BASE.length), /op=start|op=delegate/); + assert.doesNotMatch(requestNote(await next(f)), /op=start|op=delegate/); assert.equal(f.store.db.prepare('SELECT count(*) AS n FROM plans').get().n, 0, 'conditional advice never creates a plan'); }); }); @@ -397,10 +397,10 @@ test('mixed plan dispatch tracker burst coalesces reasons; proxies never relay a f.lookup = async (id: string) => ({ ...f.info(id), parentID: id === 'ses_M' ? 'ses_parent' : undefined }); await Promise.all(Array.from({ length: 30 }, (_, i) => f.after(i % 3 === 0 ? write('plan.md', `burst-${i}`) : i % 3 === 1 ? dispatchEvent(`burst-${i}`) : trackerEvent('save_comment', `burst-${i}`)))); const actor = await next(f); assert.equal(copy(actor).length, 1); - const text = copy(actor)[0].text; + const text = requestNote(actor); for (const reason of ['A possible plan document', DISPATCH_OBSERVATION, TRACKER_OBSERVATION]) assert.ok(text.includes(reason)); assert.equal(text.split('If this is tracked plan work').length - 1, 1); - const parent = copy(await next(f, 'ses_parent'))[0].text; assert.ok(parent.includes(HINT)); + const parent = requestNote(await next(f, 'ses_parent')); assert.ok(parent.includes(HINT)); assert.ok(!parent.includes(DISPATCH_OBSERVATION) && !parent.includes(TRACKER_OBSERVATION)); assert.equal(proxyHint(await next(f)), false); const inner = trackerEvent('save_issue', 'shared-call'); await f.after(inner); @@ -418,3 +418,84 @@ test('restricted or disabled proxy recipients lose only their actor flags withou assert.equal(proxyHint(await next(f)), false); }); }); + +test('request-only note picks its carrier by the latest message role, defers without one and never mutates stored objects', async () => { + await activationFixture(async f => { + const text = (value: string) => ({ type: 'text', text: value }); + const user = { role: 'user', content: [text('Make a plan')] }; + const result = (id: string, value: unknown, type = 'content') => ({ type: 'tool-result', id, name: 'write', result: { type, value } }); + const tool = (...results: any[]) => ({ role: 'tool', content: results }); + const call = { role: 'assistant', content: [{ type: 'tool-call', id: 'c1', name: 'write', input: {} }] }; + const request = (...messages: any[]) => { const c = context(); c.messages = messages; return c; }; + const stored = (...messages: any[]) => messages.map(m => structuredClone(m)); + const system = (c: any) => JSON.stringify(c.system); + let n = 0; const trigger = () => f.after(write('docs/plans/search.md', `trigger-${++n}`)); + const baseline = system(await next(f)); + + // User message: a text part after its content, on a copy. + await trigger(); + const history = [user], before = stored(user), c1 = request(...history); + await f.context(c1); + assert.deepEqual(c1.messages[0].content, [text('Make a plan'), text(HINT)]); + assert.notEqual(c1.messages[0], user); assert.deepEqual(history, before); assert.equal(c1.messages, c1.messages); + assert.equal(system(c1), baseline); + // Rebuilt from history, the next request carries nothing; a reused event loses its stale note. + const rebuilt = request(...history); await f.context(rebuilt); + assert.deepEqual(rebuilt.messages, before); assert.equal(system(rebuilt), baseline); + await f.context(c1); assert.deepEqual(c1.messages, before); assert.equal(system(c1), baseline); + assert.equal(copy(c1)[0].text, BASE); + + // Tool message with a content result: appended after the content of its last result only. + await trigger(); + const one = tool(result('c1', [text('Created file')]), result('c2', [text('Edited file')])); + const toolHistory = [user, call, one], toolBefore = stored(...toolHistory), c2 = request(...toolHistory); + await f.context(c2); + assert.deepEqual(c2.messages[2].content[0], one.content[0]); + assert.deepEqual(c2.messages[2].content[1].result, { type: 'content', value: [text('Edited file'), text(HINT)] }); + assert.deepEqual(toolHistory, toolBefore); assert.equal(c2.messages[0], user); assert.equal(c2.messages[1], call); assert.equal(system(c2), baseline); + + // Tool message with a text result: same newline-separated carrier as the completed-result note. + await trigger(); + const plain = tool(result('c1', 'Created file', 'text')), plainBefore = stored(plain), c3 = request(user, call, plain); + await f.context(c3); + assert.deepEqual(c3.messages[2].content[0].result, { type: 'text', value: `Created file\n\n${HINT}` }); + assert.deepEqual([plain], plainBefore); assert.equal(system(c3), baseline); + + // Any other tool's result carries it too: a child's standing brief must not vanish behind a read. + await trigger(); + const read = tool({ ...result('c1', [text('File contents')]), name: 'read' }), c4 = request(user, call, read); + await f.context(c4); + assert.deepEqual(c4.messages[2].content[0].result, { type: 'content', value: [text('File contents'), text(HINT)] }); + + // Roles and results with no valid carrier keep the text pending, never dropped. + await trigger(); + const unusable = [ + [user, { role: 'assistant', content: [text('Partial answer')] }], + [user, call, tool(result('c1', { ok: true }, 'json'))], + [user, call, tool(result('c1', 'failed', 'error'))], + [user, call, tool(result('c1', [{ type: 'unknown' }]))], + // The Code Mode wrapper's result stays the exact value its script returned. + [user, call, tool({ ...result('c1', '{"ok":true}', 'text'), name: 'execute' })], + [user, { role: 'system', content: [text('Operator note')] }], + [{ role: 'user', content: 'raw string content' }], + [], + ]; + for (const messages of unusable) { + const snapshot = stored(...messages), c = request(...messages); await f.context(c); + assert.deepEqual(c.messages, snapshot, 'nothing is added without a valid carrier'); + assert.equal(system(c), baseline); assert.equal(hint(c), false); + } + const delivered = request(user); await f.context(delivered); + assert.deepEqual(delivered.messages[0].content, [text('Make a plan'), text(HINT)], 'deferred text arrives on the next valid carrier'); + await f.context(delivered); assert.deepEqual(delivered.messages, [user]); + assert.equal(hint(await next(f)), false, 'delivered once'); + + // Removal paths leave neither a section nor a note. + await trigger(); const reused = request(user); await f.context(reused); assert.equal(reused.messages[0].content.length, 2); + f.store.setEnabled(false); await f.context(reused); + assert.equal(copy(reused).length, 0); assert.deepEqual(reused.messages, [user]); + f.store.setEnabled(true); + const missing = request(user); delete missing.tools.agent_progress_report; await trigger(); await f.context(missing); + assert.equal(copy(missing).length, 0); assert.deepEqual(missing.messages, [user]); + }); +}); diff --git a/tests/backend/progress-provider-view.test.ts b/tests/backend/progress-provider-view.test.ts index 3d6082c..89bf68a 100644 --- a/tests/backend/progress-provider-view.test.ts +++ b/tests/backend/progress-provider-view.test.ts @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { activationFixture, activationContext, writeEvent } from '../fixtures/activation-production.ts'; +import { activationFixture, activationContext, requestNote, writeEvent } from '../fixtures/activation-production.ts'; import { REPORT_CHECKLIST } from '../../plugin/activation.ts'; import { trackerShape } from '../fixtures/activation-proxy-shapes.ts'; @@ -20,7 +20,7 @@ const providerView = (f: any, events: any[]) => ({ messages: events.map(event => ({ role: 'tool', name: `mcp__opencode__${event.tool}`, result: event.result })), }); async function context(f: any, sessionID = 'ses_M', available = true) { - const event = activationContext(sessionID, available); event.messages = []; + const event = activationContext(sessionID, available); Object.assign(event.tools, Object.fromEntries(['subagent', 'write', 'edit', 'linear_save_issue', 'linear_save_comment'].map(name => [name, {}]))); await f.context(event); return event; } @@ -92,17 +92,17 @@ test('spec plan and host-listed worktree recognition is lexical and relays only `${f.root}/sibling/.slim/plans/example.md`]; for (const [i, file] of accepted.entries()) { await f.after(writeEvent(file, `accept-${i}`)); - assert.ok(section(await context(f))[0].text.includes('A possible plan document')); + assert.ok(requestNote(await context(f)).includes('A possible plan document')); } const rejected = ['openspec/changes/archive/example/tasks.md', 'openspec/changes/example/specs/plans/example.md', 'openspec/changes/example/design.md', `${f.root}/elsewhere/plans/x.md`]; for (const [i, file] of rejected.entries()) { await f.after(writeEvent(file, `reject-${i}`)); - assert.ok(!section(await context(f))[0].text.includes('A possible plan document')); + assert.ok(!requestNote(await context(f)).includes('A possible plan document')); } f.worktrees = async () => { throw new Error('Unavailable list'); }; await f.after(writeEvent(`${f.root}/sibling/plans/x.md`, 'unavailable')); - assert.ok(!section(await context(f))[0].text.includes('A possible plan document')); + assert.ok(!requestNote(await context(f)).includes('A possible plan document')); }); }); diff --git a/tests/backend/progress-resume-activation.test.ts b/tests/backend/progress-resume-activation.test.ts index 9f314f8..986e930 100644 --- a/tests/backend/progress-resume-activation.test.ts +++ b/tests/backend/progress-resume-activation.test.ts @@ -7,7 +7,7 @@ import { fromPromise } from '@opencode/plugin/promise/adapter'; import plugin from '../../plugin/index.ts'; import { registerActivation, ACTIVATION_GUIDANCE as BASE, ACTIVATION_HINT as HINT } from '../../plugin/activation.ts'; import { Store } from '../../shared/store.ts'; -import { activationContext as context, writeEvent } from '../fixtures/activation-production.ts'; +import { activationContext as context, requestNote, writeEvent } from '../fixtures/activation-production.ts'; import { isolatedEnvironment, publishFixtureBinding } from '../fixtures/managed.ts'; import { PARALLEL_DELEGATION_HINT } from '../../plugin/delegation.ts'; @@ -22,7 +22,7 @@ async function bounded(promise: Promise): Promise { finally { clearTimeout(timer); } } const parts = (c: any) => c.system.filter((p: any) => p.text?.startsWith('# Agent progress (companion)')); -const capsule = (c: any): string => parts(c)[0]?.text.split('\n\n## Progress resume')[1] ? `## Progress resume${parts(c)[0].text.split('\n\n## Progress resume')[1]}` : ''; +const capsule = (c: any): string => { const note = requestNote(c), at = note.indexOf('## Progress resume'); return at < 0 ? '' : note.slice(at); }; const samples: Record = {}; after(() => { if (process.env.RESUME_LIFECYCLE_EVIDENCE) fs.writeFileSync(process.env.RESUME_LIFECYCLE_EVIDENCE, JSON.stringify({ syntheticDataOnly: true, layer: 'unit/installed-adapter; not native outgoing proof', samples }, null, 2) + '\n'); @@ -153,7 +153,7 @@ async function fixture(run: (f: any) => Promise, options: { adapter?: bool test('ordinary child contexts deliver only current verified assignments without compaction or automatic reports',async()=>fixture(async f=>{ f.seed();const child={sourceId:f.binding.source.id,sessionId:'ses_C',parentId:'ses_M',ancestry:['ses_M'],agent:'synthetic',directory:'/fixture/project',verifiedSource:true}; const parent={...child,sessionId:'ses_M',parentId:null,ancestry:[]}; - const text=(c:any)=>parts(c)[0]?.text??''; + const text=(c:any)=>requestNote(c); assert.equal(text(await f.next('ses_C')).includes('last-known revision'),false); f.store.apply({op:'link',plan:'P-alpha',oid:'assign-child',rev:1,child:'ses_C',assign:['I1']},parent,undefined,child); const c=await f.next('ses_C');assert.ok(text(c).includes('Assigned-only scope: ["I1"]')); @@ -236,16 +236,16 @@ test(`durable refusal is refreshed after ${recovery} recovery on eligible coordi f.store.apply({op:'change',plan:'P-alpha',oid:'target-touch',rev:1,changes:[{id:'I1',status:'working'}]},actor); f.store.afterRun(key,0,{...actor,sessionId:'ses_C',parentId:'ses_M',ancestry:['ses_M']},'returned'); const before=f.store.get(actor.sourceId,'P-alpha'); - const absent=parts(await f.next('ses_sibling'))[0].text;assert.ok(!absent.includes('## Delegation not applied')); + const absent=requestNote(await f.next('ses_sibling'));assert.ok(!absent.includes('## Delegation not applied')); assert.equal(parts(await f.next('ses_M',false)).length,0); - const context=await f.next();const text=parts(context)[0].text; + const context=await f.next();const text=requestNote(context); assert.match(text,/Plan "P-alpha", declaration "refused-declaration" at revision 1; tasks \["I1"\]: not applied because/); assert.match(text,/re-declare at the current revision/);assert.match(text,/explicitly link/); assert.deepEqual(f.store.get(actor.sourceId,'P-alpha'),before); if(recovery==='redeclare')await f.report({op:'delegate',plan:'P-alpha',oid:'new-declaration',rev:2,assign:['I1']}); else f.store.apply({op:'link',plan:'P-alpha',oid:'recovered-link',rev:2,child:'ses_C',assign:['I1']},actor,undefined, {...actor,sessionId:'ses_C',parentId:'ses_M',ancestry:['ses_M']},recovery==='binding'?{generation:0,messageId:key.message,callId:key.call,observedAt:new Date(1000).toISOString()}:undefined); - await f.context(context);assert.ok(!parts(context)[0].text.includes('## Delegation not applied'),'reused context removes obsolete refusal'); + await f.context(context);assert.ok(!requestNote(context).includes('## Delegation not applied'),'reused context removes obsolete refusal'); f.store.setEnabled(false);assert.equal(parts(await f.next()).length,0); })); @@ -524,22 +524,89 @@ test('V6/V8 held ancestry retires on disable/disposal, no next hop or late injec }); }); -test('V8 reused system strips consumed recovery but preserves generic/file hints and unrelated context', async () => { +test('V8 reused context strips consumed recovery, hint and note, and preserves unrelated context', async () => { await fixture(async f => { f.seed(); await f.after(writeEvent()); await f.compact(); - const c = await f.next(); assert.ok(capsule(c)); assert.ok(parts(c)[0].text.includes(HINT)); + const c = await f.next(); assert.ok(capsule(c)); assert.ok(requestNote(c).includes(HINT)); assert.equal(parts(c)[0].text, BASE); const other = c.system[0], messages = c.messages, tools = c.tools, settings = c.options; - await f.context(c); assert.equal(capsule(c), ''); assert.equal(parts(c).length, 1); assert.ok(parts(c)[0].text.includes(HINT)); + // A reused event keeps neither the consumed capsule nor the consumed hint: they were for one request. + await f.context(c); assert.equal(requestNote(c), ''); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); assert.equal(c.system[0], other); assert.equal(c.messages, messages); assert.equal(c.tools, tools); assert.equal(c.options, settings); assert.equal(parts(await f.next())[0].text, BASE); - await f.compact(); await f.context(c); assert.ok(capsule(c)); assert.equal(parts(c).length, 1); + await f.compact(); await f.context(c); assert.ok(capsule(c)); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); + }); +}); + +test('system section is byte-identical across hint, refusal, capsule revision and lookup timeout; request-only text rides the latest message once', async () => { + await fixture(async f => { + f.seed(); + const stored = { role: 'user', content: [{ type: 'text', text: 'Make a plan' }] }; const snapshot = structuredClone(stored); + const systems: string[] = []; + // Every request is rebuilt from the same stored history, as the host does. + const request = async () => { f.tick(); const c = context(); c.messages = [stored]; await f.context(c); systems.push(JSON.stringify(c.system)); return c; }; + const note = async () => requestNote(await request()); + assert.equal(await note(), ''); + // One-request hint. + await f.after(writeEvent()); + assert.equal(await note(), HINT); assert.equal(await note(), ''); + // Delegation refusal appears, then clears. + await f.report({ op: 'delegate', plan: 'P-alpha', oid: 'refused-declaration', rev: 1, assign: ['I1'] }); + const actor = { sourceId: f.binding.source.id, sessionId: 'ses_M', parentId: null, ancestry: [], agent: 'synthetic', directory: '/fixture/project', verifiedSource: true }; + const key = { source: actor.sourceId, parent: actor.sessionId, message: 'message', call: 'reserved-call' }; + f.store.beforeRun(key, actor, 'subagent', {}, 1000); + f.store.apply({ op: 'change', plan: 'P-alpha', oid: 'target-touch', rev: 1, changes: [{ id: 'I1', status: 'working' }] }, actor); + f.store.afterRun(key, 0, { ...actor, sessionId: 'ses_C', parentId: 'ses_M', ancestry: ['ses_M'] }, 'returned'); + assert.match(await note(), /^## Delegation not applied/); + await f.report({ op: 'delegate', plan: 'P-alpha', oid: 'new-declaration', rev: 2, assign: ['I1'] }); + assert.equal(await note(), ''); + // Capsule naming the plan revision changes between requests. + const revision = () => f.store.get(f.binding.source.id, 'P-alpha').revision; + await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-a', rev: revision(), title: 'Synthetic alpha r2' }); + const first = revision(); assert.match(await note(), new RegExp(`last-known revision ${first}`)); + await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-b', rev: revision(), title: 'Synthetic alpha r3' }); + assert.match(await note(), new RegExp(`last-known revision ${first + 1}`)); + // The bounded capsule lookup times out for one request. + await f.compact(); + const release = deferred(); let calls = 0; + f.lookup = async (id: string) => { if (++calls > 1) await release.promise; return f.info(id); }; + assert.equal(await note(), ''); release.resolve(); f.lookup = async (id: string) => f.info(id); + await new Promise(resolve => setImmediate(resolve)); + await f.compact(); assert.match(await note(), /^## Progress resume/); + assert.equal(await note(), ''); + assert.equal(systems.length, 10); + assert.equal(new Set(systems).size, 1, 'one byte-identical system array on every request'); + assert.deepEqual(JSON.parse(systems[0]), [{ type: 'text', text: 'Other system section' }, { type: 'text', text: BASE }]); + assert.deepEqual(stored, snapshot, 'stored conversation never carries a note'); + }); +}); + +test('an armed capsule waits for a request with a carrier; an assigned child brief rides any tool continuation', async () => { + await fixture(async f => { + f.seed(); await f.compact(); + const text = (value: string) => ({ type: 'text', text: value }); + const user = { role: 'user', content: [text('Make a plan')] }; + const result = (name: string) => ({ role: 'tool', content: [{ type: 'tool-result', id: 'c1', name, result: { type: 'content', value: [text('out')] } }] }); + const without = context(); without.messages = [user, { role: 'assistant', content: [text('Partial answer')] }]; + const before = f.reads; f.tick(); await f.context(without); + assert.deepEqual(without.messages[1], { role: 'assistant', content: [text('Partial answer')] }); assert.equal(f.reads, before, 'no lookup without a carrier'); + assert.equal(without.system.filter((p: any) => p.text === BASE).length, 1, 'the section is still the fixed guidance'); + const delivered = await f.next(); assert.ok(capsule(delivered)); assert.equal(f.reads, before + 1, 'the capsule was not consumed by the request that had no carrier'); + assert.equal(capsule(await f.next()), ''); + // A child's standing brief is read again on every request, so it must survive a continuation ending in any ordinary tool result. + assert.equal((await f.report({ op: 'link', plan: 'P-alpha', oid: 'link', rev: 1, child: 'ses_C', assign: ['I1'] })).error, undefined); + for (const name of ['read', 'shell', 'write']) { + const c = context('ses_C'); c.messages = [user, { role: 'assistant', content: [] }, result(name)]; f.tick(); await f.context(c); + assert.match(requestNote(c), /Assigned-only scope: \["I1"\]/, name); + } + const wrapper = context('ses_C'); wrapper.messages = [user, { role: 'assistant', content: [] }, result('execute')]; f.tick(); await f.context(wrapper); + assert.equal(requestNote(wrapper), '', 'a Code Mode wrapper result stays the script value'); }); }); test('V8 optional recovery subscription/hook/stream failure retains generic activation and file hints', async () => { for (const unsupported of ['subscribe', 'hook', 'stream'] as const) await fixture(async f => { f.seed(); await f.after(writeEvent()); const c = await f.next(); - assert.equal(capsule(c), ''); assert.equal(parts(c).length, 1); assert.ok(parts(c)[0].text.includes(HINT)); assert.equal(f.reads, 0); + assert.equal(capsule(c), ''); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); assert.ok(requestNote(c).includes(HINT)); assert.equal(f.reads, 0); assert.equal(f.hooks.has('session:compaction'), false); }, { unsupported }); }); diff --git a/tests/fixtures/activation-native-driver.ts b/tests/fixtures/activation-native-driver.ts index 51e1599..8a0f3f3 100644 --- a/tests/fixtures/activation-native-driver.ts +++ b/tests/fixtures/activation-native-driver.ts @@ -11,6 +11,7 @@ import { ACTIVATION_GUIDANCE, ACTIVATION_HINT, REPORT_CHECKLIST } from '../../pl import { RELEASE } from '../../shared/release.ts'; import { requireRuntimeVersion } from './runtime-version.ts'; import { checkNativeCarrier } from './result-note-probe.ts'; +import { latestMessageTexts } from './latest-message-text.ts'; const root = process.argv[2]; assert.notEqual(fs.readlinkSync('/proc/self/ns/net'), process.argv[3], 'must run in independent network namespace'); @@ -61,6 +62,7 @@ try { assert.deepEqual(contexts[5].progress, { plans: 1, revisions: 1, receipts: 1, sessions: 1, chunks: 0, captures: 0, contributions: 1 }, 'only the explicit report changes Store'); assert.equal(events.some(e => e.type === 'unexpected-http'), false); const messages = await client.session.context({ sessionID: session.id }); + assert.equal(JSON.stringify(messages).includes(ACTIVATION_HINT), false, 'the one-request hint never reaches the stored conversation'); for (const event of after) assert.ok(messages.some(m => m.id === event.messageID), 'postwrite message belongs to independently queried host session'); assert.equal(fs.readFileSync(`${root}/project/docs/plans/search.md`, 'utf8'), '# Search\nThird draft\n'); const receipt = after[4].result.content; @@ -118,18 +120,30 @@ try { assert.equal(text.includes(ACTIVATION_GUIDANCE), true, 'PRODUCTION guidance reaches actual outgoing request'); assert.equal(text.split('# Agent progress (companion)').length - 1, 1, 'one owned section per primary request'); } - assert.deepEqual(primary.map(text => text.includes(ACTIVATION_HINT)), [false, true, true, true, false, false], 'native successful operations hint once; failed write and later continuation are base-only'); + // The system section is the fixed guidance only, identical on every request, so it cannot defeat a provider prompt cache. + assert.equal(new Set(primary).size, 1, 'system section is byte-identical across primary requests'); + assert.ok(primary.every(text => !text.includes(ACTIVATION_HINT)), 'the hint never travels in the system section'); + // The hint rides the latest message of one request: the output of the last tool result on a continuation after a plan-file write or edit. + const carried = (request: any) => latestMessageTexts(request.prompt).some(text => text.includes(ACTIVATION_HINT)); + assert.deepEqual(outgoing.slice(0, 6).map(carried), [false, true, true, true, false, false], 'native successful operations hint once, on the latest message; failed write and later continuation carry none'); + for (const index of [1, 2, 3]) { + const last = outgoing[index].prompt.at(-1); + assert.equal(last.role, 'tool', `continuation ${index} ends with the tool message`); + assert.ok(latestMessageTexts(outgoing[index].prompt).at(-1)!.endsWith(ACTIVATION_HINT), `hint is the end of the last tool result: ${index}`); + assert.equal(JSON.stringify(outgoing[index + 1].prompt.slice(0, outgoing[index].prompt.length)).includes(ACTIVATION_HINT), false, `the next request, rebuilt from history, no longer carries it: ${index}`); + } for (const request of childOutgoing) assert.equal(systemText(request).includes('# Agent progress (companion)'), false, 'hidden report tool receives no production instruction'); - const parentContinuation = outgoing.slice(8).map(systemText); - for (const text of parentContinuation) { + const parentContinuation = outgoing.slice(8); + for (const text of parentContinuation.map(systemText)) { assert.ok(text.includes(ACTIVATION_GUIDANCE)); assert.equal(text.split('# Agent progress (companion)').length - 1, 1); + assert.equal(text, primary[0], 'the parent section is the same bytes after the child write'); } - assert.deepEqual(parentContinuation.map(text => text.includes(ACTIVATION_HINT)), [true, false], 'direct parent receives child write hint exactly once'); + assert.deepEqual(parentContinuation.map(carried), [true, false], 'direct parent receives child write hint exactly once, on its next user message'); assert.equal((await client.session.get({sessionID:childSession.id})).parentID, session.id); console.log('native-shapes', JSON.stringify([...after, ...childAfter].map(e => ({ tool: e.tool, status: e.status })))); console.log('effective-tools', JSON.stringify({primary:contexts[0].tools, restrictedChild:hidden.tools})); - console.log('synthetic-outgoing', JSON.stringify({requests:outgoing.length,neutralPromptObserved:true,primaryReportTool:true,restrictedChildReportTool:false,restrictedChildNativeWrite:true,noManualSkillCalls:true,productionOwnedSections:8,productionHints:primary.map(text => text.includes(ACTIVATION_HINT)),parentRelayHints:parentContinuation.map(text => text.includes(ACTIVATION_HINT)),hintOnlyStoreUnchanged:true,revisedDescriptionDelivered:true,inlineSkillChecked:true,hiddenToolGuidance:false})); + console.log('synthetic-outgoing', JSON.stringify({requests:outgoing.length,neutralPromptObserved:true,primaryReportTool:true,restrictedChildReportTool:false,restrictedChildNativeWrite:true,noManualSkillCalls:true,productionOwnedSections:8,productionHints:outgoing.slice(0, 6).map(carried),systemSectionsIdentical:true,parentRelayHints:parentContinuation.map(carried),hintOnlyStoreUnchanged:true,revisedDescriptionDelivered:true,inlineSkillChecked:true,hiddenToolGuidance:false})); console.log(JSON.stringify({ nativeHookInvocation: 'PROVED-production-guidance-and-hints', contexts: contexts.length, nativeExecutions: after.length, reportReceiptRevision: 1, credentials: 0, externalTransport: 'network-namespace-no-external-interface', modelCompliance: 'NOT TESTED' })); } catch (error) { if (fs.existsSync(`${root}/events.jsonl`)) console.error('fixture-events', fs.readFileSync(`${root}/events.jsonl`, 'utf8').trim().split('\n').map(line => {const e=JSON.parse(line); return {type:e.type,tool:e.tool,status:e.status,index:e.index};})); diff --git a/tests/fixtures/activation-production.ts b/tests/fixtures/activation-production.ts index e17f171..965cd7e 100644 --- a/tests/fixtures/activation-production.ts +++ b/tests/fixtures/activation-production.ts @@ -84,7 +84,23 @@ export async function activationFixture(run: (fixture: any) => Promise, ve } } -export const activationContext = (sessionID = 'ses_M', available = true): any => ({ sessionID, agent: 'coordinator-x', model: { providerID: 'fixture', id: 'script' }, system: [{ type: 'text', text: 'Other system section' }], messages: [{ role: 'user', content: 'Make a plan' }], tools: available ? { agent_progress_report: { description: 'fixture', input: {} } } : {}, options: { temperature: 0.2 } }); +export const activationContext = (sessionID = 'ses_M', available = true): any => ({ sessionID, agent: 'coordinator-x', model: { providerID: 'fixture', id: 'script' }, system: [{ type: 'text', text: 'Other system section' }], messages: [{ role: 'user', content: [{ type: 'text', text: 'Make a plan' }] }], tools: available ? { agent_progress_report: { description: 'fixture', input: {} } } : {}, options: { temperature: 0.2 } }); +/** + * Text the companion added to the latest message for this request only: every + * text part after the original content of a user message, or the parts appended + * to the content of the last tool result of a tool message. Empty when nothing + * was added. + */ +export function requestNote(context: any, original = 1): string { + const message = context.messages?.at(-1); + if (!message || !Array.isArray(message.content)) return ''; + if (message.role === 'user') return message.content.slice(original).map((part: any) => part.text).join('\n\n'); + if (message.role === 'tool') { + const result = message.content.findLast((part: any) => part.type === 'tool-result')?.result; + if (result?.type === 'content') return result.value.slice(original).map((part: any) => part.text).join('\n\n'); + } + return ''; +} export function writeEvent(file = 'docs/plans/search.md', id = 'call_write', sessionID = 'ses_M'): any { return { tool: 'write', sessionID, agent: 'coordinator-x', messageID: 'msg_write', id, input: { path: file, content: 'Incomplete synthetic draft' }, status: 'completed', result: { output: { operation: 'write', target: `/fixture/${file}`, resource: file, existed: false } } }; } diff --git a/tests/fixtures/latest-message-text.ts b/tests/fixtures/latest-message-text.ts new file mode 100644 index 0000000..3c9694f --- /dev/null +++ b/tests/fixtures/latest-message-text.ts @@ -0,0 +1,16 @@ +/** + * Text carried by the latest message of an outgoing provider prompt. The + * companion adds its request-only notes there (a text part on a user message, + * the output of the last tool result on a tool message) and keeps its system + * section fixed. Native observers use this to find those notes. + */ +export function latestMessageTexts(prompt: any[] | undefined): string[] { + const message = prompt?.at(-1); + if (!message) return []; + const texts = (value: unknown): string[] => typeof value === 'string' ? [value] + : Array.isArray(value) ? value.flatMap(part => typeof part?.text === 'string' ? [part.text] : []) : []; + if (message.role === 'user') return texts(message.content); + if (message.role !== 'tool' || !Array.isArray(message.content)) return []; + const result = message.content.findLast((part: any) => part?.type === 'tool-result'); + return texts(result?.output?.value); +} diff --git a/tests/fixtures/progress-resume-observer.ts b/tests/fixtures/progress-resume-observer.ts index 69e5e64..909264c 100644 --- a/tests/fixtures/progress-resume-observer.ts +++ b/tests/fixtures/progress-resume-observer.ts @@ -2,6 +2,7 @@ import { Model, Provider, Plugin } from '@opencode/plugin'; import { appendFileSync, existsSync, readFileSync } from 'node:fs'; import { readManagedBinding } from '../../shared/managed-binding.ts'; +import { latestMessageTexts } from './latest-message-text.ts'; export const RESUME_SENTINEL = 'SYNTHETIC_PROGRESS_RESUME_SENTINEL'; // Fixed synthetic reply in the pinned host's Markdown checkpoint format. No conversation-derived content. @@ -111,7 +112,8 @@ export default Plugin.define({ id: 'progress-resume-observer', async setup(ctx) n + (typeof m.content === 'string' ? m.content.split(RESUME_SENTINEL).length - 1 : 0), 0); const invalidReply = latest?.kind === 'compaction' && existsSync(process.env.RESUME_FAIL!); const systems: string[] = options.prompt.filter((m: any) => m.role === 'system' && typeof m.content === 'string').map((m: any) => m.content); - const recovery = systems.flatMap(text => { + // The capsule rides the latest message for one request; the system section stays fixed. + const recovery = [...systems, ...latestMessageTexts(options.prompt)].flatMap(text => { const at = text.indexOf('## Progress resume —'); return at < 0 ? [] : [text.slice(at)]; }); diff --git a/tests/fixtures/proxy-shape-probe.ts b/tests/fixtures/proxy-shape-probe.ts index 35f95f1..5ab260b 100644 --- a/tests/fixtures/proxy-shape-probe.ts +++ b/tests/fixtures/proxy-shape-probe.ts @@ -13,6 +13,7 @@ import { Store } from '../../shared/store.ts'; import { DISPATCH_OBSERVATION, TRACKER_OBSERVATION } from '../../plugin/activation.ts'; import { requireRuntimeVersion } from './runtime-version.ts'; import { checkNativeCarrier } from './result-note-probe.ts'; +import { latestMessageTexts } from './latest-message-text.ts'; const binary = '/tmp/opencode/agent-progress-probe-cli/opencode'; const root = process.argv[3]; @@ -138,7 +139,7 @@ if (process.argv[2] !== '--driver') { // constructing the next request's immutable Code Mode inventory snapshot. await client.session.prompt({ sessionID: session.id, text: 'Synthetic catalog readiness preflight; no tool action.' }); await client.session.wait({ sessionID: session.id }, { signal: AbortSignal.timeout(15000) }); - let generation = 0; + let generation = 0, owed = 0; const prompt = async (id: string, name: string, input: any, cancel = false) => { const slowCount = records().filter(e => e.type === 'slow-entered').length; const offset = records().length; @@ -157,13 +158,21 @@ if (process.argv[2] !== '--driver') { const expected = process.env.PROXY_CODEMODE !== '1' && qualified && ['subagent', 'linear_save_issue', 'linear_save_comment'].includes(event.tool); assert.equal(JSON.stringify(event.result.content).includes('Agent Progress note'), expected, `direct-only result carrier: ${id}`); } - const hints = outgoing.filter(e => JSON.stringify(e.system).includes(DISPATCH_OBSERVATION) || JSON.stringify(e.system).includes(TRACKER_OBSERVATION)); - assert.equal(hints.length, qualified ? 1 : 0, `conditional actor hint once: ${id}`); + // The hint rides the latest message of one request; the system section never carries it. + const hinted = (e: any) => latestMessageTexts(e.prompt).some(t => t.includes(DISPATCH_OBSERVATION) || t.includes(TRACKER_OBSERVATION)); + assert.ok(outgoing.every(e => !JSON.stringify(e.system).includes(DISPATCH_OBSERVATION) && !JSON.stringify(e.system).includes(TRACKER_OBSERVATION)), 'system section never carries a hint'); + const hints = outgoing.filter(hinted); + // A direct tool's continuation carries the hint on its last result. A Code Mode wrapper + // result stays the script's exact value, so the hint waits for the next request whose + // latest message is a valid carrier, here the next case's user message, and is not dropped. + const codeMode = process.env.PROXY_CODEMODE === '1'; + assert.equal(hints.length, codeMode ? owed : qualified ? 1 : 0, `conditional actor hint once: ${id}`); + owed = codeMode && qualified ? 1 : 0; for (const e of outgoing) { const text = JSON.stringify(e.system); assert.ok(!text.includes('Synthetic issue') && !text.includes('Synthetic comment') && !text.includes('Synthetic worker complete.')); } - for (const e of fresh.filter(e => e.type === 'outgoing' && e.sessionID !== session.id)) assert.ok(!JSON.stringify(e.system).includes(DISPATCH_OBSERVATION) && !JSON.stringify(e.system).includes(TRACKER_OBSERVATION), 'no child proxy relay'); + for (const e of fresh.filter(e => e.type === 'outgoing' && e.sessionID !== session.id)) assert.ok(!hinted(e) && !JSON.stringify(e.system).includes(DISPATCH_OBSERVATION) && !JSON.stringify(e.system).includes(TRACKER_OBSERVATION), 'no child proxy relay'); } console.log('completed-case', id); }; diff --git a/tests/fixtures/subagent-activity-observer.ts b/tests/fixtures/subagent-activity-observer.ts index 31c56e9..c5da9d8 100644 --- a/tests/fixtures/subagent-activity-observer.ts +++ b/tests/fixtures/subagent-activity-observer.ts @@ -2,6 +2,7 @@ import { Model, Provider, Plugin } from '@opencode/plugin'; import fs from 'node:fs'; import { identifier } from '../../shared/progress.ts'; +import { latestMessageTexts } from './latest-message-text.ts'; export default Plugin.define({ id: 'subagent-activity-probe', async setup(ctx) { const root = process.env.ACTIVITY_ROOT!; @@ -124,8 +125,9 @@ export default Plugin.define({ id: 'subagent-activity-probe', async setup(ctx) { if (!seen.has(key) && session.agent === 'nested-worker') calls = [{ id: 'nested', input: { agent: 'restricted-worker', description: 'Synthetic nested child', prompt: 'Synthetic fixed probe.' } }]; if(!seen.has(key)&&!job&&session.agent==='reporting-worker')calls=jobs.firstReportingCall?[jobs.firstReportingCall]:[{id:'child-handoff',tool:'agent_progress_report',input:{op:'handoff',oid:'native-claim',summary:'Synthetic child reports its bounded work complete.',outcome:'done'}}]; seen.add(key); - const assignedBrief=options.prompt.some((m:any)=>m.role==='system'&&typeof m.content==='string'&&m.content.includes('Assigned-only scope:')); - const system=options.prompt.filter((m:any)=>m.role==='system'&&typeof m.content==='string').map((m:any)=>m.content).join('\n'); + // Request-only notes ride the latest message; the system section stays fixed. + const system=[...options.prompt.filter((m:any)=>m.role==='system'&&typeof m.content==='string').map((m:any)=>m.content),...latestMessageTexts(options.prompt)].join('\n'); + const assignedBrief=system.includes('Assigned-only scope:'); record({ type: 'dispatch', sessionID: identity, agent: session.agent, calls: calls?.map((c: any) => c.id) ?? [], assignedBrief, waitingForReport:job?.waitForReport, refusalHint:system.includes('## Delegation not applied'), refusalIdentity:system.includes('Plan "parallel-reporting", declaration "native-conflict"')&&system.includes('tasks ["task-c"]: not applied because'), refusalRecovery:system.includes('re-declare at the current revision')&&system.includes('explicitly link'), hold: job?.hold === true, fault: job?.fault === true }); if(job?.waitForReport){ const deadline=Date.now()+15000;let reported=false; From 8169d554b83ef2ce7ee594ee43acb6404c9a8840 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:16:45 +1100 Subject: [PATCH 06/11] test(browser): count the large-library gate by request and report what it cannot compare (#166) * test(browser): make the large-library gate count by request and report what it cannot compare Bound each timed window by log offsets read in the evaluations that start and stop its timer, and take every count the gate compares from the request log inside them. Count run reads once per window as an informational row, keep health reads out of per-refresh traffic, record the attribution method and both inbox forms, compare the list-carried inbox form per list start, and report a budget without a comparable baseline as unverified with a non-zero exit. Document how a baseline is recorded for the current artifact format. * test(browser): pin the one-uncomparable-candidate rule and align the gate docs * test(browser): drop measurement data from the baseline docs and tighten the gate's reasons --- docs/ui.md | 10 +- openspec/changes/release-1-5-2/design.md | 2 +- openspec/changes/release-1-5-2/tasks.md | 12 +- tests/browser/large-library-gate.test.ts | 238 ++++++++++++++++------ tests/browser/large-library-gate.ts | 130 +++++++----- tests/browser/large-library-qa.ts | 20 +- tests/browser/refresh-attribution.test.ts | 105 +++++++++- tests/browser/refresh-attribution.ts | 71 +++++-- 8 files changed, 441 insertions(+), 147 deletions(-) diff --git a/docs/ui.md b/docs/ui.md index 45f8820..b7b3692 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -1350,7 +1350,15 @@ For the separate **large-library** responsiveness guardrail, `tests/browser/larg The same driver checks a multi-page Search on that store: native press on Load more across an actual background search-state reply, unchanged pressed control and focus, next-page arrival, the existing explicit-action focus hand-off to Search results, and one completion announcement across another refresh. Before attaching its continuation observer it waits for the initial outcome's actual live-region text: ready result controls can precede the scheduled announcement frame. The exactly-one continuation assertion is unchanged. `--search-only --guest-root ` runs just this journey against a preserved source build, including a baseline comparison; no live profile is used. -`tests/browser/large-library-gate.ts ` checks baseline validity (page idle long-task total at least 4,000 ms; rail idle zero long tasks), then the median of three after runs: page idle/drag long-task total at most 1,000 ms, idle/keyboard longest task at most 250 ms, drag/wheel p99 frame gap at most 150 ms, cold selection at most 1,500 ms, scrollbar distance at least 90% of the refresh-paused control with the same connected element, rail zero long tasks and p99 at most 50 ms in every window, and no increased idle request count per refresh. Idle polling is judged per run and per window: a window's own elapsed time at the 3-second cadence sets how many `/health` replies and first-page list reads (refresh starts, counted apart from continuation pages) it may hold, one tick either way, and the board and rail must both pass in the same run, so doubled, absent or one-sided polling fails. Traffic is then compared per complete refresh: the driver attributes every request to the refresh that sent it (by the order requests were sent, so a slow inbox or run read stays with its own refresh) and counts only refreshes that a later first page closed inside the window, so a refresh split by the window edge counts on neither side of the ratio, a healthy extra boundary poll is not extra work, and more pages or inbox reads per refresh still fail. Inbox work counts both `/v1/needs-you` and the first window carried by `/v1/plans?needsYou=1`, recorded with explicit zeros; the gate compares the split when the baseline and at least two candidates carry it, otherwise the `/v1/needs-you` route alone, with the row naming the fallback. An artifact without complete-refresh attribution, or with no complete refresh in the window, falls back to wall-clock counts divided by list starts, or by `/health` when those are missing too, and an older artifact's recorded wall-clock inbox form is used as it is; the report names the baseline's and each candidate's fallback. Outside the timed windows the driver also records keyboard listbox state across two refreshes, board overflow/picker visibility at 1100/360/390 px, and zero-badge checks with English, Russian and Simplified Chinese captures at 390 px. Hold the shared test lock for each entire driver run. These are local synthetic-host guardrails, not host-installation, physical-phone or service-level certification; a miss is reported rather than relaxed. +`tests/browser/large-library-gate.ts ` checks baseline validity (page idle long-task total at least 4,000 ms; rail idle zero long tasks), then the median of three after runs: page idle/drag long-task total at most 1,000 ms, idle/keyboard longest task at most 250 ms, drag/wheel p99 frame gap at most 150 ms, cold selection at most 1,500 ms, scrollbar distance at least 90% of the refresh-paused control with the same connected element, rail zero long tasks and p99 at most 50 ms in every window, and no increased idle request count per refresh. Idle polling is judged per run and per window: a window's own elapsed time at the 3-second cadence sets how many `/health` reads and first-page list reads (refresh starts, counted apart from continuation pages) it may hold, one tick either way, and the board and rail must both pass in the same run, so doubled, absent or one-sided polling fails. Every count comes from the request log, between offsets the driver reads in the same browser evaluations that start and stop each timed window, so a request counts by when it was sent: one sent before the window and answered inside it is out, one sent inside and answered after it is in, and nothing logged after the stop (a first page included) is counted or closes a refresh. The reply log keeps only status, size and timing. Traffic is then compared per complete refresh: the driver attributes every request to the refresh that sent it (by the order requests were sent, so a slow inbox read stays with its own refresh) and counts only refreshes that a later first page closed inside the window, so a refresh split by the window edge counts on neither side of the ratio, a healthy extra boundary poll is not extra work, and more pages or inbox reads per refresh still fail. `/health` is read before its refresh's first page, so it stays out of those figures and cadence alone judges it. Run reads can be the automatic follow-up of a run reconciliation, sent after the next refresh started, and the log cannot say which refresh caused one; the artifact counts them once per window, and the gate shows each window's count beside its list starts as an informational row that is never compared and never changes the exit status. Inbox work counts both `/v1/needs-you` and the first window carried by `/v1/plans?needsYou=1`, recorded with explicit zeros, as complete-refresh counts and as a wall-clock split of the whole window; the artifact also records its attribution method. The form carried by the list read is compared on its own, per list start (a list start either carried it or did not, so the figure is comparable in any window), as well as in the combined figure, so an extra standalone request at a window edge cannot pay for an added window on the list read. A budget the gate cannot compare is reported as unverified: neither passed nor failed, named in the summary, with exit status 2 (1 when a budget failed or the gate aborted). That covers a baseline whose per-refresh figures do not rest on complete refreshes (no attribution method, as when an older driver bucketed replies, or fewer than two list starts in its idle window, where a refresh that began before the window changes the figure by itself), and any figure that fewer than two candidates can supply on the same basis (a candidate that cannot is named and left out of the median); the comparisons that can be made still run. An older artifact is named in the report and is never treated as an equivalent complete sample. Outside the timed windows the driver also records keyboard listbox state across two refreshes, board overflow/picker visibility at 1100/360/390 px, and zero-badge checks with English, Russian and Simplified Chinese captures at 390 px. Hold the shared test lock for each entire driver run. These are local synthetic-host guardrails, not host-installation, physical-phone or service-level certification; a miss is reported rather than relaxed. + +**Recording the gate's baseline.** The baseline must show the stall of the interface from before the responsiveness change (at least 4,000 ms of page idle long tasks, a smooth rail), be in the current artifact format, and have completed at least one refresh inside its page idle window (two or more list starts). Only the current driver writes that format, so the baseline is the current driver and service run against an older interface, tried in this order: + +1. Check out the `v1.5.0` tag into a disposable detached worktree (`git worktree add --detach v1.5.0`) and run `tests/browser/large-library-qa.ts --chromium --artifacts --guest-root ` without `--source`. The tag tracks `ui/{page,panel,status}/{index.html,main.js}`, the layout `--guest-root` reads, so nothing is built. Remove the worktree afterwards. +2. If a driver step cannot run on those guests, build guests from the last revision before the responsiveness change (the parent of `095a3e9`) with `bun run bundle:guest`, laid out as the driver's own `--source` branch does, and pass that directory as `--guest-root`. +3. As a last resort, overlay the driver and its fixtures on that older source and run with `--source`. + +Step 1 worked in the 1.5.2 rehearsal: the driver ran to its end on the 1.5.0 guests, the baseline passed the validity check, completed at least one refresh in its page idle window and recorded both inbox forms with real values (the 1.5.0 interface sends both on every refresh). Then run the three candidates with `--source` on the branch under test, each alone, and the gate on the four artifact directories. If a baseline has fewer than two list starts in its idle window, or fails the validity check, do not lengthen the window or lower a threshold: the gate cannot compare its per-refresh budgets, so report it. Keep the artifacts, logs and stores out of the repository. `tests/fixtures/large-plan.ts` supplies the shared `large-plan-v1` sequence: 980 tasks in 20 layers of 49, 20 groups, 2,000 authored task dependency links, diff --git a/openspec/changes/release-1-5-2/design.md b/openspec/changes/release-1-5-2/design.md index 935b04a..2604e22 100644 --- a/openspec/changes/release-1-5-2/design.md +++ b/openspec/changes/release-1-5-2/design.md @@ -91,7 +91,7 @@ QA only. Nothing shipped changes. 5. **The bundled inbox form is compared on its own** as well as in the combined figure, so an extra standalone request at a window edge cannot pay for an added first window on the list read. The form carried by the list read is counted per list start. A list start either carried it or did not, so that figure has no error at the window edge and is comparable in any window. The standalone form is judged in the combined figure over complete refreshes. A standalone request sent in the refresh still open when the window ends is counted in the window's split and changes no per-refresh verdict, like that refresh's list pages: a refresh the window cut is on neither side of a ratio. 6. **Health is outside per-refresh traffic.** The health read precedes its refresh's first list page, so it cannot be tied to a bucket; the cadence check already covers it. 7. **No comparable baseline means unverified.** When the baseline or too few candidates carry the inbox split, the combined inbox budget is reported as unverified. The same holds for any per-refresh budget whose baseline and candidate figures do not rest on the same denominator, even when both artifacts are in the current format. A window that completed no refresh has only wall-clock counts over a single list start, where the traffic of a refresh that began before the window changes the figure by itself: nineteen list pages over one list start would let a candidate reading eleven pages per refresh pass a ten-page contract. Such a figure is not compared with complete-refresh figures. The gate then reports neither a pass nor a failed budget and exits non-zero with that state named. The other comparisons still run. A baseline recorded with the current driver whose idle window completed at least one refresh removes the state for those budgets. Its summary names which budgets are unverified and which failed. The run-read row of decision 2 is informational and is neither. -8. **The tests tell the paths apart.** The attribution fixtures fail if requests were bucketed in reply order, and the gate fixtures use counts that differ per denominator and mix an older candidate, a current candidate and one without a split. They include a baseline with a single list start against candidates with complete refreshes, a run read on each side of the window's first and last list start, with the run-read budget reported as unverified whatever those counts are, and an inbox request sent across each window edge, with the window's split and the unchanged complete-refresh figures both asserted. +8. **The tests tell the paths apart.** The attribution fixtures fail if requests were bucketed in reply order, and the gate fixtures use counts that differ per denominator and mix an older candidate, a current candidate and one without a split. They include a baseline with a single list start against candidates with complete refreshes, a run read on each side of the window's first and last list start, with the run-read row informational whatever those counts are and never changing the exit, and an inbox request sent across each window edge, with the window's split and the unchanged complete-refresh figures both asserted. The driver is not part of portable CI. Decisions 1 to 7 put their logic in the attribution helper and the gate, which the unit tests cover; the browser-side capture of offsets is shown by one rendered run. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index d377688..ec65ba7 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -36,12 +36,12 @@ Each numbered group is one pull request into the development branch. It carries ## 5. Large-library gate precision -- [ ] 5.1 Capture the request and reply offsets of a timed window in the browser evaluations that start and stop its timer, and slice between them, in a helper the unit tests can call. Take the cadence counts and both inbox forms from the request log inside those bounds, and keep the reply log for status, size and timing. -- [ ] 5.2 Count run reads per window, outside the per-refresh figures: every run read sent inside the window, whichever refresh preceded it. Record that count beside the window's list starts as an informational row that does not affect the exit status, and judge neither. Keep health reads out of per-refresh traffic. Test a run read sent after the next refresh's first list page, one sent inside the window before the window's first list start, and that the row leaves a passing run passing whatever the counts are. -- [ ] 5.3 Record the attribution method and the wall-clock split of both inbox forms in the artifact; make the gate distinguish artifacts that bucketed replies, and compare the inbox form carried by the list read on its own as well as combined. -- [ ] 5.4 Report the combined inbox budget as unverified when the baseline or too few candidates carry the split, with its own summary state and an unsuccessful exit, while the other comparisons still run. Report a per-refresh budget the same way when its baseline and candidate figures do not rest on the same denominator, and keep comparing the inbox form carried by the list read per list start. Make the summary name each unverified budget and each failed one. -- [ ] 5.5 Strengthen the tests so they fail for reply-ordered attribution and for the wrong denominator: a reply landing after the final first-page reply, one start with two health replies and ten plan replies, a mix of an older candidate, a current candidate and one without a split, a baseline with a single list start against candidates with complete refreshes, and an inbox request sent across each window edge, asserting the window's split and that a request in the refresh left open at the window's end changes no complete-refresh figure. -- [ ] 5.6 Update the large-library paragraph of `docs/ui.md`, including how a baseline is recorded for the current artifact format: the current driver run against an interface build from before the 1.5.1 responsiveness change, the last one that shows the stall a baseline must show. Rehearse that procedure once, check that the recorded baseline completed at least one refresh inside its idle window, and report the completed baseline run in the pull request as local synthetic-host evidence without committing a measurement. Run the gate and attribution tests, and one rendered run of the driver to show the offset capture. +- [x] 5.1 Capture the request and reply offsets of a timed window in the browser evaluations that start and stop its timer, and slice between them, in a helper the unit tests can call. Take the cadence counts and both inbox forms from the request log inside those bounds, and keep the reply log for status, size and timing. +- [x] 5.2 Count run reads per window, outside the per-refresh figures: every run read sent inside the window, whichever refresh preceded it. Record that count beside the window's list starts as an informational row that does not affect the exit status, and judge neither. Keep health reads out of per-refresh traffic. Test a run read sent after the next refresh's first list page, one sent inside the window before the window's first list start, and that the row leaves a passing run passing whatever the counts are. +- [x] 5.3 Record the attribution method and the wall-clock split of both inbox forms in the artifact; make the gate distinguish artifacts that bucketed replies, and compare the inbox form carried by the list read on its own as well as combined. +- [x] 5.4 Report the combined inbox budget as unverified when the baseline or too few candidates carry the split, with its own summary state and an unsuccessful exit, while the other comparisons still run. Report a per-refresh budget the same way when its baseline and candidate figures do not rest on the same denominator, and keep comparing the inbox form carried by the list read per list start. Make the summary name each unverified budget and each failed one. +- [x] 5.5 Strengthen the tests so they fail for reply-ordered attribution and for the wrong denominator: a reply landing after the final first-page reply, one start with two health replies and ten plan replies, a mix of an older candidate, a current candidate and one without a split, a baseline with a single list start against candidates with complete refreshes, and an inbox request sent across each window edge, asserting the window's split and that a request in the refresh left open at the window's end changes no complete-refresh figure. +- [x] 5.6 Update the large-library paragraph of `docs/ui.md`, including how a baseline is recorded for the current artifact format: the current driver run against an interface build from before the 1.5.1 responsiveness change, the last one that shows the stall a baseline must show. Rehearse that procedure once, check that the recorded baseline completed at least one refresh inside its idle window, and report the completed baseline run in the pull request as local synthetic-host evidence without committing a measurement. Run the gate and attribution tests, and one rendered run of the driver to show the offset capture. ## 6. Guidance, receipt evidence and documentation diff --git a/tests/browser/large-library-gate.test.ts b/tests/browser/large-library-gate.test.ts index a5c7d66..cfd714e 100644 --- a/tests/browser/large-library-gate.test.ts +++ b/tests/browser/large-library-gate.test.ts @@ -1,4 +1,5 @@ -// The large-library gate must judge idle polling against the refresh cadence, not against its own /health count. +// The large-library gate must judge idle polling against the refresh cadence, not against its own /health count, and must say +// when it cannot compare a budget instead of passing it. import assert from 'node:assert/strict'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; @@ -8,39 +9,55 @@ import test from 'node:test'; const row = (count: number) => ({ count, bytes: count * 100 }); /** - * One idle window per surface at the 3 s cadence. Per refresh the board reads one first page plus nine continuation - * pages, one /v1/needs-you window and one /v1/plans?needsYou=1 window; the rail reads one page. The driver's complete - * refreshes are the ones a later first page closed, so one fewer than the list starts in the window. + * How the artifact was written. `current` has the attribution method, the request-log counts, run reads, the wall-clock inbox + * split and the complete refreshes. `unlabelled` has the same figures without the method (a driver that bucketed replies). + * `older` has list starts and a wall-clock inbox split counted from replies, no complete refreshes. `oldest` has reply counts only. + */ +type Format = 'current' | 'unlabelled' | 'older' | 'oldest'; +/** + * One idle window per surface at the 3 s cadence. Per refresh the board reads one first page plus nine continuation pages, + * one /v1/needs-you window and one /v1/plans?needsYou=1 window (carried by the first page); the rail reads one page. The + * driver's complete refreshes are the ones a later first page closed, so one fewer than the list starts in the window. */ interface Opt { page?: number; rail?: number; elapsed?: number; railElapsed?: number; pagesPerRefresh?: number; pageStarts?: number; railStarts?: number; - railPlans?: number; firstWindow?: number; split?: boolean; before?: boolean; - /** Wall-clock /v1/plans replies on the board, and the plan pages the driver attributed to its complete refreshes. */ + railPlans?: number; firstWindow?: number; before?: boolean; format?: Format; + /** Plan pages sent on the board inside the window, and the plan pages attributed to its complete refreshes. */ pagePlans?: number; completePlans?: number; - /** The previous driver: list starts and wall-clock inbox counts, no complete-refresh attribution. */ - legacyDriver?: boolean; + /** The inbox windows attributed to the complete refreshes (a window opened by the last, still open refresh is not among them). */ + completeInbox?: { needsYouRoute: number; plansFirstWindow: number }; + /** Standalone /v1/needs-you requests and list-carried inbox windows sent on the board inside the window. */ + standalone?: number; bundled?: number; + /** /health and run reads sent on the board inside the window. */ + health?: number; runReads?: number; } function results(o: Opt = {}) { - const page = o.page ?? 5, rail = o.rail ?? 5, split = o.split ?? true; - const window = (surface: 'page' | 'panel', refreshes: number, elapsed: number, plans: number, starts: number, first: number, completePlans: number) => ({ - surface, label: 'idle', elapsed, longTasks: { count: 0, total: o.before && surface === 'page' ? 5000 : 0, max: 0 }, frames: { p99: 16, max: 20 }, - traffic: { - [`${surface} /health`]: row(refreshes), [`${surface} /v1/plans`]: row(plans), [`${surface} /v1/needs-you`]: row(refreshes), [`${surface} /v1/subagent-runs`]: row(refreshes), - }, - ...(split && o.legacyDriver ? { listStarts: { [surface]: starts }, inbox: { [surface]: { needsYouRoute: refreshes, plansFirstWindow: first } } } : {}), - ...(split && !o.legacyDriver ? { - listStarts: { [surface]: starts }, - complete: { [surface]: { refreshes: Math.max(0, starts - 1), traffic: { '/v1/plans': completePlans, '/v1/needs-you': Math.max(0, starts - 1), '/v1/subagent-runs': Math.max(0, starts - 1) }, inbox: { needsYouRoute: Math.max(0, starts - 1), plansFirstWindow: Math.round(first * Math.max(0, starts - 1) / Math.max(1, refreshes)) } } }, - } : {}), - }); + const page = o.page ?? 5, rail = o.rail ?? 5, format = o.format ?? 'current'; + const window = (surface: 'page' | 'panel', elapsed: number, plans: number, starts: number, bundled: number, standalone: number, completePlans: number, health: number, runs: number) => { + const refreshes = Math.max(0, starts - 1); + const counts = { '/health': health, '/v1/plans': plans, '/v1/needs-you': standalone, '/v1/subagent-runs': runs }; + return { + surface, label: 'idle', elapsed, longTasks: { count: 0, total: o.before && surface === 'page' ? 5000 : 0, max: 0 }, frames: { p99: 16, max: 20 }, + traffic: Object.fromEntries(Object.entries(counts).map(([route, n]) => [`${surface} ${route}`, row(n)])), + ...(format === 'current' || format === 'unlabelled' ? { + ...(format === 'current' ? { attribution: 'request-order' } : {}), + sent: Object.fromEntries(Object.entries(counts).map(([route, n]) => [`${surface} ${route}`, n])), + listStarts: { [surface]: starts }, runReads: { [surface]: runs }, + inbox: { [surface]: { needsYouRoute: standalone, plansFirstWindow: bundled } }, + complete: { [surface]: { refreshes, traffic: { '/v1/plans': completePlans, '/v1/needs-you': refreshes }, inbox: o.completeInbox ?? { needsYouRoute: refreshes, plansFirstWindow: Math.round(bundled * refreshes / Math.max(1, starts)) } } }, + } : {}), + ...(format === 'older' ? { listStarts: { [surface]: starts }, inbox: { [surface]: { needsYouRoute: standalone, plansFirstWindow: bundled } } } : {}), + }; + }; const others = (surface: 'page' | 'panel') => ['drag', 'wheel-pan', 'selection', 'key-zoom'].map(label => ({ surface, label, elapsed: 1000, longTasks: { count: 0, total: 0, max: 0 }, frames: { p99: 16, max: 20 }, traffic: {}, })); + const starts = o.pageStarts ?? page, railStarts = o.railStarts ?? rail; return { measurements: [ - window('page', page, o.elapsed ?? 16000, o.pagePlans ?? page * (o.pagesPerRefresh ?? 10), o.pageStarts ?? page, page * (o.firstWindow ?? 1), - o.completePlans ?? Math.max(0, (o.pageStarts ?? page) - 1) * (o.pagesPerRefresh ?? 10)), - window('panel', rail, o.railElapsed ?? 16000, o.railPlans ?? rail, o.railStarts ?? rail, rail, Math.max(0, (o.railStarts ?? rail) - 1)), + window('page', o.elapsed ?? 16000, o.pagePlans ?? page * (o.pagesPerRefresh ?? 10), starts, o.bundled ?? starts * (o.firstWindow ?? 1), o.standalone ?? starts, + o.completePlans ?? Math.max(0, starts - 1) * (o.pagesPerRefresh ?? 10), o.health ?? page, o.runReads ?? starts), + window('panel', o.railElapsed ?? 16000, o.railPlans ?? rail, railStarts, 0, railStarts, Math.max(0, railStarts - 1), rail, railStarts), ...others('page'), ...others('panel'), ], scrollbar: ['paused', 'inside', 'outside'].map(mode => ({ mode, distance: 100, same: true, reportArrived: true })), @@ -48,8 +65,10 @@ function results(o: Opt = {}) { responsive: Array.from({ length: 5 }, () => ({ width: 1000, overflow: false, zeroBadges: false, filters: { open: true, overflow: false } })), }; } +interface Row { name: string; status: 'pass' | 'fail' | 'unverified' | 'informational'; before: number | null; after: number | null; note?: string } +interface Report { status: number | null; failed: string[]; unverified: string[]; info: string[]; rows: Row[]; summary: { passed: boolean; failed: string[]; unverified: string[] } | null; error: string } /** Run the gate on a baseline and three candidate runs (one option set repeats for all three). */ -function gate(after: Opt | [Opt, Opt, Opt], before: Opt = {}): { status: number | null; failed: string[]; info: string[]; error: string } { +function gate(after: Opt | [Opt, Opt, Opt], before: Opt = {}): Report { const scratch = mkdtempSync(join(tmpdir(), 'large-library-gate-')); try { const runs = Array.isArray(after) ? after : [after, after, after]; @@ -58,18 +77,38 @@ function gate(after: Opt | [Opt, Opt, Opt], before: Opt = {}): { status: number }); const run = spawnSync(process.execPath, ['--experimental-strip-types', 'tests/browser/large-library-gate.ts', ...dirs], { encoding: 'utf8' }); const report = run.stdout ? JSON.parse(run.stdout) : null; - const rows: { name: string; pass: boolean; budget: string }[] = report?.rows ?? []; - return { status: run.status, failed: rows.filter(r => !r.pass).map(r => r.name), info: rows.filter(r => r.budget === 'informational').map(r => r.name), error: run.stderr }; + const rows: Row[] = report?.rows ?? []; + const named = (status: Row['status']) => rows.filter(r => r.status === status).map(r => r.name); + return { status: run.status, failed: named('fail'), unverified: named('unverified'), info: named('informational'), rows, summary: report ? { passed: report.passed, failed: report.failed, unverified: report.unverified } : null, error: run.stderr }; } finally { rmSync(scratch, { recursive: true, force: true }); } } -const cadence = (failed: string[]) => failed.filter(n => n.startsWith('Idle cadence')); +const cadence = (names: string[]) => names.filter(n => n.startsWith('Idle cadence')); +const PLANS = 'Idle /v1/plans requests/refresh', NEEDS_YOU = 'Idle /v1/needs-you requests/refresh'; +const COMBINED = 'Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)'; +const LIST_CARRIED = 'Idle list-carried inbox windows per list start (/v1/plans?needsYou=1)'; +const RUN_READS = 'Idle run reads per window (not compared)'; +const perRefresh = [PLANS, NEEDS_YOU, COMBINED]; -test('unchanged idle polling passes, with or without the inbox form and list-start counters', () => { +test('unchanged idle polling passes in the current format and exits zero', () => { const run = gate({}); assert.equal(run.status, 0, run.error); assert.deepEqual(run.failed, []); - const legacy = gate({ split: false }, { split: false }); - assert.equal(legacy.status, 0, legacy.error); + assert.deepEqual(run.unverified, []); + assert.equal(run.summary?.passed, true); +}); + +test('a baseline or candidates without the inbox split leave the combined budget unverified and the exit non-zero', () => { + const noSplit = gate({ format: 'oldest' }, { format: 'oldest' }); + assert.equal(noSplit.status, 2, noSplit.error); + assert.deepEqual(noSplit.failed, []); + assert.deepEqual(noSplit.unverified.filter(n => n === COMBINED), [COMBINED]); + assert.equal(noSplit.summary?.passed, false); + assert.deepEqual(noSplit.summary?.unverified.filter(n => n === COMBINED), [COMBINED]); + const baseline = gate({}, { format: 'oldest' }); + assert.equal(baseline.status, 2, baseline.error); + assert.ok(baseline.unverified.includes(COMBINED)); + // The comparisons that can still be made still run. + assert.ok(baseline.rows.some(r => r.name === 'Page idle long-task total (ms)' && r.status === 'pass')); }); test('uniformly doubled idle polling fails even though every route keeps its ratio to /health', () => { @@ -89,9 +128,9 @@ test('a healthy sixth boundary poll is not extra work per refresh', () => { assert.equal(run.status, 0, `${run.error}${run.failed.join('\n')}`); }); -test('extra work per refresh still fails: more continuation pages, more inbox first windows', () => { - assert.ok(gate({ pagesPerRefresh: 11 }).failed.includes('Idle /v1/plans requests/refresh')); - assert.deepEqual(gate({ firstWindow: 3 }).failed, ['Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)']); +test('extra work per refresh still fails: more continuation pages, more inbox windows', () => { + assert.ok(gate({ pagesPerRefresh: 11 }).failed.includes(PLANS)); + assert.deepEqual(gate({ firstWindow: 3 }).failed, [COMBINED, LIST_CARRIED]); }); test('each window is judged by its own elapsed time', () => { @@ -118,10 +157,17 @@ test('list starts, not total list pages, set the list cadence on both surfaces', assert.equal(cadence(rail.failed).length, 3); }); -test('one legacy candidate does not discard the inbox form split of the others', () => { - const run = gate([{ firstWindow: 3 }, { firstWindow: 3 }, { split: false }]); - assert.equal(run.status, 1); - assert.deepEqual(run.failed.filter(n => n.startsWith('Idle inbox')), ['Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)']); +test('a candidate without the split does not discard the split of the other two, but one carrying candidate is too few', () => { + const two = gate([{ firstWindow: 3 }, { firstWindow: 3 }, { format: 'oldest' }]); + assert.equal(two.status, 1); + assert.deepEqual(two.failed, [COMBINED, LIST_CARRIED]); + // An older candidate, a current one and one without a split: only one candidate rests on complete refreshes. + const mixed = gate([{ format: 'older' }, {}, { format: 'oldest' }]); + assert.equal(mixed.status, 2, `${mixed.error}${mixed.failed.join('\n')}`); + assert.deepEqual(mixed.failed, []); + assert.deepEqual(mixed.unverified.sort(), [...perRefresh].sort()); + // The list-carried form is still compared: the older candidate and the current one both carry it. + assert.ok(mixed.rows.some(r => r.name === LIST_CARRIED && r.status === 'pass')); }); test('a refresh split by the window edge counts on neither side of the traffic ratio', () => { @@ -131,34 +177,102 @@ test('a refresh split by the window edge counts on neither side of the traffic r // 50 pages over 5 starts looks healthy by wall clock, yet the complete refreshes carried 11 pages each. const hidden = gate({ completePlans: 44 }); assert.equal(hidden.status, 1); - assert.deepEqual(hidden.failed, ['Idle /v1/plans requests/refresh']); + assert.deepEqual(hidden.failed, [PLANS]); }); -test('a legacy baseline still compares, and the report says its denominator fell back to /health', () => { - const run = gate({}, { split: false }); - assert.equal(run.status, 0, run.error); - assert.ok(run.info.includes('Baseline traffic per refresh uses its /health count (complete-refresh attribution not recorded)'), run.info.join('\n')); - assert.ok(run.info.every(n => !/^Candidate traffic/.test(n))); - const doubled = gate({ page: 10, rail: 10 }, { split: false }); - assert.equal(doubled.status, 1); - // A candidate without the attribution is reported too. - const legacy = gate([{}, {}, { split: false }]); - assert.ok(legacy.info.some(n => /^Candidate traffic per refresh without complete-refresh attribution: run 3 \(\/health count/.test(n)), legacy.info.join('\n')); -}); - -test('a baseline with no complete refresh is insufficient evidence: it falls back to the wall-clock form instead of a zero budget', () => { - // One list start and a ten-page read: nothing closed it, so complete-refresh traffic is 0 over 0 refreshes. - const run = gate({}, { page: 1, pageStarts: 1, pagePlans: 10 }); - assert.equal(run.status, 0, `${run.error}${run.failed.join('\n')}`); - assert.ok(run.info.includes('Baseline traffic per refresh uses its wall-clock list starts (no complete refresh recorded)'), run.info.join('\n')); +test('an artifact whose driver bucketed replies is named and not used as an equivalent complete sample', () => { + const baseline = gate({}, { format: 'unlabelled' }); + assert.equal(baseline.status, 2, `${baseline.error}${baseline.failed.join('\n')}`); + assert.deepEqual(baseline.unverified.sort(), [...perRefresh].sort()); + assert.ok(baseline.rows.some(r => /baseline/.test(r.name + (r.note ?? '')) && /attribution method not recorded/.test(r.name + (r.note ?? ''))), JSON.stringify(baseline.rows.filter(r => r.status !== 'pass'))); + const candidate = gate([{}, {}, { format: 'unlabelled' }]); + assert.ok(candidate.rows.some(r => /run 3/.test(r.name + (r.note ?? '')) && /attribution method not recorded/.test(r.name + (r.note ?? ''))), JSON.stringify(candidate.rows.filter(r => r.status !== 'pass'))); +}); + +test('one candidate that cannot be compared is named and left out; two such candidates leave the budget unverified', () => { + const one = gate([{}, {}, { format: 'unlabelled' }]); + assert.equal(one.status, 0, `${one.error}${one.failed.join('\n')}`); + assert.deepEqual(one.unverified, []); + const plans = one.rows.find(r => r.name === PLANS); + assert.equal(plans?.status, 'pass'); + assert.match(plans?.note ?? '', /run 3: attribution method not recorded/); + // Two comparable candidates give the larger of the two as their median, so an over-budget one cannot hide behind the other. + const over = gate([{ pagesPerRefresh: 11 }, {}, { format: 'unlabelled' }]); + assert.equal(over.status, 1, `${over.error}`); + assert.deepEqual(over.failed, [PLANS]); + const two = gate([{}, { format: 'unlabelled' }, { format: 'unlabelled' }]); + assert.equal(two.status, 2, `${two.error}${two.failed.join('\n')}`); + assert.deepEqual(two.unverified.sort(), [...perRefresh].sort()); +}); + +test('a baseline with one list start is unverified for the per-refresh budgets, not compared by its wall-clock count', () => { + // Nineteen pages over one list start: a candidate at eleven pages per refresh must not pass a ten-page contract against it. + const run = gate([{}, {}, { pagesPerRefresh: 11 }], { page: 1, pageStarts: 1, pagePlans: 19 }); + assert.equal(run.status, 2, `${run.error}${run.failed.join('\n')}`); + assert.deepEqual(run.failed, []); + assert.ok(run.unverified.includes(PLANS), run.unverified.join('\n')); + assert.ok(run.rows.find(r => r.name === PLANS)?.note?.includes('baseline'), 'the row names the baseline'); + assert.ok(!run.rows.some(r => r.name === PLANS && r.status === 'pass')); + // The summary names each unverified budget. + assert.deepEqual(run.summary?.unverified.sort(), [...perRefresh].sort()); +}); + +test('a single list start still has its split compared: an added list-carried inbox window fails', () => { + const run = gate({}, { page: 1, pageStarts: 1, pagePlans: 10, firstWindow: 0, standalone: 1 }); + assert.equal(run.status, 1, `${run.error}`); + assert.deepEqual(run.failed, [LIST_CARRIED]); + assert.deepEqual(run.unverified.sort(), [...perRefresh].sort()); +}); + +test('the list-carried form is compared on its own, so a standalone request at a window edge cannot pay for it', () => { + // The older baseline counts six standalone requests over five list starts and no list-carried windows. The candidate sends five + // standalone requests and one list-carried window, opened by the refresh still open at the window's end: the combined figure over + // complete refreshes is lower than the baseline's, yet one list start in five now carries an inbox window. + const run = gate({ standalone: 5, bundled: 1, completeInbox: { needsYouRoute: 4, plansFirstWindow: 0 } }, { format: 'older', pageStarts: 5, standalone: 6, firstWindow: 0 }); + assert.deepEqual(run.failed, [LIST_CARRIED]); + assert.equal(run.status, 1); + assert.ok(run.unverified.includes(COMBINED)); }); -test('an older artifact\'s recorded wall-clock inbox form still sets the baseline for the split', () => { - const same = gate({}, { legacyDriver: true }); - assert.equal(same.status, 0, `${same.error}${same.failed.join('\n')}`); - assert.ok(same.info.includes('Baseline inbox form uses wall-clock counts (older artifact)'), same.info.join('\n')); - // The baseline made no needsYou=1 list reads; candidates that opt in on every poll double the inbox work per refresh. - const more = gate({}, { legacyDriver: true, firstWindow: 0 }); +test('the list-carried form is divided by list starts, never by health replies', () => { + // One list start, two health replies, ten plan replies: the baseline sent one list-carried window per list start. + const run = gate({}, { page: 2, health: 2, pageStarts: 1, pagePlans: 10, firstWindow: 1 }); + assert.equal(run.rows.find(r => r.name === LIST_CARRIED)?.status, 'pass', JSON.stringify(run.rows.find(r => r.name === LIST_CARRIED))); + assert.equal(run.rows.find(r => r.name === LIST_CARRIED)?.before, 1); + // Complete refreshes are divided by refreshes, not health replies: eight health replies in the baseline window, 40 pages over four refreshes. + const complete = gate({}, { health: 8 }); + assert.equal(complete.status, 0, `${complete.error}${complete.failed.join('\n')}`); + assert.equal(complete.rows.find(r => r.name === PLANS)?.before, 10); +}); + +test('an older artifact\'s recorded wall-clock inbox form still sets the list-carried baseline', () => { + const same = gate({}, { format: 'older' }); + assert.equal(same.status, 2, `${same.error}${same.failed.join('\n')}`); + assert.deepEqual(same.failed, []); + assert.ok(same.rows.some(r => r.name === LIST_CARRIED && r.status === 'pass')); + // The baseline made no list-carried reads; candidates that opt in on every poll add inbox work. + const more = gate({}, { format: 'older', firstWindow: 0 }); assert.equal(more.status, 1); - assert.deepEqual(more.failed, ['Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)']); + assert.deepEqual(more.failed, [LIST_CARRIED]); +}); + +test('run reads are an informational row: counts and list starts for the baseline and each run, and the exit is unchanged', () => { + for (const [baseline, candidate] of [[5, 5], [0, 40], [40, 0]] as const) { + const run = gate({ runReads: candidate }, { runReads: baseline }); + assert.equal(run.status, 0, `${run.error}${run.failed.join('\n')}`); + assert.deepEqual(run.failed, []); + assert.deepEqual(run.unverified, []); + const summary = run.rows.find(r => r.name.startsWith(RUN_READS)); + assert.equal(summary?.status, 'informational'); + assert.ok(!run.rows.some(r => r.name.includes('/v1/subagent-runs') && r.status !== 'informational'), 'run reads are not a per-refresh budget'); + const text = `${summary?.name} ${summary?.note ?? ''}`; + assert.match(text, new RegExp(`baseline page ${baseline} over 5 list starts`)); + for (const n of [1, 2, 3]) assert.match(text, new RegExp(`run ${n} page ${candidate} over 5 list starts`)); + } +}); + +test('run reads of an older artifact are shown as not recorded', () => { + const run = gate({}, { format: 'older' }); + const summary = run.rows.find(r => r.name.startsWith(RUN_READS)); + assert.match(`${summary?.name} ${summary?.note ?? ''}`, /baseline page not recorded over 5 list starts/); }); diff --git a/tests/browser/large-library-gate.ts b/tests/browser/large-library-gate.ts index 365a298..fb059f8 100644 --- a/tests/browser/large-library-gate.ts +++ b/tests/browser/large-library-gate.ts @@ -1,7 +1,9 @@ // Usage: node --experimental-strip-types tests/browser/large-library-gate.ts // Each argument is an artifact directory containing large-library-qa.ts results.json. +// Exit status: 0 when every budget passed, 1 when a budget failed or the gate aborted (an uncaught error also exits 1), 2 when none failed but a budget could not be compared. import { readFileSync } from 'node:fs'; import path from 'node:path'; +import { ATTRIBUTION_METHOD, HEALTH_ROUTE, INBOX_ROUTE, type CompleteRefreshes } from './refresh-attribution.ts'; const dirs = process.argv.slice(2); if (dirs.length !== 4) throw Error('Usage: '); const [before, ...after] = dirs.map(dir => JSON.parse(readFileSync(path.join(dir, 'results.json'), 'utf8'))); @@ -12,10 +14,13 @@ const measurement = (r: any, surface: string, label: string) => { }; if (measurement(before, 'page', 'idle').longTasks.total < 4000 || measurement(before, 'panel', 'idle').longTasks.count !== 0) throw Error('Baseline does not reproduce the reported page stall with a smooth rail'); const median = (values: number[]) => values.slice().sort((a,b) => a-b)[Math.floor(values.length / 2)]; -const rows: { name: string; before: number; after: number; budget: string; pass: boolean }[] = []; +// A row is a passed or failed budget, a budget that could not be compared (unverified), or information that never changes the exit. +type Row = { name: string; before: number | null; after: number | null; budget: string; status: 'pass' | 'fail' | 'unverified' | 'informational'; note?: string }; +const rows: Row[] = []; +const info = (name: string) => rows.push({ name, before: null, after: null, budget: 'informational', status: 'informational' }); function check(name: string, read: (r: any) => number, limit: number, minimum = false) { const value = median(after.map(read)); - rows.push({ name, before: read(before), after: value, budget: `${minimum ? '>=' : '<='} ${limit}`, pass: minimum ? value >= limit : value <= limit }); + rows.push({ name, before: read(before), after: value, budget: `${minimum ? '>=' : '<='} ${limit}`, status: (minimum ? value >= limit : value <= limit) ? 'pass' : 'fail' }); } for (const [label, field, limit] of [ ['idle', 'total', 1000], ['idle', 'max', 250], ['drag', 'total', 1000], ['key-zoom', 'max', 250], @@ -29,7 +34,7 @@ for (const mode of ['inside', 'outside']) { if (!(control?.distance > 0) || !live) throw Error('Missing scrollbar control'); return 100 * live.distance / control.distance; }, 90, true); - if (after.some(r => !r.scrollbar.find((v: any) => v.mode === mode)?.same)) rows.push({ name: `Scrollbar ${mode} element continuity`, before: 0, after: 0, budget: 'same connected element in all runs', pass: false }); + if (after.some(r => !r.scrollbar.find((v: any) => v.mode === mode)?.same)) rows.push({ name: `Scrollbar ${mode} element continuity`, before: 0, after: 0, budget: 'same connected element in all runs', status: 'fail' }); if (after.some(r => !r.scrollbar.find((v: any) => v.mode === mode)?.reportArrived)) throw Error(`Reported change did not arrive during ${mode} scrollbar drag`); } for (const label of ['idle', 'selection', 'drag', 'wheel-pan', 'key-zoom']) { @@ -38,66 +43,92 @@ for (const label of ['idle', 'selection', 'drag', 'wheel-pan', 'key-zoom']) { } // Idle polling. A refresh starts with a first-page list read; /health is read once per refresh. Each window's own elapsed // time (at the product cadence, ui/shared/app.ts REFRESH_MS) sets the allowed count, +/- one boundary tick, and both -// surfaces must pass within the same run, so one healthy surface cannot cover for a stalled or doubled one. Traffic is then -// compared per complete refresh: the driver attributes every reply to the refresh whose first page started it and counts only -// refreshes that a later first page closed inside the window, so a refresh split by the window edge counts on neither side -// of the ratio. Artifacts from before the driver recorded that fall back to wall-clock counts divided by list starts, or by -// /health when list starts are missing too; every fallback is named in a row, for the baseline and for each candidate. +// surfaces must pass within the same run, so one healthy surface cannot cover for a stalled or doubled one. Every count comes +// from the request log inside the window's offsets (the artifact's `sent`, `listStarts`, `runReads` and `inbox` figures), by +// when a request was sent. +// +// Per-refresh budgets compare complete refreshes: the driver attributes every request to the refresh whose first page started +// it and counts only refreshes that a later first page closed inside the window, so a refresh split by the window edge counts on +// neither side of the ratio. An artifact is comparable that way only when it names the attribution method and completed at least +// one refresh. A budget whose baseline or candidates rest on anything else (a single list start, wall-clock counts, an older +// driver that bucketed replies) is unverified, not passed. The form of the inbox read carried by the list read is compared on its +// own, per list start, which is comparable in any window. Run reads are shown per window and judged by no one. const REFRESH_MS = 3000; const idle = (r: any, surface: string) => measurement(r, surface, 'idle'); -const requests = (r: any, surface: string, route: string) => idle(r, surface).traffic[`${surface} ${route}`]?.count ?? 0; +// Older artifacts recorded reply counts only; a current one records what was sent. The row names any run that falls back. +const sentCount = (r: any, surface: string, route: string): number => { + const window = idle(r, surface), key = `${surface} ${route}`; + return window.sent ? window.sent[key] ?? 0 : window.traffic[key]?.count ?? 0; +}; const listStarts = (r: any, surface: string): number | undefined => idle(r, surface).listStarts?.[surface]; -type Form = { needsYouRoute: number; plansFirstWindow: number }; -const recorded = (r: any) => idle(r, 'page').complete?.page as { refreshes: number; traffic: Record; inbox: Form } | undefined; +const recorded = (r: any) => idle(r, 'page').complete?.page as CompleteRefreshes | undefined; +const labelled = (r: any) => idle(r, 'page').attribution === ATTRIBUTION_METHOD; // Zero complete refreshes (a window with a single list start, or a stalled baseline) is insufficient evidence, not a zero budget. -const settled = (r: any) => (recorded(r)?.refreshes ?? 0) >= 1 ? recorded(r) : undefined; -const denominator = (r: any) => settled(r) ? 'complete refreshes' - : `${listStarts(r, 'page') !== undefined ? 'wall-clock list starts' : '/health count'}${recorded(r) ? ' (no complete refresh recorded)' : ' (complete-refresh attribution not recorded)'}`; +const settled = (r: any): CompleteRefreshes | undefined => labelled(r) && (recorded(r)?.refreshes ?? 0) >= 1 && recorded(r)?.inbox ? recorded(r) : undefined; +const why = (r: any) => { + if (!labelled(r)) return 'attribution method not recorded (an older driver, which may have bucketed replies)'; + if ((recorded(r)?.refreshes ?? 0) < 1) return `no complete refresh inside its idle window (${listStarts(r, 'page') ?? 0} list start${listStarts(r, 'page') === 1 ? '' : 's'})`; + return 'no inbox split recorded for its complete refreshes'; +}; +const names = ['baseline', ...after.map((_, n) => `run ${n + 1}`)]; +const all = [before, ...after]; +{ + const noLog = after.map((r, n) => idle(r, 'page').sent && idle(r, 'panel').sent ? null : `run ${n + 1}`).filter(Boolean); + if (noLog.length) info(`Idle counts for ${noLog.join(', ')} come from replies: the artifact predates the request-log counts`); +} const startsFallback: string[] = []; after.forEach((r, n) => { const violations: string[] = []; for (const surface of ['page', 'panel']) { const window = idle(r, surface).elapsed / REFRESH_MS, min = Math.floor(window) - 1, max = Math.ceil(window); const within = (what: string, count: number, upper = true) => { if (count < min || (upper && count > max)) violations.push(`${surface} ${what} ${count} outside ${min}-${max}`); }; - within('/health', requests(r, surface, '/health')); + within(HEALTH_ROUTE, sentCount(r, surface, HEALTH_ROUTE)); const starts = listStarts(r, surface); - if (starts === undefined) { startsFallback.push(`run ${n + 1} ${surface}`); within('/v1/plans reads', requests(r, surface, '/v1/plans'), false); } + if (starts === undefined) { startsFallback.push(`run ${n + 1} ${surface}`); within('/v1/plans reads', sentCount(r, surface, '/v1/plans'), false); } else within('list starts', starts); } - rows.push({ name: `Idle cadence, run ${n + 1}: page and rail /health and list starts${violations.length ? ` (${violations.join('; ')})` : ''}`, before: 0, after: violations.length, budget: '== 0', pass: violations.length === 0 }); + rows.push({ name: `Idle cadence, run ${n + 1}: page and rail /health and list starts${violations.length ? ` (${violations.join('; ')})` : ''}`, before: 0, after: violations.length, budget: '== 0', status: violations.length === 0 ? 'pass' : 'fail' }); }); -if (startsFallback.length) rows.push({ name: `Idle list starts not recorded (${startsFallback.join(', ')}): counted /v1/plans reads against the lower bound only`, before: 0, after: 0, budget: 'informational', pass: true }); -if (!settled(before)) rows.push({ name: `Baseline traffic per refresh uses its ${denominator(before)}`, before: 0, after: 0, budget: 'informational', pass: true }); -{ - const fallback = after.map((r, n) => settled(r) ? null : `run ${n + 1} (${denominator(r)})`).filter(Boolean); - if (fallback.length) rows.push({ name: `Candidate traffic per refresh without complete-refresh attribution: ${fallback.join(', ')}`, before: 0, after: 0, budget: 'informational', pass: true }); -} -const perRefresh = (route: (r: any) => number, complete: (r: any) => number) => (r: any) => { - const done = settled(r); - return done ? complete(r) / Math.max(1, done.refreshes) : route(r) / Math.max(1, listStarts(r, 'page') ?? requests(r, 'page', '/health')); -}; -for (const route of ['/v1/plans', '/v1/needs-you', '/v1/subagent-runs']) { - const read = perRefresh(r => requests(r, 'page', route), r => settled(r)!.traffic[route] ?? 0); - check(`Idle ${route} requests/refresh`, read, read(before)); +if (startsFallback.length) info(`Idle list starts not recorded (${startsFallback.join(', ')}): counted /v1/plans reads against the lower bound only`); +/** + * Compare a figure the baseline and at least two candidates carry on the same denominator; otherwise report it unverified and + * say which artifacts are missing. `read` returns undefined when an artifact does not carry the figure. + */ +function budget(name: string, read: (r: any) => number | undefined, missing: (r: any) => string) { + const base = read(before); + const carrying = after.filter(r => read(r) !== undefined); + if (base === undefined || carrying.length < 2) { + const reasons = all.filter(r => read(r) === undefined).map(r => `${names[all.indexOf(r)]}: ${missing(r)}`); + rows.push({ name, before: null, after: null, budget: 'comparable figures from the baseline and two candidates', status: 'unverified', note: reasons.join('; ') }); + return; + } + const value = median(carrying.map(r => read(r)!)); + rows.push({ name, before: base, after: value, budget: `<= ${base}`, status: value <= base ? 'pass' : 'fail', + ...carrying.length < after.length ? { note: `compared over ${carrying.map(r => names[all.indexOf(r)]).join(', ')}; ${after.filter(r => read(r) === undefined).map(r => `${names[all.indexOf(r)]}: ${missing(r)}`).join('; ')}` } : {} }); } +// Which artifacts do not rest on complete refreshes, and why, once, for the reader. +for (const r of all) if (!settled(r)) info(`${names[all.indexOf(r)]} figures per refresh are not comparable: ${why(r)}`); +const perRefresh = (figure: (done: CompleteRefreshes) => number) => (r: any) => { const done = settled(r); return done ? figure(done) / done.refreshes : undefined; }; +budget('Idle /v1/plans requests/refresh', perRefresh(done => done.traffic['/v1/plans'] ?? 0), why); +budget('Idle /v1/needs-you requests/refresh', perRefresh(done => done.traffic[INBOX_ROUTE] ?? 0), why); +// Both inbox forms together, per complete refresh: the standalone route and the first window carried by /v1/plans?needsYou=1. +budget('Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)', perRefresh(done => done.inbox.needsYouRoute + done.inbox.plansFirstWindow), why); +// The form carried by the list read, per list start: a list start either carried it or did not, so the figure has no error at +// the window edge and any artifact with list starts and the wall-clock split can be compared, in any window. +budget('Idle list-carried inbox windows per list start (/v1/plans?needsYou=1)', r => { + const form = idle(r, 'page').inbox?.page, starts = listStarts(r, 'page'); + return form && starts ? form.plansFirstWindow / starts : undefined; +}, r => [ + ...idle(r, 'page').inbox?.page ? [] : ['no inbox split recorded'], + ...listStarts(r, 'page') === undefined ? ['no list starts recorded'] : listStarts(r, 'page') === 0 ? ['no list start in its idle window'] : [], +].join(' and ')); { - // Compare both inbox forms when the baseline and at least two candidates carry them; otherwise compare the - // /v1/needs-you route alone and say so. Complete-refresh counts are preferred; an older artifact's recorded wall-clock - // form (idle.inbox.page) is used, over its own wall-clock denominator, when it has no complete-refresh counts. - const form = (r: any): Form | undefined => settled(r)?.inbox ?? idle(r, 'page').inbox?.page; - const comparable = after.filter(form); - const both = !!form(before) && comparable.length >= 2; - if (form(before) && !settled(before)) rows.push({ name: 'Baseline inbox form uses wall-clock counts (older artifact)', before: 0, after: 0, budget: 'informational', pass: true }); - const read = (r: any) => { - const f = both ? form(r) : undefined, done = settled(r); - const count = f ? f.needsYouRoute + f.plansFirstWindow : done ? done.traffic['/v1/needs-you'] ?? 0 : requests(r, 'page', '/v1/needs-you'); - return count / Math.max(1, done?.refreshes ?? listStarts(r, 'page') ?? requests(r, 'page', '/health')); - }; - const value = median((both ? comparable : after).map(read)); + // Run reads cannot be tied to the refresh that caused them (the request log holds no cause), so each window's count is shown + // beside its list starts and judged by no one. This row never changes the exit. + const figure = (r: any, surface: string) => `${idle(r, surface).runReads?.[surface] ?? 'not recorded'} over ${listStarts(r, surface) ?? 'not recorded'} list starts`; rows.push({ - name: both ? 'Idle inbox requests/refresh (/v1/needs-you + /v1/plans?needsYou=1)' - : `Idle inbox requests/refresh (/v1/needs-you only: ${form(before) ? 'fewer than two candidates carry' : 'baseline lacks'} the form split)`, - before: read(before), after: value, budget: `<= ${read(before)}`, pass: value <= read(before), + name: 'Idle run reads per window (not compared)', before: null, after: null, budget: 'informational', status: 'informational', + note: all.map(r => `${names[all.indexOf(r)]} page ${figure(r, 'page')}, rail ${figure(r, 'panel')}`).join('; '), }); } for (const r of after) if (r.errors?.length) throw Error('Browser errors reported'); @@ -106,5 +137,8 @@ for (const r of after) { if (!r.keyboard?.focusedListbox || !r.keyboard?.activeOption) throw Error('Keyboard listbox state did not survive refresh'); if (r.responsive?.length !== 5 || r.responsive.some((v: any) => v.overflow || v.zeroBadges || !v.filters?.open || v.filters.overflow || (v.width < 820 && !v.planPicker))) throw Error('Responsive board/count observations failed'); } -console.log(JSON.stringify({ passed: rows.every(r => r.pass), rows }, null, 2)); -if (rows.some(r => !r.pass)) process.exitCode = 1; +const failed = rows.filter(r => r.status === 'fail').map(r => r.name), unverified = rows.filter(r => r.status === 'unverified').map(r => r.name); +console.log(JSON.stringify({ passed: !failed.length && !unverified.length, failed, unverified, rows }, null, 2)); +if (unverified.length) console.error(`Not compared (unverified), so neither passed nor failed: ${unverified.join('; ')}`); +if (failed.length) console.error(`Failed: ${failed.join('; ')}`); +process.exitCode = failed.length ? 1 : unverified.length ? 2 : 0; diff --git a/tests/browser/large-library-qa.ts b/tests/browser/large-library-qa.ts index 9765550..e140f4a 100644 --- a/tests/browser/large-library-qa.ts +++ b/tests/browser/large-library-qa.ts @@ -7,7 +7,7 @@ import { execFileSync } from 'node:child_process'; import { startSearchShell } from './plan-task-search-shell.ts'; import { launchChromium } from './phone-cdp.ts'; import { boardInput } from './board-qa.ts'; -import { attributeRefreshes } from './refresh-attribution.ts'; +import { summarizeWindow } from './refresh-attribution.ts'; import { searchStatusText } from '../../ui/shared/search.ts'; import type { ItemInput } from '../../shared/progress.ts'; @@ -81,18 +81,16 @@ const select = async (s: string, title: string, id: string) => { const result: any = { shape: { bulkPlans: 500, tasksPerBulk: '30–80', histories: 12, selectedTasks: 60, selectedHistory: 80, runs: 600, projects: 6, sources: 2 }, measurements: [] }; const save = () => fs.writeFileSync(path.join(out, 'results.json'), JSON.stringify(result, null, 2)); async function window(s: string, label: string, run: () => Promise) { - await guest(s, `w.__p={frames:[],long:[],rootReplacements:0,mapReplacements:0,start:performance.now(),last:performance.now()};let root=d.querySelector('[data-testid="progress-root"]'),map=d.querySelector('[data-testid="map-region"]');const po=new w.PerformanceObserver(l=>{for(const e of l.getEntries())w.__p.long.push(e.duration)});po.observe({type:'longtask',buffered:false});const mo=new w.MutationObserver(()=>{const r=d.querySelector('[data-testid="progress-root"]'),m=d.querySelector('[data-testid="map-region"]');if(r!==root){w.__p.rootReplacements++;root=r}if(m!==map){w.__p.mapReplacements++;map=m}});mo.observe(d.body,{childList:true,subtree:true});const tick=t=>{w.__p.frames.push(t-w.__p.last);w.__p.last=t;w.__raf=w.requestAnimationFrame(tick)};w.__raf=w.requestAnimationFrame(tick);w.__stop=()=>{w.cancelAnimationFrame(w.__raf);po.disconnect();mo.disconnect();return {...w.__p,elapsed:performance.now()-w.__p.start,dom:d.querySelectorAll('*').length}};return true`); - const mark = await evaluate('qa.replies.length'), requestMark = await evaluate('qa.requests.length'); + // The log offsets are read in the evaluation that starts the timer and in the one that stops it, so whatever is logged + // after the window ends and before the driver reads the logs is not part of the window (see refresh-attribution.ts). + const start = await guest(s, `const offsets={requests:qa.requests.length,replies:qa.replies.length};w.__p={frames:[],long:[],rootReplacements:0,mapReplacements:0,start:performance.now(),last:performance.now()};let root=d.querySelector('[data-testid="progress-root"]'),map=d.querySelector('[data-testid="map-region"]');const po=new w.PerformanceObserver(l=>{for(const e of l.getEntries())w.__p.long.push(e.duration)});po.observe({type:'longtask',buffered:false});const mo=new w.MutationObserver(()=>{const r=d.querySelector('[data-testid="progress-root"]'),m=d.querySelector('[data-testid="map-region"]');if(r!==root){w.__p.rootReplacements++;root=r}if(m!==map){w.__p.mapReplacements++;map=m}});mo.observe(d.body,{childList:true,subtree:true});const tick=t=>{w.__p.frames.push(t-w.__p.last);w.__p.last=t;w.__raf=w.requestAnimationFrame(tick)};w.__raf=w.requestAnimationFrame(tick);w.__stop=()=>{w.cancelAnimationFrame(w.__raf);po.disconnect();mo.disconnect();return {...w.__p,elapsed:performance.now()-w.__p.start,dom:d.querySelectorAll('*').length}};return offsets`); await run(); - const p = await guest(s, 'return w.__stop()'); + const p = await guest(s, 'const offsets={requests:qa.requests.length,replies:qa.replies.length};return {...w.__stop(),offsets}'); const frames = p.frames.sort((a: number, b: number) => a - b); - const traffic: Record = {}; - for (const r of await evaluate(`qa.replies.slice(${mark})`)) { - const row = traffic[r.frame + ' ' + r.path] ??= { count: 0, bytes: 0 }; row.count++; row.bytes += r.bytes; - } - // Refresh attribution follows the order requests were sent (see refresh-attribution.ts), not the order replies arrived. - const { listStarts, complete } = attributeRefreshes(await evaluate(`qa.requests.slice(${requestMark})`)); - const m = { surface: s, label, elapsed: p.elapsed, dom: p.dom, rootReplacements: p.rootReplacements, mapReplacements: p.mapReplacements, longTasks: { count: p.long.length, total: p.long.reduce((a: number, b: number) => a + b, 0), max: Math.max(0, ...p.long) }, frames: { p99: frames[Math.min(frames.length - 1, Math.floor(frames.length * .99))], max: Math.max(...frames) }, traffic, listStarts, complete }; + // Every count comes from the logs between the captured offsets. Refresh attribution follows the order requests were sent, not the + // order replies arrived; the reply log keeps status, size and timing (see refresh-attribution.ts). + const summary = summarizeWindow(await evaluate("({requests:qa.requests,replies:qa.replies})"), { start, stop: p.offsets }); + const m = { surface: s, label, elapsed: p.elapsed, dom: p.dom, rootReplacements: p.rootReplacements, mapReplacements: p.mapReplacements, longTasks: { count: p.long.length, total: p.long.reduce((a: number, b: number) => a + b, 0), max: Math.max(0, ...p.long) }, frames: { p99: frames[Math.min(frames.length - 1, Math.floor(frames.length * .99))], max: Math.max(...frames) }, ...summary }; result.measurements.push(m); save(); console.log(JSON.stringify(m)); } async function searchJourney() { diff --git a/tests/browser/refresh-attribution.test.ts b/tests/browser/refresh-attribution.test.ts index acc7535..d459f0a 100644 --- a/tests/browser/refresh-attribution.test.ts +++ b/tests/browser/refresh-attribution.test.ts @@ -1,21 +1,25 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import { attributeRefreshes, type IssuedRequest } from './refresh-attribution.ts'; +import * as attribution from './refresh-attribution.ts'; +import type { IssuedRequest, LoggedReply } from './refresh-attribution.ts'; +const { attributeRefreshes } = attribution; const plans = (frame: string, cursor?: string, needsYou?: string): IssuedRequest => ({ frame, path: '/v1/plans', query: { ...(cursor ? { cursor } : {}), ...(needsYou ? { needsYou } : {}) } }); const other = (frame: string, path: string): IssuedRequest => ({ frame, path, query: null }); +const reply = (r: IssuedRequest): LoggedReply & Pick => ({ ...r, bytes: 100, status: 200, ms: 5 }); +const empty = { traffic: {}, inbox: { needsYouRoute: 0, plansFirstWindow: 0 } }; test('requests belong to the refresh that issued them; only refreshes closed by a later first page are complete', () => { const { listStarts, complete } = attributeRefreshes([ - plans('page', undefined, '1'), plans('page', 'c1'), plans('page', 'c2'), other('page', '/v1/subagent-runs'), + plans('page', undefined, '1'), plans('page', 'c1'), plans('page', 'c2'), other('page', '/v1/needs-you'), plans('page', undefined, '1'), plans('page', 'c1'), other('page', '/v1/needs-you'), plans('page', undefined, '1'), plans('page', 'c1'), // still sending when the window ends ]); assert.equal(listStarts.page, 3); assert.equal(complete.page.refreshes, 2); - assert.deepEqual(complete.page.traffic, { '/v1/plans': 5, '/v1/subagent-runs': 1, '/v1/needs-you': 1 }); - assert.deepEqual(complete.page.inbox, { needsYouRoute: 1, plansFirstWindow: 2 }); - assert.deepEqual(complete.panel, { refreshes: 0, traffic: {}, inbox: { needsYouRoute: 0, plansFirstWindow: 0 } }); + assert.deepEqual(complete.page.traffic, { '/v1/plans': 5, '/v1/needs-you': 2 }); + assert.deepEqual(complete.page.inbox, { needsYouRoute: 2, plansFirstWindow: 2 }); + assert.deepEqual(complete.panel, { refreshes: 0, ...empty }); }); test('a read still in flight when the next refresh starts stays with its issuing refresh', () => { @@ -39,3 +43,94 @@ test('frames are attributed separately and requests before the first start are i assert.equal(complete.page.traffic['/v1/needs-you'], undefined); assert.equal(complete.panel.traffic['/v1/needs-you'], 1); }); + +test('run reads are counted once per window, whichever refresh preceded them, and stay out of the per-refresh figures', () => { + const { listStarts, runReads, complete } = attributeRefreshes([ + other('page', '/v1/subagent-runs'), // sent inside the window before its first list start + plans('page'), plans('page', 'c1'), + plans('page'), // next refresh starts + other('page', '/v1/subagent-runs'), // the reconciliation follow-up, sent after that first page + plans('page', 'c1'), + plans('page'), // closes the second refresh + other('page', '/v1/subagent-runs'), // sent after the last list start, with the refresh still open + ]); + assert.equal(complete.page.refreshes, 2); + assert.deepEqual(complete.page.traffic, { '/v1/plans': 4 }); + assert.equal(listStarts.page, 3); + assert.equal(runReads.page, 3); + assert.equal(runReads.panel, 0); +}); + +test('a health read sent before its refresh\'s first page is not added to the previous refresh', () => { + const { complete } = attributeRefreshes([plans('page'), other('page', '/health'), plans('page'), other('page', '/health'), plans('page')]); + assert.equal(complete.page.refreshes, 2); + assert.deepEqual(complete.page.traffic, { '/v1/plans': 2 }); +}); + +/** The driver's window summary: both logs are sliced between the offsets captured when the timer started and stopped. */ +const window = (requests: IssuedRequest[], replies: (LoggedReply & Pick)[], start: [number, number], stop: [number, number]) => + attribution.summarizeWindow({ requests, replies }, { start: { requests: start[0], replies: start[1] }, stop: { requests: stop[0], replies: stop[1] } }); + +test('entries logged after the stop offset are ignored, and a first page logged after the stop closes no refresh', () => { + const requests = [plans('page'), plans('page', 'c1'), plans('page'), other('page', '/v1/needs-you'), plans('page'), other('page', '/health')]; + const replies = requests.map(reply); + // The timer stopped with four requests and three replies logged; two more requests and replies landed before the driver read the logs. + const summary = window(requests, replies, [0, 0], [4, 3]); + assert.equal(summary.listStarts.page, 2); + assert.equal(summary.complete.page.refreshes, 1); + assert.deepEqual(summary.complete.page.traffic, { '/v1/plans': 2 }); + assert.deepEqual(summary.sent, { 'page /v1/plans': 3, 'page /v1/needs-you': 1 }); + assert.deepEqual(summary.traffic, { 'page /v1/plans': { count: 3, bytes: 300 } }); + assert.equal(summary.attribution, 'request-order'); +}); + +test('entries logged before the start offset are not part of the window', () => { + const requests = [plans('page'), other('page', '/v1/needs-you'), plans('page'), other('page', '/health')]; + const summary = window(requests, requests.map(reply), [2, 2], [4, 4]); + assert.equal(summary.listStarts.page, 1); + assert.deepEqual(summary.sent, { 'page /v1/plans': 1, 'page /health': 1 }); + assert.deepEqual(summary.inbox.page, { needsYouRoute: 0, plansFirstWindow: 0 }); +}); + +test('a request counts by when it was sent, not when it was answered', () => { + for (const route of ['/v1/needs-you', '/health']) { + const first = plans('page'), sentBefore = other('page', route), sentInside = other('page', route); + // Sent before the window, answered inside it: out of the request counts, though its reply is in the reply log slice. + const early = window([sentBefore, first], [reply(sentBefore), reply(first)], [1, 0], [2, 2]); + assert.equal(early.sent[`page ${route}`], undefined, `${route} sent before the window`); + assert.equal(early.traffic[`page ${route}`]?.count, 1); + // Sent inside the window, answered after it: in the request counts, and its reply is outside the reply bounds. + const late = window([first, sentInside], [reply(first), reply(sentInside)], [0, 0], [2, 1]); + assert.equal(late.sent[`page ${route}`], 1, `${route} sent inside the window`); + assert.equal(late.traffic[`page ${route}`], undefined); + } +}); + +test('attribution follows the order requests were sent, not the order replies arrived', () => { + // Refresh 1 sends an inbox read; refresh 2 and refresh 3 start; the inbox reply arrives after the final first-page reply. + const p1 = plans('page'), inbox = other('page', '/v1/needs-you'), p2 = plans('page'), p3 = plans('page'); + const requests = [p1, inbox, p2, p3]; + const replies = [reply(p1), reply(p2), reply(p3), reply(inbox)]; + const summary = window(requests, replies, [0, 0], [4, 4]); + assert.equal(summary.complete.page.refreshes, 2); + assert.deepEqual(summary.complete.page.traffic, { '/v1/plans': 2, '/v1/needs-you': 1 }); + assert.deepEqual(summary.complete.page.inbox, { needsYouRoute: 1, plansFirstWindow: 0 }); +}); + +test('a standalone request after the final list start is in the window split and changes no complete-refresh figure', () => { + const base = [plans('page', undefined, '1'), plans('page', 'c1'), plans('page', undefined, '1'), plans('page', 'c1'), plans('page', undefined, '1')]; + const without = window(base, base.map(reply), [0, 0], [base.length, base.length]); + const late = [...base, other('page', '/v1/needs-you')]; + const withLate = window(late, late.map(reply), [0, 0], [late.length, late.length]); + assert.deepEqual(without.inbox.page, { needsYouRoute: 0, plansFirstWindow: 3 }); + assert.deepEqual(withLate.inbox.page, { needsYouRoute: 1, plansFirstWindow: 3 }); + assert.deepEqual(withLate.complete, without.complete); + assert.deepEqual(withLate.listStarts, without.listStarts); +}); + +test('a standalone request sent before the window and answered inside it is out of the split; one sent inside and answered after is in', () => { + const early = other('page', '/v1/needs-you'), p1 = plans('page'), late = other('page', '/v1/needs-you'); + const summary = window([early, p1, late], [reply(p1), reply(early)], [1, 0], [3, 2]); + assert.deepEqual(summary.inbox.page, { needsYouRoute: 1, plansFirstWindow: 0 }); + assert.equal(summary.sent['page /v1/needs-you'], 1); +}); diff --git a/tests/browser/refresh-attribution.ts b/tests/browser/refresh-attribution.ts index db38eca..854c9d9 100644 --- a/tests/browser/refresh-attribution.ts +++ b/tests/browser/refresh-attribution.ts @@ -1,23 +1,55 @@ -// Idle-window traffic attribution for the large-library QA driver. A refresh starts with a first-page /v1/plans request -// (no cursor); everything the same frame issues after it, until its next first page, belongs to that refresh: continuation -// pages, /v1/needs-you windows and run reads. Requests are taken in the order they were issued, never the order replies -// arrived, so an inbox or run read that is still in flight when the next refresh starts stays with the refresh that sent it. -// Only refreshes closed by a later first page inside the window are complete: the last one may still be sending. +// Idle-window traffic attribution for the large-library QA driver. +// +// The driver captures how long the request log and the reply log are in the same evaluations that start and stop a timed +// window, and `summarizeWindow` slices both logs between those offsets. Every count the gate compares (cadence, list starts, +// run reads, both inbox forms) comes from the request log, so a request counts by when it was sent: one sent before the window +// and answered inside it is out, one sent inside and answered after it is in. The reply log keeps only what a reply can show: +// status, size and timing. +// +// A refresh starts with a first-page /v1/plans request (no cursor); everything the same frame issues after it, until its next +// first page, belongs to that refresh: continuation pages and /v1/needs-you windows. Requests are taken in the order they were +// sent, never the order replies arrived, so an inbox read that is still in flight when the next refresh starts stays with the +// refresh that sent it. Only refreshes closed by a later first page inside the window are complete: the last one may still be +// sending. +// +// Two routes are kept out of the per-refresh figures. /health is read before its refresh's first page, so it cannot be tied to +// a bucket and the cadence check covers it. A run read can be the automatic follow-up of a run reconciliation, sent after the +// next refresh started; the request log cannot say which refresh caused it, so run reads are counted once per window instead. +export const ATTRIBUTION_METHOD = 'request-order'; +export const HEALTH_ROUTE = '/health'; +export const RUN_READ_ROUTE = '/v1/subagent-runs'; +export const INBOX_ROUTE = '/v1/needs-you'; export interface IssuedRequest { frame: string; path: string; query?: Record | null } -export interface CompleteRefreshes { refreshes: number; traffic: Record; inbox: { needsYouRoute: number; plansFirstWindow: number } } +export interface LoggedReply { frame: string; path: string; bytes: number; status?: number; ms?: number } +export interface InboxForms { needsYouRoute: number; plansFirstWindow: number } +export interface CompleteRefreshes { refreshes: number; traffic: Record; inbox: InboxForms } +/** How long each log was when a window started or stopped. */ +export interface LogOffsets { requests: number; replies: number } +export interface WindowBounds { start: LogOffsets; stop: LogOffsets } + +const isFirstPage = (r: IssuedRequest) => r.path === '/v1/plans' && !r.query?.cursor; export function attributeRefreshes(requests: readonly IssuedRequest[], frames: readonly string[] = ['page', 'panel']) { type Bucket = { traffic: Record; needsYouRoute: number; plansFirstWindow: number }; - const listStarts: Record = {}, buckets: Record = {}; - for (const frame of frames) { listStarts[frame] = 0; buckets[frame] = []; } + const listStarts: Record = {}, runReads: Record = {}, buckets: Record = {}; + const inbox: Record = {}; + const start = (frame: string) => { + listStarts[frame] ??= 0; runReads[frame] ??= 0; buckets[frame] ??= []; inbox[frame] ??= { needsYouRoute: 0, plansFirstWindow: 0 }; + }; + for (const frame of frames) start(frame); for (const r of requests) { - const refreshes = buckets[r.frame] ??= []; - const first = r.path === '/v1/plans' && !r.query?.cursor; - if (first) { listStarts[r.frame] = (listStarts[r.frame] ?? 0) + 1; refreshes.push({ traffic: {}, needsYouRoute: 0, plansFirstWindow: 0 }); } + start(r.frame); + const first = isFirstPage(r), refreshes = buckets[r.frame]!; + // The window's own inbox split counts every request sent inside it, whichever refresh is open. + if (r.path === INBOX_ROUTE) inbox[r.frame]!.needsYouRoute++; + else if (first && String(r.query?.needsYou) === '1') inbox[r.frame]!.plansFirstWindow++; + if (first) { listStarts[r.frame]!++; refreshes.push({ traffic: {}, needsYouRoute: 0, plansFirstWindow: 0 }); } + if (r.path === RUN_READ_ROUTE) { runReads[r.frame]!++; continue; } + if (r.path === HEALTH_ROUTE) continue; const current = refreshes.at(-1); if (!current) continue; // issued by a refresh that started before the window current.traffic[r.path] = (current.traffic[r.path] ?? 0) + 1; - if (r.path === '/v1/needs-you') current.needsYouRoute++; + if (r.path === INBOX_ROUTE) current.needsYouRoute++; else if (first && String(r.query?.needsYou) === '1') current.plansFirstWindow++; } const complete: Record = {}; @@ -29,5 +61,18 @@ export function attributeRefreshes(requests: readonly IssuedRequest[], frames: r } complete[frame] = sum; } - return { listStarts, complete }; + return { listStarts, runReads, inbox, complete }; +} + +/** Everything one timed window records, from the two logs and the offsets captured when it started and stopped. */ +export function summarizeWindow(logs: { requests: readonly IssuedRequest[]; replies: readonly LoggedReply[] }, bounds: WindowBounds, frames?: readonly string[]) { + const requests = logs.requests.slice(bounds.start.requests, bounds.stop.requests); + const replies = logs.replies.slice(bounds.start.replies, bounds.stop.replies); + const sent: Record = {}, traffic: Record = {}; + for (const r of requests) sent[`${r.frame} ${r.path}`] = (sent[`${r.frame} ${r.path}`] ?? 0) + 1; + for (const r of replies) { + const row = traffic[`${r.frame} ${r.path}`] ??= { count: 0, bytes: 0 }; + row.count++; row.bytes += r.bytes; + } + return { attribution: ATTRIBUTION_METHOD, sent, traffic, ...attributeRefreshes(requests, frames) }; } From d33735d6308874652124c88386690964b538d256 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:07:59 +1100 Subject: [PATCH 07/11] fix(companion): keep delivered context notes in place on later requests (#167) * fix(companion): keep delivered context notes in place on later requests A context note present on one request and absent from the next still edits the history: the provider writes its cache at the end of the latest message, where the note sits, and never reads that entry again. Standing notes (an assigned child's capsule, an outstanding refusal) went out on every request, so those sessions got no conversation-history cache, and extended thinking bound to the prefix was lost too. The companion now remembers each delivered note per session with its carrier (tool result: call id, position and a digest of its original output; user message: its id, else position and a digest of its content) and adds the same bytes in the same place on every later request that still holds the carrier, so each request's messages begin with the previous request's. Notes due together are one note; a capsule or refusal is delivered again only when its text changed or its carrier is gone; a refusal that stops applying gets one fixed cleared line after a complete read. The memory is bounded (128 sessions, 64 carriers and 64 KiB per session) and every path that removes the section removes the notes. Refs #161 * fix(companion): tighten context note memory after review - An incomplete empty refusal read still delivers the omission text but no longer opens the cleared line; only a real refusal does. - A note too large for its carrier leaves an armed capsule armed. - The cleared line is delivered again when a revert removes it but keeps the refusal it clears. - Notes stay on the message they were delivered on when user messages share an identifier. - A session has memory only once it holds a note, and the memory is recorded only after the notes were added to the request. - The array is restored again just before keys are computed, so overlapping requests on a reused event never hash their own copies. - Raise the per-session bound to 256 carriers and 128 KiB, so long sessions keep the cache of the start of the conversation. - Hash binary parts by their raw bytes and take the latest carrier once. --- docs/backend.md | 49 +- docs/compatibility.md | 25 +- docs/contracts.md | 91 +++- openspec/changes/release-1-5-2/design.md | 4 +- openspec/changes/release-1-5-2/tasks.md | 4 +- plugin/activation.ts | 180 +++++-- tests/backend/progress-activation.test.ts | 60 +-- .../progress-resume-activation.test.ts | 476 ++++++++++++++++-- tests/fixtures/activation-native-driver.ts | 10 +- tests/fixtures/activation-observer.ts | 2 +- tests/fixtures/activation-production.ts | 6 +- tests/fixtures/latest-message-text.ts | 7 +- tests/fixtures/subagent-activity-observer.ts | 6 +- 13 files changed, 752 insertions(+), 168 deletions(-) diff --git a/docs/backend.md b/docs/backend.md index 3abeb33..a39e8c7 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -1010,8 +1010,9 @@ Hints mention a possible delegated child, never paths, names or assignments. The same bounded recipient map coalesces plan-write, dispatch and tracker reason bits into one conditional hint. Proxy reasons target only the actor, never a child or parent; only qualifying plan writes retain the direct-parent relay. The existing -128-recipient/256-call caps, one-shot next-context consumption and synchronous -duplicate/disable/disposal checks apply to all reasons, with no extra queues, +128-recipient/256-call caps, one-shot consumption by the next context whose latest +message has a valid carrier (a request without one leaves the hint pending) and +synchronous duplicate/disable/disposal checks apply to all reasons, with no extra queues, per-tool history or progress lookup. A shared inner/outer Code Mode call identity may conservatively lose a second reason rather than create more history. @@ -1064,14 +1065,34 @@ Both system-forwarding and system-dropping providers get the checklist via the short report description; result notes do not depend on plugin system text. The owned system section is the fixed guidance only and stays byte-identical across requests, so it does not defeat a provider's prompt cache. The context hook adds -the one-request hint, the resume capsule and the refusal note after the content -of the request's latest message instead, on a copy of that message so the stored -conversation is unchanged: a text part on a user message, the output of the last -tool result on a tool message (native-proven string or content-array shapes, as for -result notes; the Code Mode wrapper result stays the script's exact value, so a hint -raised by an inner call waits for the next valid carrier), and nothing on any other -role or shape, where the hint stays pending, an armed capsule stays armed and the -refusal is read again on the next request. +the hint, the resume capsule and the refusal note after the content of a message +instead, on a copy of it so the stored conversation is unchanged: a text part on a +user message, the output of the last tool result on a tool message (native-proven +string or content-array shapes, as for result notes; the Code Mode wrapper result +stays the script's exact value, so a hint raised by an inner call waits for the next +valid carrier), and nothing on any other role or shape, where the hint stays +pending, an armed capsule stays armed and the refusal is read again on the next +request. Notes due together are one note: hint, capsule, then refusal or cleared +line, joined by a blank line. +A process-local memory (128 sessions least recently used first; per session 256 +carriers and 128 KiB of note text, carriers absent from the latest request first, +then the oldest) keeps each delivered note with its carrier (tool: call identifier, +position and a digest of the original output; user: message identifier, else +position and a digest of the original content) and adds the same bytes in the same +place on every later request that still holds the carrier, so each request begins +with the previous one and a provider's cache entry written at the end of the latest +message is read again. The comparison with the last delivery and the memory update +run in one synchronous step after the request's last wait. A capsule or refusal is +delivered again only when its text changed or its last carrier is absent (compaction, +revert, eviction, restart, fork); a timeout adds nothing. A refusal that stops +applying gets one fixed cleared line, only after a successful complete read that +finds none while the last real refusal delivered is still in the request with its +note (an incomplete empty read delivers the existing omission text, which is not a +refusal), and again if its carrier is later gone while the refusal's is not. The +memory entry for a session is created only when a note is recorded, and recorded +only after the notes were added to the request. Every path that removes the section +removes every added note; the memory is cleared only by capture off or unavailable, +a source binding change or disposal. Providers that drop plugin system sections therefore receive these notes too. The context section and inline/packaged skill share that checklist. The listing line names the plan/dispatch load boundary; detailed operation help stays in the @@ -1091,7 +1112,9 @@ Both start→hook→end and hook→delivered-start→end can qualify; arbitrary of the durable stream and background/precomputed compactions are not certified. Terminals retire the window; failures clear pending state. The first following primary consumes pending and incomplete evidence before awaits, preserving a -creation-time retirement fence against delayed stream backfill. Eviction, floor +creation-time retirement fence against delayed stream backfill; a request whose +latest message has no valid carrier does no lookup and leaves pending completion +armed for the next one. Eviction, floor rejection and lifecycle clearing promote removed records' fences into the global event floor, even after clock rollback, conservatively declining older queued episodes. There is no @@ -1526,8 +1549,8 @@ linked children at a later revision; archived/deleted plans and disabled/unverified contexts expose none. A pending or reserved receipt whose state disagrees with its dispatch, or that names no task, marks evidence incomplete instead of yielding a refusal. -The refreshed coordinator note, carried on the latest message and not in the -system section, is capped at 4 KiB, uses fixed reasons +The refreshed coordinator note, delivered on a message and kept in place on later +requests rather than in the system section, is capped at 4 KiB, uses fixed reasons and explicitly marks omissions, including an empty incomplete result. It is advisory and read-only: recovery requires an intentional fresh declaration or verified explicit link, never an automatic diff --git a/docs/compatibility.md b/docs/compatibility.md index a467ce3..cf86bc5 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -694,8 +694,8 @@ The separately named `progress resume` native case verifies production activatio and Store lookup on OpenCode **2.x >= 2.2.2** at the actual outgoing scripted-provider boundary. It uses direct synthetic Store construction and local plugin loading, not installation. The observer records metadata and the synthetic recovery text -from the latest outgoing message, where the capsule rides for one request while -the system section stays fixed; it never manufactures recovery in regression +from the latest outgoing message, where the capsule is delivered and then stays in +place on later requests while the system section stays fixed; it never manufactures recovery in regression mode or retains conversation/summary text. No real model or provider credentials are used. Node 24.19.0 and OpenCode 2.2.2 are the tested baselines; later 24.x/2.x releases are accepted but not separately certified. The test requires Node 24.x @@ -784,10 +784,16 @@ Tool descriptions and results survive under host-prefixed names. The companion therefore puts its checklist and start example inside the first 2,048 description characters (4,096 overall), and appends conditional fixed notes to qualifying completed direct calls. The one-request hint, the resume capsule and the -delegation refusal note ride the latest message of their request (a text part on -a user message, the last tool result's output on a tool message), so providers -that drop plugin system sections now receive them too. The system section remains -for providers that forward it and is the fixed guidance only, identical on every +delegation refusal note ride a message (a text part on a user message, the last +tool result's output on a tool message), so providers that drop plugin system +sections now receive them too. A delivered note stays in the same place on every +later request that holds its carrier, so each request begins with the previous one +and the provider's cache entry written at the end of the latest message, and the +thinking bound to it, stays readable. A capsule or refusal is delivered again only +when its text changed or its carrier is gone, and a refusal that stops applying +gets one fixed cleared line after a complete read that finds none (an incomplete empty read +delivers the existing omission text and never opens that line). The system section remains for +providers that forward it and is the fixed guidance only, identical on every request, so it does not defeat a provider's prompt cache. No provider identifier or custom instructions are required. @@ -798,8 +804,11 @@ those calls retain context hints but get no result note, and their hint waits fo next request whose latest message can carry it, since the wrapper result stays the script's exact value. Adapter checks cover both run-observer orders and the provider view that drops system text. The native -activation case checks the outgoing request of a real plan-file write continuation: -the hint ends the last tool result and the system section is unchanged. These +activation case checks the outgoing requests of a real plan-file write continuation: +the hint ends the last tool result, the system section is unchanged, the next +outgoing request repeats that result with the hint byte for byte, and the stored +conversation never contains it; it also records whether the host's user messages +carry an identifier. Prompt-cache hit rates are not measured: that needs a live provider. These checks establish delivery, not that a real model will mirror a plan unprompted. That live workflow remains an owner-only check, never a paid-model test. diff --git a/docs/contracts.md b/docs/contracts.md index 128fb7e..b179734 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -553,8 +553,8 @@ and one conditional possible-plan-file hint. The section is the fixed activation guidance only: its text never changes within a session and is byte-identical on every request where it is present, so it does not defeat a provider's prompt cache. Everything that varies per request (the one-request hint, the sub-agent -resume capsule and the delegation refusal note) is carried on the latest message -of that request instead, as described below. Neither is a report receipt, plan, +resume capsule and the delegation refusal note) is carried on messages instead and +stays in place on later requests, as described below. Neither is a report receipt, plan, assignment, review/acceptance, capture, or completion event. Existing explicit `agent_progress_report` operations, source-optional inputs, transactional control, authorization and outputs remain unchanged. Hidden/restricted tools are never @@ -580,7 +580,7 @@ checks are repeated after awaited lookups; recipient flags publish synchronously The same process-local bounded state may coalesce three advisory reasons: possible plan write, native dispatch and tracker mutation. At most one conditional hint is added after the content of the latest message of the recipient's next eligible -request, consumed on delivery, not a receipt. Proxy reasons are actor-only: no child/parent/ancestor fan-out. +request that has a valid carrier, consumed on delivery, not a receipt. Proxy reasons are actor-only: no child/parent/ancestor fan-out. Only plan writes retain the verified-direct-parent relay. Existing 128 pending recipient and 256 recent call caps remain; no new queues, per-tool history, plan lookup, source read, report or automatic progress mutation is introduced. @@ -593,23 +593,62 @@ Only lexical path and host metadata are used: no file, folder or repository metadata is read. A missing, failing, malformed or timed-out worktree list declines cross-directory observation and relay. -Request-only text (the one-request hint, the resume capsule and the delegation -refusal note, with their text and eligibility unchanged) is added for that request -only, after the content of the request's latest message, in a carrier valid for -that message's role. On a user message it is a text part after the content. On a -tool message, the continuation after a tool call such as a plan-file write, a -separate part is not valid, so it is appended to the output of the message's last -tool result: the carrier the completed-result note below uses, with the same -shape limits (a native-proven string or content-array result). The Code Mode -wrapper (`execute`) result is the exact value its script returned and never -carries the text. Any other role or shape has no valid carrier, and the text -waits for the next request that has one; the hint stays pending, an armed capsule -stays armed and the refusal is read again then, never dropped. The standing -assigned-child brief and refusal note are read again on every request, so they -ride any ordinary tool continuation, not only the tools that receive result notes. The message and part are copied: the stored conversation never -carries the text, so a request rebuilt from history is identical up to its latest -message and a reused host array loses a stale note. The text is therefore -delivered even to providers that drop plugin system sections. +Context notes (the one-request hint, the resume capsule and the delegation +refusal note, with their text and eligibility unchanged) are added after the content +of a message, in a carrier valid for that message's role. On a user message a note +is a text part after the content. On a tool message, the continuation after a tool +call such as a plan-file write, a separate part is not valid, so it is appended to +the output of the message's last tool result: the carrier the completed-result +note below uses, with the same shape limits (a native-proven string or +content-array result). The Code Mode wrapper (`execute`) result is the exact value +its script returned and never carries a note. Any other role or shape has no valid +carrier, and a due note waits for the next request that has one: the hint stays +pending, an armed capsule stays armed, and the capsule and refusal are read again +then, never dropped. Notes due together form one note, in the order hint, capsule, +refusal or cleared line, joined by a blank line. The message and part are copied: +the stored conversation never carries a note. The text is therefore delivered even +to providers that drop plugin system sections. + +A delivered note stays where it was put. A provider writes its cache at the end of +the latest message, which is where the note sits, and reads it only when a later +request repeats that prefix byte for byte; with extended thinking the reply's +thinking is bound to that prefix as well. So the companion remembers, per session, +each note it delivered with its carrier (a tool carrier by its call identifier, +position and a digest of its original output, because providers do not keep call +identifiers unique across turns; a user carrier by the message identifier when it +has one, else by its position and a digest of its original content) and adds the +same text in the same place on every later request whose messages still hold that +carrier. Each request's messages therefore begin with the previous request's +messages byte for byte, and a later note on a carrier follows the earlier ones +without rewriting them. The memory is process-local and bounded: 128 sessions, +least recently used first, and per session 256 carriers and 128 KiB of note text, +dropping carriers absent from the latest request first, then the oldest. An +evicted carrier, a restart or a fork loses its note once, which changes the prefix +once from that message on. + +A resume capsule or refusal note is delivered again only when its text differs from +the last one delivered in the session, or when the carrier of that delivery is not +in this request with its note (after compaction, a reverted message, an evicted +carrier, a restart or a fork). A capsule lookup that times out adds nothing, and a +note left out as unchanged counts as delivered. A delivered refusal stays in +history after it stops applying, so one fixed line is delivered in the same way: +`Agent Progress note (delegation): the earlier delegation refusal no longer +applies; read the current plan before you declare or link.` It is delivered only +after a successful, complete refusal read that finds no refusal while the last +refusal delivered is still in the request with its note; a read that fails or is +incomplete adds no cleared line, and an incomplete read with no refusal still +delivers the existing omission text, which is not a refusal and does not open the +cleared-line gate. It counts as the last refusal delivered, so the same refusal +returning is delivered again, and it is delivered again when that refusal is still +in the request with its note and the cleared line's carrier is not. A capsule that becomes empty gets no cleared line: the capsule +already says to read current state first. + +Every path that removes the section (capture off, report tool unavailable, source +unverified, caller lookup failed, an epoch change, disposal, a failure in the hook) +also removes every added note from that request. The memory is cleared only when +capture is off or unavailable, the source binding changes or the companion is disposed; a +transient failure, or a request without the report tool, keeps it and the notes +return with the section. Hints also travel in completed tool results, independently of forwarded system text. The latest verified eligible context must expose both the report tool and @@ -666,8 +705,8 @@ than broaden history. Hints conditionally ask about unreported canonical state, never assert work start, review/owner approval, assignment or completion, and never map issue state to plan status. No receipt correlation or compliance promise exists. -Recovery is an optional request-only addition on the latest message, never part -of the owned section, only after a +Recovery is an optional note on the latest message, never part of the owned +section, only after a host compaction observed during the loaded plugin lifetime: a live start, an observe-only compaction hook and an increasing, matching-reason successful end must pair for the same session/source. Hook/start callback delivery order is not @@ -1971,10 +2010,10 @@ structure, not implementation completion or approval. Review and owner approval are separate; reflect only existing canonical gate/work items, never invent review tasks. Dispatch is not work start. No file or automatic per-turn report is required. No custom instructions or provider-specific branch is needed. System-dropping -providers retain tool definitions, result notes and the request-only hint, -capsule and refusal note on the latest message; providers forwarding system -text retain the owned section too, which stays identical across requests so it -does not defeat a provider's prompt cache. Clients can still omit/truncate descriptions +providers retain tool definitions, result notes and the hint, capsule and +refusal note carried on messages; providers forwarding system text retain the +owned section too, which stays identical across requests so it does not defeat a +provider's prompt cache. Clients can still omit/truncate descriptions below the supported budget; delivery does not guarantee reporting or model compliance. diff --git a/openspec/changes/release-1-5-2/design.md b/openspec/changes/release-1-5-2/design.md index 2604e22..54fde3f 100644 --- a/openspec/changes/release-1-5-2/design.md +++ b/openspec/changes/release-1-5-2/design.md @@ -111,8 +111,8 @@ Items 3 and 4 change documentation only. 3. **A delivered note stays where it was put.** A provider writes its cache at the end of the latest message, which is where the note sits, and reads it only when a later request repeats that prefix byte for byte; with extended thinking, the reply's thinking is also bound to that prefix. So a note added to one request and absent from the next would cost the cache and the thinking of every request it was on. The companion therefore remembers, per session, each note it delivered with its carrier: a tool carrier by its call identifier together with its position and a digest of its original output, because providers do not keep call identifiers unique across turns; a user carrier by the message's identifier when it has one, or else by its position and a digest of its original content. On every later request whose messages still hold that carrier, it adds the same text in the same place, so each request's messages are the previous request's messages followed by new ones, and the stored conversation still never changes. - **Notes due together are one note**: hint, then capsule, then refusal note or cleared line, joined by a blank line. It is stored and added back exactly as delivered. A later note on the same carrier, for example on a retry, follows the earlier ones and never rewrites them. The comparison with the last delivery and the memory update happen in one synchronous step after the request's last wait, so two concurrent requests each record their own carrier. - **Standing text.** A resume capsule or refusal note is delivered again when its text differs from the last one delivered in the session, or when the carrier of that last delivery is not in this request with its note, which covers compaction, a reverted message, an evicted carrier, a restart and a fork. A capsule lookup that times out adds nothing. A capsule or refusal left out as unchanged counts as delivered, and an armed capsule is consumed. - - **Cleared refusal.** A delivered refusal stays in history after it stops applying, so one fixed line is delivered in the same way: `Agent Progress note (delegation): the earlier delegation refusal no longer applies; read the current plan before you declare or link.` It is the one text this change adds. It is delivered only after a successful, complete refusal read that finds no refusal, while the last refusal delivered is still in this request with its note; a read that fails or is incomplete adds nothing. The cleared line counts as the last refusal delivered, so the same refusal returning is delivered again. A resume capsule that becomes empty after a successful lookup gets no cleared line: the capsule already says to read the current state first, and the earlier capsule staying in history is accepted. - - **Memory bound.** At most 128 sessions, least recently used first, and per session at most 64 carriers and 64 KiB of note text. Entries whose carrier is absent from the latest request are evicted first, then the oldest. A carrier evicted from the memory, a restart or a fork loses its note once, which changes the prefix once from that message on, and is accepted; the standing-text rule then delivers the current capsule or refusal again. + - **Cleared refusal.** A delivered refusal stays in history after it stops applying, so one fixed line is delivered in the same way: `Agent Progress note (delegation): the earlier delegation refusal no longer applies; read the current plan before you declare or link.` It is the one text this change adds. It is delivered only after a successful, complete refusal read that finds no refusal, while the last refusal delivered is still in this request with its note; a read that fails or is incomplete adds no cleared line; an incomplete read with no refusal still delivers the existing omission text, which is not a refusal and does not open the cleared-line gate. The cleared line counts as the last refusal delivered, so the same refusal returning is delivered again. The cleared line is delivered again when the last refusal delivered is still in this request with its note and the cleared line's carrier is not. A resume capsule that becomes empty after a successful lookup gets no cleared line: the capsule already says to read the current state first, and the earlier capsule staying in history is accepted. + - **Memory bound.** At most 128 sessions, least recently used first, and per session at most 256 carriers and 128 KiB of note text. Entries whose carrier is absent from the latest request are evicted first, then the oldest. A carrier evicted from the memory, a restart or a fork loses its note once, which changes the prefix once from that message on, and is accepted; the standing-text rule then delivers the current capsule or refusal again. 4. **What stays as it is.** The tool set, the tool description, the skill text and the note added once to a completed tool result already stay identical after their first send. On every path that removes the section (capture off, report tool unavailable, source unverified, caller lookup failed, an epoch change, disposal, or a failure in the hook), every note the companion added is removed from that request too, so a disabled or unverified context exposes none. The session's memory is cleared only when capture is turned off, the source binding changes or the companion is disposed; a transient failure, or a request without the report tool, keeps it, and the notes come back with the section. Turning those on or off still changes the prefix once. Compaction already rebuilds the prompt. 5. **Tests.** A context-hook test runs consecutive requests built from a growing stored history across a hint trigger, a capsule revision, a capsule lookup timeout, and a refusal appearing, clearing and appearing again, on a user carrier with and without an identifier and on a tool carrier. It asserts that the system array is identical each time and that each request's messages, including every note, are a byte-identical prefix of the next request's. Further cases: removal followed by the section coming back, a missing carrier or compaction causing the standing note to be delivered again, a failed refusal read adding no cleared line, and a reused tool call identifier in a later turn not receiving the earlier note. The native activation driver also checks the outgoing requests of a real plan-file write continuation: the hint arrives inside the last tool result, the system section is unchanged, the next outgoing request repeats that tool result with the hint, and the stored conversation does not contain it; it records whether the host's user messages carry an identifier. Prompt-cache hit rates are not measured: that needs a live provider. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index ec65ba7..12ef979 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -52,8 +52,8 @@ Each numbered group is one pull request into the development branch. It carries ## 8. Stable system prompt section -- [ ] 8.1 Keep the companion's system prompt section to the fixed activation guidance only, identical on every request where it is present, and add the one-request hint, the sub-agent resume capsule and the delegation refusal note after the content of its latest message, in a carrier valid for its role: a text part on a user message, the output of the last tool result on a tool message (not the Code Mode `execute` wrapper's result or a non-text result), and otherwise the next request with a valid carrier, never dropped. Their text and eligibility stay unchanged. Keep each delivered note in the same place on later requests built from the same history, keyed as design 8.3 says and bounded as it says; join notes due together in its order; deliver a capsule or refusal again when its text changed or its last carrier is gone; deliver the fixed cleared line under design 8.3's gates; remove every added note on every path that removes the section, and clear the memory only on the paths design 8.4 names. Test the cases design 8.5 lists: the system array is identical each time, and each request's messages are a byte-identical prefix of the next request's. Extend the native activation driver as design 8.5 says. -- [ ] 8.2 Update the statements in `docs/contracts.md`, `docs/backend.md` and `docs/compatibility.md` about where the section and its notes are delivered, including what providers that drop plugin system sections now receive, that delivered notes stay in place on later requests, when standing notes are delivered again, the fixed cleared line, and that the section stays identical across requests so it does not defeat a provider's prompt cache. Replace the statements that notes are added for that request only and that standing notes are read again on every request (`docs/contracts.md` around 596-612, `docs/backend.md` around 1013 and 1092). +- [x] 8.1 Keep the companion's system prompt section to the fixed activation guidance only, identical on every request where it is present, and add the one-request hint, the sub-agent resume capsule and the delegation refusal note after the content of its latest message, in a carrier valid for its role: a text part on a user message, the output of the last tool result on a tool message (not the Code Mode `execute` wrapper's result or a non-text result), and otherwise the next request with a valid carrier, never dropped. Their text and eligibility stay unchanged. Keep each delivered note in the same place on later requests built from the same history, keyed as design 8.3 says and bounded as it says; join notes due together in its order; deliver a capsule or refusal again when its text changed or its last carrier is gone; deliver the fixed cleared line under design 8.3's gates; remove every added note on every path that removes the section, and clear the memory only on the paths design 8.4 names. Test the cases design 8.5 lists: the system array is identical each time, and each request's messages are a byte-identical prefix of the next request's. Extend the native activation driver as design 8.5 says. +- [x] 8.2 Update the statements in `docs/contracts.md`, `docs/backend.md` and `docs/compatibility.md` about where the section and its notes are delivered, including what providers that drop plugin system sections now receive, that delivered notes stay in place on later requests, when standing notes are delivered again, the fixed cleared line, and that the section stays identical across requests so it does not defeat a provider's prompt cache. Replace the statements that notes are added for that request only and that standing notes are read again on every request (`docs/contracts.md` around 596-612, `docs/backend.md` around 1013 and 1092). ## 7. Joined verification and release diff --git a/plugin/activation.ts b/plugin/activation.ts index 06d39a9..f16cdad 100644 --- a/plugin/activation.ts +++ b/plugin/activation.ts @@ -2,6 +2,7 @@ import type { Plugin } from '@opencode/plugin'; import type { ToolHooks } from '@opencode/plugin/effect/tool'; import type { SessionHooks } from '@opencode/plugin/effect/session'; import path from 'node:path'; +import { createHash } from 'node:crypto'; import { identifier } from '../shared/progress.ts'; import type { ResumeRead, ResumeRequest, ResumeSelection } from '../shared/progress-resume.ts'; import type { DelegationRefusals } from '../shared/subagent-runs.ts'; @@ -51,35 +52,56 @@ function hintText(reasons: number) { } /** - * Where request-only text can ride on the latest message of a request, chosen - * by its role. A user message takes a text part after its content. A tool - * message, the continuation after a tool call, takes the text on the output of - * its last tool result: a separate part is not valid there, and this is the - * carrier the completed-result note already uses, so it has the same shape - * limits (a string, or text/file parts). The Code Mode wrapper's result is the - * exact structured value its script returned and never carries a note. Any - * other role, shape or result has no valid carrier. The stored message is never - * changed; the returned copy remembers its original so a reused host array can - * be restored. + * Where context notes can ride on a message, chosen by its role. A user message + * takes a text part after its content. A tool message, the continuation after a + * tool call, takes the text on the output of its last tool result: a separate + * part is not valid there, and this is the carrier the completed-result note + * already uses, so it has the same shape limits (a string, or text/file parts). + * The Code Mode wrapper's result is the exact structured value its script + * returned and never carries a note. Any other role, shape or result has no + * valid carrier. The stored message is never changed; the returned copy + * remembers its original so a reused host array can be restored. + * + * A carrier is identified so a delivered note can be put back in the same place + * on later requests: a tool message by its position, the call identifier and a + * digest of its original output (providers do not keep call identifiers unique + * across turns), a user message by its identifier when it has one, else by its + * position and a digest of its original content. */ const CODE_MODE_TOOL = 'execute'; const restored = Symbol('agent-progress-note'); -function carrier(messages: unknown): { index: number; apply: (text: string) => Record } | undefined { - if (!Array.isArray(messages) || !messages.length) return; - const index = messages.length - 1, message = messages[index]; +interface Carrier { index: number; key: string; id?: string; apply: (text: string) => Record } +/** Binary parts are hashed by their raw bytes, never stringified element by element. */ +function digest(value: unknown) { + const text = JSON.stringify(value, function (this: any, name: string, current: unknown) { + const original = this?.[name]; + if (original instanceof ArrayBuffer) return { bytes: createHash('sha256').update(new Uint8Array(original)).digest('hex') }; + if (ArrayBuffer.isView(original)) return { bytes: createHash('sha256').update(new Uint8Array(original.buffer, original.byteOffset, original.byteLength)).digest('hex') }; + return current; + }); + return createHash('sha256').update(text ?? '').digest('hex').slice(0, 32); +} +function carrierAt(messages: unknown, index: number, positional = false, keyed = true): Carrier | undefined { + if (!Array.isArray(messages)) return; + const message = messages[index]; if (!record(message) || !Array.isArray(message.content)) return; const copy = (content: unknown[]) => { const value = Object.assign(Object.create(Object.getPrototypeOf(message)), message, { content }); Object.defineProperty(value, restored, { value: message }); return value; }; - if (message.role === 'user') return { index, apply: text => copy([...message.content, { type: 'text', text }]) }; - if (message.role !== 'tool') return; - const at = message.content.findLastIndex((part: unknown) => record(part) && part.type === 'tool-result'); - const part = message.content[at], output = part?.result; - if (part?.name === CODE_MODE_TOOL || !record(output) || !(output.type === 'text' ? typeof output.value === 'string' : output.type === 'content' && Array.isArray(output.value))) return; - if (appended(output.value, '') === undefined) return; - return { index, apply: text => copy(message.content.map((entry: unknown, i: number) => i === at ? { ...part, result: { ...output, value: appended(output.value, text) } } : entry)) }; + try { + if (message.role === 'user') { + const id = !positional && boundedID(message.id) ? message.id : undefined; + return { index, id, key: !keyed ? '' : id !== undefined ? `user:${id}` : `user:${index}:${digest(message.content)}`, apply: text => copy([...message.content, { type: 'text', text }]) }; + } + if (message.role !== 'tool') return; + const at = message.content.findLastIndex((part: unknown) => record(part) && part.type === 'tool-result'); + const part = message.content[at], output = part?.result; + if (part?.name === CODE_MODE_TOOL || typeof part?.id !== 'string' || !record(output) || !(output.type === 'text' ? typeof output.value === 'string' : output.type === 'content' && Array.isArray(output.value))) return; + if (appended(output.value, '') === undefined) return; + return { index, key: keyed ? `tool:${index}:${part.id}:${digest(output)}` : '', apply: text => copy(message.content.map((entry: unknown, i: number) => i === at ? { ...part, result: { ...output, value: appended(output.value, text) } } : entry)) }; + } catch { /* an unhashable message has no carrier */ } } /** Put back every message this owner replaced on a reused host array. */ function restoreNotes(messages: unknown) { @@ -87,6 +109,21 @@ function restoreNotes(messages: unknown) { for (let i = 0; i < messages.length; i++) if (record(messages[i]) && Object.prototype.hasOwnProperty.call(messages[i], restored)) messages[i] = messages[i][restored]; } +/** Sent after a delivered delegation refusal stops applying. Fixed text. */ +export const CLEARED_REFUSAL = 'Agent Progress note (delegation): the earlier delegation refusal no longer applies; read the current plan before you declare or link.'; +const NOTE_SEPARATOR = '\n\n'; +const MAX_NOTE_SESSIONS = 128, MAX_NOTE_CARRIERS = 256, MAX_NOTE_BYTES = 128 * 1024; +/** One delivered note and where it sits. Text is exactly what was added. */ +interface DeliveredNote { key: string; id?: string; index: number; text: string } +/** Last delivered standing text and the carrier it went out on. */ +interface Standing { text: string; key: string } +/** + * `refusal` is the last refusal text of any kind delivered (a refusal, the omission text or the + * cleared line); `real` the last real refusal; `cleared` the cleared line delivered since. + */ +interface NoteMemory { notes: Map; capsule?: Standing; refusal?: Standing; real?: Standing; cleared?: Standing } +const REFUSAL_HEADER = '## Delegation not applied'; + const record = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const boundedID = (value: unknown): value is string => typeof value === 'string' && value.length > 0 && value.length <= 512; const uuid = (value: unknown) => typeof value === 'string' && /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(value); @@ -239,10 +276,11 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri const recent = new Set(); // max256 qualifying source/session/message/call IDs const eligibility = new Map>(); // latest context, max128 sessions const noted = new Set(); // max256 source/session/model-message IDs + const memories = new Map(); // delivered context notes; max128 sessions, least recently used first const owned = Symbol('agent-progress-section'); // The section is fixed text: it must be byte-identical on every request, or // a provider's prompt cache misses from this point on. Anything that varies - // per request rides the latest message instead (see `carrier`). + // per request rides a message instead and stays there (see `carrierAt`). function section() { const part = { type: 'text' as const, text: ACTIVATION_GUIDANCE }; Object.defineProperty(part, owned, { value: true }); @@ -271,9 +309,9 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri } function control() { const current = JSON.stringify([source.id, source.verified, recovery?.storeId]); - if (current !== binding) { binding = current; retireRecovery(); pending.clear(); eligibility.clear(); noted.clear(); disableEpoch++; } + if (current !== binding) { binding = current; retireRecovery(); pending.clear(); eligibility.clear(); noted.clear(); memories.clear(); disableEpoch++; } try { if (enabled() === true) return true; } catch { /* unavailable control is not enabled */ } - pending.clear(); eligibility.clear(); noted.clear(); retireRecovery(); disableEpoch++; return false; + pending.clear(); eligibility.clear(); noted.clear(); memories.clear(); retireRecovery(); disableEpoch++; return false; } function remember(set: Set, key: string, cap: number) { set.add(key); @@ -312,7 +350,7 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri finally { if (timer !== undefined) clearTimeout(timer); } } async function dispose() { - disposed = true; pending.clear(); recent.clear(); eligibility.clear(); noted.clear(); retireRecovery(); replay.clear(); + disposed = true; pending.clear(); recent.clear(); eligibility.clear(); noted.clear(); memories.clear(); retireRecovery(); replay.clear(); await stopRecovery?.(); for (const registration of registrations.splice(0)) { try { await registration.dispose(); } catch { /* host scope also owns cleanup */ } @@ -394,10 +432,11 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri if (disposed || epoch !== disableEpoch) { removeOwned(); return; } if (!caller || !control()) { pending.delete(sessionKey); removeOwned(); return; } let capsule = ''; - // Request-only text needs a carrier valid for the latest message's role. - // Without one nothing is computed or consumed: the hint stays pending and - // an armed capsule stays armed for the next request that has a carrier. - const carried = carrier(event.messages) !== undefined; + // A new note needs a carrier valid for the latest message's role. Without one + // nothing new is computed or consumed: the hint stays pending and an armed capsule + // stays armed for the next request that has a carrier. Delivered notes are still + // put back in place. + const carried = Array.isArray(event.messages) && carrierAt(event.messages, event.messages.length - 1, false, false) !== undefined; // validity only; the keyed carrier is taken once after the awaits const rearm = () => { if (armed && compactions.get(sessionKey) === attempt) attempt.pending = true; }; if (!carried) rearm(); // Ordinary coordinators do not scan plans. Children reuse the bounded, @@ -431,11 +470,14 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri finally { if (timer !== undefined) clearTimeout(timer); controller.abort(); } } if (disposed || !control() || epoch !== disableEpoch || !source.verified || !Object.prototype.hasOwnProperty.call(event.tools, REPORT_TOOL)) { removeOwned(); return; } - let refusal=''; + // 'failed' adds nothing; 'cleared' is a successful, complete read that found no refusal. + let refusal='',refusalRead:'failed'|'read'|'cleared'='failed'; try { const selection=carried?recovery?.refusals?.(event.sessionID):undefined; - if(selection?.sourceId===source.id&&selection.sessionId===event.sessionID)refusal=delegationRefusalText(selection); - } catch { /* Optional bounded receipt read never enables a report or blocks guidance. */ } + if(selection?.sourceId===source.id&&selection.sessionId===event.sessionID){ + refusal=delegationRefusalText(selection);refusalRead=refusal?'read':'cleared'; + } + } catch { refusal='';refusalRead='failed'; /* Optional bounded receipt read never enables a report or blocks guidance. */ } if(disposed||!control()||epoch!==disableEpoch||!source.verified||!Object.prototype.hasOwnProperty.call(event.tools,REPORT_TOOL)){removeOwned();return;} if (eligibility.get(sessionKey) === effective) for (const tool of NOTE_TOOLS) { if (Object.prototype.hasOwnProperty.call(event.tools, tool)) effective.add(tool); @@ -444,12 +486,76 @@ export async function registerActivation(ctx: Plugin.Context, source: { id: stri const existing = event.system.findIndex(part => Object.prototype.hasOwnProperty.call(part, owned)); if (existing !== -1) event.system[existing] = section(); else event.system.push(section()); const hint = (pending.get(sessionKey) ?? 0) & 7; - const target = carrier(event.messages); - if (!target) { rearm(); return; } // the hint stays pending; capsule and refusal are read again next request - const text = [hint ? hintText(hint) : '', capsule, refusal].filter(Boolean).join('\n\n'); - if (text) event.messages[target.index] = target.apply(text) as typeof event.messages[number]; - const remaining = (pending.get(sessionKey) ?? 0) & ~7; - if (remaining) pending.set(sessionKey, remaining); else pending.delete(sessionKey); + // One synchronous step from here: compare with the last delivery, add every note and + // then record the memory, so concurrent requests each record their own carrier and a + // failure while adding leaves no phantom note. + const messages = event.messages; + // An overlapping request on a reused array may have added its copies since the top. + restoreNotes(messages); + const current = memories.get(sessionKey); + const notes = new Map(current?.notes); + let { capsule: lastCapsule, refusal: lastRefusal, real: lastReal, cleared: lastCleared } = current ?? {} as NoteMemory; + const ids = new Map(); + if (Array.isArray(messages)) messages.forEach((message, i) => { if (record(message) && message.role === 'user' && boundedID(message.id) && !ids.has(message.id)) ids.set(message.id, i); }); + const placed = new Map(); // remembered notes whose carrier this request still holds + for (const note of notes.values()) { + // A shared user identifier: the position the note was delivered at wins. + const at = note.id === undefined ? note.index : record(messages?.[note.index]) && messages[note.index].id === note.id ? note.index : ids.get(note.id) ?? -1; + const found = carrierAt(messages, at); + if (found?.key === note.key) placed.set(note.key, found); + } + let latest = Array.isArray(messages) ? carrierAt(messages, messages.length - 1) : undefined; + // A user identifier shared with a message that already holds a note is not this message's key. + if (latest?.id !== undefined && placed.has(latest.key) && placed.get(latest.key)!.index !== latest.index) latest = carrierAt(messages, messages.length - 1, true); + let consumed = false, recorded = false; + if (!latest) rearm(); // the hint stays pending; an armed capsule stays armed; capsule and refusal are read again next request + else { + const due: string[] = []; + if (hint) due.push(hintText(hint)); + const standing = (last: Standing | undefined, text: string) => !last || last.text !== text || !placed.has(last.key); + const capsuleDue = !!capsule && standing(lastCapsule, capsule); + if (capsuleDue) due.push(capsule); + let refusalDue: string | undefined; + if (refusalRead === 'read' && standing(lastRefusal, refusal)) refusalDue = refusal; + else if (refusalRead === 'cleared' && lastReal && placed.has(lastReal.key) && !(lastCleared && placed.has(lastCleared.key))) refusalDue = CLEARED_REFUSAL; + if (refusalDue !== undefined) due.push(refusalDue); + const before = notes.get(latest.key); + const text = [...(before ? [before.text] : []), ...(due.length ? [due.join(NOTE_SEPARATOR)] : [])].join(NOTE_SEPARATOR); + if (!due.length || Buffer.byteLength(text) <= MAX_NOTE_BYTES) { + if (due.length) { + // A later note on a carrier follows the earlier ones; it is also the newest. + notes.delete(latest.key); + notes.set(latest.key, { key: latest.key, id: latest.id, index: latest.index, text }); + placed.set(latest.key, latest); + if (capsuleDue) lastCapsule = { text: capsule, key: latest.key }; + if (refusalDue !== undefined) { + lastRefusal = { text: refusalDue, key: latest.key }; + if (refusalDue === CLEARED_REFUSAL) lastCleared = lastRefusal; + else if (refusalDue.startsWith(REFUSAL_HEADER)) { lastReal = lastRefusal; lastCleared = undefined; } + } + recorded = true; + } + consumed = true; + } else rearm(); // too large for this carrier: the armed capsule waits for another + } + // Bound: carriers absent from this request go first, then the oldest. + let bytes = 0; + for (const note of notes.values()) bytes += Buffer.byteLength(note.text); + while (notes.size > MAX_NOTE_CARRIERS || bytes > MAX_NOTE_BYTES) { + const victim = [...notes.values()].find(note => !placed.has(note.key)) ?? notes.values().next().value!; + notes.delete(victim.key); placed.delete(victim.key); bytes -= Buffer.byteLength(victim.text); + } + for (const [noteKey, carrier] of placed) messages[carrier.index] = carrier.apply(notes.get(noteKey)!.text) as typeof messages[number]; + // Applied: now record. A session's memory exists only once it holds a note. + if (current || recorded) { + memories.delete(sessionKey); + memories.set(sessionKey, { notes, capsule: lastCapsule, refusal: lastRefusal, real: lastReal, cleared: lastCleared }); + if (memories.size > MAX_NOTE_SESSIONS) memories.delete(memories.keys().next().value!); + } + if (consumed) { + const remaining = (pending.get(sessionKey) ?? 0) & ~7; + if (remaining) pending.set(sessionKey, remaining); else pending.delete(sessionKey); + } } catch { pending.delete(key(event.sessionID)); eligibility.delete(key(event.sessionID)); try { removeOwned(); } catch { /* malformed/immutable host context */ } } }; registrations.push(await ctx.session.hook('context',context)); diff --git a/tests/backend/progress-activation.test.ts b/tests/backend/progress-activation.test.ts index 49fada2..a32db30 100644 --- a/tests/backend/progress-activation.test.ts +++ b/tests/backend/progress-activation.test.ts @@ -419,10 +419,10 @@ test('restricted or disabled proxy recipients lose only their actor flags withou }); }); -test('request-only note picks its carrier by the latest message role, defers without one and never mutates stored objects', async () => { +test('a context note picks its carrier by the message role, defers without one, stays in place and never mutates stored objects', async () => { await activationFixture(async f => { const text = (value: string) => ({ type: 'text', text: value }); - const user = { role: 'user', content: [text('Make a plan')] }; + let turn = 0; const user = () => ({ role: 'user', content: [text(`Make a plan ${++turn}`)] }); const result = (id: string, value: unknown, type = 'content') => ({ type: 'tool-result', id, name: 'write', result: { type, value } }); const tool = (...results: any[]) => ({ role: 'tool', content: results }); const call = { role: 'assistant', content: [{ type: 'tool-call', id: 'c1', name: 'write', input: {} }] }; @@ -432,70 +432,70 @@ test('request-only note picks its carrier by the latest message role, defers wit let n = 0; const trigger = () => f.after(write('docs/plans/search.md', `trigger-${++n}`)); const baseline = system(await next(f)); - // User message: a text part after its content, on a copy. + // User message: a text part after its content, on a copy, in the same array the host passed. await trigger(); - const history = [user], before = stored(user), c1 = request(...history); + const first = user(), history = [first], before = stored(first), c1 = request(...history), array = c1.messages; await f.context(c1); - assert.deepEqual(c1.messages[0].content, [text('Make a plan'), text(HINT)]); - assert.notEqual(c1.messages[0], user); assert.deepEqual(history, before); assert.equal(c1.messages, c1.messages); + assert.equal(c1.messages, array, 'the host array is updated in place'); + assert.deepEqual(c1.messages[0].content, [first.content[0], text(HINT)]); + assert.notEqual(c1.messages[0], first); assert.deepEqual(history, before); assert.equal(system(c1), baseline); - // Rebuilt from history, the next request carries nothing; a reused event loses its stale note. + // Rebuilt from the same history the note is in the same place, once; the stored message is unchanged. const rebuilt = request(...history); await f.context(rebuilt); - assert.deepEqual(rebuilt.messages, before); assert.equal(system(rebuilt), baseline); - await f.context(c1); assert.deepEqual(c1.messages, before); assert.equal(system(c1), baseline); + assert.deepEqual(rebuilt.messages, c1.messages); assert.equal(system(rebuilt), baseline); assert.deepEqual(history, before); + await f.context(c1); assert.deepEqual(c1.messages[0].content, [first.content[0], text(HINT)], 'a reused event keeps one note, not two'); assert.equal(copy(c1)[0].text, BASE); // Tool message with a content result: appended after the content of its last result only. await trigger(); const one = tool(result('c1', [text('Created file')]), result('c2', [text('Edited file')])); - const toolHistory = [user, call, one], toolBefore = stored(...toolHistory), c2 = request(...toolHistory); + const toolHistory = [user(), call, one], toolBefore = stored(...toolHistory), c2 = request(...toolHistory); await f.context(c2); assert.deepEqual(c2.messages[2].content[0], one.content[0]); assert.deepEqual(c2.messages[2].content[1].result, { type: 'content', value: [text('Edited file'), text(HINT)] }); - assert.deepEqual(toolHistory, toolBefore); assert.equal(c2.messages[0], user); assert.equal(c2.messages[1], call); assert.equal(system(c2), baseline); + assert.deepEqual(toolHistory, toolBefore); assert.equal(c2.messages[1], call); assert.equal(system(c2), baseline); // Tool message with a text result: same newline-separated carrier as the completed-result note. await trigger(); - const plain = tool(result('c1', 'Created file', 'text')), plainBefore = stored(plain), c3 = request(user, call, plain); + const plain = tool(result('c1', 'Created file', 'text')), plainBefore = stored(plain), c3 = request(user(), call, plain); await f.context(c3); assert.deepEqual(c3.messages[2].content[0].result, { type: 'text', value: `Created file\n\n${HINT}` }); assert.deepEqual([plain], plainBefore); assert.equal(system(c3), baseline); // Any other tool's result carries it too: a child's standing brief must not vanish behind a read. await trigger(); - const read = tool({ ...result('c1', [text('File contents')]), name: 'read' }), c4 = request(user, call, read); + const read = tool({ ...result('c1', [text('File contents')]), name: 'read' }), c4 = request(user(), call, read); await f.context(c4); assert.deepEqual(c4.messages[2].content[0].result, { type: 'content', value: [text('File contents'), text(HINT)] }); // Roles and results with no valid carrier keep the text pending, never dropped. await trigger(); const unusable = [ - [user, { role: 'assistant', content: [text('Partial answer')] }], - [user, call, tool(result('c1', { ok: true }, 'json'))], - [user, call, tool(result('c1', 'failed', 'error'))], - [user, call, tool(result('c1', [{ type: 'unknown' }]))], + () => [user(), { role: 'assistant', content: [text('Partial answer')] }], + () => [user(), call, tool(result('c1', { ok: true }, 'json'))], + () => [user(), call, tool(result('c1', 'failed', 'error'))], + () => [user(), call, tool(result('c1', [{ type: 'unknown' }]))], // The Code Mode wrapper's result stays the exact value its script returned. - [user, call, tool({ ...result('c1', '{"ok":true}', 'text'), name: 'execute' })], - [user, { role: 'system', content: [text('Operator note')] }], - [{ role: 'user', content: 'raw string content' }], - [], + () => [user(), call, tool({ ...result('c1', '{"ok":true}', 'text'), name: 'execute' })], + () => [user(), { role: 'system', content: [text('Operator note')] }], + () => [{ role: 'user', content: 'raw string content' }], + () => [], ]; - for (const messages of unusable) { - const snapshot = stored(...messages), c = request(...messages); await f.context(c); + for (const build of unusable) { + const messages = build(), snapshot = stored(...messages), c = request(...messages); await f.context(c); assert.deepEqual(c.messages, snapshot, 'nothing is added without a valid carrier'); assert.equal(system(c), baseline); assert.equal(hint(c), false); } - const delivered = request(user); await f.context(delivered); - assert.deepEqual(delivered.messages[0].content, [text('Make a plan'), text(HINT)], 'deferred text arrives on the next valid carrier'); - await f.context(delivered); assert.deepEqual(delivered.messages, [user]); + const later = user(), delivered = request(later); await f.context(delivered); + assert.deepEqual(delivered.messages[0].content, [later.content[0], text(HINT)], 'deferred text arrives on the next valid carrier'); assert.equal(hint(await next(f)), false, 'delivered once'); // Removal paths leave neither a section nor a note. - await trigger(); const reused = request(user); await f.context(reused); assert.equal(reused.messages[0].content.length, 2); + await trigger(); const reusedUser = user(), reused = request(reusedUser); await f.context(reused); assert.equal(reused.messages[0].content.length, 2); f.store.setEnabled(false); await f.context(reused); - assert.equal(copy(reused).length, 0); assert.deepEqual(reused.messages, [user]); + assert.equal(copy(reused).length, 0); assert.deepEqual(reused.messages, [reusedUser]); f.store.setEnabled(true); - const missing = request(user); delete missing.tools.agent_progress_report; await trigger(); await f.context(missing); - assert.equal(copy(missing).length, 0); assert.deepEqual(missing.messages, [user]); + const missingUser = user(), missing = request(missingUser); delete missing.tools.agent_progress_report; await trigger(); await f.context(missing); + assert.equal(copy(missing).length, 0); assert.deepEqual(missing.messages, [missingUser]); }); }); diff --git a/tests/backend/progress-resume-activation.test.ts b/tests/backend/progress-resume-activation.test.ts index 986e930..72e7105 100644 --- a/tests/backend/progress-resume-activation.test.ts +++ b/tests/backend/progress-resume-activation.test.ts @@ -5,7 +5,7 @@ import fs from 'node:fs'; import { Effect, DateTime, Stream } from 'effect'; import { fromPromise } from '@opencode/plugin/promise/adapter'; import plugin from '../../plugin/index.ts'; -import { registerActivation, ACTIVATION_GUIDANCE as BASE, ACTIVATION_HINT as HINT } from '../../plugin/activation.ts'; +import { registerActivation, delegationRefusalText, ACTIVATION_GUIDANCE as BASE, ACTIVATION_HINT as HINT } from '../../plugin/activation.ts'; import { Store } from '../../shared/store.ts'; import { activationContext as context, requestNote, writeEvent } from '../fixtures/activation-production.ts'; import { isolatedEnvironment, publishFixtureBinding } from '../fixtures/managed.ts'; @@ -21,6 +21,7 @@ async function bounded(promise: Promise): Promise { try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Synthetic fixture wait timed out')), 3000); })]); } finally { clearTimeout(timer); } } +const CLEARED = 'Agent Progress note (delegation): the earlier delegation refusal no longer applies; read the current plan before you declare or link.'; const parts = (c: any) => c.system.filter((p: any) => p.text?.startsWith('# Agent progress (companion)')); const capsule = (c: any): string => { const note = requestNote(c), at = note.indexOf('## Progress resume'); return at < 0 ? '' : note.slice(at); }; const samples: Record = {}; @@ -160,7 +161,9 @@ test('ordinary child contexts deliver only current verified assignments without assert.ok(text(c).includes('last-known revision 2'));assert.equal(f.store.get(child.sourceId,'P-alpha').revision,2); assert.equal(parts(await f.next('ses_C',false)).length,0); f.store.apply({op:'link',plan:'P-alpha',oid:'unlink-child',rev:2,child:'ses_C',assign:[]},parent,undefined,child); - await f.context(c);assert.equal(text(c).includes('Assigned-only scope:'),false); + // The delivered brief stays where it was put on a rebuilt request; only a new turn after the unlink has none. + await f.context(c);assert.equal(text(c).includes('Assigned-only scope:'),true); + assert.equal(text(await f.next('ses_C')).includes('Assigned-only scope:'),false); assert.equal(f.store.get(child.sourceId,'P-alpha').items[0].status,'pending'); })); @@ -245,7 +248,10 @@ test(`durable refusal is refreshed after ${recovery} recovery on eligible coordi if(recovery==='redeclare')await f.report({op:'delegate',plan:'P-alpha',oid:'new-declaration',rev:2,assign:['I1']}); else f.store.apply({op:'link',plan:'P-alpha',oid:'recovered-link',rev:2,child:'ses_C',assign:['I1']},actor,undefined, {...actor,sessionId:'ses_C',parentId:'ses_M',ancestry:['ses_M']},recovery==='binding'?{generation:0,messageId:key.message,callId:key.call,observedAt:new Date(1000).toISOString()}:undefined); - await f.context(context);assert.ok(!requestNote(context).includes('## Delegation not applied'),'reused context removes obsolete refusal'); + // The delivered refusal stays in place; the fixed cleared line follows it once the read is complete and finds none. + await f.context(context);assert.equal(requestNote(context),`${text}\n\n${CLEARED}`,'delivered refusal stays, then the cleared line'); + await f.context(context);assert.equal(requestNote(context),`${text}\n\n${CLEARED}`,'the cleared line is delivered once'); + assert.equal(requestNote(await f.next()),'','a new turn has nothing to clear'); f.store.setEnabled(false);assert.equal(parts(await f.next()).length,0); })); @@ -524,59 +530,445 @@ test('V6/V8 held ancestry retires on disable/disposal, no next hop or late injec }); }); -test('V8 reused context strips consumed recovery, hint and note, and preserves unrelated context', async () => { +test('V8 reused context keeps delivered notes in place once and preserves unrelated context', async () => { await fixture(async f => { f.seed(); await f.after(writeEvent()); await f.compact(); const c = await f.next(); assert.ok(capsule(c)); assert.ok(requestNote(c).includes(HINT)); assert.equal(parts(c)[0].text, BASE); const other = c.system[0], messages = c.messages, tools = c.tools, settings = c.options; - // A reused event keeps neither the consumed capsule nor the consumed hint: they were for one request. - await f.context(c); assert.equal(requestNote(c), ''); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); + // A rebuilt request keeps the delivered note exactly where it was, once, and never adds the section twice. + const delivered = requestNote(c); + await f.context(c); assert.equal(requestNote(c), delivered); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); assert.equal(c.system[0], other); assert.equal(c.messages, messages); assert.equal(c.tools, tools); assert.equal(c.options, settings); assert.equal(parts(await f.next())[0].text, BASE); await f.compact(); await f.context(c); assert.ok(capsule(c)); assert.equal(parts(c).length, 1); assert.equal(parts(c)[0].text, BASE); }); }); -test('system section is byte-identical across hint, refusal, capsule revision and lookup timeout; request-only text rides the latest message once', async () => { +// ---- Delivered context notes: stable system section, notes kept in place on later requests ---- +// The cleared line is the one fixed text this behaviour adds; the tests spell it out. +const textPart = (value: string) => ({ type: 'text', text: value }); +/** + * A stored conversation that only grows, from which the host rebuilds each request. + * Every request checks that the stored objects never carry a note, that the system + * array never changes and that its messages begin with the previous request's messages + * byte for byte. `added` lists every note on a request as [index, text]. + */ +let conversationTurns = 0; // distinct text for every message of every conversation +function conversation(f: any, withId = false, sessionID = 'ses_M') { + const history: any[] = [], sent: string[][] = [], systems: string[] = []; + const t = { + history, systems, + user: (value = `turn ${++conversationTurns}`) => { history.push({ role: 'user', ...(withId ? { id: `msg_${sessionID}_${++conversationTurns}` } : {}), content: [textPart(value)] }); }, + tool: (name = 'write', value = 'Created file', callId = `call_${++conversationTurns}`) => { + history.push({ role: 'assistant', content: [{ type: 'tool-call', id: callId, name, input: {} }] }, + { role: 'tool', content: [{ type: 'tool-result', id: callId, name, result: { type: 'content', value: [textPart(value)] } }] }); + }, + get last() { return history.length - 1; }, + async request(available = true, check = true, messages: any[] = history) { + const stored = JSON.stringify(messages); + const c = context(sessionID, available); c.messages = [...messages]; f.tick(); + await f.context(c); + assert.equal(JSON.stringify(messages), stored, 'the stored conversation never carries a note'); + if (check) { + const previous = sent.at(-1); + if (previous) assert.deepEqual(c.messages.slice(0, previous.length).map((m: any) => JSON.stringify(m)), previous, 'messages begin with the previous request\'s, notes included'); + systems.push(JSON.stringify(c.system)); + sent.push(c.messages.map((m: any) => JSON.stringify(m))); + } + return c; + }, + added(c: any, messages: any[] = history): Array<[number, string]> { + return c.messages.flatMap((m: any, i: number): Array<[number, string]> => { + if (JSON.stringify(m) === JSON.stringify(messages[i])) return []; + const parts = m.role === 'user' ? m.content.slice(1) : m.content.at(-1).result.value.slice(1); + return [[i, parts.map((p: any) => p.text).join('\n\n')]]; + }); + }, + }; + return t; +} +/** Controls what the production refusal read returns, per request. */ +function refusalReads() { + let state: any = { complete: true, refusals: [] }; + const read = mock.method(Store.prototype, 'delegationRefusals', function (sourceId: string, sessionId: string) { + if (state === 'fail') throw new Error('synthetic read failure'); + return { sourceId, sessionId, ...state }; + }); + const refused = (oid: string, taskIds = ['I1']) => ({ complete: true, refusals: [{ plan: 'P-alpha', reason: 'conflict', recovery: 'redeclare-or-link', declaration: { oid, taskIds, declaredRevision: 1 } }] }); + return { + set: (value: any) => { state = value; }, refused, restore: () => read.mock.restore(), + text: (oid: string, taskIds?: string[]) => delegationRefusalText({ sourceId: 'x', sessionId: 'y', ...refused(oid, taskIds) } as any), + }; +} + +for (const withId of [true, false]) test(`delivered notes stay in place on later requests and the system section never changes (${withId ? 'user message ids' : 'no user message ids'})`, async () => { await fixture(async f => { f.seed(); - const stored = { role: 'user', content: [{ type: 'text', text: 'Make a plan' }] }; const snapshot = structuredClone(stored); - const systems: string[] = []; - // Every request is rebuilt from the same stored history, as the host does. - const request = async () => { f.tick(); const c = context(); c.messages = [stored]; await f.context(c); systems.push(JSON.stringify(c.system)); return c; }; - const note = async () => requestNote(await request()); - assert.equal(await note(), ''); - // One-request hint. - await f.after(writeEvent()); - assert.equal(await note(), HINT); assert.equal(await note(), ''); - // Delegation refusal appears, then clears. - await f.report({ op: 'delegate', plan: 'P-alpha', oid: 'refused-declaration', rev: 1, assign: ['I1'] }); - const actor = { sourceId: f.binding.source.id, sessionId: 'ses_M', parentId: null, ancestry: [], agent: 'synthetic', directory: '/fixture/project', verifiedSource: true }; - const key = { source: actor.sourceId, parent: actor.sessionId, message: 'message', call: 'reserved-call' }; - f.store.beforeRun(key, actor, 'subagent', {}, 1000); - f.store.apply({ op: 'change', plan: 'P-alpha', oid: 'target-touch', rev: 1, changes: [{ id: 'I1', status: 'working' }] }, actor); - f.store.afterRun(key, 0, { ...actor, sessionId: 'ses_C', parentId: 'ses_M', ancestry: ['ses_M'] }, 'returned'); - assert.match(await note(), /^## Delegation not applied/); - await f.report({ op: 'delegate', plan: 'P-alpha', oid: 'new-declaration', rev: 2, assign: ['I1'] }); - assert.equal(await note(), ''); - // Capsule naming the plan revision changes between requests. - const revision = () => f.store.get(f.binding.source.id, 'P-alpha').revision; - await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-a', rev: revision(), title: 'Synthetic alpha r2' }); - const first = revision(); assert.match(await note(), new RegExp(`last-known revision ${first}`)); - await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-b', rev: revision(), title: 'Synthetic alpha r3' }); - assert.match(await note(), new RegExp(`last-known revision ${first + 1}`)); - // The bounded capsule lookup times out for one request. - await f.compact(); + const refusals = refusalReads(); + try { + const t = conversation(f, withId); + const revision = () => f.store.get(f.binding.source.id, 'P-alpha').revision; + t.user(); assert.deepEqual(t.added(await t.request()), []); + // A hint after a plan-file write rides the tool carrier and stays there. + await f.after(writeEvent('docs/plans/search.md', 'w1')); t.tool(); const hinted = t.last; + assert.deepEqual(t.added(await t.request()), [[hinted, HINT]]); + t.user(); assert.deepEqual(t.added(await t.request()), [[hinted, HINT]], 'the earlier hint is repeated, and not added again'); + // A user carrier: a later hint on a user message. + await f.after(writeEvent('docs/plans/search.md', 'w2')); t.user(); const userHint = t.last; + assert.deepEqual(t.added(await t.request()), [[hinted, HINT], [userHint, HINT]]); + // A refusal appears, is repeated, clears once and appears again. + refusals.set(refusals.refused('d1')); t.tool('read'); const refused = t.last; + assert.deepEqual(t.added(await t.request()), [[hinted, HINT], [userHint, HINT], [refused, refusals.text('d1')]]); + t.user(); assert.equal(t.added(await t.request()).length, 3, 'an unchanged refusal whose carrier is present is not delivered again'); + refusals.set({ complete: true, refusals: [] }); t.tool('read'); const cleared = t.last; + assert.deepEqual(t.added(await t.request()).slice(3), [[cleared, CLEARED]]); + t.user(); assert.equal(t.added(await t.request()).length, 4, 'the cleared line is delivered once'); + refusals.set(refusals.refused('d1')); t.tool('read'); const again = t.last; + assert.deepEqual(t.added(await t.request()).slice(4), [[again, refusals.text('d1')]], 'the same refusal returning after the cleared line is delivered again'); + refusals.set({ complete: true, refusals: [] }); + // A hint, a capsule and a cleared line due together are one note, in that order. + await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-a', rev: revision(), title: 'Synthetic alpha r2' }); + await f.after(writeEvent('docs/plans/search.md', 'w3')); t.user(); const combined = t.last; + const joint = t.added(await t.request()).slice(5); + assert.equal(joint.length, 1); assert.equal(joint[0][0], combined); + const pieces = joint[0][1].split('\n\n'); + assert.equal(pieces.length, 3); assert.equal(pieces[0], HINT); assert.match(pieces[1], /^## Progress resume.*last-known revision 2/s); assert.equal(pieces[2], CLEARED); + t.user(); assert.equal(t.added(await t.request()).length, 6, 'the capsule is repeated, not delivered again'); + // A capsule revision delivers the new capsule after the latest message; the old one stays. + await f.compact(); await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-b', rev: revision(), title: 'Synthetic alpha r3' }); + t.user(); const revised = t.last; + const afterRevision = t.added(await t.request()); + assert.equal(afterRevision.length, 7); assert.equal(afterRevision[6][0], revised); assert.match(afterRevision[6][1], /last-known revision 3/); + assert.match(afterRevision[5][1], /last-known revision 2/); + // A lookup that times out adds nothing and leaves every earlier note where it was. + await f.compact(); const release = deferred(); let calls = 0; + f.lookup = async (id: string) => { if (++calls > 1) await release.promise; return f.info(id); }; + t.user(); assert.equal(t.added(await t.request()).length, 7); + release.resolve(); f.lookup = async (id: string) => f.info(id); await new Promise(resolve => setImmediate(resolve)); + assert.equal(new Set(t.systems).size, 1, 'one byte-identical system array on every request'); + assert.deepEqual(JSON.parse(t.systems[0]), [{ type: 'text', text: 'Other system section' }, { type: 'text', text: BASE }]); + assert.equal(t.systems.length, 13); + } finally { refusals.restore(); } + }); +}); + +test('an assigned child gets its brief once, a changed brief after the latest message, and nothing on a lookup timeout', async () => { + await fixture(async f => { + f.seed(); + assert.equal((await f.report({ op: 'link', plan: 'P-alpha', oid: 'link', rev: 1, child: 'ses_C', assign: ['I1'] })).error, undefined); + const t = conversation(f, false, 'ses_C'); + // The brief is read on every request; it is delivered once and then only repeated. + t.user(); const first = t.last; + const delivered = t.added(await t.request()); + assert.equal(delivered.length, 1); assert.equal(delivered[0][0], first); assert.match(delivered[0][1], /last-known revision 2.*Assigned-only scope: \["I1"\]/s); + t.tool('read'); t.user(); t.tool('read'); + assert.deepEqual(t.added(await t.request()), delivered, 'later requests repeat the brief and do not add it again'); + // The plan moves on: the new brief follows the latest message, the old one stays. + await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise', rev: 2, title: 'Synthetic alpha r2' }); + t.user(); const revised = t.last; + const second = t.added(await t.request()); + assert.equal(second.length, 2); assert.deepEqual(second[0], delivered[0]); assert.equal(second[1][0], revised); assert.match(second[1][1], /last-known revision 3/); + // A lookup that times out adds nothing and leaves both briefs where they were. + await f.report({ op: 'revise', plan: 'P-alpha', oid: 'revise-again', rev: 3, title: 'Synthetic alpha r3' }); const release = deferred(); let calls = 0; f.lookup = async (id: string) => { if (++calls > 1) await release.promise; return f.info(id); }; - assert.equal(await note(), ''); release.resolve(); f.lookup = async (id: string) => f.info(id); - await new Promise(resolve => setImmediate(resolve)); - await f.compact(); assert.match(await note(), /^## Progress resume/); - assert.equal(await note(), ''); - assert.equal(systems.length, 10); - assert.equal(new Set(systems).size, 1, 'one byte-identical system array on every request'); - assert.deepEqual(JSON.parse(systems[0]), [{ type: 'text', text: 'Other system section' }, { type: 'text', text: BASE }]); - assert.deepEqual(stored, snapshot, 'stored conversation never carries a note'); + t.user(); assert.deepEqual(t.added(await t.request()), second); + release.resolve(); f.lookup = async (id: string) => f.info(id); await new Promise(resolve => setImmediate(resolve)); + assert.equal(new Set(t.systems).size, 1); + }); +}); + +const OMISSION = 'Additional refusal evidence may be unavailable or omitted.'; + +test('an incomplete empty read delivers the omission text but never opens the cleared line', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f); + refusals.set({ complete: false, refusals: [] }); t.user(); + assert.deepEqual(t.added(await t.request()).map(([, text]) => text), [OMISSION], 'the existing omission text is still delivered'); + refusals.set({ complete: true, refusals: [] }); t.user(); + assert.equal(t.added(await t.request()).length, 1, 'no refusal was ever shown, so nothing is cleared'); + // A real refusal followed by an omission still gets its cleared line. + const real = conversation(f); refusals.set(refusals.refused('d1')); real.user(); assert.equal(real.added(await real.request()).length, 1); + refusals.set({ complete: false, refusals: [] }); real.user(); assert.equal(real.added(await real.request()).length, 2); + refusals.set({ complete: true, refusals: [] }); real.user(); + assert.equal(real.added(await real.request()).at(-1)![1], CLEARED); + } finally { refusals.restore(); } + }); +}); + +test('a note too large for its carrier leaves an armed capsule armed', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f), long = Array.from({ length: 30 }, (_, i) => `T${String(i).padStart(2, '0')}-${'x'.repeat(140)}`); + t.user(); let skipped = false; + // Retries of one request append refusals to the same carrier until the next would not fit. + for (let i = 0; i < 200 && !skipped; i++) { + refusals.set(refusals.refused(`d${i}`, long)); + const [[, text] = [0, '']] = t.added(await t.request(true, false)); + assert.ok(Buffer.byteLength(text) <= 128 * 1024); + skipped = !text.includes(refusals.text(`d${i}`, long)); + } + assert.ok(skipped, 'the carrier filled up'); + await f.compact(); + assert.ok(!t.added(await t.request(true, false)).some(([, text]) => text.includes('## Progress resume')), 'too large: nothing is added'); + t.user(); + assert.ok(t.added(await t.request(true, false)).at(-1)![1].includes('## Progress resume'), 'the capsule was not consumed by the skipped request'); + } finally { refusals.restore(); } + }); +}); + +test('a cleared line is delivered again when a revert removes it but keeps the refusal', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f); refusals.set(refusals.refused('d1')); t.user(); t.tool('read'); const refusedAt = t.last; + assert.deepEqual(t.added(await t.request()), [[refusedAt, refusals.text('d1')]]); + refusals.set({ complete: true, refusals: [] }); t.tool('read'); + assert.equal(t.added(await t.request()).at(-1)![1], CLEARED); + // Revert the message that carried the cleared line. + const reverted = [...t.history.slice(0, -2), { role: 'user', content: [textPart('After the revert')] }]; + const c = await t.request(true, false, reverted); + assert.deepEqual(t.added(c, reverted), [[refusedAt, refusals.text('d1')], [reverted.length - 1, CLEARED]]); + // Only once more while that carrier is present. + reverted.push({ role: 'user', content: [textPart('Next')] }); + assert.equal(t.added(await t.request(true, false, reverted), reverted).length, 2); + } finally { refusals.restore(); } + }); +}); + +test('user messages sharing an identifier keep their note on the message it was delivered on', async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); + const first = { role: 'user', id: 'msg_shared', content: [textPart('First')] }, second = { role: 'user', id: 'msg_shared', content: [textPart('Second')] }; + await f.after(writeEvent('docs/plans/search.md', 'w1')); + assert.deepEqual(t.added(await t.request(true, true, [first, second]), [first, second]), [[1, HINT]]); + const later = [first, second, { role: 'user', id: 'msg_other', content: [textPart('Third')] }]; + assert.deepEqual(t.added(await t.request(true, false, later), later), [[1, HINT]], 'the first message with that identifier did not take the note'); + // A shared identifier on the latest message is not its key: the earlier note is not appended to. + const same = [first, second, { role: 'user', id: 'msg_shared', content: [textPart('Fourth')] }]; + await f.after(writeEvent('docs/plans/search.md', 'w2')); + assert.deepEqual(t.added(await t.request(true, false, same), same), [[1, HINT], [2, HINT]]); + }); +}); + +test('a session has memory only once it holds a note', async () => { + await fixture(async f => { + f.seed(); + const holder = conversation(f, false, 'ses_holder'); + await f.after(writeEvent('docs/plans/search.md', 'h1', 'ses_holder')); holder.user(); holder.tool(); + assert.equal(holder.added(await holder.request()).length, 1); + for (let i = 0; i < 130; i++) { const quiet = conversation(f, false, `ses_quiet${i}`); quiet.user(); assert.deepEqual(quiet.added(await quiet.request(true, false)), []); } + assert.equal(holder.added(await holder.request(true, false)).length, 1, 'sessions without notes never evict one that has them'); + }); +}); + +test('overlapping requests on one reused event do not feed their own copies to the next', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f); t.user(); + await f.after(writeEvent('docs/plans/search.md', 'w1')); refusals.set(refusals.refused('d1')); + const c = context(); c.messages = [...t.history]; + const gate = deferred(); let held = false; + f.lookup = async (id: string) => { if (!held) { held = true; await gate.promise; } return f.info(id); }; + const slow = f.context(c); // waits on its first lookup, after restoring the array + await f.context(c); // an overlapping request delivers the notes onto the same array + gate.resolve(); await slow; f.lookup = async (id: string) => f.info(id); + assert.deepEqual(t.added(c), [[0, `${HINT}\n\n${refusals.text('d1')}`]], 'one note, not a copy of a copy'); + } finally { refusals.restore(); } + }); +}); + +test('a failure while adding notes leaves no phantom note in the memory', async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); t.user(); + await f.after(writeEvent('docs/plans/search.md', 'w1')); + const frozen = context(); frozen.messages = Object.freeze([...t.history]); + await f.context(frozen); + assert.equal(parts(frozen).length, 0, 'the failed request carries no section'); + assert.deepEqual(t.added(await t.request(true, false)), [], 'nothing was recorded for the failed request'); + }); +}); + +for (const mode of ['an epoch change', 'disposal'] as const) test(`${mode} while notes are present removes every note from the request`, async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); + await f.after(writeEvent('docs/plans/search.md', 'w1')); t.user(); t.tool(); + const c = await t.request(); assert.equal(t.added(c).length, 1); + const stored = JSON.stringify(t.history), gate = deferred(); let held = false; + f.lookup = async (id: string) => { if (!held) { held = true; await gate.promise; } return f.info(id); }; + const task = f.context(c); + if (mode === 'disposal') await f.dispose(); + else { f.store.setEnabled(false); await f.next('ses_other'); f.store.setEnabled(true); } + gate.resolve(); await task; + assert.equal(parts(c).length, 0); assert.deepEqual(t.added(c), []); assert.equal(JSON.stringify(t.history), stored); + }); +}); + +test('binary parts are keyed by their raw bytes, so media keeps its note and different bytes are a different carrier', async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); + const media = (fill: number) => ({ role: 'user', content: [textPart('Look at this'), { type: 'media', media: { source: { type: 'bytes', data: new Uint8Array(256 * 1024).fill(fill), mediaType: 'image/png' } } }] }); + const first = media(1); await f.after(writeEvent('docs/plans/search.md', 'w1')); + assert.equal(t.added(await t.request(true, true, [first]), [first]).length, 1); + const grown = [first, { role: 'user', content: [textPart('More')] }]; + assert.equal(t.added(await t.request(true, true, grown), grown).length, 1, 'the note stays on the media message'); + const other = [media(2), { role: 'user', content: [textPart('More')] }]; + assert.equal(t.added(await t.request(true, false, other), other).length, 0, 'different bytes are a different carrier'); + }); +}); + +test('a standing capsule or refusal is delivered again when its carrier is gone, and a gone carrier keeps nothing alive', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f); refusals.set(refusals.refused('d1')); + await f.compact(); t.user(); + const first = t.added(await t.request()); + assert.equal(first.length, 1); const [capsuleText, refusalText] = first[0][1].split('\n\n'); + assert.match(capsuleText, /^## Progress resume/); assert.equal(first[0][1], `${capsuleText}\n\n${refusalText}`); + await f.compact(); t.user(); + assert.equal(t.added(await t.request()).length, 1, 'unchanged text with its carrier present is not delivered again, and consumes the armed capsule'); + // Compaction rebuilds the prompt: the old carriers are gone, the text is unchanged. + const rebuilt = conversation(f); rebuilt.user('Summary of the earlier conversation'); + await f.compact(); + const again = rebuilt.added(await rebuilt.request()); + assert.deepEqual(again, [[0, first[0][1]]], 'both standing notes arrive again after the latest message'); + // A reverted message: the carrier of the last delivery is missing from this request. + rebuilt.user(); rebuilt.user(); + const reverted = rebuilt.history.slice(); reverted.splice(0, 1, { role: 'user', content: [textPart('A different first message')] }); + const c = await rebuilt.request(true, false, reverted); + assert.equal(rebuilt.added(c, reverted).filter(([, text]) => text.includes(refusals.text('d1'))).length, 1); + } finally { refusals.restore(); } + }); +}); + +test('a failed or incomplete refusal read adds no cleared line; only a complete read that finds none does', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f); refusals.set(refusals.refused('d1')); t.user(); + assert.equal(t.added(await t.request()).length, 1); + refusals.set('fail'); t.user(); assert.equal(t.added(await t.request()).length, 1, 'a failed read adds nothing'); + refusals.set({ complete: false, refusals: [] }); t.user(); + assert.ok(!t.added(await t.request()).some(([, text]) => text.includes(CLEARED)), 'an incomplete read adds no cleared line'); + // No cleared line while the last refusal delivered is not in this request. + refusals.set({ complete: true, refusals: [] }); + const other = conversation(f); other.user(); + assert.deepEqual(other.added(await other.request()), [], 'a request that does not hold the refusal has nothing to clear'); + t.user(); const last = t.last; + const done = t.added(await t.request()); + assert.deepEqual(done.at(-1), [last, CLEARED]); + } finally { refusals.restore(); } + }); +}); + +test('a tool call identifier reused in a later turn does not receive the earlier note', async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); + await f.after(writeEvent('docs/plans/search.md', 'w1')); t.user(); t.tool('write', 'First result', 'call_shared'); const first = t.last; + assert.deepEqual(t.added(await t.request()), [[first, HINT]]); + t.user(); t.tool('write', 'Second result', 'call_shared'); + assert.deepEqual(t.added(await t.request()), [[first, HINT]], 'the later result with the same identifier stays unchanged'); + // The same position and identifier with a different original output is a different carrier. + const edited = t.history.slice(); edited[first] = { ...edited[first], content: [{ ...edited[first].content[0], result: { type: 'content', value: [textPart('Another output')] } }] }; + const c = await t.request(true, false, edited); + assert.deepEqual(t.added(c, edited), [], 'the note belongs to the original output'); + }); +}); + +test('delivered notes are removed with the section and come back with it; only capture off clears the memory', async () => { + await fixture(async f => { + f.seed(); + const t = conversation(f); + await f.after(writeEvent('docs/plans/search.md', 'w1')); t.user(); t.tool(); const hinted = t.last; + assert.deepEqual(t.added(await t.request()), [[hinted, HINT]]); + // No report tool, a failed caller lookup: no section and no note, nothing lost. + t.user(); + const noTool = await t.request(false, false); assert.equal(parts(noTool).length, 0); assert.deepEqual(t.added(noTool), []); + f.lookup = async () => { throw new Error('lookup unavailable'); }; + const noCaller = await t.request(true, false); assert.equal(parts(noCaller).length, 0); assert.deepEqual(t.added(noCaller), []); + f.lookup = async (id: string) => f.info(id); + const back = await t.request(true, false); assert.equal(parts(back).length, 1); assert.deepEqual(t.added(back), [[hinted, HINT]], 'the note returns with the section'); + // A reused event that already carries notes loses them where the section goes. + const reused = await t.request(); assert.equal(t.added(reused).length, 1); + f.lookup = async () => { throw new Error('lookup unavailable'); }; await f.context(reused); f.lookup = async (id: string) => f.info(id); + assert.equal(parts(reused).length, 0); assert.deepEqual(t.added(reused), []); + // Capture off clears the memory: the note does not return when capture is on again. + f.store.setEnabled(false); const off = await t.request(true, false); assert.equal(parts(off).length, 0); assert.deepEqual(t.added(off), []); + f.store.setEnabled(true); const on = await t.request(true, false); assert.equal(parts(on).length, 1); assert.deepEqual(t.added(on), []); + }); +}); + +test('a user message identifier keeps its note across a shifted history; without one the position and content are the key', async () => { + for (const withId of [true, false]) await fixture(async f => { + f.seed(); + const t = conversation(f, withId); + t.user('First'); await f.after(writeEvent('docs/plans/search.md', 'w1')); t.user('Second'); const carrier = t.last; + assert.deepEqual(t.added(await t.request()), [[carrier, HINT]]); + t.user('Third'); + const shifted = [{ role: 'user', content: [textPart('Summary')] }, ...t.history]; + const c = await t.request(true, false, shifted); + assert.deepEqual(t.added(c, shifted), withId ? [[carrier + 1, HINT]] : []); + }); +}); + +test('memory is bounded: 128 sessions, 256 carriers and 128 KiB per session, absent carriers first', async () => { + await fixture(async f => { + f.seed(); + // Sessions: the least recently used loses its notes. + const sessions = Array.from({ length: 129 }, (_, i) => conversation(f, false, `ses_s${i}`)); + for (const [i, s] of sessions.entries()) { await f.after(writeEvent('docs/plans/search.md', `s${i}`, `ses_s${i}`)); s.user(); s.tool(); assert.equal(s.added(await s.request()).length, 1); } + assert.equal(sessions[1].added(await sessions[1].request(true, false)).length, 1); + assert.equal(sessions[128].added(await sessions[128].request(true, false)).length, 1); + assert.deepEqual(sessions[0].added(await sessions[0].request(true, false)), [], 'the least recently used session was evicted'); + // Carriers: 257 carried hints on one session keep 256, oldest first. + const t = conversation(f); + for (let i = 0; i < 257; i++) { await f.after(writeEvent('docs/plans/search.md', `c${i}`)); t.user(); const c = await t.request(true, false); assert.equal(t.added(c).at(-1)![0], t.last); } + const full = t.added(await t.request(true, false)); assert.equal(full.length, 256); + assert.ok(!full.some(([i]) => i === 0) && full.some(([i]) => i === 1), 'the first carrier lost its note'); + // A carrier absent from the latest request goes before older ones that are present. + const trimmed = t.history.slice(); trimmed[40] = { role: 'user', content: [textPart('Edited')] }; + await f.after(writeEvent('docs/plans/search.md', 'c-next')); const next = [...trimmed, { role: 'user', content: [textPart('Newest')] }]; + await t.request(true, false, next); + const extended = [...t.history, { role: 'user', content: [textPart('Newest')] }]; + const kept = t.added(await t.request(true, false, extended), extended).map(([i]) => i); + assert.ok(kept.includes(1), 'an older present carrier kept its note'); + assert.ok(!kept.includes(40), 'the absent carrier was evicted first'); + }); +}); + +test('memory is bounded to 128 KiB of note text per session, oldest first', async () => { + await fixture(async f => { + f.seed(); + const refusals = refusalReads(); + try { + const t = conversation(f), long = Array.from({ length: 30 }, (_, i) => `T${String(i).padStart(2, '0')}-${'x'.repeat(40)}`); + const sizes: number[] = [], carriers: number[] = []; + for (let i = 0; i < 80; i++) { + refusals.set(refusals.refused(`d${i}`, long)); t.user(); carriers.push(t.last); + const added = t.added(await t.request(true, false)); sizes.push(Buffer.byteLength(added.at(-1)![1])); + const total = added.reduce((n, [, text]) => n + Buffer.byteLength(text), 0); + assert.ok(total <= 128 * 1024, `note text stays within 128 KiB: ${total}`); + } + assert.ok(sizes.reduce((a, b) => a + b) > 128 * 1024 && Math.min(...sizes) > 1500, 'each refusal note is large enough to fill the bound'); + const final = t.added(await t.request(true, false)); + assert.ok(!final.some(([i]) => i === 0), 'the oldest note was evicted'); assert.ok(final.some(([i]) => i === t.last), 'the newest is kept'); assert.ok(final.some(([i]) => i === carriers[75]), 'recent notes stay in place on later requests'); + } finally { refusals.restore(); } }); }); diff --git a/tests/fixtures/activation-native-driver.ts b/tests/fixtures/activation-native-driver.ts index 8a0f3f3..4a209ff 100644 --- a/tests/fixtures/activation-native-driver.ts +++ b/tests/fixtures/activation-native-driver.ts @@ -130,8 +130,12 @@ try { const last = outgoing[index].prompt.at(-1); assert.equal(last.role, 'tool', `continuation ${index} ends with the tool message`); assert.ok(latestMessageTexts(outgoing[index].prompt).at(-1)!.endsWith(ACTIVATION_HINT), `hint is the end of the last tool result: ${index}`); - assert.equal(JSON.stringify(outgoing[index + 1].prompt.slice(0, outgoing[index].prompt.length)).includes(ACTIVATION_HINT), false, `the next request, rebuilt from history, no longer carries it: ${index}`); } + // A delivered note stays in place: each primary request begins with the previous one, byte for byte, notes included. + const encoded = (request: any) => request.prompt.map((message: any) => JSON.stringify(message)); + for (const index of [0, 1, 2, 3, 4]) assert.deepEqual(encoded(outgoing[index + 1]).slice(0, outgoing[index].prompt.length), encoded(outgoing[index]), `request ${index + 1} repeats request ${index} exactly`); + const hintedResults = (request: any) => request.prompt.filter((m: any) => m.role === 'tool' && JSON.stringify(m).includes(ACTIVATION_HINT)).length; + assert.deepEqual(outgoing.slice(0, 6).map(hintedResults), [0, 1, 2, 3, 3, 3], 'every hinted tool result is repeated on later requests; the failed write and the later continuation add none'); for (const request of childOutgoing) assert.equal(systemText(request).includes('# Agent progress (companion)'), false, 'hidden report tool receives no production instruction'); const parentContinuation = outgoing.slice(8); for (const text of parentContinuation.map(systemText)) { @@ -140,6 +144,10 @@ try { assert.equal(text, primary[0], 'the parent section is the same bytes after the child write'); } assert.deepEqual(parentContinuation.map(carried), [true, false], 'direct parent receives child write hint exactly once, on its next user message'); + assert.deepEqual(encoded(parentContinuation[1]).slice(0, parentContinuation[0].prompt.length), encoded(parentContinuation[0]), 'the next parent request repeats the user message with its hint'); + // The host's user messages: does each carry a message identifier, so a note on one keeps that key when the history shifts? + const hostUserMessagesCarryId = contexts.flatMap(e => e.messageIds).filter(([role]: [string, boolean]) => role === 'user').every(([, hasId]: [string, boolean]) => hasId); + console.log('host-user-message-ids', hostUserMessagesCarryId); assert.equal((await client.session.get({sessionID:childSession.id})).parentID, session.id); console.log('native-shapes', JSON.stringify([...after, ...childAfter].map(e => ({ tool: e.tool, status: e.status })))); console.log('effective-tools', JSON.stringify({primary:contexts[0].tools, restrictedChild:hidden.tools})); diff --git a/tests/fixtures/activation-observer.ts b/tests/fixtures/activation-observer.ts index 4ce65cc..c499142 100644 --- a/tests/fixtures/activation-observer.ts +++ b/tests/fixtures/activation-observer.ts @@ -21,7 +21,7 @@ export default Plugin.define({ id: 'activation-observer-fixture', async setup(ct let progress; try { progress = Object.fromEntries(['plans', 'revisions', 'receipts', 'sessions', 'chunks', 'captures', 'contributions'].map(table => [table, store.db.prepare(`SELECT count(*) AS n FROM ${table}`).get()!.n])); } finally { store.close(); } - record({ type: 'context', sessionID: event.sessionID, agent: event.agent, tools: Object.keys(event.tools), system: event.system, progress }); + record({ type: 'context', sessionID: event.sessionID, agent: event.agent, tools: Object.keys(event.tools), system: event.system, messageIds: event.messages.map((m: any) => [m.role, typeof m.id === 'string']), progress }); }); await ctx.tool.hook('execute.after', (event: any) => { // All inputs here are fixture-authored. Never ship this observer or transcript capture. diff --git a/tests/fixtures/activation-production.ts b/tests/fixtures/activation-production.ts index 965cd7e..980920f 100644 --- a/tests/fixtures/activation-production.ts +++ b/tests/fixtures/activation-production.ts @@ -84,9 +84,11 @@ export async function activationFixture(run: (fixture: any) => Promise, ve } } -export const activationContext = (sessionID = 'ses_M', available = true): any => ({ sessionID, agent: 'coordinator-x', model: { providerID: 'fixture', id: 'script' }, system: [{ type: 'text', text: 'Other system section' }], messages: [{ role: 'user', content: [{ type: 'text', text: 'Make a plan' }] }], tools: available ? { agent_progress_report: { description: 'fixture', input: {} } } : {}, options: { temperature: 0.2 } }); +let turns = 0; +/** Each call is a new conversation turn: a distinct user message, so delivered notes of an earlier call stay with that call's own message. */ +export const activationContext = (sessionID = 'ses_M', available = true): any => ({ sessionID, agent: 'coordinator-x', model: { providerID: 'fixture', id: 'script' }, system: [{ type: 'text', text: 'Other system section' }], messages: [{ role: 'user', content: [{ type: 'text', text: `Make a plan (turn ${++turns})` }] }], tools: available ? { agent_progress_report: { description: 'fixture', input: {} } } : {}, options: { temperature: 0.2 } }); /** - * Text the companion added to the latest message for this request only: every + * Text the companion added to the latest message of this request: every * text part after the original content of a user message, or the parts appended * to the content of the last tool result of a tool message. Empty when nothing * was added. diff --git a/tests/fixtures/latest-message-text.ts b/tests/fixtures/latest-message-text.ts index 3c9694f..1bed8fe 100644 --- a/tests/fixtures/latest-message-text.ts +++ b/tests/fixtures/latest-message-text.ts @@ -1,6 +1,6 @@ /** * Text carried by the latest message of an outgoing provider prompt. The - * companion adds its request-only notes there (a text part on a user message, + * companion adds a context note there when it delivers it (a text part on a user message, * the output of the last tool result on a tool message) and keeps its system * section fixed. Native observers use this to find those notes. */ @@ -14,3 +14,8 @@ export function latestMessageTexts(prompt: any[] | undefined): string[] { const result = message.content.findLast((part: any) => part?.type === 'tool-result'); return texts(result?.output?.value); } + +/** Text of every user message and tool result in an outgoing prompt, notes that stayed in place included. */ +export function allMessageTexts(prompt: any[] | undefined): string[] { + return (prompt ?? []).flatMap((_, i, messages) => latestMessageTexts(messages.slice(0, i + 1))); +} diff --git a/tests/fixtures/subagent-activity-observer.ts b/tests/fixtures/subagent-activity-observer.ts index c5da9d8..243611b 100644 --- a/tests/fixtures/subagent-activity-observer.ts +++ b/tests/fixtures/subagent-activity-observer.ts @@ -2,7 +2,7 @@ import { Model, Provider, Plugin } from '@opencode/plugin'; import fs from 'node:fs'; import { identifier } from '../../shared/progress.ts'; -import { latestMessageTexts } from './latest-message-text.ts'; +import { allMessageTexts } from './latest-message-text.ts'; export default Plugin.define({ id: 'subagent-activity-probe', async setup(ctx) { const root = process.env.ACTIVITY_ROOT!; @@ -125,8 +125,8 @@ export default Plugin.define({ id: 'subagent-activity-probe', async setup(ctx) { if (!seen.has(key) && session.agent === 'nested-worker') calls = [{ id: 'nested', input: { agent: 'restricted-worker', description: 'Synthetic nested child', prompt: 'Synthetic fixed probe.' } }]; if(!seen.has(key)&&!job&&session.agent==='reporting-worker')calls=jobs.firstReportingCall?[jobs.firstReportingCall]:[{id:'child-handoff',tool:'agent_progress_report',input:{op:'handoff',oid:'native-claim',summary:'Synthetic child reports its bounded work complete.',outcome:'done'}}]; seen.add(key); - // Request-only notes ride the latest message; the system section stays fixed. - const system=[...options.prompt.filter((m:any)=>m.role==='system'&&typeof m.content==='string').map((m:any)=>m.content),...latestMessageTexts(options.prompt)].join('\n'); + // Context notes ride the message they were delivered on and stay there on later requests; the system section stays fixed. + const system=[...options.prompt.filter((m:any)=>m.role==='system'&&typeof m.content==='string').map((m:any)=>m.content),...allMessageTexts(options.prompt)].join('\n'); const assignedBrief=system.includes('Assigned-only scope:'); record({ type: 'dispatch', sessionID: identity, agent: session.agent, calls: calls?.map((c: any) => c.id) ?? [], assignedBrief, waitingForReport:job?.waitForReport, refusalHint:system.includes('## Delegation not applied'), refusalIdentity:system.includes('Plan "parallel-reporting", declaration "native-conflict"')&&system.includes('tasks ["task-c"]: not applied because'), refusalRecovery:system.includes('re-declare at the current revision')&&system.includes('explicitly link'), hold: job?.hold === true, fault: job?.fault === true }); if(job?.waitForReport){ From 10bf7ebe73d443e4408867084419b7c2ed34fdc3 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Wed, 18 Nov 2026 22:08:08 +1100 Subject: [PATCH 08/11] fix(ui): keep cleanup repaints and focus moves from disturbing the person (#168) * fix(ui): keep cleanup repaints and focus moves from disturbing the person A count that finishes by itself, a Tidy run's progress and the end of a run now repaint as background data, so they wait for a held control or an open picker instead of replacing it. A refresh no longer expires a result that has not been painted yet. A deferred focus move is decided when it is applied and is dropped once focus is anywhere other than the control it was queued from. * fix(ui): judge a deferred focus move from the control that had focus before the paint The recheck read the focused element after the paint had replaced the root, so a rebuilt control such as Undo looked like no focus and lost it to Tidy or Cancel. Emptiness and identity are now taken before the root is replaced. forgetPlans keeps its dev signature and no longer bumps a version; each caller picks the repaint lane. The harness replaces a focused control on every paint, and the rendered driver checks that focus on Undo survives the return of Tidy. --- docs/contracts.md | 12 +- docs/ui.md | 4 +- openspec/changes/release-1-5-2/tasks.md | 8 +- tests/browser/cleanup-tidy-controller.test.ts | 227 +++++++++++++++++- tests/browser/cleanup-tidy-qa.ts | 21 ++ ui/shared/app.ts | 62 +++-- 6 files changed, 301 insertions(+), 33 deletions(-) diff --git a/docs/contracts.md b/docs/contracts.md index b179734..04726c8 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1255,9 +1255,11 @@ Requests run sequentially; a refused/changed or unconfirmed plan is not retried automatically. Stop and a change of account, store/binding or board reading end the run after the in-flight request. One progress line shows completed/total counts; start and result are announced once, not per plan. One final -invalidation/re-read reconciles the result, including uncertain failures. Only -validated receipts count as completed. A plan the service refused (changed, -closed, reused operation, not found, store busy) and a plan the run did not send +invalidation/re-read reconciles the result, including uncertain failures, +unless an account, store or binding change was observed during the run: a run +that ends after such a change shows no result and changes nothing on the board +shown then. Only validated receipts count as completed. A plan the service +refused (changed, closed, reused operation, not found, store busy) and a plan the run did not send (left out of the view before sending, or after Stop) are reported as skipped. A plan whose attempted request got no valid answer (a lost reply, a connection or host failure, an unreadable receipt, or an attempt that failed before the service @@ -1270,8 +1272,8 @@ fresh operation ID. It never widens to other archived plans. Changed or refused restores are reported, not treated as success. Archive and Undo preserve lifecycle, counts, report history and copied documents. Delete offers no Undo. The result and Undo survive the action's reconciliation read and remain until -the next action or refresh, not a timer. Other surfaces converge through their -existing refresh cadence; no polling loop or new stored state is introduced. +the next action or refresh after they were shown, not a timer. Other surfaces +converge through their existing refresh cadence; no polling loop or new stored state is introduced. Authenticated, query-free **POST** `/v1/plan/archive`, `/v1/plan/restore`, and `/v1/plan/delete` accept only this JSON body (identifiers use the existing80-character diff --git a/docs/ui.md b/docs/ui.md index b7b3692..5097a29 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -992,7 +992,7 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Branch counts.** Both group and task-parent plan-order summaries keep full descendant done/total and in-progress/blocked totals separate from tasks hidden by filters, tasks shown for context and tasks folded by a closed disclosure. Closed-plan aggregates say "Last reported". The muted summary text updates when the native disclosure opens or closes; folded tasks exclude those already hidden by filters. - **Reading-owned explanations.** All reading ⓘ disclosures, including About sub-agent records, survive benign same-reading repaints but retire with the reading. Returning to a prior session/plan does not reopen them; detached old callbacks cannot restore their state. - **Popup keyboard ownership.** Menu/listbox arrow-key selection is not changed by a pointer boundary event caused by layout or scrolling under a stationary pointer. Actual pointer movement restores hover selection; pointer activation remains available. -- **Pointer activation.** Background paints preserve a pressed control through pointer release and native click delivery. Pointer capture delivers releases outside the guest iframe; release outside the control cancels activation. Cancellation, capture loss or window blur releases the deferral without a timer. Navigation, authority changes and explicit UI actions still retire immediately; map-background drags keep their own live repaint/capture path. +- **Pointer activation.** Background paints preserve a pressed control through pointer release and native click delivery. Pointer capture delivers releases outside the guest iframe; release outside the control cancels activation. Cancellation, capture loss or window blur releases the deferral without a timer. Navigation, authority changes and explicit UI actions still retire immediately; a cleanup count that finishes by itself and a Tidy run's own progress and end are background paints, so they wait for a held control or an open picker too (see Tidy result and Undo); map-background drags keep their own live repaint/capture path. - **Reading expanded facts.** When a task's expanded facts cross the top of the viewport, preserve that facts body's offset rather than anchoring the following task. Changing prerequisite-body height must not scroll the facts being read out of view. - **Jumps.** "Jump to in progress (n)" and "Jump to blocked (n)" ("Jump to reported …" on closed plans) cover every reported working/blocked task of the whole plan in hierarchy order, whatever order or filter is shown. Repeated activation advances and wraps, announced in the task view's status line ("In progress 2 of 5: "); a removed last target restarts at the first. With no target the button is disabled and says so ("No blocked tasks"). - Jumps, prerequisite and Unlocks links, History's View current task and search task hits share one navigation path. It acts only inside the current plan article (same plan, source and revision), opens the row's Done/Skipped fold (recorded in the reading) and ancestors, focuses the canonical row (`tabindex=-1`, focus ring) and scrolls it into view once, instantly. A button from a replaced paint does nothing; a missing target shows a local notice. @@ -1020,7 +1020,7 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Keyboard order.** Tidy precedes the selection bar, which precedes confirmation/result actions. Outside Select mode this gives Tidy → Select → Undo when an archive result is shown. In Select mode, Done and Select all come first; when plans remain selected, Archive/Restore, Delete permanently… and Clear follow, then Undo. The count is a live status, not a Tab stop. - **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: in a searched or truncated scope, on a service that offers `planTaskSearch:1`, their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle, except where search or session criteria apply, where the point lookup skips it as changed. A complete browse list uses the loaded rows instead, and an older service counts a truncated browse scope by list scan. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. - **Unsupported in-progress plans.** Archive/Delete counting excludes these plans before applying the 1,000-target ceiling, in loaded selections and scans alike. Their distinct-plan warning count is separate from eligible targets; they still consume scan slots/windows, so a scan that has not reached eligible plans offers Check more rather than an empty terminal target ceiling. -- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A plan the service refuses (changed, closed, reused operation, not found, store busy) is skipped; a plan whose attempted request gets no valid answer is unconfirmed; neither is retried automatically. Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. One final invalidation and authoritative re-read reconciles the run, including uncertain failures, unless an account, store or binding change was observed during the run: then the run touches nothing on the board shown and shows no result. The result is one sentence stating completed, skipped and unconfirmed counts apart: an unconfirmed plan "could not be confirmed and may have been" archived, restored or deleted, and a plan the run did not send (left out of the view before sending, or after Stop) is skipped, never unconfirmed. It offers Undo for precisely the successful archive receipts, and Try again recounting the skipped and unconfirmed plans together, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; an unconfirmed plan has no receipt and is not restored by it, and if its archive was applied it can be restored on its own once an Archived plans list or search shows it (the reconciliation read is not promised to). After a partial Undo, Try again does not recount: it sends the restore again for exactly the remaining plans, each bound to its archive receipt, so a restore that was in fact applied is confirmed from the receipt the service saved and not repeated, and a plan another cleanup changed since is refused and reported as skipped; unsuccessful restores are reported and changed plans stay untouched. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer. Stop and Undo are keyboard reachable; focus returns to Tidy only when the activated control disappears and still owns focus, never from another control or frame. Likewise a count that finishes in the background gives focus back to Cancel only if the panel still owns focus or its focused control was removed; someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. +- **Tidy result and Undo.** The shared run engine sends one existing per-plan request at a time, bound to the captured progress revision and cleanup generation. A plan the service refuses (changed, closed, reused operation, not found, store busy) is skipped; a plan whose attempted request gets no valid answer is unconfirmed; neither is retried automatically. Stop ends after the in-flight request, as does an account, store/binding or board-reading change. One line shows completed/total progress and Stop; start and result are announced once, never per plan. The progress line and the end of the run, with its result line and the selection changes its receipts cause, are background paints: they wait while a control is held or a picker is open, so a press on Stop is not lost to a progress update and the run's last reply does not replace a held control. Only the paint waits: the run, the release of its busy state, the cache invalidation and the reconciliation read happen when the last reply arrives. Starting a run, Undo, Try again, opening Tidy, Cancel, Check more and the confirm buttons are explicit actions and repaint at once; Stop only ends the run after the request in flight, and the end of the run paints as above. One final invalidation and authoritative re-read reconciles the run, including uncertain failures, unless an account, store or binding change was observed during the run: then the run touches nothing on the board shown and shows no result. That invalidation retires the controls of the board whose data it invalidated, as every cache reset does, so a board control such as Filters that was held at that moment stays in place but ignores that click. The result is one sentence stating completed, skipped and unconfirmed counts apart: an unconfirmed plan "could not be confirmed and may have been" archived, restored or deleted, and a plan the run did not send (left out of the view before sending, or after Stop) is skipped, never unconfirmed. It offers Undo for precisely the successful archive receipts, and Try again recounting the skipped and unconfirmed plans together, with their current revisions and eligibility, before asking for confirmation again (never the whole scope or plans that began matching since). Undo uses each receipt's returned generation; an unconfirmed plan has no receipt and is not restored by it, and if its archive was applied it can be restored on its own once an Archived plans list or search shows it (the reconciliation read is not promised to). After a partial Undo, Try again does not recount: it sends the restore again for exactly the remaining plans, each bound to its archive receipt, so a restore that was in fact applied is confirmed from the receipt the service saved and not repeated, and a plan another cleanup changed since is refused and reported as skipped; unsuccessful restores are reported and changed plans stay untouched. Archive and Undo preserve lifecycle, counts and history. Delete offers no Undo. The result survives its own reconciliation read, then lasts until the next action or refresh, not a timer; a refresh does not expire a result that has not been painted yet, so a hold that outlasts it loses neither the result line, its unconfirmed warning nor Undo, and the refresh after the paint expires it. Stop and Undo are keyboard reachable. A focus move that cleanup defers (to Tidy after a run that ended while Stop had focus, to Cancel after a count) is decided when it is applied, at every paint until then: it happens only while focus is still on the control the move was queued from, or on no control because that control was removed. Once the person has focused anything else, in the cleanup panel (Undo, while the Tidy button is still absent) or outside it, the move is dropped and is not kept for a later paint, as it is when another frame has focus. Someone who moved to Search keeps typing. The result uses one stable polite live region, not repeated announcements on repaint. Copy ships together in English, Russian and Simplified Chinese. - **Archived plans** is a page-level view above filters, including when ordinary results are empty. It uses the existing list/detail/document/history views. **Restore** preserves the plan's lifecycle and history, including an archived in-progress plan, which accepts reports again after restoration. More offers Restore and Delete permanently for archived plans of any lifecycle (in-progress deletion requires the service capability). Switching Current/Archived plans resets filters and selection so archived work is discoverable. - **Delete permanently…** is a separate per-plan action for a visible closed plan or any archived plan (in-progress deletion requires `planCleanupActive:1`). It opens an inline confirmation (not a modal) naming the plan and explaining deletion of stored tasks/history/copied document, preservation of the original file, irreversibility, the minimal replay guard and non-secure-erasure/recovery-backup limits. Nothing is sent on open or Cancel. The confirmation opens below the plan and is scrolled into view once; Cancel receives focus; Enter there cancels, Escape cancels, and focus returns to the opener (the ⋯ trigger, or the Delete permanently… button where the buttons are shown). The destructive button requires its own activation. Pending controls are disabled and the controller rejects duplicate submissions. - **Binding.** The confirmation captures store/source/plan, current progress revision and cleanup generation. Context, integration account/store, selection or revision changes invalidate it. A retired confirmation callback cannot act on a newer dialog. The controller checks eligibility and binding again before the POST; the server remains authoritative. The busy state belongs to the request that set it, in a bulk run and in a single-plan action alike. An integration account change the host announced, or a store or binding change a list reply showed, releases it, so the new board's cleanup controls work at once while an earlier request is still held; the late answer of that request can neither complete, release nor reset a newer one, also after a switch away and back to the same account and store, which comparing the two identities would read as no change. A store change with no account change is observed with a list reply; list reads pause while a bulk run keeps its panel, so one is then first observed by the read after the run, and they resume when a filter or search change ends that panel. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index 12ef979..6257201 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -21,10 +21,10 @@ Each numbered group is one pull request into the development branch. It carries ## 3. Background updates and focus -- [ ] 3.1 Repaint a count that finishes by itself, its failure and the end of a Check more continuation through the background lane; keep explicit actions on the immediate lane. Test: a count finishing during a press on an unrelated control leaves that control in place until its click. -- [ ] 3.2 Repaint run progress, and the end of a run with its result line, through the background lane, without delaying the release of the busy state, the cache invalidation or the reconciliation read. Do not let a refresh expire a result that has not been painted yet. Test: a receipt arriving during a press on Stop leaves Stop in place, and the run stops after the request in flight; the run's last reply arriving during a press on an unrelated control leaves that control in place while it is held, while the reconciliation read is sent; a hold that lasts past the next refresh still ends with the result line and Undo painted. Do not assert that a held board control such as Filters acts on that click: the cache invalidation retires it. -- [ ] 3.3 Decide a deferred cleanup focus move when it is applied: apply it only if focus is still on the control the move was queued from, or is on no control because that control was removed, and drop it otherwise, also when focus moved to another control of the cleanup panel. Test: focus moved to Search before the Tidy button reappears stays in Search; focus moved to Undo before the Tidy button reappears stays on Undo while Undo is shown, and the dropped move is not applied after the result expires; focus left on Stop moves to Tidy; a count delayed by a held control does not take focus back. -- [ ] 3.4 Update the result, focus and controller repaint statements of `docs/ui.md`. Run the cleanup rendered driver's keyboard pass at desktop width and 390 px, the root and interface typechecks and the browser logic tests. +- [x] 3.1 Repaint a count that finishes by itself, its failure and the end of a Check more continuation through the background lane; keep explicit actions on the immediate lane. Test: a count finishing during a press on an unrelated control leaves that control in place until its click. +- [x] 3.2 Repaint run progress, and the end of a run with its result line, through the background lane, without delaying the release of the busy state, the cache invalidation or the reconciliation read. Do not let a refresh expire a result that has not been painted yet. Test: a receipt arriving during a press on Stop leaves Stop in place, and the run stops after the request in flight; the run's last reply arriving during a press on an unrelated control leaves that control in place while it is held, while the reconciliation read is sent; a hold that lasts past the next refresh still ends with the result line and Undo painted. Do not assert that a held board control such as Filters acts on that click: the cache invalidation retires it. +- [x] 3.3 Decide a deferred cleanup focus move when it is applied: apply it only if focus is still on the control the move was queued from, or is on no control because that control was removed, and drop it otherwise, also when focus moved to another control of the cleanup panel. Test: focus moved to Search before the Tidy button reappears stays in Search; focus moved to Undo before the Tidy button reappears stays on Undo while Undo is shown, and the dropped move is not applied after the result expires; focus left on Stop moves to Tidy; a count delayed by a held control does not take focus back. +- [x] 3.4 Update the result, focus and controller repaint statements of `docs/ui.md`. Run the cleanup rendered driver's keyboard pass at desktop width and 390 px, the root and interface typechecks and the browser logic tests. ## 4. Unconfirmed results diff --git a/tests/browser/cleanup-tidy-controller.test.ts b/tests/browser/cleanup-tidy-controller.test.ts index cf201ff..5fed69f 100644 --- a/tests/browser/cleanup-tidy-controller.test.ts +++ b/tests/browser/cleanup-tidy-controller.test.ts @@ -62,6 +62,10 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa replaceChildren(node: Node) { this.children = [node]; } } const mount = new Node(); + let popupOpen = false; + const nativeQueryAll = mount.querySelectorAll.bind(mount); + mount.querySelectorAll = ((selector?: string) => popupOpen && selector?.includes('aria-haspopup') ? [{ closest: () => null }] : nativeQueryAll()) as typeof mount.querySelectorAll; + const frames: (() => void)[] = []; const document = { documentElement: new Node(), head: new Node(), body: new Node(), visibilityState: 'visible', get activeElement() { return focused; }, hasFocus: () => ownsFrame, scrollingElement: { scrollTop: 0 }, getElementById: (id: string) => id === 'root' ? mount : {}, addEventListener(type: string, fn: (e: unknown) => void) { docListeners[type] = fn; } }; const plans = opts.plans ?? [summary('one', [], { lifecycle: active ? 'active' : 'finished' }), summary('two', [], { lifecycle: 'cancelled' })]; const feed = opts.live ? liveFeed(opts.live) : null; @@ -109,7 +113,7 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa const exports: any = {}; runInNewContext(APP, { exports, document, AbortController, crypto: globalThis.crypto, queueMicrotask, performance, console, - setTimeout: () => 1, clearTimeout() {}, + setTimeout: () => 1, clearTimeout() {}, requestAnimationFrame: (fn: () => void) => frames.push(fn), window: { addEventListener: (key: string, fn: any) => { listeners[key] = fn; } }, require: (name: string) => ({ ...appCountsModules, @@ -132,7 +136,12 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa return { plans: offset === 0 ? c.read!.plans.slice(0, 1) : offset === 2000 ? c.read!.plans.slice(1) : [], visited: 50, nextCursor: offset === 2000 ? null : String(offset + 50) }; }) : undefined, - wantProjects: () => [], wantDetails: () => [], ...extra, paint: (root, c) => { vc = c; (extra as any).paint?.(root, c); }, + wantProjects: () => [], wantDetails: () => [], ...extra, paint: (root, c) => { + vc = c; (extra as any).paint?.(root, c); + // A rebuilt control is replaced by a new node that takes focus back; the old one is detached, as in the browser. + const before = focused as { isConnected: boolean; rebuild?: () => unknown } | null; + if (before?.rebuild) { before.isConnected = false; focused = before.rebuild(); } + }, }; exports.startView(spec); listeners.ready({ session: { id: S.M }, directory: '/fixture', connection: { connected: true, account: 'example' }, features: { deviceStorage: true }, locale: 'en', surface, settings: {}, item: opts.item ?? null, theme: {} }); @@ -149,7 +158,13 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa const node = { focused: 0, tagName: 'BUTTON', focus() { node.focused++; }, querySelector: () => null }; focusables.set(`[data-testid="${id}"]`, node); return node; }, + /** The control is no longer painted: its marker is gone, so a focus request for it finds nothing. */ + absent(id: string) { focusables.delete(`[data-testid="${id}"]`); }, focusAt(element: unknown) { focused = element; }, + /** The pointer is lifted: the press ends and the paint it held can run. */ + releasePress() { docListeners.pointercancel({ type: 'pointercancel' }); for (const next of frames.splice(0)) next(); }, + /** A picker is open (or closed): background paints wait for it. */ + popup(on: boolean) { popupOpen = on; }, ownsFocus(on: boolean) { ownsFrame = on; }, normalizeScope(value: string) { effectiveScope = value; }, hold() { holds++; }, @@ -1209,3 +1224,211 @@ test('a later equal list read replaces the facts a failed read granted, after a assert.equal(await refusesCleanup(f), true); } finally { f.stop(); } }); + +// Background cleanup updates and deferred focus moves. A press is simulated with `press` and ended with `releasePress`; +// a paint is counted through the spec's paint hook, so "the control is not replaced" is "no paint ran". +/** + * The focused element as the controller reads it: the test id of its owner and whether it sits in the cleanup panel. + * `rebuilt`: a control every paint replaces (Search, Undo): the old node is detached and a new one holds focus. + */ +const control = (id: string, rebuilt = true) => { + const node: { isConnected: boolean; closest: (selector: string) => unknown; rebuild?: () => unknown } = { + isConnected: true, + closest: (selector: string) => selector === '[data-testid]' ? { dataset: { testid: id } } + : selector === `[data-testid="${id}"]` || selector === '[data-testid="tidy-actions"]' && id.startsWith('tidy-') ? {} : null, + }; + if (rebuilt) node.rebuild = () => control(id); + return node; +}; +const pressing = () => ({ closest: () => ({}), isConnected: true, setPointerCapture() {} }); +const threePlans = () => [summary('one', [], { lifecycle: 'finished' }), summary('two', [], { lifecycle: 'cancelled' }), summary('three', [], { lifecycle: 'finished' })]; +function countedScan() { + let release!: () => void; + const held = new Promise<void>(r => { release = r; }); + const paints = { n: 0 }; + const extra = { + tidyScan: (c: any, key: string) => new cleanup.CleanupScan(key, c.read.storeId, false, async () => { await held; return { plans: c.read.plans, visited: 1, nextCursor: null }; }), + paint: () => { paints.n++; }, + } as Partial<ViewSpec<any>>; + return { release: () => release(), paints, extra }; +} + +test('a count that finishes during a press does not replace the pressed control', async () => { + const scan = countedScan(); + const f = frame('page', false, false, true, scan.extra); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); + f.press(pressing()); + const before = scan.paints.n; + scan.release(); await drain(); + assert.equal(scan.paints.n, before, 'the finished count waits for the press'); + f.releasePress(); await drain(); + assert.ok(scan.paints.n > before, 'the count line is painted once the press is over'); + assert.ok(f.vc.cleanup.tidy?.confirmation, 'the count is shown'); + } finally { f.stop(); } +}); + +test('a count that fails during a press waits for it too, and pressing Cancel while counting still paints at once', async () => { + const paints = { n: 0 }; + let fail!: () => void; + const held = new Promise<void>((_, reject) => { fail = () => reject(new Error('storage')); }); + const f = frame('page', false, false, true, { + tidyScan: (c: any, key: string) => new cleanup.CleanupScan(key, c.read.storeId, false, async () => { await held; return { plans: [], visited: 0, nextCursor: null }; }), + paint: () => { paints.n++; }, + }); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); + f.press(pressing()); + const before = paints.n; + fail(); await drain(); + assert.equal(paints.n, before, 'the failed count waits for the press'); + f.releasePress(); await drain(); + assert.ok(paints.n > before); + assert.equal(f.vc.cleanup.tidy?.countFailed, true); + } finally { f.stop(); } +}); + +test('Cancel while a count is running repaints at once, with another control pressed', async () => { + const scan = countedScan(); + const f = frame('page', false, false, true, scan.extra); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); + f.press(pressing()); + const before = scan.paints.n; + f.vc.cancelTidy(); await drain(); + assert.ok(scan.paints.n > before, 'an explicit action is not held'); + } finally { f.stop(); } +}); + +test('a receipt arriving during a press on Stop does not replace Stop, and the run stops after the request in flight', async () => { + const paints = { n: 0 }; + const f = frame('page', false, false, true, { ...boardSpy().extra, paint: () => { paints.n++; } }, { plans: threePlans() }); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); f.hold(); f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 1); await drain(); + const stop = f.vc.stopTidy; + f.press(pressing()); + const before = paints.n; + f.release(); await until(() => f.posts.length === 2); await drain(); + assert.equal(paints.n, before, 'the progress update waits for the press'); + stop(); f.releasePress(); + f.release(); await drain(); + assert.equal(f.posts.length, 2, 'no request is sent after the one in flight'); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2); + } finally { f.stop(); } +}); + +/** A two-plan run whose last reply arrives while an unrelated control is pressed (or a picker is open). */ +async function lastReplyHeld(f: Held, hold: () => void) { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); f.hold(); f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 1); f.release(); await until(() => f.posts.length === 2); await drain(); + hold(); + const lists = f.lists; + f.release(); await until(() => f.lists > lists); +} + +test('the last reply of a run arriving during a press leaves the pressed control, sends the reconciliation read and paints the result after the press', async () => { + const paints = { n: 0 }; + const f = frame('page', false, false, true, { ...boardSpy().extra, paint: () => { paints.n++; } }); + try { + let before = 0; + await lastReplyHeld(f, () => { f.press(pressing()); before = paints.n; }); + await drain(); + assert.equal(paints.n, before, 'the run end waits for the press'); + assert.equal(f.vc.cleanup.pending, true, 'the painted state is still the one before the run ended'); + f.releasePress(); await drain(); + assert.ok(paints.n > before); + assert.equal(f.vc.cleanup.pending, false); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2, 'the result line is painted after the press'); + } finally { f.stop(); } +}); + +for (const hold of ['press', 'picker'] as const) test(`a hold that lasts past the next refresh does not lose the result (${hold})`, async () => { + const paints = { n: 0 }; + const f = frame('page', false, false, true, { ...boardSpy().extra, paint: () => { paints.n++; } }); + try { + let before = 0; + await lastReplyHeld(f, () => { if (hold === 'press') f.press(pressing()); else f.popup(true); before = paints.n; }); + await drain(); + f.vc.retry(); await drain(); + f.vc.retry(); await drain(); + assert.equal(paints.n, before, 'the refresh neither expires the result nor repaints around the hold'); + if (hold === 'press') f.releasePress(); else { f.popup(false); f.vc.invalidate(); } + await drain(); + assert.equal(f.vc.cleanup.tidy?.result?.succeeded.length, 2, 'the result is painted after the hold'); + f.vc.retry(); await drain(); + assert.equal(f.vc.cleanup.tidy, undefined, 'the refresh after that paint expires it'); + } finally { f.stop(); } +}); + +/** A run whose last receipt arrives while focus is on Stop and whose reconciliation read is held, so Tidy is absent. */ +async function endedOnStop(f: Held) { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 1); + f.focusAt(control('tidy-stop', false)); + f.holdHealth(); f.release(); + await until(() => f.vc.cleanup.tidy?.result !== undefined && !f.vc.cleanup.pending); + await drain(); +} +const finishRead = async (f: Held) => { f.releaseHealth(); await until(() => !!f.vc.read); await drain(); }; + +test('focus left on Stop moves to the Tidy button when it reappears', async () => { + const f = frame('page'); + try { + await endedOnStop(f); + f.focusAt(null); // the removed Stop took focus with it + const tidy = f.focusable('tidy-open'); + await finishRead(f); + assert.equal(tidy.focused, 1); + } finally { f.stop(); } +}); + +test('focus moved elsewhere before the Tidy button returns stays there', async () => { + const f = frame('page'); + try { + await endedOnStop(f); + f.focusAt(control('search')); + const tidy = f.focusable('tidy-open'); + await finishRead(f); + f.vc.invalidate(); await drain(); + assert.equal(tidy.focused, 0, 'neither the paint that brings the button back nor a later one takes focus'); + } finally { f.stop(); } +}); + +test('focus moved to Undo before the Tidy button returns stays there, also after the result expires', async () => { + const f = frame('page'); + try { + await endedOnStop(f); + f.focusAt(control('tidy-undo')); // inside the cleanup panel, but not the control the move was queued from + const tidy = f.focusable('tidy-open'); + await finishRead(f); + assert.equal(tidy.focused, 0); + f.vc.retry(); await drain(); + assert.equal(f.vc.cleanup.tidy, undefined, 'the result has expired'); + f.vc.invalidate(); await drain(); + assert.equal(tidy.focused, 0, 'the dropped move is not applied after Undo is gone'); + } finally { f.stop(); } +}); + +for (const moved of [false, true]) test(`a count delayed by a held control ${moved ? 'does not take focus back after focus moved' : 'still moves focus to Cancel when focus stayed'}`, async () => { + const scan = countedScan(); + const f = frame('page', false, false, true, scan.extra); + try { + await until(() => !!f.vc?.read); + const cancel = f.focusable('tidy-cancel'); + f.vc.requestTidy(); await drain(); + f.focusAt(control('tidy-cancel')); + const opened = cancel.focused; + f.press(pressing()); + scan.release(); await drain(); + if (moved) f.focusAt(control('search')); + f.releasePress(); await drain(); + assert.equal(cancel.focused, opened + (moved ? 0 : 1)); + } finally { f.stop(); } +}); diff --git a/tests/browser/cleanup-tidy-qa.ts b/tests/browser/cleanup-tidy-qa.ts index 4367ce5..7ddcc45 100644 --- a/tests/browser/cleanup-tidy-qa.ts +++ b/tests/browser/cleanup-tidy-qa.ts @@ -249,6 +249,27 @@ try { await evaluate(`qa.release('tidy-stop');true`); await wait('page', `!!d.querySelector('[data-testid="tidy-result"]')?.textContent.includes('skipped')`); check('stop-after-inflight-only', await posts() === stopPosts + 1); + // Focus was on Stop when the run ended and nothing else took it: it returns to Tidy once the board is read again. + await wait('page', `!!d.querySelector('[data-testid="tidy-open"] button') && !!d.activeElement?.closest('[data-testid="tidy-open"]')`); + check('stop-focus-returns-to-tidy', true); + // The person moves on while the board is read again: focus must stay put when Tidy comes back. + // (The search box is not painted while the board is read again, so only Undo can take focus then.) + for (const [name, target] of [['undo', '[data-testid="tidy-undo"] button']] as const) { + await open('page'); + await evaluate(`qa.holds.push({tag:'stop-${name}',kind:'service',surface:'page',path:'/v1/plan/archive'});true`); + await click('page', '[data-testid="tidy-confirm-archive"] button'); + await wait('page', `qa.held.some(h=>h.tag==='stop-${name}') && !!d.querySelector('[data-testid="tidy-stop"] button')`); + await click('page', '[data-testid="tidy-stop"] button'); + await evaluate(`qa.holds.push({tag:'read-${name}',kind:'service',surface:'page',path:'/v1/plans'});qa.release('stop-${name}');true`); + await wait('page', `!!d.querySelector('[data-testid="tidy-undo"] button') && qa.held.some(h=>h.tag==='read-${name}') && !d.querySelector('[data-testid="tidy-open"]')`); + await guest('page', `const n=d.querySelector(${js(target)});if(!n)throw Error('Missing '+${js(name)}+': '+d.body.innerText.slice(0,300));n.focus();return true`); + await evaluate(`qa.release('read-${name}');true`); + await wait('page', `!!d.querySelector('[data-testid="tidy-open"] button')`); + await evaluate(`new Promise(r=>setTimeout(r,500))`); + check(`stop-then-${name}-keeps-focus`, await guest('page', `return !!d.activeElement?.closest(${js(target)}) && !d.activeElement.closest('[data-testid="tidy-open"]')`)); + await click('page', '[data-testid="tidy-undo"] button'); + await wait('page', `d.querySelector('[data-testid="tidy-result"]')?.textContent.includes('restored')`); + } // Archived Tidy has Delete only; no eligible targets leaves just the empty line and Cancel. await wait('page', `!!d.querySelector('[data-testid="board-filters-trigger"]')`); await click('page', '[data-testid="board-filters-trigger"]'); diff --git a/ui/shared/app.ts b/ui/shared/app.ts index d711f7f..dc83c5c 100644 --- a/ui/shared/app.ts +++ b/ui/shared/app.ts @@ -582,6 +582,15 @@ export function startView<U>(spec: ViewSpec<U>) { /** An account change the host announced, or a store or binding change a list reply showed. */ const observeSwitch = () => { cleanupBusy = false; cleanupToken = 0; }; let cleanupFocus: string | null = null; + /** + * A deferred focus move is decided when it is applied: `from` is the cleanup control it was queued from + * (null: no control had focus). `undefined` for an explicit move, which is never rechecked. + */ + let cleanupFocusFrom: string | null | undefined; + const askFocus = (id: string | null, from?: string | null) => { cleanupFocus = id; cleanupFocusFrom = id ? from : undefined; }; + const controlId = (el: Element | null) => el?.closest<HTMLElement>('[data-testid]')?.dataset.testid ?? ''; + /** The result object the last paint showed; a refresh expires only a result that was shown. */ + let paintedResult: object | null = null; let tidyReconcile = false; let handoff: (Handoff & { from: FocusKey }) | null = null; /** The hand-off's short notice, kept while focus stays on that heading (repaints rebuild the root). */ @@ -788,9 +797,10 @@ export function startView<U>(spec: ViewSpec<U>) { cleanup.tidy.scan?.cancel(); cleanup = { ...cleanup, tidy: undefined }; versions.data++; }; /** `confirmed`: plans a cleanup receipt took out of view; `returned`: plans a receipt put back (Undo). */ + /** Callers choose how the change repaints: an explicit action or refresh bumps `versions.ui`, a run's own end `versions.data`. */ const forgetPlans = (keys: Set<string>, confirmed?: ReadonlySet<string>, returned?: ReadonlySet<string>) => { if (reading && keys.has(reading.plan)) clearReading(); - if (keys.size && spec.forgetPlans) { ui = { ...ui, ...spec.forgetPlans(keys, ui, context(), confirmed, returned) }; versions.ui++; } + if (keys.size && spec.forgetPlans) ui = { ...ui, ...spec.forgetPlans(keys, ui, context(), confirmed, returned) }; }; /** @@ -893,7 +903,8 @@ export function startView<U>(spec: ViewSpec<U>) { if (cleanupBusy && cleanup.tidy) { plan(REFRESH_MS); return; } if (cleanup.tidy?.result) { if (tidyReconcile) tidyReconcile = false; - else { cleanup = initialCleanup(); versions.ui++; schedule(); } + // A result expires only once it has been shown: a hold that outlasts this refresh must not lose it. + else if (cleanup.tidy.result === paintedResult) { cleanup = initialCleanup(); versions.ui++; schedule(); } } language.refresh(); void deviceView?.refresh(ctx.features?.deviceStorage === true); @@ -989,7 +1000,7 @@ export function startView<U>(spec: ViewSpec<U>) { const next = nextRead.plans.find((n) => n.key === p.key); return !next || (next.cleanup?.revision ?? 0) !== (p.cleanup?.revision ?? 0); }).map((p) => p.key)); - if (changed.size) { resetCaches(); forgetPlans(changed); } + if (changed.size) { resetCaches(); forgetPlans(changed); versions.ui++; } } identity = nextIdentity; // The source-wide inbox window of this same read; an unchanged one repaints nothing. @@ -1067,7 +1078,7 @@ export function startView<U>(spec: ViewSpec<U>) { const listed = (spec.tidyPlans?.(vc) ?? []).filter(p => !keys || keys.has(p.key)); const confirmation = scan ? undefined : { ...tidyConfirmation(listed, read.storeId, key, spec.tidyArchived?.(vc)), matching: spec.tidyMatching?.(vc) }; cleanup = { ...initialCleanup(), tidy: { context: key, confirmation, scan, ...(remaining ? { recount: remaining } : {}) } }; - cleanupFocus = 'tidy-cancel'; versions.ui++; schedule(); + askFocus('tidy-cancel'); versions.ui++; schedule(); if (scan) void moreTidy(); } function requestSelection(action: 'archive' | 'restore' | 'delete', selection: SelectionRequest) { @@ -1085,7 +1096,7 @@ export function startView<U>(spec: ViewSpec<U>) { const confirmation = scan ? undefined : selectionConfirmation(selection.plans.filter(p => latest.has(p.key) && (!shown || shown.has(p.key))).map(p => latest.get(p.key)!), read.storeId, key, !!spec.tidyArchived?.(vc), action, health.planCleanupActive === 1); cleanup = { ...initialCleanup(), tidy: { context: key, selection: action, selectionRequest: selection, opener: `selection-${action}`, confirmation, scan } }; - cleanupFocus = 'tidy-cancel'; versions.ui++; schedule(); + askFocus('tidy-cancel'); versions.ui++; schedule(); if (scan) void moreTidy(); } async function moreTidy() { @@ -1104,23 +1115,26 @@ export function startView<U>(spec: ViewSpec<U>) { if (current()) { state.counting = false; // Cancel took focus when the panel opened; keep it only if the panel still owns focus or lost it. + // The move belongs to the control that has focus now, and is decided again when it is applied. const at = document.activeElement; - if (!at || at === document.body || at.closest('[data-testid="tidy-actions"]')) cleanupFocus = 'tidy-cancel'; - versions.ui++; schedule(); + if (!at || at === document.body) askFocus('tidy-cancel', null); + else if (at.closest('[data-testid="tidy-actions"]')) askFocus('tidy-cancel', controlId(at)); + // A count that finishes by itself is background data: it waits for a held control or an open picker. + versions.data++; schedule(); } } } function cancelTidy() { if (cleanupBusy) return; cleanup.tidy?.scan?.cancel(); - cleanupFocus = cleanup.tidy?.opener ?? 'tidy-open'; cleanup = initialCleanup(); versions.ui++; schedule(); + askFocus(cleanup.tidy?.opener ?? 'tidy-open'); cleanup = initialCleanup(); versions.ui++; schedule(); } let tidyStopped = false; function deleteTidy() { const state = cleanup.tidy; if (cleanupBusy || !state?.confirmation || state.context !== tidyContext()) return; state.confirmation = { ...state.confirmation, deleting: true }; - cleanupFocus = 'tidy-cancel'; versions.ui++; schedule(); + askFocus('tidy-cancel'); versions.ui++; schedule(); } async function executeTidy(undo: boolean, deleting = false) { const state = cleanup.tidy; @@ -1138,13 +1152,13 @@ export function startView<U>(spec: ViewSpec<U>) { const current = () => !tidyStopped && !disposed && cleanup.tidy === state && state.context === tidyContext() && health?.planCleanup === 1; state.scan?.cancel(); state.confirmation = undefined; state.progress = { action, done: 0, total: targets.length }; - cleanupFocus = 'tidy-stop'; + askFocus('tidy-stop'); const token = claimCleanup(); cleanup = { ...cleanup, pending: true }; versions.ui++; gate.retire(); schedule(); const result = await runTidy(guardedHost(current), action, targets, current, (done, total, confirmed) => { const checkpoint = confirmed && deleted.get(confirmed.key); if (checkpoint) { if (digests) digests.forget(checkpoint); else void new CheckpointStore(host.storage, () => ctx?.features?.deviceStorage === true).forget(checkpoint); } - if (cleanup.tidy === state && state.context === tidyContext()) { state.progress = { action, done, total }; versions.ui++; schedule(); } + if (cleanup.tidy === state && state.context === tidyContext()) { state.progress = { action, done, total }; versions.data++; schedule(); } }, !!state.selection && (action === 'restore' || health?.planCleanupActive === 1) || undo, // Undo restores exactly the receipts; everything else must still be in the displayed scope when sent. undo || !spec.tidyMember ? undefined : t => spec.tidyMember!(context(), t)); @@ -1155,7 +1169,7 @@ export function startView<U>(spec: ViewSpec<U>) { // switch away and back (its Delete receipts already retired their review markers above). if (!mine) return; const same = cleanup.tidy === state && state.context === tidyContext(); - if (same && document.activeElement?.closest('[data-testid="tidy-stop"]')) cleanupFocus = 'tidy-open'; + if (same && document.activeElement?.closest('[data-testid="tidy-stop"]')) askFocus('tidy-open', 'tidy-stop'); // Reconcile once, including uncertain requests; never retry a refused plan automatically. const receipts = new Set(result.succeeded.map(t => t.key)); // Undo of an archive puts plans back in view; every other successful receipt takes them out. @@ -1164,21 +1178,22 @@ export function startView<U>(spec: ViewSpec<U>) { read = null; readScope = ''; readSig = ''; failure = null; cleanup = { ...initialCleanup(), tidy: same ? { context: state.context, result: back ? { ...result, returned: true } : result, selection: state.selection, selectionRequest: state.selectionRequest, opener: state.opener } : undefined }; tidyReconcile = same; - versions.ui++; versions.data++; schedule(); retry(); + // The end of a run is background data: the result line and the selection changes wait for a held control or an open picker. + versions.data++; schedule(); retry(); } function validTarget(target: CleanupTarget) { return !disposed && !failure && health?.planCleanup === 1 && cleanupMatches(target, spec.actionPlan?.(context()) ?? null, read?.storeId, cleanupContext()); } function cancelCleanup() { if (cleanupBusy) return; - cleanup = initialCleanup(); cleanupFocus = 'cleanup-delete'; versions.ui++; schedule(); + cleanup = initialCleanup(); askFocus('cleanup-delete'); versions.ui++; schedule(); } function requestDelete(plan: PlanView) { if (cleanupBusy || !read || !cleanupEligible('delete', plan)) return; if (!cleanupClosed(plan) && health?.planCleanupActive !== 1) return; const target = cleanupTarget(plan, read.storeId, cleanupContext()); if (!validTarget(target)) return; - cleanup = { ...initialCleanup(), target }; cleanupFocus = 'cleanup-cancel'; versions.ui++; schedule(); + cleanup = { ...initialCleanup(), target }; askFocus('cleanup-cancel'); versions.ui++; schedule(); } async function runCleanup(action: CleanupAction, target: CleanupTarget) { if (cleanupBusy || !validTarget(target)) { if (!cleanupBusy) cancelCleanup(); return; } @@ -1201,7 +1216,7 @@ export function startView<U>(spec: ViewSpec<U>) { gate.retire(); resetCaches(); forgetPlans(new Set([target.key]), new Set(result.ok ? [target.key] : [])); read = null; readScope = ''; readSig = ''; failure = null; cleanup = { ...initialCleanup(), error: !result.ok, message: sameContext ? (result.ok ? { kind: action } : { kind: 'error', code: result.failure.code }) : null }; - cleanupFocus = result.ok ? 'cleanup-notice' : 'cleanup-error'; versions.ui++; versions.data++; schedule(); retry(); + askFocus(result.ok ? 'cleanup-notice' : 'cleanup-error'); versions.ui++; versions.data++; schedule(); retry(); } const headReads = new Map<string, { reading: string; queued: boolean; current: () => boolean }>(); @@ -1564,12 +1579,15 @@ export function startView<U>(spec: ViewSpec<U>) { paintedContextGeneration = contextGeneration; if (cleanup.target && !cleanupBusy && !validTarget(cleanup.target)) cleanup = initialCleanup(); if (cleanup.tidy && cleanup.tidy.context !== tidyContext()) cleanup = { ...initialCleanup(), pending: cleanupBusy }; + paintedResult = cleanup.tidy?.result ?? null; preparePreview(); let vc = context(); languagePaint = paintedLanguage !== null && paintedLanguageSignature !== languageSignature; const ownsFocus = document.hasFocus?.() ?? true; const active = !ownsFocus && !retainDeferredFocus ? null : deferredFocus && emptyFocus(document.activeElement) ? deferredFocus : document.activeElement as HTMLElement | null; + // What had focus is judged before the root is replaced: a rebuilt control is detached afterwards, and that must not read as "no focus". + const activeEmpty = emptyFocus(active), activeId = cleanupFocusFrom ? controlId(active) : ''; const focus = focusKey(mount!, active); const coverage = coverageFocus(mount!, active); deferredFocus = null; @@ -1732,8 +1750,12 @@ export function startView<U>(spec: ViewSpec<U>) { const owner = root.querySelector<HTMLElement>(`[data-testid="${cleanupFocus}"]`); const target = owner?.querySelector<HTMLElement>('button') ?? owner; // Never pull focus out of the host or a sibling frame; that request is dropped, not kept for a later paint. - if (!(document.hasFocus?.() ?? true)) cleanupFocus = null; - else if (target) { if (target.tagName !== 'BUTTON') target.tabIndex = -1; target.focus({ preventScroll: true }); cleanupFocus = null; } + if (!(document.hasFocus?.() ?? true)) askFocus(null); + // A deferred move is applied only while focus is still on the control it was queued from, or on none because + // that control was removed. Judged from the element that had focus before this paint replaced the root, at + // every paint, also while its target is absent: a person who moved on keeps focus, whatever appears later. + else if (cleanupFocusFrom !== undefined && !activeEmpty && !(cleanupFocusFrom && activeId === cleanupFocusFrom)) askFocus(null); + else if (target) { if (target.tagName !== 'BUTTON') target.tabIndex = -1; target.focus({ preventScroll: true }); askFocus(null); } } const nextText = root.querySelector<HTMLTextAreaElement>('[data-testid="summary-text"]'); const nextSupport = root.querySelector<HTMLTextAreaElement>('[data-testid="reporting-support-preview"]'); @@ -1821,7 +1843,7 @@ export function startView<U>(spec: ViewSpec<U>) { // Board Tidy belongs to its filtered scope, not the host's current session. // A genuine scope/authority transition still drops the captured state forever. const tidy = cleanup.tidy?.context === tidyContext() ? cleanup.tidy : undefined; - cleanup = { ...initialCleanup(), pending: cleanupBusy, tidy }; cleanupFocus = null; handoff = null; handoffNote = null; + cleanup = { ...initialCleanup(), pending: cleanupBusy, tidy }; askFocus(null); handoff = null; handoffNote = null; live.restart(); // A full snapshot or incremental event can move context. Duplicate follow-up events // are idempotent; directory-only enrichment does not change a session list scope. @@ -1926,7 +1948,7 @@ export function startView<U>(spec: ViewSpec<U>) { contextGeneration++; gate.retire(); resetCaches(); clearReading(); ui = spec.initialUi(); identity = ''; read = null; readScope = ''; readSig = ''; health = null; failure = null; lastGoodAt = null; - observeSwitch(); cleanup = initialCleanup(); cleanupFocus = null; handoff = null; handoffNote = null; + observeSwitch(); cleanup = initialCleanup(); askFocus(null); handoff = null; handoffNote = null; session = nextSession; directory = nextDirectory; requestedScope = scopeKey(currentScope()); versions.ctx++; live.restart(); spec.onContext?.(context()); gate.request(); From 5eff3cb27b97aa5aa04684f065c8b0f08cec8e24 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 00:26:15 +1100 Subject: [PATCH 09/11] fix(ui): keep Tidy and selection counts exact while plans change (#169) * fix(ui): keep Tidy and selection counts exact while plans change A Tidy or Select all count taken from a list read in more than one page now says some plans may have been missed, on both steps, without adding a read. Search freshness replies certify only the result page they were asked about and only when they covered every plan it shows, are retired by a cleanup in the frame, and report plans they show gone to the selection whichever page is shown. A page opened by Load more starts unchecked. A Select all departure carries the cleanup generation that took the plan out, so a plan restored elsewhere is counted again. * fix(ui): keep selection rows, counts and scans in agreement on departed plans A departed plan known at a newer cleanup generation is now treated the same by the row, the selection count, the snapshot plans and a scan. PlanSelection.forget takes only a map of plan to generation. A selection that throws while following plans a freshness reply showed gone no longer leaves the search half updated. Document the qualified zero line, clarify the multi-page flag, and run the two slow search scenarios on one smaller backend. --- docs/contracts.md | 12 +- docs/ui.md | 10 +- openspec/changes/release-1-5-2/tasks.md | 14 +- tests/browser/cleanup-selection-page.test.ts | 28 ++- tests/browser/cleanup-selection.test.ts | 97 ++++++- tests/browser/cleanup-tidy-controller.test.ts | 125 ++++++++- .../plan-task-search-controller.test.ts | 237 ++++++++++++++++++ ui/page/main.ts | 11 +- ui/shared/app.ts | 32 ++- ui/shared/cleanup.ts | 63 +++-- ui/shared/model.ts | 6 + ui/shared/search.ts | 34 ++- ui/shared/source.ts | 5 +- 13 files changed, 605 insertions(+), 69 deletions(-) diff --git a/docs/contracts.md b/docs/contracts.md index 04726c8..2ea9d69 100644 --- a/docs/contracts.md +++ b/docs/contracts.md @@ -1220,7 +1220,17 @@ envelope carries no change token), so a count that crossed such a boundary is qualified as possibly missing plans, never presented as verified complete; an overlap anchor that changed is counted at its new version, or dropped when its new version no longer belongs to the view. A fully read count of that kind says -plans may have been missed, rather than that more plans were not checked. Plans a user +plans may have been missed, rather than that more plans were not checked. A complete loaded +scope that was read in more than one list page (more than 50 plans) is qualified the +same way, on the count line and on the delete step: the list read records that it +crossed a page boundary and the count adds no request. A list read in one page is one +answer from the service and stays exact, and so do rows explicitly chosen from it. A +Try again recount names its plans; on a list read in several pages it stays exact only +when it found every plan it names among the loaded rows, because otherwise it cannot +show whether the plan left the view or was missed. Under Select all the selection +bar's count is the number of selected plans the frame has loaded, with a plus only while +matching plans are known not to be loaded, and the confirmation is what says a list read +in several pages may have missed plans. Plans a user explicitly chose, and the remaining plans of a retry, are not searched for: they are validated with `/v1/search-state` point lookups (at most 50 keys and the service's 16 KiB encoded-query limit each, pinned to the expected store and diff --git a/docs/ui.md b/docs/ui.md index 5097a29..8d8dff8 100644 --- a/docs/ui.md +++ b/docs/ui.md @@ -558,7 +558,7 @@ Find reported plans and tasks by title or stable ID across the whole recorded st - **Progressive results.** Search, Load more results, Continue searching and Retry are the only actions that read; each issues at most 10 sequential windows of up to 50 and stops at a full page of 50 hits, exhaustion or failure. There is no 500-plan ceiling and no automatic continuation. A pause with nothing yet shows "No matches found yet; more recorded plans remain unchecked." with Continue searching, never "No results". Results are grouped by plan (title, ID, location, lifecycle, other/unverified source, whole-plan done/total) with matching task rows (status glyph, title, status, ID and an abbreviated "In: root › … N more › parent" breadcrumb from the reply; nothing is invented). A plan matched only by its own title or ID says so; a group continued from the previous page is labelled. At most two pages are kept (Previous/Next results); earlier pages need a new search. - **Counts.** "Found P plans, T matching tasks." accumulates only accepted windows' per-plan deltas after the location choice. The same sentence is announced once for the explicit outcome, not repeated as a visible completion notice. There is no page/context/counts explanation; Previous/Next controls appear only when another retained page is available. Plan done/total still cover the whole plan. A short neutral sentence qualifies checking, incomplete search or changed results, never clean completion. It does not list skipped-record counts or scan limits; unreadable records remain qualified. Exhaustion is not a live census or frozen snapshot. - **Opening a result.** A plan row selects that plan; a task row selects it and, once the existing detail loader has complete current detail, checks the same run, source/plan identity, revision and archive mode, then uses the canonical reveal (opens ancestors, clears hiding task filters, focuses `item-<id>`) once with "Search result: …". A task no longer in the plan, a plan moved in or out of the archive, or a failed detail read is announced and the plan stays readable. The detail pane is painted from complete detail metadata, never from the search summary; Summary preview and the History digest are offered when the loaded list holds the same revision of that plan. Any change of search run or selection (also for plans outside the loaded list) retires in-flight detail, document and history reads of the previous selection: a released held reply sends no continuation page, paints nothing and never delays the next selection. While searching, those part caches keep only the selection and the three plans opened just before it (across searches of the same integration account/store; a cache reset clears them); others are evicted, and an evicted in-flight read cannot repopulate the cache (it reads again when reopened). Ordinary browsing keeps its existing caching. -- **Freshness.** While results are shown, the frame's existing poll (3 s, 8 s after failure, visible frames only) sends one `/v1/search-state` read for the displayed plan keys plus the selection (≤ 50 per read, at most two) **instead of** the list read; with nothing shown it reads the list as usual. A missing, deleted or archive-moved plan leaves the results; a new revision or cleanup generation (also archive + restore with the same revision) is marked "Changed since found". Either retires continuation and count authority and offers Refresh search. A conflicting store/binding falls back to the list read, which resets for the new store. A successful current poll also updates capture state and its diagnostic in the current and remembered list envelope, preserving the remembered list age and unrelated diagnostics; other cached scopes with obsolete capture state are evicted. A capture change refreshes the selected detail and any open progress/handoff preview even at an unchanged plan revision. Unchanged metadata does not repaint or add detail/list requests. Missing/malformed capture metadata or disagreement between batches is a failed poll: no partial rows or capture state are applied. A failed freshness read keeps the results under the stale banner, never as an empty result. +- **Freshness.** While results are shown, the frame's existing poll (3 s, 8 s after failure, visible frames only) sends one `/v1/search-state` read for the displayed plan keys plus the selection (≤ 50 per read, at most two) **instead of** the list read; with nothing shown it reads the list as usual. A missing, deleted or archive-moved plan leaves the results, and leaves the selection too, whichever result page is shown when the reply arrives; a new revision or cleanup generation (also archive + restore with the same revision) is marked "Changed since found". Either retires continuation and count authority and offers Refresh search. A conflicting store/binding falls back to the list read, which resets for the new store. A successful current poll also updates capture state and its diagnostic in the current and remembered list envelope, preserving the remembered list age and unrelated diagnostics; other cached scopes with obsolete capture state are evicted. A capture change refreshes the selected detail and any open progress/handoff preview even at an unchanged plan revision. Unchanged metadata does not repaint or add detail/list requests. A reply certifies only the result page it was asked about, identified by its number in the search (retained pages shift when Load more drops the oldest), and only when it covered every plan the page shows when it arrives: a search still running can append hits the reply could not have seen. Hits the search reads into a page after it was checked leave it checked, as the hits of a new search's first page are. A page opened by Load more starts unchecked, whatever the page before it was, and becomes checked when a reply covers its own plans, with no time limit (the poll backs off after a failure and pauses while the frame is hidden); a page that shows no plan has nothing to check, so it shows no checking note and adds no read. A cleanup action in this frame retires the freshness reads the frame already sent: a reply from before it marks nothing checked and changes no selection, while a cleanup made in another frame retires nothing here, and a reply that shows its effect is evidence like any other. Missing/malformed capture metadata or disagreement between batches is a failed poll: no partial rows or capture state are applied. A failed freshness read keeps the results under the stale banner, never as an empty result. - **Retirement.** A run is keyed by integration account, store + binding, criteria and a submit counter. New criteria, Refresh search, Clear all, mode switch, a cache reset (integration account/store/binding change, setup action, local cleanup success or ambiguous failure, list eviction), membership change, hiding and disposal retire its in-flight window: a held reply cannot add results or counts, and no further window is sent. Hiding pauses an action; the user continues it explicitly from the last accepted window. Hiding and disposal also retire an in-flight freshness read whether or not a scan is running: generation and visibility are checked before each freshness batch and before any reply is accepted, so a hidden frame sends no further batch and applies nothing. Retired replies carry no capture metadata and cannot clear failures or advance successful freshness. Transport overlap is one retired plus one current window, with one queued follow-up. - **Accessibility.** Native/kit buttons, selects and field with accessible names; one persistent polite region (`search-announcer`, outside the repainted root) speaks each explicit outcome once, never per poll. Focus, typed text and caret in the field survive unrelated repaints. When an action's own control leaves the paint — Continue searching / Load more results (while results load, and for good after the last window), Retry, a removed chip, Clear search and filters — focus moves once to the results region's heading with a short notice (see Task view › Restoration): **Search results** (`search-results-heading`, present in every result state) while searching, **Plans** (`plan-list-heading`) once browsing resumes; no obsolete result is kept for it. At 360 px and 200% reflow everything wraps without horizontal scrolling. - **Saved views:** not built. The named-view slice is blocked because host storage has no proven authenticated-user isolation; search reads and writes no preference storage. @@ -1012,11 +1012,11 @@ The shipped reading control is **Help & filters → Show all / Unfinished**, on - **Placement.** Archive, Restore and Delete permanently… join the single **More** menu in List, Map and every panel. Deletion is last and destructive; its confirmation is never inside the menu. An archived plan keeps its visible state line and each action keeps the existing result notice. - **Archive** is the ordinary per-plan action for a closed plan (Finished, Cancelled or Failed) in the rail/page. It hides the plan from ordinary lists and featured choices, retaining tasks, counts, report age, document and history. Archived plans cannot receive further reports until restored. Visible in-progress plans have no per-plan cleanup action; they can be acted on only through full-page selection. There is no automatic cleanup. -- **Tidy.** The full-page bar always offers **Tidy** beside search and Filters when a library and `planCleanup:1` are available, including during search/filtering and when nothing is eligible. Neither the rail nor More offers bulk cleanup. Tidy covers Finished, Cancelled and Failed plans matching the current search and filters, or all closed plans in the current view without narrowing. It includes plans not loaded into the list and never targets in-progress plans or sends their acknowledgement. In Current plans it offers Archive and Delete permanently; in Archived plans only Delete permanently. An inline panel has one short count/scope line, no plan titles, named action buttons and Cancel. With no targets it says **No closed plans here.** and offers no cleanup action. -- **Counting and confirmation.** A complete loaded scope supplies targets without a read. Otherwise a separate bounded list/search traversal counts them, applying the same effective filters as the displayed board (including normalized project/worktree choices) and, when browsing, the board's own placement of a plan by its recorded directory (the search-only check that a chosen location is currently discoverable applies to searches alone) without populating ordinary list/search caches or changing refresh budgets. Each explicit scan stops at 2,000 plan slots or 40 request windows, whichever comes first. Forty windows match the ordinary 50-plan list-page budget and prevent task-heavy search continuations from causing thousands of round trips. **Check more** continues from its last cursor with fresh per-action budgets, adding matches without repeating windows. The cursor is discarded on a store, account, binding, view, search or filter change. At most 1,000 targets belong to a confirmation. **First 1000 closed plans; more remain.** appears only once a further match has been found (a full set keeps counting within the scan budget to prove it); a cursor that merely remains, including after exactly 1,000 matches, says that more plans weren’t checked, never that more match. Each browse page after the first starts one row early and must open with the plan that ended the previous page; if another frame archived or deleted a plan behind the cursor, the count fails (**Could not count plans. Try again.**) instead of skipping plans and claiming completeness. The final **Delete permanently…** step repeats the same one-line subset qualification when the count is limited or unchecked. Cancel gets initial focus, Enter never defaults to a destructive action, and Escape cancels and returns focus to Tidy. Opening/cancelling sends no cleanup request. **Archive N plans** confirms Archive; **Delete permanently…** opens its own second step, whose count line says it cannot be undone. One collapsed disclosure keeps the stored tasks/history/document-copy removal, original-file preservation and non-erasure details reachable. -- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded) and is never stored. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests. A refusal as changed, closed, reused operation, not found or store busy is skipped; any other refusal is reported as unconfirmed, for example the 503 `storage` answer of a withdrawn store. Tidy, Select and the other cleanup controls follow what the latest health reply the frame accepted said, whichever remembered list is shown: switching to a remembered Current or Archived list neither brings back support (or in-progress support) a later reply withdrew nor hides support a later reply granted, and support returns only with a newer reply that offers it, even when its list is unchanged. A health reply is accepted when the refresh that read it settles, complete or failed; one that arrived inside a refresh still reading its list pages takes effect then, and until then a request is checked when it is sent and by the service. A count, confirmation or run already open is not re-checked when only in-progress support is withdrawn. +- **Tidy.** The full-page bar always offers **Tidy** beside search and Filters when a library and `planCleanup:1` are available, including during search/filtering and when nothing is eligible. Neither the rail nor More offers bulk cleanup. Tidy covers Finished, Cancelled and Failed plans matching the current search and filters, or all closed plans in the current view without narrowing. It includes plans not loaded into the list and never targets in-progress plans or sends their acknowledgement. In Current plans it offers Archive and Delete permanently; in Archived plans only Delete permanently. An inline panel has one short count/scope line, no plan titles, named action buttons and Cancel. With no targets it says **No closed plans here.** and offers no cleanup action; a count from a list read in several pages says **0 closed plans found; some plans may have been missed.** instead, because it cannot show that no plan was missed. +- **Counting and confirmation.** A complete loaded scope supplies targets without a read; when that list was read in more than one page (more than 50 plans) the count line and the deletion step say that some plans may have been missed, because offsets between pages are not a snapshot. A list read in one page is one answer from the service and stays exact, and so do rows chosen one by one. The qualification adds no request and is on the confirmation line only. Otherwise a separate bounded list/search traversal counts them, applying the same effective filters as the displayed board (including normalized project/worktree choices) and, when browsing, the board's own placement of a plan by its recorded directory (the search-only check that a chosen location is currently discoverable applies to searches alone) without populating ordinary list/search caches or changing refresh budgets. Each explicit scan stops at 2,000 plan slots or 40 request windows, whichever comes first. Forty windows match the ordinary 50-plan list-page budget and prevent task-heavy search continuations from causing thousands of round trips. **Check more** continues from its last cursor with fresh per-action budgets, adding matches without repeating windows. The cursor is discarded on a store, account, binding, view, search or filter change. At most 1,000 targets belong to a confirmation. **First 1000 closed plans; more remain.** appears only once a further match has been found (a full set keeps counting within the scan budget to prove it); a cursor that merely remains, including after exactly 1,000 matches, says that more plans weren’t checked, never that more match. Each browse page after the first starts one row early and must open with the plan that ended the previous page; if another frame archived or deleted a plan behind the cursor, the count fails (**Could not count plans. Try again.**) instead of skipping plans and claiming completeness. The final **Delete permanently…** step repeats the same one-line subset qualification when the count is limited or unchecked. Cancel gets initial focus, Enter never defaults to a destructive action, and Escape cancels and returns focus to Tidy. Opening/cancelling sends no cleanup request. **Archive N plans** confirms Archive; **Delete permanently…** opens its own second step, whose count line says it cannot be undone. One collapsed disclosure keeps the stored tasks/history/document-copy removal, original-file preservation and non-erasure details reachable. +- **Select.** The full page alone offers Select beside Tidy. In this mode, plan rows and search plan results are independent toggle buttons with names and pressed states; Space toggles the focused row. The count is announced once per change. At widths below 820 px, rows replace the detail until Done, with 44 px targets. Clear and Done empty the selection. Selection belongs to the frame's account/store/binding, Current/Archived view, filters and submitted search; it survives refreshes, loses departed plans (in a partial list, those whose cleanup receipt succeeded, and those a search freshness reply showed gone, on whichever result page) and is never stored. Under Select all the selection bar counts the selected plans the frame has loaded, with a plus only while matching plans are known not to be loaded: a complete list read in several pages carries no plus, and it is the confirmation that says some plans may have been missed. Select mode ends when the service stops offering cleanup (also in Archived, where the list read is then empty), and the selection and any open count or confirmation are retired with it (also when the service reports it is no longer set up, or a list read fails after its health reply stopped offering cleanup). Ending Select mode does not touch a finished result, which stays bound to its store and board scope until the next refresh or action. A finished result and its receipts stay while it is shown, but its Undo and Try again are unavailable without support; the result expires at the next refresh, which does not bring those actions back. A populated search revalidates through its own freshness read, which carries no service capabilities; loss of support is therefore observed at the next list read (search cleared, store or binding change, reload), and until then the service refuses cleanup requests. A refusal as changed, closed, reused operation, not found or store busy is skipped; any other refusal is reported as unconfirmed, for example the 503 `storage` answer of a withdrawn store. Tidy, Select and the other cleanup controls follow what the latest health reply the frame accepted said, whichever remembered list is shown: switching to a remembered Current or Archived list neither brings back support (or in-progress support) a later reply withdrew nor hides support a later reply granted, and support returns only with a newer reply that offers it, even when its list is unchanged. A health reply is accepted when the refresh that read it settles, complete or failed; one that arrived inside a refresh still reading its list pages takes effect then, and until then a request is checked when it is sent and by the service. A count, confirmation or run already open is not re-checked when only in-progress support is withdrawn. - **Effective selection scope.** Ownership includes the board's normalized location filters. If the last plan in a project or worktree leaves and the board falls back to all locations, Select all is retired; selecting those other locations requires a new gesture. Old action callbacks cannot open a broader confirmation before repaint. Search counts update when hits are appended to the same result-page array and still count each plan only once. -- **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view. Where a chosen plan is validated by point lookup (a truncated or searched scope, only when the service offers `planTaskSearch:1`), the baseline it is compared with is the revision supplied to the count: the revision the selection carried and, on Try again, the original target's revision, not the revision when the count began. Where search or session criteria apply, the point lookup skips a plan whose revision moved as changed and does not adopt the new one; that skip belongs to the point lookup only. A complete browse list counts a chosen plan from the displayed rows and an older service's list scan takes it as the scan's row shows it; neither compares it with the supplied revision. A count that read every page of an offset-paged list says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. A plan a cleanup receipt took out of a Select all rule is selected again when an Undo receipt puts it back or a verified read lists it again (a cached, unchecked search page is not evidence), and a click on such an unpressed row selects it; a plan the user deselected stays deselected. +- **Tidy and selection context.** A count, its confirmation and its run are bound to the *effective* board scope: the filters the board displays after normalization (or the submitted search), as well as the saved choice, the Current/Archived view, the selection and the account/store/binding. A refresh that changes what the board displays between counting and confirming (for example the chosen project's plans reappearing after the list had briefly fallen back to all locations) retires the open confirmation, for both Tidy and Select all; no request is sent for the earlier count. Placement can also change without any plan changing (a live owner session leaving), so right before each request the view re-checks that the target is still placed in the scope the user confirmed; a search target must also still pass the chosen locations' availability check that a fresh search count applies (browse keeps recorded-directory placement); a target that does not is skipped and counted as skipped, never sent. This is one predicate, shared by counting (scans and named plans alike) and by the send-time check: location placement and, for a search, whether its chosen locations are discoverable now. What the client cannot evaluate (query, task status, lifecycle, session) is bound by the plan's revision, which every request carries and the service enforces, so a count never adopts a newer revision for such a view. Where a chosen plan is validated by point lookup (a truncated or searched scope, only when the service offers `planTaskSearch:1`), the baseline it is compared with is the revision supplied to the count: the revision the selection carried and, on Try again, the original target's revision, not the revision when the count began. Where search or session criteria apply, the point lookup skips a plan whose revision moved as changed and does not adopt the new one; that skip belongs to the point lookup only. A complete browse list counts a chosen plan from the displayed rows and an older service's list scan takes it as the scan's row shows it; neither compares it with the supplied revision. A count that read every page of an offset-paged list, or took a complete loaded list that was read in more than one page, says plans may have been missed (it cannot prove the offsets were stable), not that some were not checked. While a run is in flight or its result is shown, the scope it was confirmed under stays fixed: a host-session change that restarts live discovery cannot retire a run or discard the receipts of requests already sent, and the remaining targets are re-checked against the live placement as it reloads. Try again after a partial selection result retries only the captured remaining plans under the scope displayed then, and shows its own count first, taken from the plans the board still displays when the list is complete. On a complete list read in several pages that recount is exact only when it found every plan it names among the loaded rows; when one is missing it cannot tell a plan that left the view from one that was missed and says so, still without a request (a list read in one page stays exact). Departures and deselections under Select all are kept apart. A plan a cleanup receipt, or a search freshness reply that showed it gone, took out of the rule is a departure; it carries the cleanup generation that took it out, which for a receipt is the one the receipt returned (handed over with the receipt, never read from a loaded row, because Select all can archive a plan the page never loaded) and for a freshness reply is the one of the row that showed it gone, none when the plan no longer exists. A departure ends when an Undo receipt puts the plan back, when a verified read lists it again (a cached, unchecked search page is not evidence), when the person clicks its unpressed row, or when a fresh count finds it in the view at a newer cleanup generation than took it out, so a plan archived here and restored elsewhere is counted by the next action. Those returns end the departure only: a plan the user deselected stays deselected until they click its row or press Select all again, which replaces the selection and clears both. - **Keyboard order.** Tidy precedes the selection bar, which precedes confirmation/result actions. Outside Select mode this gives Tidy → Select → Undo when an archive result is shown. In Select mode, Done and Select all come first; when plans remain selected, Archive/Restore, Delete permanently… and Clear follow, then Undo. The count is a live status, not a Tab stop. - **Select all and actions.** Select all is a rule over every matching plan, including unloaded plans and closed Finished folds; deselecting a row excludes that plan. An incomplete count carries a plus, and opening an action uses Tidy's bounded scan and shared confirmation/run/result/Undo path to count actual targets. Chosen rows (not Select all) are not searched for: in a searched or truncated scope, on a service that offers `planTaskSearch:1`, their known plans are validated by point lookups of at most 50 plans each, so a chosen result beyond the scan budget is counted at once, an unrelated unreadable record cannot prevent the count, plans that are gone drop out, and a plan whose progress revision moved is counted at its current revision and lifecycle, except where search or session criteria apply, where the point lookup skips it as changed. A complete browse list uses the loaded rows instead, and an older service counts a truncated browse scope by list scan. With a selection, Current offers Archive and Delete permanently…, Archived offers Restore and Delete permanently…, plus Clear. These actions include any lifecycle. The one-line Archive/Delete confirmation states the in-progress count and consequence. With `planCleanupActive:1`, only in-progress Archive/Delete requests carry `active:true`; without it those targets are excluded and the line counts them. Restore and Undo never carry it. Cancel/Escape returns focus to the selection action that opened the panel, rather than Tidy. - **Unsupported in-progress plans.** Archive/Delete counting excludes these plans before applying the 1,000-target ceiling, in loaded selections and scans alike. Their distinct-plan warning count is separate from eligible targets; they still consume scan slots/windows, so a scan that has not reached eligible plans offers Check more rather than an empty terminal target ceiling. diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index 6257201..bb1dabb 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -4,13 +4,13 @@ Each numbered group is one pull request into the development branch. It carries ## 1. Counts and selection while plans change -- [ ] 1.1 Record on the list read that it crossed a page boundary, and carry that into Tidy and Select all confirmations built from the loaded list: the count line and the deletion step say that some plans may have been missed. Keep a single-page list, and rows explicitly chosen from the loaded list, exact; a count that runs through a scan keeps the scan's own rules. Keep a Try again recount exact when it found every plan it names, and qualify it when the list was read in several pages and a named plan is not among the loaded rows. Add no read, and leave the selection bar's plus rule as it is: under Select all its count is the number of selected plans the frame has loaded, not a verified total. Test the controller with a multi-page and a single-page list, for Tidy, Select all, chosen rows, and Try again with every named plan found and with one not found. -- [ ] 1.2 Make a search freshness reply certify the result page it was asked about by that page's number in the search, never another page, and only when it covered every plan the page shows when it arrives. Keep a checked page checked when the search reads further hits into it. Test with a held reply across a Load more that drops the oldest retained page, with a held reply while the search appends hits to the same page, and with hits read after the reply, which leave the page checked. -- [ ] 1.3 Retire freshness reads in flight when a cleanup action in this frame retires the search; a cleanup made in another frame retires nothing. Test with a reply held across an archive under Select all: it marks nothing checked and does not select the archived plan again. Keep the case of a plan archived from another frame, whose reply still removes it. -- [ ] 1.4 Pass the plans a freshness reply showed gone to the selection separately from the page's checked state, so they leave the selection whichever page is shown. Test with a selected plan whose hits span two retained pages. -- [ ] 1.5 Keep receipt departures apart from deselections when an action captures a Select all rule, and let a fresh count include a departed plan it finds in the view at a newer cleanup generation than its receipt returned. Hand that generation from the run to the selection with each receipt, as a map from plan to cleanup generation, for the bulk run and the single-plan action alike; do not read it from a loaded row. A return by receipt, verified read or fresh count ends the departure only; a deselection of the same plan ends when the person clicks its row, or replaces the selection with Select all, which clears deselections and departures as it does today. Test: restored elsewhere and counted again; a departed plan the page never loaded, restored elsewhere and counted again; deselected stays out; deselected and departed stays out; still archived stays out; Select all pressed again selects a deselected plan again. -- [ ] 1.6 Start a result page opened by Load more unchecked, whatever the previous page's state, and keep it unchecked until a freshness reply covers it, with no time limit. A page that shows no plan shows no checking note and adds no freshness read. Test after a checked page, with a failed freshness read, which leaves the page unchecked, and with a Load more that ends without a hit. -- [ ] 1.7 Update the counting, Select and selection-context statements of `docs/ui.md` and the bulk-count paragraph of `docs/contracts.md`, including the consequence for lists longer than one page. Run the root and interface typechecks and the browser logic tests. +- [x] 1.1 Record on the list read that it crossed a page boundary, and carry that into Tidy and Select all confirmations built from the loaded list: the count line and the deletion step say that some plans may have been missed. Keep a single-page list, and rows explicitly chosen from the loaded list, exact; a count that runs through a scan keeps the scan's own rules. Keep a Try again recount exact when it found every plan it names, and qualify it when the list was read in several pages and a named plan is not among the loaded rows. Add no read, and leave the selection bar's plus rule as it is: under Select all its count is the number of selected plans the frame has loaded, not a verified total. Test the controller with a multi-page and a single-page list, for Tidy, Select all, chosen rows, and Try again with every named plan found and with one not found. +- [x] 1.2 Make a search freshness reply certify the result page it was asked about by that page's number in the search, never another page, and only when it covered every plan the page shows when it arrives. Keep a checked page checked when the search reads further hits into it. Test with a held reply across a Load more that drops the oldest retained page, with a held reply while the search appends hits to the same page, and with hits read after the reply, which leave the page checked. +- [x] 1.3 Retire freshness reads in flight when a cleanup action in this frame retires the search; a cleanup made in another frame retires nothing. Test with a reply held across an archive under Select all: it marks nothing checked and does not select the archived plan again. Keep the case of a plan archived from another frame, whose reply still removes it. +- [x] 1.4 Pass the plans a freshness reply showed gone to the selection separately from the page's checked state, so they leave the selection whichever page is shown. Test with a selected plan whose hits span two retained pages. +- [x] 1.5 Keep receipt departures apart from deselections when an action captures a Select all rule, and let a fresh count include a departed plan it finds in the view at a newer cleanup generation than its receipt returned. Hand that generation from the run to the selection with each receipt, as a map from plan to cleanup generation, for the bulk run and the single-plan action alike; do not read it from a loaded row. A return by receipt, verified read or fresh count ends the departure only; a deselection of the same plan ends when the person clicks its row, or replaces the selection with Select all, which clears deselections and departures as it does today. Test: restored elsewhere and counted again; a departed plan the page never loaded, restored elsewhere and counted again; deselected stays out; deselected and departed stays out; still archived stays out; Select all pressed again selects a deselected plan again. +- [x] 1.6 Start a result page opened by Load more unchecked, whatever the previous page's state, and keep it unchecked until a freshness reply covers it, with no time limit. A page that shows no plan shows no checking note and adds no freshness read. Test after a checked page, with a failed freshness read, which leaves the page unchecked, and with a Load more that ends without a hit. +- [x] 1.7 Update the counting, Select and selection-context statements of `docs/ui.md` and the bulk-count paragraph of `docs/contracts.md`, including the consequence for lists longer than one page. Run the root and interface typechecks and the browser logic tests. ## 2. Account, store and capability diff --git a/tests/browser/cleanup-selection-page.test.ts b/tests/browser/cleanup-selection-page.test.ts index f1ba8c0..f78bfaf 100644 --- a/tests/browser/cleanup-selection-page.test.ts +++ b/tests/browser/cleanup-selection-page.test.ts @@ -39,7 +39,7 @@ function frame() { const globals = createContext({ vc, ui: vc.ui, read: vc.read, selection, derivedBoard, visiblePlans: () => derivedBoard().plans, ownerOf: () => 'fixture', v: null, isSearching: () => !!vc.ui.search, - selectionPlans: null, selectionHits: null, selectionHitCount: -1, selectionSearchPlans: [], selectionPage: '', selectionEpoch: 0 }); + selectionPlans: null, selectionHits: null, selectionHitCount: -1, selectionSearchPlans: [], selectionEpoch: 0 }); for (const node of [scope, endWithoutCleanup]) if (node) runInContext(ts.transpileModule(node.getText(file), { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, globals); return { vc, selection, derivedBoard, globals, @@ -114,7 +114,7 @@ test('a cached search page does not reselect a plan a receipt took out; a checke const page = { hits, number: 1, checked: true }; f.globals.v = { page, criteria: { ...NO_FILTERS } }; f.paint(); f.selection.mode = true; f.selection.selectAll(); - f.selection.forget([plans[0].key]); + f.selection.forget(new Map<string, number | null>([[plans[0].key, null]])); page.checked = false; f.globals.v = { page: { ...page, hits: [...hits] }, criteria: { ...NO_FILTERS } }; f.paint(); assert.equal(f.selection.has(plans[0].key), false, 'an unverified cached page is not evidence'); @@ -122,3 +122,27 @@ test('a cached search page does not reselect a plan a receipt took out; a checke f.paint(); assert.equal(f.selection.has(plans[0].key), true); }); + +// The page's own search host: a plan a freshness reply shows gone reaches the selection however the page is painted. +function searchHost(selection: PlanSelection) { + let host: { gone?: (plans: ReadonlyMap<string, number | null>) => void } | undefined; + const declaration = file.statements.flatMap(n => ts.isVariableStatement(n) ? [...n.declarationList.declarations] : []) + .find(d => ts.isIdentifier(d.name) && d.name.text === 'search'); + assert.ok(declaration?.initializer, 'the page constructs its search controller'); + const globals = createContext({ SearchController: class { constructor(h: typeof host) { host = h; } }, frame: null, document: { visibilityState: 'visible' }, selection }); + runInContext(ts.transpileModule(`(${declaration.initializer.getText(file)})`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, globals); + assert.ok(host, 'the controller received its host'); + return host; +} +test('a plan a freshness reply shows gone leaves the selection with that reply\'s generation, whatever page is painted', () => { + const rows = ['a', 'b'].map(id => ({ ...plans[0], key: id, id, cleanup: { state: 'visible' as const, revision: 1 } })); + const selection = new PlanSelection(); + selection.reconcile('scope', rows, true); selection.mode = true; selection.selectAll(); + const host = searchHost(selection); + assert.equal(typeof host.gone, 'function', 'the host passes departures on'); + host.gone!(new Map<string, number | null>([['a', 3]])); + assert.equal(selection.has('a'), false); + assert.equal(selection.count, 1); + assert.equal(selection.snapshot().includes({ ...rows[0], cleanup: { state: 'visible', revision: 3 } }), false); + assert.equal(selection.snapshot().includes({ ...rows[0], cleanup: { state: 'visible', revision: 4 } }), true, 'restored elsewhere since'); +}); diff --git a/tests/browser/cleanup-selection.test.ts b/tests/browser/cleanup-selection.test.ts index fd99225..ab1070b 100644 --- a/tests/browser/cleanup-selection.test.ts +++ b/tests/browser/cleanup-selection.test.ts @@ -57,7 +57,7 @@ test('departed search results are removed without clearing the other selected pa const s = new PlanSelection(), a = plan('a'), b = plan('b'); s.reconcile('search', [a], true); s.toggle(a); s.reconcile('search', [b], true); s.toggle(b); - s.forget([a.key]); + s.forget(new Map<string, number | null>([[a.key, null]])); assert.equal(s.count, 1); assert.equal(s.has(b.key), true); assert.equal(s.has(a.key), false); s.selectAll(); s.toggle(b); @@ -96,7 +96,7 @@ test('a receipt-confirmed plan is no longer selected under Select all and does n const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); const earlier = selection.snapshot().includes; - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); assert.equal(selection.has('a'), false); assert.equal(selection.has('b'), true); assert.equal(selection.count, 2); @@ -110,7 +110,7 @@ test('a plan confirmed back in scope after Undo is selected again; an explicit e const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); selection.toggle(plans[1]); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); selection.reconcile('scope', [...plans], true); assert.equal(selection.has('a'), true, 'the receipt departure is cleared when the plan returns'); assert.equal(selection.has('b'), false, 'the user exclusion is kept'); @@ -122,13 +122,13 @@ test('a cached, unchecked page cannot clear a receipt departure; a click on a de const plans = ['a', 'b'].map(id => plan(id, 'completed')); const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); selection.reconcile('scope', [...plans], true, false); assert.equal(selection.has('a'), false, 'no evidence that it returned'); selection.toggle(plans[0]); assert.equal(selection.has('a'), true, 'an unpressed row is chosen by a click'); assert.equal(selection.snapshot().includes(plans[0]), true, 'not recorded as an exclusion'); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); selection.reconcile('scope', [...plans], true, true); assert.equal(selection.has('a'), true, 'a checked page is evidence'); }); @@ -136,7 +136,7 @@ test('an Undo receipt clears only the departure, not explicit exclusions', () => const plans = ['a', 'b', 'c'].map(id => plan(id, 'completed')); const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); selection.toggle(plans[1]); - selection.forget(['a', 'b']); + selection.forget(new Map<string, number | null>([['a', null], ['b', null]])); selection.returned(['a', 'b']); assert.equal(selection.has('a'), true); assert.equal(selection.has('b'), false); @@ -147,7 +147,7 @@ test('a departed row kept in a cached page is not counted as selected', () => { const plans = ['a', 'b'].map(id => plan(id, 'completed')); const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); assert.equal(selection.count, 1); selection.reconcile('scope', [...plans], true, false); assert.equal(selection.count, 1, 'the cached row is known but not selected'); @@ -157,10 +157,89 @@ test('one click selects a row that was both excluded by the user and taken out b const selection = new PlanSelection(); selection.reconcile('scope', plans, true); selection.selectAll(); selection.toggle(plans[0]); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); selection.returned(['a']); assert.equal(selection.has('a'), false, 'passive handling keeps the exclusion'); - selection.forget(['a']); + selection.forget(new Map<string, number | null>([['a', null]])); selection.toggle(plans[0]); assert.equal(selection.has('a'), true, 'an explicit click selects it in one step'); }); + +const cleaned = (id: string, revision: number): CleanupPlan => ({ ...plan(id, 'completed'), cleanup: { state: 'visible', revision } }); +const departures = (...pairs: [string, number][]) => new Map<string, number | null>(pairs); + +test('a departed plan found at a newer cleanup generation than its receipt is counted again; at that generation it is not', () => { + const plans = ['a', 'b'].map(id => cleaned(id, 1)); + const selection = new PlanSelection(); + selection.reconcile('scope', plans, true); selection.selectAll(); + selection.forget(departures(['a', 3])); + const rule = selection.snapshot().includes; + assert.equal(rule(cleaned('a', 3)), false, 'still at the generation the receipt returned'); + assert.equal(rule(cleaned('a', 2)), false, 'an older copy is no evidence'); + assert.equal(rule(cleaned('a', 4)), true, 'restored or archived again elsewhere since'); + assert.equal(rule(cleaned('b', 1)), true, 'another plan is unaffected'); +}); +test('a departed plan the selection never loaded is counted again from the generation its receipt returned', () => { + const selection = new PlanSelection(); + selection.reconcile('scope', [cleaned('a', 1)], true); selection.selectAll(); + // Select all archived a plan the page never loaded: only the receipt knows its generation. + selection.forget(departures(['never-loaded', 7])); + const rule = selection.snapshot().includes; + assert.equal(rule(cleaned('never-loaded', 7)), false); + assert.equal(rule(cleaned('never-loaded', 8)), true); +}); +test('a deselected plan stays out at a newer generation, with or without a departure', () => { + const plans = ['a', 'b'].map(id => cleaned(id, 1)); + const selection = new PlanSelection(); + selection.reconcile('scope', plans, true); selection.selectAll(); + selection.toggle(plans[0]); + assert.equal(selection.snapshot().includes(cleaned('a', 9)), false, 'deselected only'); + selection.forget(departures(['a', 3])); + assert.equal(selection.snapshot().includes(cleaned('a', 9)), false, 'deselected and departed'); + selection.returned(['a']); + assert.equal(selection.snapshot().includes(cleaned('a', 9)), false, 'a receipt ends the departure only'); + selection.selectAll(); + assert.equal(selection.snapshot().includes(cleaned('a', 9)), true, 'Select all again replaces the selection'); +}); +test('a plan taken out with no generation to compare is not counted again by a count', () => { + const selection = new PlanSelection(); + selection.reconcile('scope', [cleaned('a', 1)], true); selection.selectAll(); + selection.forget(new Map<string, number | null>([['a', null]])); + assert.equal(selection.snapshot().includes(cleaned('a', 99)), false); +}); +test('a later departure keeps the newer generation and one without a generation never ends by a count', () => { + const selection = new PlanSelection(); + selection.reconcile('scope', [cleaned('a', 1), cleaned('b', 1)], true); selection.selectAll(); + selection.forget(departures(['a', 5], ['b', 5])); + selection.forget(departures(['a', 3])); + selection.forget(new Map<string, number | null>([['b', null]])); + const rule = selection.snapshot().includes; + assert.equal(rule(cleaned('a', 4)), false, 'the older reply cannot lower the generation'); + assert.equal(rule(cleaned('a', 6)), true); + assert.equal(rule(cleaned('b', 99)), false, 'a deleted or vanished plan has no generation to supersede'); +}); + +test('the row, the count and the plans of a snapshot agree with a count on a departed plan known at a newer generation', () => { + const plans = ['a', 'b'].map(id => cleaned(id, 1)); + const selection = new PlanSelection(); + selection.reconcile('scope', plans, true); selection.selectAll(); + selection.forget(departures(['a', 3])); + assert.equal(selection.has('a'), false); + assert.equal(selection.count, 1); + // A cached page shows the plan at the generation that took it out: still departed. + selection.reconcile('scope', [cleaned('a', 3), plans[1]], true, false); + assert.equal(selection.has('a'), false); + assert.equal(selection.count, 1); + // A cached page carrying it at a newer generation: the row, the bar count, the snapshot and a scan agree. + selection.reconcile('scope', [cleaned('a', 4), plans[1]], true, false); + assert.equal(selection.has('a'), true); + assert.equal(selection.count, 2); + const snapshot = selection.snapshot(); + assert.deepEqual(snapshot.plans.map(p => p.key).sort(), ['a', 'b']); + assert.equal(snapshot.includes(cleaned('a', 4)), true); + // A deselected plan still stays out everywhere. + selection.toggle(cleaned('a', 4)); + assert.equal(selection.has('a'), false); + assert.equal(selection.count, 1); + assert.equal(selection.snapshot().includes(cleaned('a', 4)), false); +}); diff --git a/tests/browser/cleanup-tidy-controller.test.ts b/tests/browser/cleanup-tidy-controller.test.ts index 5fed69f..0ed5dac 100644 --- a/tests/browser/cleanup-tidy-controller.test.ts +++ b/tests/browser/cleanup-tidy-controller.test.ts @@ -46,7 +46,7 @@ function liveFeed(config: { projects: LiveProject[]; sessions: LiveSession[]; wo }; } const liveSession = (id: string, projectId = 'proj', directory = '/fixture/proj'): LiveSession => ({ id, title: id, projectId, directory, parentId: null, archivedAt: null, worktree: null, activity: 'idle', outcome: null }); -type Opts = { plans?: PlanSummary[]; item?: unknown; live?: { projects: LiveProject[]; sessions: LiveSession[]; worktrees?: { directory: string; name: string; branch: string; status: 'ready' }[] } }; +type Opts = { plans?: PlanSummary[]; item?: unknown; /** Serve the list in cursor pages of this many plans; one page without it. */ pageSize?: number; live?: { projects: LiveProject[]; sessions: LiveSession[]; worktrees?: { directory: string; name: string; branch: string; status: 'ready' }[] } }; function frame(surface: 'page' | 'panel', scan = false, active = false, activeCapability = true, extra: Partial<ViewSpec<any>> = {}, opts: Opts = {}) { const listeners: Record<string, (v?: any) => void> = {}; const focusables = new Map<string, { focused: number; tagName: string; focus(): void; querySelector(): null }>(); @@ -87,14 +87,20 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa let effectiveScope = 'initial'; let vc!: ViewContext<{ filter: string }>; const host = { - async serviceRequest(q: { path: string; body?: string }) { + async serviceRequest(q: { path: string; body?: string; query?: Record<string, string> }) { if (q.path === '/health') { // The reply is decided when the request arrives, as at a real service. const body = JSON.stringify({ ...HEALTH, ...(setupLost ? { ready: false } : {}), ...(capability && !setupLost ? { planCleanup: 1 } : {}), ...(activeCapability ? { planCleanupActive: 1 } : {}) }); if (healthHolds > 0) { healthHolds--; await new Promise<void>(r => { healthWaiting.push(r); }); } return { status: 200, body }; } - if (q.path === '/v1/plans') { lists++; return plansFail ? { status: 500, body: '{"error":"storage"}' } : { status: 200, body: JSON.stringify(plansPage(plans, null, storeId ? { storeId } : {})) }; } + if (q.path === '/v1/plans') { + lists++; + if (plansFail) return { status: 500, body: '{"error":"storage"}' }; + const from = Number(q.query?.cursor ?? 0), size = opts.pageSize; + const page = size ? plans.slice(from, from + size) : plans; + return { status: 200, body: JSON.stringify(plansPage(page, size && from + size < plans.length ? String(from + size) : null, storeId ? { storeId } : {})) }; + } if (['/v1/plan/archive', '/v1/plan/restore', '/v1/plan/delete'].includes(q.path)) { posts.push(q.path); const request = JSON.parse(q.body!); @@ -153,6 +159,8 @@ function frame(surface: 'page' | 'panel', scan = false, active = false, activeCa press(target: unknown) { docListeners.pointerdown({ button: 0, target }); }, refuse(plan: string) { refused = plan; }, addPlan(plan: (typeof plans)[number]) { plans.push(plan); }, + /** Another frame removed the plan from this view: the next list read no longer carries it. */ + dropPlan(id: string) { const at = plans.findIndex(p => p.id === id); if (at >= 0) plans.splice(at, 1); }, /** The control painted with this test id; counts the times the controller moved focus to it. */ focusable(id: string) { const node = { focused: 0, tagName: 'BUTTON', focus() { node.focused++; }, querySelector: () => null }; @@ -1432,3 +1440,114 @@ for (const moved of [false, true]) test(`a count delayed by a held control ${mov assert.equal(cancel.focused, opened + (moved ? 0 : 1)); } finally { f.stop(); } }); + +// Counts from a list read in more than one page, and what the selection learns from a run's receipts. +const isMap = (v: unknown) => Object.prototype.toString.call(v) === '[object Map]', isSet = (v: unknown) => Object.prototype.toString.call(v) === '[object Set]'; +const plain = (v: unknown) => JSON.parse(JSON.stringify(v)); +const closedPlans = () => ['one', 'two', 'three', 'four'].map(id => summary(id, [], { lifecycle: 'finished' })); +const SELECT_ALL = (f: Held) => ({ all: true, plans: f.vc.read!.plans, includes: () => true, scope: 'initial' }); +const named = (f: Held, ids: string[]) => ({ all: false, plans: f.vc.read!.plans.filter(p => ids.includes(p.id)), includes: (p: { id: string }) => ids.includes(p.id), scope: 'initial' }); + +for (const paged of [true, false]) test(`Tidy on a complete list read in ${paged ? 'several pages is qualified on both steps' : 'one page stays exact'}, with no request added`, async () => { + const f = frame('page', false, false, true, {}, { plans: closedPlans(), ...(paged ? { pageSize: 2 } : {}) }); + try { + await until(() => !!f.vc?.read); + const lists = f.lists; + f.vc.requestTidy(); await drain(); + const c = f.vc.cleanup.tidy?.confirmation; + assert.equal(c?.targets.length, 4); + assert.equal(c?.unverified, paged ? true : undefined); + f.vc.deleteTidy(); await drain(); + assert.equal(f.vc.cleanup.tidy?.confirmation?.deleting, true); + assert.equal(f.vc.cleanup.tidy?.confirmation?.unverified, paged ? true : undefined, 'the deletion step repeats the line'); + assert.equal(f.lists, lists, 'no read is sent to produce the count'); + } finally { f.stop(); } +}); +for (const action of ['archive', 'delete'] as const) test(`Select all on a complete list read in several pages is qualified (${action}), and its selection count carries no plus`, async () => { + const f = frame('page', false, false, true, {}, { plans: closedPlans(), pageSize: 2 }); + try { + await until(() => !!f.vc?.read); + const selection = new cleanup.PlanSelection(); + selection.reconcile('scope', f.vc.read!.plans as never, !!f.vc.read!.truncated); selection.selectAll(); + assert.equal(selection.incomplete, false, 'no plus on a complete multi-page list'); + const lists = f.lists; + f.vc.requestSelection(action, SELECT_ALL(f) as never); await drain(); + assert.equal(f.vc.cleanup.tidy?.confirmation?.unverified, true); + assert.equal(f.lists, lists); + } finally { f.stop(); } +}); +test('rows chosen from a complete list read in several pages stay exact', async () => { + const f = frame('page', false, false, true, {}, { plans: closedPlans(), pageSize: 2 }); + try { + await until(() => !!f.vc?.read); + f.vc.requestSelection('archive', named(f, ['one', 'two', 'three']) as never); await drain(); + assert.equal(f.vc.cleanup.tidy?.confirmation?.targets.length, 3); + assert.equal(f.vc.cleanup.tidy?.confirmation?.unverified, undefined); + } finally { f.stop(); } +}); + +/** A run that leaves 'two' unarchived; another frame removes it from the view before the run's last read. */ +async function partialRun(f: Held, selection: boolean, dropIt: boolean) { + await until(() => !!f.vc?.read); + f.refuse('two'); + if (selection) f.vc.requestSelection('archive', named(f, ['one', 'two']) as never); else f.vc.requestTidy(); + await drain(); + f.hold(); f.vc.confirmTidy(); + await until(() => f.posts.length === 1); + if (dropIt) f.dropPlan('two'); + f.release(); + await until(() => !!f.vc.cleanup.tidy?.result); + await until(() => !!f.vc.read && f.vc.read.plans.length === (dropIt ? 3 : 4)); + assert.deepEqual(f.vc.cleanup.tidy?.result?.remaining.map(t => t.request.plan), ['two']); +} +for (const selection of [false, true]) for (const [paged, absent, expected] of [[true, false, undefined], [true, true, true], [false, true, undefined]] as const) { + test(`Try again (${selection ? 'selection' : 'Tidy'}) on a list read in ${paged ? 'several pages' : 'one page'} with the named plan ${absent ? 'missing from' : 'among'} the rows is ${expected ? 'qualified' : 'exact'}, with no request added`, async () => { + const f = frame('page', false, false, true, {}, { plans: closedPlans(), ...(paged ? { pageSize: 2 } : {}) }); + try { + await partialRun(f, selection, absent); + const lists = f.lists; + f.vc.retryTidy(); await drain(); + const c = f.vc.cleanup.tidy?.confirmation; + assert.ok(c, 'the recount is shown'); + assert.deepEqual(c.targets.map(t => t.request.plan), absent ? [] : ['two']); + assert.equal(c.unverified, expected); + assert.equal(f.lists, lists, 'no request is sent to look for the plan'); + } finally { f.stop(); } + }); +} + +// What a run hands the selection: each receipt's cleanup generation, never one read from a loaded row. +test('a bulk run hands the selection a map of plan to the cleanup generation its receipt returned', async () => { + const seen: unknown[] = [], returned: unknown[] = []; + const f = frame('page', false, false, true, { forgetPlans: (_keys: Set<string>, _ui: unknown, _vc: unknown, confirmed: unknown, back: unknown) => { seen.push(confirmed); returned.push(back); return {}; } }); + try { + await until(() => !!f.vc?.read); + f.vc.requestTidy(); await drain(); f.vc.confirmTidy(); + await until(() => !!f.vc.cleanup.tidy?.result); + const receipts = f.vc.cleanup.tidy!.result!.succeeded.map(t => [t.key, t.request.cleanupRev]); + assert.equal(receipts.length, 2); + assert.ok(receipts.every(([, rev]) => rev === 1), 'the fixture service answers with the next generation'); + assert.ok(isMap(seen[0]), 'confirmed receipts travel as a map'); + assert.deepEqual(plain([...(seen[0] as Map<string, number>)]), receipts); + assert.equal(returned[0], undefined); + // Undo: the same receipts come back as a set of keys. + f.vc.undoTidy(); + await until(() => seen.length === 2); + assert.equal(seen[1], undefined); + assert.ok(isSet(returned[1]) && [...returned[1] as Set<string>].length === 2); + } finally { f.stop(); } +}); +test('a single-plan action hands the selection the generation its receipt returned, not the one it started from', async () => { + const spy = boardSpy(); const seen: unknown[] = []; + const f = frame('page', false, false, true, { ...spy.extra, forgetPlans: (_k: Set<string>, _u: unknown, _v: unknown, confirmed: unknown) => { seen.push(confirmed); return {}; } }); + try { + await until(() => !!f.vc?.read); + const plan = f.vc.read!.plans[1]; + f.vc.requestDelete(plan); await until(() => !!f.vc.cleanup.target); + const started = f.vc.cleanup.target!.request.cleanupRev; + f.vc.confirmDelete(); + await until(() => seen.length === 1); + assert.ok(isMap(seen[0]), 'confirmed receipts travel as a map'); + assert.deepEqual(plain([...(seen[0] as Map<string, number>)]), [[plan.key, started + 1]]); + } finally { f.stop(); } +}); diff --git a/tests/browser/plan-task-search-controller.test.ts b/tests/browser/plan-task-search-controller.test.ts index baf85a7..889ecf8 100644 --- a/tests/browser/plan-task-search-controller.test.ts +++ b/tests/browser/plan-task-search-controller.test.ts @@ -573,3 +573,240 @@ test('remembered scopes cannot restore obsolete capture state or pretend their l } finally { a.stop(); } }); }); + +// Result pages, freshness replies and the selection: the production SearchController over the real service. +type Departures = ReadonlyMap<string, number | null>; +/** The plans numbered in `matching` carry the search word in their title; `total` plans are seeded. */ +function seedWord(b: Backend, matching: Iterable<number>, total: number) { + const hits = new Set(matching); + for (let n = 0; n < total; n++) b.f.seedPlan(libraryId(n), hits.has(n) ? `Zq plan ${n}` : 'Ordinary report', [{ id: 'T', title: 'Ordinary task', kind: 'task', status: 'pending' }]); +} +function resultPages(svc: SearchProxy, b: Backend, onGone?: (departures: Departures) => void) { + const gone: Departures[] = []; + let changes = 0; + const c = new SearchController({ + service: (current) => ({ serviceRequest: (q) => (current() ? svc.serviceRequest(q) : Promise.reject(new Error('Retired read'))) }), + changed: () => { changes++; }, visible: () => true, + gone: (departures: Departures) => { gone.push(new Map(departures)); onGone?.(departures); }, + } as ConstructorParameters<typeof SearchController>[0]); + const identity = { storeId: b.f.storeId, binding: { sourceId: b.f.alpha.id, verified: true } }; + const idle = () => until(() => !!c.view() && !c.view()!.busy, 'search action finished'); + let n = 0; + return { + c, gone, plain: { serviceRequest: svc.serviceRequest }, get changes() { return changes; }, + async run(q: string) { c.submit(`pages-${++n}`, criteria({ q }), identity, EMPTY_LIVE); await idle(); return c.view()!; }, + async more() { c.more(); await idle(); return c.view()!; }, + /** A reused page is shown again: nothing has checked it since. */ + revisit() { c.showPage(-1); c.showPage(1); return c.view()!; }, + }; +} +const planKeysOf = (c: SearchController) => [...new Map(c.view()!.page.hits.map(h => [h.plan.key, h.plan])).values()]; + +test('a freshness reply for one page is never credited to the page that took its place', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 120 }, (_, n) => n), 120); + const p = resultPages(svc, b); + await p.run('Zq'); let v = await p.more(); + assert.equal(v.page.number, 2); v = p.revisit(); + assert.equal(v.page.checked, false); + const release = svc.hold('/v1/search-state'); + const reading = p.c.revalidate(p.plain); + await until(() => svc.count('/v1/search-state') === 1, 'the reply for page 2 is held'); + v = await p.more(); + assert.equal(v.page.number, 3, 'Load more dropped page 1 and page 3 took its position'); + release(); await reading; await settle(); + assert.equal(p.c.view()!.page.checked, false, 'the reply was asked about page 2, not page 3'); + await p.c.revalidate(p.plain); + assert.equal(p.c.view()!.page.checked, true, 'a reply that covered its own plans checks it'); + }); +}); + +test('a reply certifies a page only when it covered every plan the page shows; hits read after a page was checked leave it checked', async () => { + await withBackend(false, async (b, svc) => { + // Page 1 is full; page 2 gets one hit, and the next match lies beyond what one action can reach (640 plan slots). + seedWord(b, [...Array.from({ length: 50 }, (_, n) => n), 100, 750], 760); + { + const p = resultPages(svc, b); + await p.run('Zq'); let v = await p.more(); + assert.deepEqual(v.page.hits.map(h => h.plan.id), [libraryId(100)], 'the page is part filled and the search paused'); + p.revisit(); + const base = svc.count('/v1/search-state'); + const release = svc.hold('/v1/search-state'); + const reading = p.c.revalidate(p.plain); + await until(() => svc.count('/v1/search-state') === base + 1, 'the reply for the shown plans is held'); + v = await p.more(); + assert.deepEqual(v.page.hits.map(h => h.plan.id), [libraryId(100), libraryId(750)], 'the running search appended a plan the reply cannot have covered'); + release(); await reading; + assert.equal(p.c.view()!.page.checked, false, 'the reply did not cover the appended plan'); + await p.c.revalidate(p.plain); + assert.equal(p.c.view()!.page.checked, true, 'the next reply covers both'); + } + { + const p = resultPages(svc, b); + let v = await p.run('Zq'); + assert.equal(v.page.checked, true, 'a new search starts checked, filled only by reads of that search'); + v = await p.more(); p.revisit(); + await p.c.revalidate(p.plain); + assert.equal(p.c.view()!.page.checked, true); + v = await p.more(); + assert.deepEqual(v.page.hits.map(h => h.plan.id), [libraryId(100), libraryId(750)]); + assert.equal(v.page.checked, true, 'read from the service just now'); + } + }); +}); + +test('a page opened by Load more starts unchecked and stays so until a reply covers it, also after a failed read', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 80 }, (_, n) => n), 120); + const p = resultPages(svc, b); + let v = await p.run('Zq'); + assert.equal(v.page.checked, true); + v = await p.more(); + assert.equal(v.page.number, 2); + assert.equal(v.page.checked, false, 'a new page is not covered by the replies for the page before it'); + const failing = { serviceRequest: async () => ({ status: 503, body: '{"error":"busy"}' }) }; + assert.equal((await p.c.revalidate(failing)).state, 'failed'); + assert.equal(p.c.view()!.page.checked, false, 'a failed read leaves it unchecked'); + await p.c.revalidate(p.plain); + assert.equal(p.c.view()!.page.checked, true); + }); +}); +test('a Load more page that ends with no hit has nothing to check: no note and no freshness read', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 50 }, (_, n) => n), 120); + const p = resultPages(svc, b); + await p.run('Zq'); + const reads = svc.count('/v1/search-state'); + const v = await p.more(); + assert.equal(v.page.hits.length, 0); + assert.equal(v.exhausted, true); + assert.equal(v.page.checked, true, 'an empty page reports no need to check'); + assert.deepEqual(p.c.freshKeys(), []); + assert.deepEqual(await p.c.revalidate(p.plain), { state: 'retired' }); + assert.equal(svc.count('/v1/search-state'), reads, 'no read was sent for it'); + }); +}); + +test('a cleanup in this frame retires a freshness reply held across it; one made in another frame does not', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 80 }, (_, n) => n), 120); + const p = resultPages(svc, b); + await p.run('Zq'); await p.more(); p.revisit(); + const release = svc.hold('/v1/search-state'); + const reading = p.c.revalidate(p.plain); + await until(() => svc.count('/v1/search-state') === 1, 'the reply is held'); + p.c.retire(); + release(); + assert.deepEqual(await reading, { state: 'retired' }); + assert.equal(p.c.view()!.page.checked, false, 'a reply from before the cleanup marks nothing checked'); + // The selection keeps a plan the cleanup took out: the unchecked page is no evidence that it returned. + const plans = planKeysOf(p.c); + const selection = new cleanup.PlanSelection(); + selection.reconcile('scope', plans, true, false); selection.selectAll(); + selection.forget(new Map<string, number | null>([[plans[0].key, 1]])); + selection.reconcile('scope', plans, true, p.c.view()!.page.checked); + assert.equal(selection.has(plans[0].key), false, 'the departure is not cleared by the retired reply'); + }); +}); +test('a plan archived from another frame still leaves the results and the selection through a reply held meanwhile', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 5 }, (_, n) => n), 10); + const p = resultPages(svc, b); + await p.run('Zq'); + // The service answers when the read arrives; the reply is held on its way back to the frame. + await b.act('archive', libraryId(2)); + const release = svc.hold('/v1/search-state'); + const reading = p.c.revalidate(p.plain); + await until(() => svc.count('/v1/search-state') === 1, 'the reply is held'); + release(); await reading; + assert.deepEqual(p.c.view()!.page.hits.map(h => h.plan.id), [0, 1, 3, 4].map(libraryId)); + assert.equal(p.c.view()!.removed, 1); + }); +}); + +test('a plan a freshness reply shows gone leaves the selection whichever page is shown, with the generation that showed it gone', async () => { + await withBackend(false, async (b, svc) => { + // One plan with 60 matching tasks: its hits span two result pages. + const tasks = Array.from({ length: 60 }, (_, n) => ({ id: `T${n}`, title: `Zq task ${n}`, kind: 'task' as const, status: 'pending' as const })); + b.f.seedPlan('P-span', 'Spanning plan', tasks); + // Finished in two writes (a request changes at most 50 tasks), so cleanup can act on it. + for (let n = 0; n < tasks.length; n += 50) b.f.apply('P-span', { op: 'change', changes: tasks.slice(n, n + 50).map(t => ({ id: t.id, status: 'done' })) }); + b.f.apply('P-span', { op: 'finish', outcome: 'finished' }); + const p = resultPages(svc, b); + await p.run('Zq'); await p.more(); + assert.equal(p.c.view()!.page.number, 2); + const span = planKeysOf(p.c)[0]; + const selection = new cleanup.PlanSelection(); + selection.reconcile('scope', [span as never], true); selection.mode = true; selection.toggle(span as never); + assert.equal(selection.count, 1); + // Another frame archives the plan; the reply for page 2 shows it, and arrives after the person went back to page 1. + await b.act('archive', 'P-span'); + const release = svc.hold('/v1/search-state'); + const reading = p.c.revalidate(p.plain); + await until(() => svc.count('/v1/search-state') === 1, 'the reply for page 2 is held'); + p.c.showPage(-1); + assert.equal(p.c.view()!.page.number, 1); + const generation = b.f.store.detail(b.f.alpha.id, 'P-span').plan.cleanup?.revision; + assert.ok(generation && generation > 0); + release(); await reading; + assert.deepEqual(p.gone.map(g => [...g]), [[[span.key, generation]]], 'the host is told, with the generation of the row that showed the plan archived'); + for (const g of p.gone) selection.forget(g); + assert.equal(selection.count, 0, 'the selected count dropped though page 1 was the page shown'); + }); +}); +test('a plan a reply shows deleted leaves the selection with no generation to compare', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, [0, 1], 4); + const p = resultPages(svc, b); + await p.run('Zq'); + const gone = planKeysOf(p.c)[0]; + await b.act('delete', libraryId(0)); + await p.c.revalidate(p.plain); + assert.deepEqual(p.gone.map(g => [...g]), [[[gone.key, null]]]); + }); +}); +test('a plan archived elsewhere and restored elsewhere is counted again by the next action', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, [0, 1], 4); + const p = resultPages(svc, b); + await p.run('Zq'); + const plans = planKeysOf(p.c); + const selection = new cleanup.PlanSelection(); + selection.reconcile('scope', plans as never, true); selection.selectAll(); + await b.act('archive', libraryId(0)); + await p.c.revalidate(p.plain); + const generation = b.f.store.detail(b.f.alpha.id, libraryId(0)).plan.cleanup!.revision; + for (const g of p.gone) selection.forget(g); + assert.equal(selection.has(plans[0].key), false, 'the selection forgot it'); + const view = (revision: number) => ({ ...plans[0], cleanup: { state: 'visible' as const, revision } }) as never; + assert.equal(selection.snapshot().includes(view(generation)), false, 'still at the generation that showed it gone'); + await b.act('restore', libraryId(0)); + const restored = b.f.store.detail(b.f.alpha.id, libraryId(0)).plan.cleanup!.revision; + assert.ok(restored > generation); + assert.equal(selection.snapshot().includes(view(restored)), true, 'restored elsewhere: counted again at its current generation'); + }); +}); + +test('a selection that throws while following gone plans cannot leave the search half updated or break the poll', async () => { + await withBackend(false, async (b, svc) => { + seedWord(b, Array.from({ length: 5 }, (_, n) => n), 10); + const p = resultPages(svc, b, () => { throw new Error('selection bug'); }); + await p.run('Zq'); + await b.act('archive', libraryId(2)); + const reported: unknown[][] = []; + const original = console.error; + console.error = (...args: unknown[]) => { reported.push(args); }; + const changes = p.changes; + let result: Awaited<ReturnType<typeof p.c.revalidate>>; + try { result = await p.c.revalidate(p.plain); } finally { console.error = original; } + assert.equal(result.state, 'fresh', 'the poll still completes'); + const v = p.c.view()!; + assert.deepEqual(v.page.hits.map(h => h.plan.id), [0, 1, 3, 4].map(libraryId)); + assert.equal(v.removed, 1); + assert.equal(v.stop, 'changed', 'the traversal is retired as for any plan shown gone'); + assert.equal(v.countsCurrent, false); + assert.equal(v.status.message?.kind, 'removed'); + assert.ok(p.changes > changes, 'the frame is told to repaint'); + assert.equal(reported.length, 1, 'the failure is reported, not swallowed silently'); + }); +}); diff --git a/ui/page/main.ts b/ui/page/main.ts index 1681ef8..f81d87e 100644 --- a/ui/page/main.ts +++ b/ui/page/main.ts @@ -86,7 +86,6 @@ let selectionPlans: PlanView[] | null = null; let selectionHits: SearchViewState['page']['hits'] | null = null; let selectionHitCount = -1; let selectionSearchPlans: SearchViewState['page']['hits'][number]['plan'][] = []; -let selectionPage = ''; const derivedBoard = (vc: ViewContext<Ui>) => boardDerivation.get({ plans: vc.read?.plans ?? [], live: vc.env.live, filters: vc.ui.filters, bound: vc.env.boundSource, locale: resolveLanguage('auto', vc.env.locale), archived: vc.ui.archived, @@ -120,6 +119,8 @@ const search = new SearchController({ service: (current) => (frame ? frame.service(current) : { serviceRequest: () => Promise.reject(new Error('Retired read')) }), changed: () => frame?.invalidate(), visible: () => document.visibilityState !== 'hidden', + // A plan a freshness reply shows gone leaves the selection whichever page is shown, with the generation that showed it. + gone: (plans) => selection.forget(plans), }); let submits = 0; let notices = 0; @@ -334,7 +335,7 @@ startView<Ui>({ forgetPlans: (keys, ui, _vc, confirmed, returned) => { // A receipt, not a failed or unsent target, removes a plan from a selection held across a partial list; // an Undo receipt puts it back under a Select all rule (it need not be in the loaded list). - if (confirmed?.size) selection.forget([...confirmed]); + if (confirmed?.size) selection.forget(confirmed); if (returned?.size) selection.returned(returned); if (!keys.has(ui.selected ?? '')) return {}; captures.retire(); reporting.retire(); search.select(null); return { selected: null }; @@ -415,12 +416,6 @@ startView<Ui>({ if (v) search.membership(env.live); // Derive once per list/search page, never walk every plan during an idle paint. if (v && (selectionHits !== v.page.hits || selectionHitCount !== v.page.hits.length)) { - const page = `${ui.search?.key}:${v.page.number}`; - if (selectionPage === page && v.page.checked) { - const keys = new Set(v.page.hits.map(h => h.plan.key)); - selection.forget(selectionSearchPlans.filter(p => !keys.has(p.key)).map(p => p.key)); - } - selectionPage = page; selectionHits = v.page.hits; selectionHitCount = v.page.hits.length; selectionSearchPlans = [...new Map(v.page.hits.map(h => [h.plan.key, h.plan])).values()]; diff --git a/ui/shared/app.ts b/ui/shared/app.ts index dc83c5c..07e5401 100644 --- a/ui/shared/app.ts +++ b/ui/shared/app.ts @@ -250,8 +250,8 @@ export interface ViewSpec<U> { tidyScope?: (vc: ViewContext<U>) => string; /** Whether a counted target is still in the view's scope right now; asked before each cleanup request. */ tidyMember?: (vc: ViewContext<U>, target: CleanupTarget) => boolean; - /** `confirmed`: keys whose cleanup receipt succeeded, given only when a cleanup action ended. */ - forgetPlans?: (keys: Set<string>, ui: U, vc: ViewContext<U>, confirmed?: ReadonlySet<string>, returned?: ReadonlySet<string>) => Partial<U>; + /** `confirmed`: keys whose cleanup receipt succeeded, each with the cleanup generation the receipt returned; given only when a cleanup action ended. */ + forgetPlans?: (keys: Set<string>, ui: U, vc: ViewContext<U>, confirmed?: ReadonlyMap<string, number>, returned?: ReadonlySet<string>) => Partial<U>; /** * The plan this view reads in full detail and the explicit view scope it is read under (rail: the * selected session; board: its own list scope, never the host session). Its task-reading state @@ -796,9 +796,12 @@ export function startView<U>(spec: ViewSpec<U>) { // The old callbacks die with the state; the repaint is background data, never an explicit UI action. cleanup.tidy.scan?.cancel(); cleanup = { ...cleanup, tidy: undefined }; versions.data++; }; - /** `confirmed`: plans a cleanup receipt took out of view; `returned`: plans a receipt put back (Undo). */ + /** + * `confirmed`: plans a cleanup receipt took out of view, each with the cleanup generation the receipt returned; + * `returned`: plans a receipt put back (Undo). + */ /** Callers choose how the change repaints: an explicit action or refresh bumps `versions.ui`, a run's own end `versions.data`. */ - const forgetPlans = (keys: Set<string>, confirmed?: ReadonlySet<string>, returned?: ReadonlySet<string>) => { + const forgetPlans = (keys: Set<string>, confirmed?: ReadonlyMap<string, number>, returned?: ReadonlySet<string>) => { if (reading && keys.has(reading.plan)) clearReading(); if (keys.size && spec.forgetPlans) ui = { ...ui, ...spec.forgetPlans(keys, ui, context(), confirmed, returned) }; }; @@ -1076,7 +1079,10 @@ export function startView<U>(spec: ViewSpec<U>) { ? spec.tidyScan?.(vc, key, p => keys.has(p.key), false, remaining!.map(t => remainingPlan(t, vc))) : spec.tidyScan?.(vc, key)) ?? undefined; const listed = (spec.tidyPlans?.(vc) ?? []).filter(p => !keys || keys.has(p.key)); - const confirmation = scan ? undefined : { ...tidyConfirmation(listed, read.storeId, key, spec.tidyArchived?.(vc)), matching: spec.tidyMatching?.(vc) }; + // A list read in several pages cannot show that no plan crossed a boundary. A recount that found every + // plan it names is exact; one that did not cannot tell a plan that left from one that was missed. + const unverified = !!read.multiPage && (!remaining || listed.length < remaining.length); + const confirmation = scan ? undefined : { ...tidyConfirmation(listed, read.storeId, key, spec.tidyArchived?.(vc), unverified), matching: spec.tidyMatching?.(vc) }; cleanup = { ...initialCleanup(), tidy: { context: key, confirmation, scan, ...(remaining ? { recount: remaining } : {}) } }; askFocus('tidy-cancel'); versions.ui++; schedule(); if (scan) void moreTidy(); @@ -1093,8 +1099,12 @@ export function startView<U>(spec: ViewSpec<U>) { const latest = new Map(read.plans.map(p => [p.key, p])); // A complete list is the displayed one: a plan that has since moved out of scope is not offered. const shown = spec.tidyPlans ? new Set(spec.tidyPlans(vc).map(p => p.key)) : null; - const confirmation = scan ? undefined : selectionConfirmation(selection.plans.filter(p => latest.has(p.key) && (!shown || shown.has(p.key))).map(p => latest.get(p.key)!), read.storeId, key, - !!spec.tidyArchived?.(vc), action, health.planCleanupActive === 1); + const found = selection.plans.filter(p => latest.has(p.key) && (!shown || shown.has(p.key))).map(p => latest.get(p.key)!); + // Rows chosen one by one name their plans and are exact; Select all is a census of the loaded list, and a + // recount is exact only when it found every plan it names (see requestTidy). + const unverified = !!read.multiPage && (selection.all || (!!selection.recount && found.length < selection.plans.length)); + const confirmation = scan ? undefined : selectionConfirmation(found, read.storeId, key, + !!spec.tidyArchived?.(vc), action, health.planCleanupActive === 1, unverified); cleanup = { ...initialCleanup(), tidy: { context: key, selection: action, selectionRequest: selection, opener: `selection-${action}`, confirmation, scan } }; askFocus('tidy-cancel'); versions.ui++; schedule(); if (scan) void moreTidy(); @@ -1171,10 +1181,10 @@ export function startView<U>(spec: ViewSpec<U>) { const same = cleanup.tidy === state && state.context === tidyContext(); if (same && document.activeElement?.closest('[data-testid="tidy-stop"]')) askFocus('tidy-open', 'tidy-stop'); // Reconcile once, including uncertain requests; never retry a refused plan automatically. - const receipts = new Set(result.succeeded.map(t => t.key)); + const receipts = new Map(result.succeeded.map(t => [t.key, t.request.cleanupRev] as const)); // Undo of an archive puts plans back in view; every other successful receipt takes them out. const back = undo && (state.result?.action === 'archive' || !!state.result?.returned); - gate.retire(); resetCaches(); forgetPlans(new Set(targets.map(t => t.key)), back ? undefined : receipts, back ? receipts : undefined); + gate.retire(); resetCaches(); forgetPlans(new Set(targets.map(t => t.key)), back ? undefined : receipts, back ? new Set(receipts.keys()) : undefined); read = null; readScope = ''; readSig = ''; failure = null; cleanup = { ...initialCleanup(), tidy: same ? { context: state.context, result: back ? { ...result, returned: true } : result, selection: state.selection, selectionRequest: state.selectionRequest, opener: state.opener } : undefined }; tidyReconcile = same; @@ -1213,7 +1223,7 @@ export function startView<U>(spec: ViewSpec<U>) { const sameContext = target.context === cleanupContext(); // Also reconcile ambiguous failures. Never replay an action automatically or retain // pre-action data as a fresh success; every part/list reply from before this is retired. - gate.retire(); resetCaches(); forgetPlans(new Set([target.key]), new Set(result.ok ? [target.key] : [])); + gate.retire(); resetCaches(); forgetPlans(new Set([target.key]), new Map(result.ok ? [[target.key, result.cleanup.revision] as const] : [])); read = null; readScope = ''; readSig = ''; failure = null; cleanup = { ...initialCleanup(), error: !result.ok, message: sameContext ? (result.ok ? { kind: action } : { kind: 'error', code: result.failure.code }) : null }; askFocus(result.ok ? 'cleanup-notice' : 'cleanup-error'); versions.ui++; versions.data++; schedule(); retry(); @@ -1493,7 +1503,7 @@ export function startView<U>(spec: ViewSpec<U>) { // Only the captured remaining plans, under the scope displayed now (each is re-checked when sent). const selection = remaining ? { scope: spec.selectionScope?.(context()), - all: false, includes: (p: CleanupPlan) => keys.has(p.key), + all: false, recount: true, includes: (p: CleanupPlan) => keys.has(p.key), plans: remaining.map(t => remainingPlan(t, context())), } : tidyState.selectionRequest; requestSelection(tidyState.selection, selection); diff --git a/ui/shared/cleanup.ts b/ui/shared/cleanup.ts index d0846b9..bf6ab17 100644 --- a/ui/shared/cleanup.ts +++ b/ui/shared/cleanup.ts @@ -119,11 +119,14 @@ export interface TidyState { export function tidyEligible(plan: CleanupPlan, archived = false) { return cleanupClosed(plan) && (plan.cleanup?.state === 'archived') === archived; } -/** Use a loaded list only when its scope is complete; otherwise use CleanupScan. */ -export function tidyConfirmation(plans: CleanupPlan[], storeId: string, context: string, archived = false): TidyConfirmation { +/** + * Use a loaded list only when its scope is complete; otherwise use CleanupScan. `unverified`: the list was + * read in several pages, so a plan that crossed a page boundary may be missing from it. + */ +export function tidyConfirmation(plans: CleanupPlan[], storeId: string, context: string, archived = false, unverified = false): TidyConfirmation { const eligible = plans.filter(p => tidyEligible(p, archived)); return { context, archived, total: Math.min(eligible.length, TIDY_LIMIT), limited: eligible.length > TIDY_LIMIT, - targets: eligible.slice(0, TIDY_LIMIT).map(p => cleanupTarget(p, storeId, context)) }; + targets: eligible.slice(0, TIDY_LIMIT).map(p => cleanupTarget(p, storeId, context)), ...(unverified ? { unverified: true } : {}) }; } export interface CleanupScanPage { plans: CleanupPlan[]; @@ -220,18 +223,28 @@ export class PlanSelection { private known = new Map<string, CleanupPlan>(); private chosen = new Set<string>(); private omitted = new Set<string>(); - /** Plans a cleanup receipt took out of scope: not a user choice, so a plan back in scope is selected again. */ - private departed = new Set<string>(); + /** + * Plans a cleanup receipt (or a freshness reply) took out of scope: not a user choice, so a plan back in + * scope is selected again. The value is the cleanup generation that took the plan out; null when there is + * none to compare, and then only the other rules end the departure. + */ + private departed = new Map<string, number | null>(); private partial = false; private plans: CleanupPlan[] | null = null; private fresh = true; private selectedCount = 0; + /** A departure still holds unless the plan is known at a newer cleanup generation than took it out. */ + private departedHolds(key: string) { + const left = this.departed.get(key); + if (left === undefined) return false; + return left === null || (this.known.get(key)?.cleanup?.revision ?? 0) <= left; + } private recount() { if (!this.all) { this.selectedCount = this.chosen.size; return; } // Only rows the rule actually selects: not user exclusions, not receipt departures kept in a cached page. let out = 0; for (const k of this.omitted) if (this.known.has(k)) out++; - for (const k of this.departed) if (this.known.has(k) && !this.omitted.has(k)) out++; + for (const k of this.departed.keys()) if (this.known.has(k) && !this.omitted.has(k) && this.departedHolds(k)) out++; this.selectedCount = this.known.size - out; } /** `fresh`: the plans are verified membership (a list read, a checked search page), not a cached page. */ @@ -250,7 +263,7 @@ export class PlanSelection { this.recount(); this.version++; } - has(key: string) { return this.all ? !this.omitted.has(key) && !this.departed.has(key) : this.chosen.has(key); } + has(key: string) { return this.all ? !this.omitted.has(key) && !this.departedHolds(key) : this.chosen.has(key); } get count() { return this.selectedCount; } get incomplete() { return this.all && this.partial; } clear() { this.all = false; this.chosen.clear(); this.omitted.clear(); this.departed.clear(); this.selectedCount = 0; this.version++; } @@ -259,18 +272,28 @@ export class PlanSelection { this.known.set(p.key, p); // An explicit click on an unpressed departed row selects it at once (also when the user had excluded it); // passive receipt handling (forget, returned, reconcile) never touches exclusions. - if (this.all && this.departed.delete(p.key)) { this.omitted.delete(p.key); this.recount(); this.version++; return; } + if (this.all && this.departedHolds(p.key)) { this.departed.delete(p.key); this.omitted.delete(p.key); this.recount(); this.version++; return; } + // A departure that no longer holds shows the row pressed: the click is an ordinary toggle. + if (this.all) this.departed.delete(p.key); const set = this.all ? this.omitted : this.chosen; if (set.has(p.key)) set.delete(p.key); else set.add(p.key); this.recount(); this.version++; } - forget(keys: string[]) { - if (!keys.length) return; - for (const key of keys) { + /** + * Plans left the view, each with the cleanup generation that took it out (a receipt's, or the freshness row + * that showed it gone); null when there is none to compare, and a count never takes such a plan back. + */ + forget(departures: ReadonlyMap<string, number | null>) { + if (!departures.size) return; + for (const [key, generation] of departures) { this.known.delete(key); this.chosen.delete(key); // A Select all rule must not keep a departed plan pressed or target it in a later scan. - if (this.all) this.departed.add(key); + if (this.all) { + const had = this.departed.get(key); + // The newest departure decides; one with no generation to compare stays that way. + this.departed.set(key, had === undefined ? generation : had === null || generation === null ? null : Math.max(had, generation)); + } } this.recount(); this.version++; @@ -282,14 +305,22 @@ export class PlanSelection { if (any) { this.recount(); this.version++; } } snapshot(): SelectionRequest { - const all = this.all, chosen = new Set(this.chosen), omitted = new Set([...this.omitted, ...this.departed]); + const all = this.all, chosen = new Set(this.chosen), omitted = new Set(this.omitted), departed = new Map(this.departed); return { all, plans: [...this.known.values()].filter(p => this.has(p.key)), - includes: p => all ? !omitted.has(p.key) : chosen.has(p.key) }; + // A departed plan is counted again only where the view shows it at a newer cleanup generation than took it out. + includes: p => { + if (!all) return chosen.has(p.key); + if (omitted.has(p.key)) return false; + const left = departed.get(p.key); + return left === undefined || (left !== null && (p.cleanup?.revision ?? 0) > left); + } }; } } export interface SelectionRequest { scope?: string; all: boolean; + /** Try again after a run: names the plans it left, looked up among the loaded rows. */ + recount?: boolean; plans: CleanupPlan[]; includes: (plan: CleanupPlan) => boolean; } @@ -301,13 +332,13 @@ export function selectionTargets(c: TidyConfirmation, action: CleanupAction, act const targets = exclude ? c.targets.filter(cleanupClosed) : c.targets; return { ...c, selection: action, activeCount, excludedActive, targets, total: targets.length, deleting: action === 'delete' }; } -export function selectionConfirmation(plans: CleanupPlan[], storeId: string, context: string, archived: boolean, action: CleanupAction, active: boolean) { +export function selectionConfirmation(plans: CleanupPlan[], storeId: string, context: string, archived: boolean, action: CleanupAction, active: boolean, unverified = false) { const matching = plans.filter(p => (p.cleanup?.state === 'archived') === archived); const exclude = action !== 'restore' && !active; const eligible = exclude ? matching.filter(cleanupClosed) : matching; return selectionTargets({ context, archived, targets: eligible.slice(0, TIDY_LIMIT).map(p => cleanupTarget(p, storeId, context)), excludedActive: matching.length - eligible.length, - total: Math.min(eligible.length, TIDY_LIMIT), limited: eligible.length > TIDY_LIMIT }, action, active); + total: Math.min(eligible.length, TIDY_LIMIT), limited: eligible.length > TIDY_LIMIT, ...(unverified ? { unverified: true } : {}) }, action, active); } /** Shared sequential engine: receipt-bound results, no retries, context/Stop checked before each request. * Selection explicitly opts into active targets; Tidy never does. `admit` is asked right before each diff --git a/ui/shared/model.ts b/ui/shared/model.ts index 9d3f6d1..65b8e2b 100644 --- a/ui/shared/model.ts +++ b/ui/shared/model.ts @@ -191,6 +191,12 @@ export interface StoreRead { plans: PlanView[]; /** More pages exist than this frame loaded. */ truncated: boolean; + /** + * A second page was available when the list was read (also when the read stopped at its page bound). + * Offsets between pages are not a snapshot, so a count taken from such a list cannot show that no plan + * crossed a page boundary. Absent: one page, or not recorded. + */ + multiPage?: boolean; } export interface HealthView { ready: boolean; sqlite: boolean; node?: string; diagnostics: string[]; planCleanup?: 1; planCleanupActive?: 1; planChangeDigests?: 1; planTaskSearch?: 1; documentCaptureComparison?: 1; subagentRuns?: 1; planGraph?: 1; needsYouInbox?: 1; delegationIntent?: 1 } diff --git a/ui/shared/search.ts b/ui/shared/search.ts index 32febd1..99e156e 100644 --- a/ui/shared/search.ts +++ b/ui/shared/search.ts @@ -271,9 +271,16 @@ interface Run { status: { id: number; message: SearchStatus | null }; } +/** + * Plans a freshness reply showed gone (missing, deleted or across the archive boundary), each with the cleanup + * generation of the row that showed it; null when the reply holds no such generation (the plan no longer exists). + */ +export type GonePlans = ReadonlyMap<string, number | null>; export interface SearchHost { /** Guarded proxy: a retired caller can no longer send requests. */ service: (current: () => boolean) => ServiceHost; + /** A frame-wide selection follows these plans out, whichever result page is shown. Called before `changed`. */ + gone?: (plans: GonePlans) => void; /** Repaint request after a state change. */ changed: () => void; visible: () => boolean; @@ -351,6 +358,8 @@ export class SearchController { * out of date with Refresh search (cleanup, list eviction). A held reply can no longer act. */ retire(reason: 'retired' | 'identity' = 'retired') { + // A freshness read already sent belongs to what was retired, also when the run was retired before. + this.freshness++; const r = this.run; if (!r) return; this.gate.retire(); @@ -378,6 +387,8 @@ export class SearchController { if (!r || r.busy || r.blocked || !this.continuable(r)) return; if (r.view !== r.pages.length - 1) { r.view = r.pages.length - 1; r.checked = false; } if (r.pages[r.view].length >= SEARCH_PAGE) { + // A new page is certified by a reply that covered its own plans, whatever the page before it was. + r.checked = false; r.pages.push([]); if (r.pages.length > SEARCH_PAGES) { r.pages.shift(); r.firstPage++; } r.view = r.pages.length - 1; @@ -454,8 +465,9 @@ export class SearchController { const current = () => !this.disposed && this.run === r && generation === this.freshness && this.host.visible(); if (!r || !keys.length || !current()) return { state: 'retired' }; const rows = []; - // The keys above belong to the page shown now; a reply is evidence for that page only. - const view = r.view; + // The keys above belong to the page shown now; a reply is evidence for that page only, identified by its + // number in the run: retained pages shift when Load more drops the oldest, so a position is not an identity. + const asked = r.firstPage + r.view; let captureEnabled = true; let firstInbox: InboxFirst | undefined; for (let i = 0; i < keys.length; i += STATE_KEYS) { @@ -471,11 +483,16 @@ export class SearchController { rows.push(...result.state.data); } let gone = 0, moved = 0, reselect = false; + const departures = new Map<string, number | null>(); for (const row of rows) { const key = `${row.source}/${row.plan}`; const known = this.planOf(r, key); if (!known) continue; - if (!row.exists || row.cleanup.state === 'deleted' || (row.cleanup.state === 'archived') !== r.criteria.archived) { this.drop(r, key); gone++; continue; } + if (!row.exists || row.cleanup.state === 'deleted' || (row.cleanup.state === 'archived') !== r.criteria.archived) { + // The generation of the row that showed it gone; none when the plan no longer exists. + departures.set(key, row.exists && row.cleanup.state !== 'deleted' ? row.cleanup.revision : null); + this.drop(r, key); gone++; continue; + } if (row.revision !== known.revision || row.cleanup.revision !== known.cleanup.revision) { if (!r.changed.has(key)) moved++; r.changed.add(key); @@ -484,8 +501,14 @@ export class SearchController { if (s?.key === key && (s.plan.revision !== row.revision || s.plan.cleanup.revision !== row.cleanup.revision)) { r.selected = { key, plan: { ...s.plan, revision: row.revision!, cleanup: { state: row.cleanup.state, revision: row.cleanup.revision } } }; reselect = true; } } } + // A selection held by the frame follows a plan out whichever page is shown, so it hears of every one. + // A selection that fails to follow must not leave the search half updated: the state below is still applied. + if (departures.size) { try { this.host.gone?.(departures); } catch (error) { console.error('The selection could not follow plans a freshness reply showed gone.', error); } } // Repaint only on a change: an unchanged poll leaves the DOM (focus, scroll, selection) alone. - const covers = r.view === view; + // The page shown now is certified only when it is the page asked about and every plan it shows was covered: + // a search still running can append hits the reply could not have seen. + const covered = new Set(rows.map((row) => `${row.source}/${row.plan}`)); + const covers = r.firstPage + r.view === asked && r.pages[r.view].every((h) => covered.has(h.plan.key)); const checked = covers && !r.checked && rows.length > 0; if (covers && rows.length) r.checked = true; if (!gone && !moved) { if (checked || reselect) this.host.changed(); return { state: 'fresh', captureEnabled, ...(inbox ? { inbox: firstInbox } : {}) }; } @@ -511,7 +534,8 @@ export class SearchController { busy: r.busy, stop: r.stop, failure: r.failure, exhausted: r.exhausted && !r.buffer.length, counts: { matchedPlans: r.matchedPlans, matchingTasks: r.matchingTasks }, countsCurrent: r.countsCurrent, coverage: { gapped: r.gapped, skippedRecords: r.skippedRecords, reasons: [...r.reasons] }, windows: r.windows, - page: { number: r.firstPage + r.view, hits, groups, contextRows: context.size, checked: r.checked }, + // A page that shows no plan has nothing to check; derived from the hits each time, never stored. + page: { number: r.firstPage + r.view, hits, groups, contextRows: context.size, checked: r.checked || hits.length === 0 }, hasPrevious: r.view > 0, hasNext: r.view < r.pages.length - 1, more: r.buffer.length > 0 || !r.exhausted, removed: r.removed, changedKeys: r.changed.size, diff --git a/ui/shared/source.ts b/ui/shared/source.ts index 8b4f6b6..ed63a13 100644 --- a/ui/shared/source.ts +++ b/ui/shared/source.ts @@ -205,8 +205,9 @@ export type ListResult = /** `health`: the capabilities of a health reply that was read before the failure, when there was one. */ | { ok: false; failure: ReadFailure; health?: ReturnType<typeof parseHealth> }; -const toRead = (e: EnvelopeView, plans: PlanView[], truncated: boolean): StoreRead => ({ +const toRead = (e: EnvelopeView, plans: PlanView[], truncated: boolean, multiPage = false): StoreRead => ({ storeId: e.storeId, sources: e.sources, binding: e.binding, captureEnabled: e.captureEnabled, coverage: e.coverage, diagnostics: e.diagnostics, plans, truncated, + ...(multiPage ? { multiPage: true } : {}), }); /** Null checks availability without plans; {} deliberately reads the unfiltered history board. */ @@ -271,7 +272,7 @@ export async function readList(host: ServiceHost, scope: ListScope | null, maxPa } cursor = next.nextCursor; } - const read = toRead(first.envelope, plans, Boolean(cursor)); + const read = toRead(first.envelope, plans, Boolean(cursor), first.nextCursor !== null); return { ok: true, health, read, ...(inbox ? { inbox: firstInbox(askInbox, firstBody, read, inbox.demand === 'rows', receivedAt) } : {}) }; } catch (error) { return { ok: false, failure: classify(error), ...(seen ? { health: seen } : {}) }; From 5ba4567ca3405661ab2f5330637c2f7b7e70c0ab Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:30:38 +1100 Subject: [PATCH 10/11] test: run the serial backend group beside the other suites (#170) Run the port-bound backend group in its own lane beside the typechecks, the parallel backend group and the browser and automation tests, so the Linux check step finishes sooner. The serial group stays one --test-concurrency=1 invocation; a listen probe found no other lane binding Setup ports, and the built-service cleanup test joins the serial group when CP_BUILT_SERVICE=1. - Node compile cache under node_modules/.cache, emptied at each run start and turned off with a note if it cannot be created. - The Linux jobs skip the zip/unzip install when the tools are present. - The Windows job runs its two native files concurrently, each waited on as a whole process tree. - New bun run test:fast and test:all share one plan with CI. - The lane runner stops every process group it starts on every exit path, retires groups once empty, never signals an unsafe or reused id, handles SIGINT, SIGTERM and SIGHUP, and exits 128 plus the signal when interrupted. Stopping on Windows is best effort and was not run there. No tests were removed and the counts are unchanged. --- .github/workflows/ci.yml | 68 +++- CONTRIBUTING.md | 71 +++- docs/compatibility.md | 3 +- openspec/changes/release-1-5-2/tasks.md | 10 + package.json | 2 + scripts/ci-backend.ts | 24 +- scripts/ci.ts | 17 +- scripts/test-lanes.ts | 255 +++++++++++++ scripts/test-plan.ts | 69 ++++ scripts/test.ts | 23 ++ tests/automation/ci.test.ts | 81 +++- tests/automation/release.test.ts | 4 +- tests/automation/test-lanes.test.ts | 410 +++++++++++++++++++++ tests/automation/workflow-triggers.test.ts | 13 +- tsconfig.json | 2 +- 15 files changed, 1017 insertions(+), 35 deletions(-) create mode 100644 scripts/test-lanes.ts create mode 100644 scripts/test-plan.ts create mode 100644 scripts/test.ts create mode 100644 tests/automation/test-lanes.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 71ed3ea..68b61b8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,7 +125,8 @@ jobs: with: bun-version: 1.3.14 - name: Install ZIP tools - run: sudo apt-get update && sudo apt-get install -y zip unzip + # Hosted images already carry both tools; install only if one is missing. + run: command -v zip >/dev/null && command -v unzip >/dev/null || (sudo apt-get update && sudo apt-get install -y zip unzip) - name: Install project dependencies run: bun install --frozen-lockfile --ignore-scripts - name: Run Linux tests, builds and package checks @@ -172,7 +173,8 @@ jobs: with: bun-version: 1.3.14 - name: Install ZIP tools - run: sudo apt-get update && sudo apt-get install -y zip unzip + # Hosted images already carry both tools; install only if one is missing. + run: command -v zip >/dev/null && command -v unzip >/dev/null || (sudo apt-get update && sudo apt-get install -y zip unzip) - name: Install project dependencies run: bun install --frozen-lockfile --ignore-scripts - name: Run Linux tests, builds and package checks @@ -216,9 +218,23 @@ jobs: # ownership semantics without relaxing the product's SID policy. $name = 'progress' + [Guid]::NewGuid().ToString('N').Substring(0, 10) $password = ConvertTo-SecureString ('Aa1!' + [Guid]::NewGuid().ToString('N')) -AsPlainText -Force - $output = Join-Path $env:RUNNER_TEMP ($name + '.stdout') - $errors = Join-Path $env:RUNNER_TEMP ($name + '.stderr') $trace = Join-Path $env:RUNNER_TEMP 'windows-migration-trace.jsonl' + # The two native files run side by side, each in its own serial test + # runner. Only the service file starts a server and request workers, + # which are what take Setup coordination ports; the platform file + # drives the setup controller directly. Each runs under Start-Process + # -Wait inside a thread job, so it is waited for with everything it + # started, exactly as when they ran one after the other. Starting the + # two at the same instant can be refused once, so the start is retried. + $runs = @('windows-platform', 'windows-service') | ForEach-Object { + [pscustomobject]@{ + File = $_ + Output = Join-Path $env:RUNNER_TEMP ($name + '.' + $_ + '.stdout') + Errors = Join-Path $env:RUNNER_TEMP ($name + '.' + $_ + '.stderr') + Job = $null + ExitCode = $null + } + } # Leave a fixed diagnostic even if principal/process creation fails. '{"request":"runner-start","completed":false}' | Set-Content -LiteralPath $trace -Encoding utf8 $created = $false @@ -227,23 +243,45 @@ jobs: $created = $true Add-LocalGroupMember -SID 'S-1-5-32-545' -Member $user $credential = [PSCredential]::new(($env:COMPUTERNAME + '\' + $name), $password) - $process = Start-Process -FilePath (Get-Command node).Source -ArgumentList '--experimental-strip-types --test --test-concurrency=1 tests/backend/windows-platform.test.ts tests/backend/windows-service.test.ts' -WorkingDirectory $env:GITHUB_WORKSPACE -Credential $credential -LoadUserProfile -WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput $output -RedirectStandardError $errors - if (Test-Path $output) { - Get-Content -LiteralPath $output + foreach ($run in $runs) { + $run.Job = Start-ThreadJob -ArgumentList $run, $credential, $env:GITHUB_WORKSPACE, (Get-Command node).Source -ScriptBlock { + param($run, $credential, $workspace, $node) + # The secondary logon service creates one process at a time and + # refuses a second request while it is busy; retry only that refusal. + $process = $null + for ($attempt = 1; -not $process; $attempt++) { + try { + $process = Start-Process -FilePath $node -ArgumentList "--experimental-strip-types --test --test-concurrency=1 tests/backend/$($run.File).test.ts" -WorkingDirectory $workspace -Credential $credential -LoadUserProfile -WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput $run.Output -RedirectStandardError $run.Errors -ErrorAction Stop + } catch { + if ($attempt -ge 30 -or $_.Exception.Message -notmatch 'already running') { throw } + Start-Sleep -Seconds 1 + } + } + $process.ExitCode + } + } + $null = $runs.Job | Wait-Job + foreach ($run in $runs) { $run.ExitCode = @(Receive-Job -Job $run.Job -ErrorAction Stop)[-1] } + foreach ($run in $runs) { + if (Test-Path $run.Output) { + Get-Content -LiteralPath $run.Output + } + if (Test-Path $run.Errors) { Get-Content -LiteralPath $run.Errors } } - if (Test-Path $errors) { Get-Content -LiteralPath $errors } - if ($process.ExitCode -ne 0) { throw 'Native Windows tests failed.' } + if (@($runs | Where-Object { $_.ExitCode -ne 0 }).Count -gt 0) { throw 'Native Windows tests failed.' } } finally { # Preserve per-request evidence even on an assertion/process failure. # Never upload raw stdout/stderr, local principal names or paths. - if (Test-Path $output) { - $traces = @(Get-Content -LiteralPath $output | ForEach-Object { - if ($_ -match '^\s*(?:#\s*)?WINDOWS_MIGRATION_TRACE (.+)$') { $Matches[1] } - }) - if ($traces.Count -gt 0) { $traces | Add-Content -LiteralPath $trace -Encoding utf8 } + foreach ($run in $runs) { + if (Test-Path $run.Output) { + $traces = @(Get-Content -LiteralPath $run.Output | ForEach-Object { + if ($_ -match '^\s*(?:#\s*)?WINDOWS_MIGRATION_TRACE (.+)$') { $Matches[1] } + }) + if ($traces.Count -gt 0) { $traces | Add-Content -LiteralPath $trace -Encoding utf8 } + } } if ($created) { Remove-LocalUser -Name $name } - Remove-Item -LiteralPath $output, $errors -Force -ErrorAction SilentlyContinue + Remove-Item -LiteralPath @($runs | ForEach-Object { $_.Output; $_.Errors }) -Force -ErrorAction SilentlyContinue } $requests = @(Get-Content -LiteralPath $trace | ForEach-Object { $_ | ConvertFrom-Json } | Where-Object { $_.request -and $_.request -notin @('runner-start','summary') }) if ($requests.Count -eq 0) { throw 'Native Windows request trace is missing.' } diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 38a891f..47d9a95 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -40,6 +40,20 @@ Released-writer delegation fixtures require the local `v1.3.0` tag. Run skip with a prerequisite diagnostic when the tag is unavailable. Full portable CI requires full history and tags, so these cases run there. +Two scripts run the portable groups side by side after building every entry, and print each step's duration at the end: + +```sh +# Edit-and-check loop: both typechecks, the parallel backend group, browser-model +# and automation tests. It skips the serial Setup-port backend group (below), +# which holds most of the full run's time, so it is not what CI runs. +bun run test:fast + +# Everything portable CI tests, minus packaging and the rebuild comparison +bun run test:all +``` + +Both leave out the five native-only backend tests (see [Portable CI](#portable-ci--fresh-disposable-checkout-only)) and say so. Run `bun run test:all` or the commands below before a pull request when you touched backend, setup or service code; `test:fast` can pass where the serial group would fail. They are not replacements for `node --experimental-strip-types scripts/ci.ts` in a fresh checkout. + Run the checks relevant to your change: ```sh @@ -89,6 +103,56 @@ concurrent writer. Keep new fenced HTTP/worker test files in the list in This isolates tests, not product requests; no port override or relaxed refusal is used. +That serial group is the longest part of the run. It is one request after another, +each starting a worker thread, plus a few deliberate deadline waits, so it is bound by +latency rather than by cores; no other group acquires Setup ports (checked with a probe +on the acquisition call). `scripts/ci.ts` +and `bun run test:all` therefore run it in one lane beside a second lane that +holds both typechecks, the parallel backend group and the browser-model and +automation tests (`scripts/test-plan.ts`, `scripts/test-lanes.ts`). The second +lane is capped at the machine's cores minus two and runs under `nice`, so the +timing assertions in the serial group keep their headroom (the cap never goes below +one worker, so on one to three cores the lane runs one worker at a time). A file that takes +a Setup port belongs in the serial group; never add one to the other lane. A listen probe +(a preload on `net.Server.prototype.listen`, covering worker threads, child processes and the +bundled `build/service/main.js`) found that no file in the parallel group or the browser and +automation tests takes one in the CI configuration. One file does in one configuration CI does +not use: `plan-cleanup-service.test.ts` runs the built service when `CP_BUILT_SERVICE=1`, and the +plan then moves it into the serial group (`fencedWhenSet` in `scripts/ci-backend.ts`). + +The runner (`scripts/test-lanes.ts`) is POSIX-first: it prints each step's output whole under its +own heading (the last 2 MB if a step is noisier, saying what was dropped), names the steps still +running about every minute, and ends with a per-step duration list. The first failure, SIGINT, +SIGTERM, SIGHUP or a closed output pipe (`test:all | head`) stops both lanes and prints what the +running steps had written. Each step runs in its own process group, so the runner stops the groups +itself: a repeated signal, or a step that has not stopped ten seconds after the first, is killed +outright and abandoned even if a leftover process still holds its output pipes, and every group +the runner started is swept as soon as its leader has exited and its pipes have closed (SIGTERM, a short +bound, SIGKILL, a short bound, then a probe that finds the group empty), whether the step passed or not, +because a leader that exits 0 can leave descendants holding a port. A group leaves the record the moment a +probe finds it empty and is never signalled afterwards, since its id may then belong to an unrelated +process; every signal is preceded by a fresh probe, and the closing sweep and the exit hook touch only +groups not yet confirmed empty. Group ids are checked before use (a whole number above 1 that is neither +the runner nor its parent), and a crash of the runner kills what is still recorded. On Windows `taskkill` +goes only to a child whose `exit` has not fired. An +interrupted run exits 128 plus the signal number (130, 143, 129, 141), a failed one 1. A step +the runner stopped is reported as stopped; one that fails on its own is reported as failed with +its output, whenever it does so. On Windows steps are not detached and are stopped with +`taskkill /T /F`; that path is covered by a unit test of the stop command but has not been run on +Windows, and the typecheck step's `./node_modules/.bin/tsc` is a POSIX path, so on Windows run the +individual commands listed under Local development by hand. The process-group and signal cases of +`tests/automation/test-lanes.test.ts` are skipped on Windows (its stop-command case runs), and every case +stops the processes it started even when it fails. + +Both runners also turn on Node's compile cache for every step they start +(`NODE_COMPILE_CACHE`, a folder under the ignored `node_modules/.cache/`). It keeps +V8's compiled code per source file and checks it against the source's hash, so a changed +file is recompiled rather than served stale, and each test process and each request +worker the managed-step tests start compiles a shared module once. It changes no test +input and is emptied at the start of every run (fixtures run from fresh temporary folders, so a +kept cache only grows); a standalone `node --test` run does not use it unless you export the +variable yourself. + This is **not native GUI/OpenCode or host-installer certification**. The external host-installer gate is separate, as described below. Full `bun run check` retains the native backend prerequisites; it is not the portable CI command. The [workflow](.github/workflows/ci.yml) runs on pushes to `main` and `dev`, on every pull request whatever branch it targets, weekly on Tuesday at 04:17 UTC, and on manual dispatch. A PR stacked on another feature branch gets the same selection as one targeting `dev`. It retains the Linux portable checks on exactly Node 24.19.0, repeats them on the newest Node 24 release, and adds a targeted Windows native-filesystem suite. A newer push to a pull request cancels that pull request's earlier run. Versioned publication also waits for the full Windows job on its `main` push. Neither job substitutes for actual OpenCode/OpenChamber integration acceptance. @@ -114,7 +178,12 @@ dispatch run the full set, even for UI/docs-only changes. The workflow sets `AP_WINDOWS_FULL=1` only for those full runs and fetches `v1.1.1` only then. Without that opt-in, the three journeys explicitly skip; no per-request assertion, budget or deadline is relaxed. Local full native runs must also set -`AP_WINDOWS_FULL=1`. Weekly and manual CI runs target Windows only; the Linux +`AP_WINDOWS_FULL=1`. The Windows job starts the platform file and the service file +as two processes at once, each in its own serial test runner and as the same +unprivileged principal, each started with `Start-Process -Wait` inside a PowerShell thread job so +it is waited for together with everything it started, and reads both exit codes after both end; only the +service file starts a server and request workers, which take the Setup coordination +ports. Weekly and manual CI runs target Windows only; the Linux jobs retain their PR/push coverage. See [native Windows verification](docs/compatibility.md#native-windows-verification). Only `main` pushes can publish releases. A `dev` push runs portable checks but is never release-eligible; its publish job may appear as skipped. Accept the source on `dev` first, then prepare a promotion commit containing that source and its built outputs. Run the required host gates on the promotion checkout before its PR into `main` merges. diff --git a/docs/compatibility.md b/docs/compatibility.md index cf86bc5..1f8554f 100644 --- a/docs/compatibility.md +++ b/docs/compatibility.md @@ -493,7 +493,8 @@ permits cleanup/permission repair. See The `Windows setup, storage and capture` CI job runs the native platform suite and `tests/backend/windows-service.test.ts` in the same provisioned non-admin -account. Ordinary PRs run it when backend/build/test inputs change (unknown +account, as two processes at once, each in its own serial test runner and each waited for +with everything it started (`Start-Process -Wait` inside a thread job). Ordinary PRs run it when backend/build/test inputs change (unknown paths conservatively run it); UI, documentation, OpenSpec and browser-test-only PRs skip it, as do duplicate same-repository main/dev heads outside promotion. Every `dev` push runs the fast set. This retains every native test except three diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/release-1-5-2/tasks.md index bb1dabb..a090f5b 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/release-1-5-2/tasks.md @@ -64,6 +64,16 @@ Each numbered group is one pull request into the development branch. It carries - [ ] 7.5 In the same pull request, reconcile the task lists of the 1.5.0 change, the 1.5.1 change and this one: tick each task whose work shipped, and leave a task that did not happen unticked with a note saying whether it is deferred, superseded or out of scope. - [ ] 7.6 In the same pull request, archive the 1.5.0 change, then the 1.5.1 change, then this one, in that order, because each later change modifies capabilities the earlier ones introduced. Never use `--skip-specs` or `--no-validate`. A rehearsal showed what this pull request must correct in the 1.5.1 change's deltas before archiving that change. First, restore the two scenario names that the 1.5.0 specs hold and two of its modified requirements dropped, either by putting the old name on the new content or by keeping the old scenario beside the renamed one. Second, shorten or split the four requirement texts that would exceed 500 characters once in the specs, keeping their meaning and their scenarios. That includes the result requirement at 628 characters, although this change replaces it in the third archive: strict validation runs after the second archive too. After each archive, write the purpose of every capability it created, ten in all, and validate the specs strictly. That validation reports nothing after each of the three archives. If an archive refuses any other delta, correct the delta. +## 9. Faster test suites + +- [x] 9.1 Measure where the portable run spends its time before changing anything: the serial backend group that acquires Setup coordination ports is about two thirds of the Linux step, and one file in it is most of that group. Record the per-step durations of recent CI runs and the per-file durations of that group. +- [x] 9.2 Run the serial Setup-port backend group beside the typechecks, the parallel backend group and the browser-model and automation tests instead of before them, in portable CI and in a new local runner that shares one plan with it. Keep the serial group as one `--test-concurrency=1` invocation that nothing else joins, cap the other lane at the machine's cores minus two, print each step's output whole under its own heading, stop every lane at the first failure or on SIGINT, SIGTERM, SIGHUP or a closed output pipe, keeping the output of steps still running and sweeping each step's group as soon as its leader has exited and its pipes closed, passed or not, retiring a group the moment it is empty and never signalling it afterwards, and sweeping only unconfirmed groups at the end (and killing them after a crash or a repeated signal), exit with 128 plus the signal number when interrupted, tail-limit and heartbeat the step output, mark a step the runner stopped as stopped and one that fails by itself as failed, and keep the second build comparison and the package checks after all tests. Show with a preload probe on the listen call, covering worker threads, child processes and the bundled service, that the parallel backend group and the browser and automation tests take no Setup port, and fence the one file that does when `CP_BUILT_SERVICE=1` is set. Give the plan a core count so one to three cores are tested. +- [x] 9.3 Add `bun run test:fast` (both typechecks, the parallel backend group, browser-model and automation tests) and `bun run test:all` (everything portable CI tests except packaging and the rebuild comparison), document them in the contributor guide, and cover the plan and the runner with automation tests: every portable file runs once, the serial group is alone and serial, and a failure stops the other lane. +- [x] 9.4 Turn on Node's compile cache, in a folder under the ignored dependency folder, for every step of the CI and local runners. It checks each cached file against the source's hash, so no test input changes. Record its effect from CI step timings and from the heaviest managed-step test run alone, and say that the typecheck times did not move. +- [x] 9.5 Skip installing the ZIP tools in the two Linux CI jobs when the runner image already has them. Keep every job and check name, the secrets scan and the second build unchanged. +- [x] 9.6 Start the two native Windows test files as two processes at once in the Windows job, each in its own `--test-concurrency=1` runner and as the same unprivileged principal, each waited for with everything it started, and read both exit codes and both request traces after both end. Only the service file starts a server and request workers, so only it takes Setup coordination ports. The same 26 tests run, with the same pass and skip counts as before. +- [x] 9.7 Remove or merge no test. Record what was considered and rejected as unsafe or unproven in the pull request. + ## Deferred acceptance and out-of-scope follow-up - [ ] Promotion to the distribution branch and its host gates, as the contributor guide describes. It follows the release pull request, and so the archive of this change. The nine generated outputs are built and committed by the promotion only. diff --git a/package.json b/package.json index 56f46f9..5922356 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,8 @@ "scripts": { "typecheck": "tsc --noEmit", "test:backend": "bun run build:all && node --experimental-strip-types --test tests/backend/*.test.ts", + "test:all": "bun run build:all && node --experimental-strip-types scripts/test.ts", + "test:fast": "bun run build:all && node --experimental-strip-types scripts/test.ts --fast", "build:backend": "bun scripts/build.ts", "build:all": "node --experimental-strip-types scripts/build-all.ts", "build": "bun run build:all", diff --git a/scripts/ci-backend.ts b/scripts/ci-backend.ts index f3d52ff..d9c74e0 100644 --- a/scripts/ci-backend.ts +++ b/scripts/ci-backend.ts @@ -16,8 +16,28 @@ const fenceTests = new Set([ 'windows-service.test.ts', ]); -export function backendTestCommands(files: string[]): string[][] { - const fenced = (file: string) => fenceTests.has(file.split('/').at(-1)!); +/** Backend files that need an independent OpenCode binary and Linux isolation + * tools. Portable CI and the local runners leave them out and say so. */ +export const nativeOnlyTests = [ + 'production-runtime.test.ts', + 'plugin-failure-runtime.test.ts', + 'progress-activation-runtime.test.ts', + 'subagent-activity-runtime.test.ts', + 'subagent-upgrade-runtime.test.ts', +]; + +/** Files that take Setup ports only when an environment variable opts in, mapped to + * that variable. `plan-cleanup-service.test.ts` runs the checked-in built service, + * whose readiness probe takes writer slots, when `CP_BUILT_SERVICE=1` (found with a + * listen probe, bundled service included). Where the opt-in is set the file is + * fenced; where it is not, the file takes no port and stays in the parallel group. */ +export const fencedWhenSet: Record<string, string> = { 'plan-cleanup-service.test.ts': 'CP_BUILT_SERVICE' }; + +export function backendTestCommands(files: string[], environment: NodeJS.ProcessEnv = process.env): string[][] { + const fenced = (file: string) => { + const name = file.split('/').at(-1)!; + return fenceTests.has(name) || (name in fencedWhenSet && environment[fencedWhenSet[name]] === '1'); + }; return [ ['--experimental-strip-types', '--test', ...files.filter(file => !fenced(file))], ['--experimental-strip-types', '--test', '--test-concurrency=1', ...files.filter(fenced)], diff --git a/scripts/ci.ts b/scripts/ci.ts index 128c41c..02dcc82 100644 --- a/scripts/ci.ts +++ b/scripts/ci.ts @@ -4,7 +4,9 @@ import { readFileSync, readdirSync, mkdirSync, existsSync, copyFileSync, writeFi import { createHash } from 'node:crypto'; import { eligibility, assetNames, validateReleaseNotes } from './release.ts'; import { verifyCompanionEntry } from './companion-entry.ts'; -import { backendTestCommands } from './ci-backend.ts'; +import { nativeOnlyTests } from './ci-backend.ts'; +import { LanesError, runLanes } from './test-lanes.ts'; +import { freshCompileCache, portableLanes } from './test-plan.ts'; import { buildAll, outputHashes, compareOutputs } from './build-all.ts'; import { revisionKind, trackedOutputs } from './revision-kind.ts'; @@ -14,7 +16,6 @@ if (existsSync('build/artifacts') && readdirSync('build/artifacts').length > 0) process.exit(1); } -const excluded = ['production-runtime.test.ts', 'plugin-failure-runtime.test.ts', 'progress-activation-runtime.test.ts', 'subagent-activity-runtime.test.ts', 'subagent-upgrade-runtime.test.ts']; function run(command:string, args:string[]) { if (spawnSync(command,args,{stdio:'inherit'}).status !== 0) throw new Error('Portable check failed'); } @@ -33,12 +34,12 @@ if (kind === 'source') buildAll(); const before = outputHashes(); verifyCompanionEntry(process.cwd()); mkdirSync('/tmp/opencode',{recursive:true}); -console.log(`Native-only tests NOT RUN: ${excluded.join(', ')}`); -run('bun',['run','typecheck']); -run('./node_modules/.bin/tsc',['-p','ui/tsconfig.json','--noEmit']); -const tests = (dir:string) => readdirSync(dir).filter(f=>f.endsWith('.test.ts')).sort().map(f=>`${dir}/${f}`); -for (const args of backendTestCommands(tests('tests/backend').filter(f=>!excluded.includes(f.split('/').at(-1)!)))) run('node',args); -run('node',['--experimental-strip-types','--test',...tests('tests/browser'),...tests('tests/automation')]); +console.log(`Native-only tests NOT RUN: ${nativeOnlyTests.join(', ')}`); +// Root and UI typechecks, the parallel backend group, and browser-model and +// automation tests run beside the serial backend group that binds Setup ports. +// Output is grouped per step and the first failure stops every lane. +try { await runLanes(portableLanes({ fenced: true, env: freshCompileCache() })); } +catch (error) { console.error(error instanceof Error ? error.message : error); process.exit(error instanceof LanesError ? error.exitCode : 1); } buildAll(); compareOutputs(before); // The SDK's own readiness check: manifest schema, page scripts and service entry. diff --git a/scripts/test-lanes.ts b/scripts/test-lanes.ts new file mode 100644 index 0000000..261a233 --- /dev/null +++ b/scripts/test-lanes.ts @@ -0,0 +1,255 @@ +/** Runs independent groups of checks side by side. A lane is an ordered list of + * steps that stop at the first failure; lanes share nothing but the checkout. + * Output is captured per step and written whole when the step ends, so lines + * from different lanes never interleave. + * + * POSIX first. Each step runs in its own process group, so a signal to this + * process would not reach it; the runner therefore stops every step itself, on the + * first failure and on SIGINT, SIGTERM, SIGHUP or a closed output pipe, and a step + * left running would keep holding the Setup ports the next run needs. A repeated + * signal, or a step that ignores the first one for too long, is killed outright + * and abandoned even if its output pipes are still held open; every group the + * runner started is swept as soon as its leader has exited and its pipes have + * closed, passing or not, since a leader that exits 0 can leave descendants + * holding ports. A group is retired the moment a probe finds it empty and never + * signalled afterwards (its id may then belong to someone else); every signal is + * preceded by a probe, and the exit hook and closing sweep touch only groups not + * yet confirmed empty. On Windows steps are not detached and are stopped with + * `taskkill /T /F`; that path is untested on Windows. */ +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; + +/** `lowPriority` runs the step under `nice`, so a lane that must keep its timing + * headroom wins the cores when the machine is short of them. */ +export type Step = { label: string; command: string; args: string[]; lowPriority?: boolean; env?: Record<string, string> }; +export type Lane = { name: string; steps: Step[] }; +export type StepResult = { lane: string; label: string; seconds: number; status: 'passed' | 'failed' | 'stopped' }; +export type RunOptions = { + /** How often to name the steps still running. */ + heartbeatMs?: number; + /** How long a step may take to stop before it is killed and abandoned. */ + killAfterMs?: number; + /** How long a step that has exited may keep its output pipes open. */ + graceMs?: number; + /** The most output kept per step; the earliest is dropped first. */ + maxOutputBytes?: number; + /** How long a group sweep waits for the group to leave after SIGTERM, and again after SIGKILL. */ + sweepMs?: number; + /** Replaces process.kill for every probe and signal sent to a process group; for tests. */ + kill?: Kill; +}; + +export type Kill = (pid: number, signal: NodeJS.Signals | 0) => void; + +const SIGNAL_NUMBER: Record<string, number> = { SIGHUP: 1, SIGINT: 2, SIGPIPE: 13, SIGTERM: 15 }; + +/** `exitCode` is 1 for a failed run and 128 plus the signal number for an interrupted one. */ +export class LanesError extends Error { + readonly exitCode: number; + constructor(message: string, exitCode: number) { super(message); this.exitCode = exitCode; } +} + +export type StopPlan = + | { kind: 'group'; group: number; signal: 'SIGTERM' | 'SIGKILL' } + | { kind: 'command'; command: string; args: string[] }; + +/** How to stop a step and everything it started on a platform. */ +export function stopPlan(platform: NodeJS.Platform, pid: number, force: boolean): StopPlan { + if (platform === 'win32') return { kind: 'command', command: 'taskkill', args: ['/T', '/F', '/PID', String(pid)] }; + return { kind: 'group', group: -pid, signal: force ? 'SIGKILL' : 'SIGTERM' }; +} + +/** Steps get their own process group everywhere but Windows, which has none to use. */ +export const detachesSteps = (platform: NodeJS.Platform) => platform !== 'win32'; + +const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); + +/** A pid or group id the runner may signal: a whole number above 1 that is neither this process nor its + * parent. Zero would be this process's own group, a negative number another group, and 1 is init. */ +export function validPid(pid: unknown): pid is number { + return typeof pid === 'number' && Number.isInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid; +} + +/** What to run to stop a step, if anything. On Windows `taskkill /T /F` goes only to a child whose `exit` has + * not fired: its PID may have been reused since. On POSIX a group is signalled only after a fresh probe. */ +export function stopAction(platform: NodeJS.Platform, exited: boolean, pid: number, force: boolean): StopPlan | undefined { + if (!validPid(pid)) return undefined; + if (platform === 'win32' && exited) return undefined; + return stopPlan(platform, pid, force); +} + +/** The last `max` bytes written, with a note of what was dropped. */ +class Tail { + private chunks: Buffer[] = []; + private size = 0; + private dropped = 0; + private readonly max: number; + constructor(max: number) { this.max = max; } + push(chunk: Buffer) { + this.chunks.push(chunk); this.size += chunk.length; + while (this.size > this.max && this.chunks.length > 1) { + const first = this.chunks.shift()!; this.size -= first.length; this.dropped += first.length; + } + if (this.size > this.max) { + const cut = this.size - this.max; + this.chunks[0] = this.chunks[0].subarray(cut); this.size -= cut; this.dropped += cut; + } + } + text() { + const text = Buffer.concat(this.chunks).toString('utf8'); + return this.dropped ? `[${this.dropped} bytes of earlier output dropped]\n${text}` : text; + } +} + +const github = process.env.GITHUB_ACTIONS === 'true'; +const stamp = (seconds: number) => `${seconds.toFixed(1)}s`; + +function print(label: string, text: string, ok: boolean) { + // One write per block keeps another lane's output out of the middle of it. + const body = text.endsWith('\n') || text === '' ? text : `${text}\n`; + process.stdout.write(github ? `::group::${label}\n${body}::endgroup::\n` : `\n=== ${label} ${ok ? '' : '(failed) '}===\n${body}`); +} + +type Live = { label: string; started: number; child: ChildProcess; exited: boolean; signalled: boolean; printed: boolean; dump: () => void; force: (note: string) => void }; + +export async function runLanes(lanes: Lane[], options: RunOptions = {}): Promise<StepResult[]> { + const { heartbeatMs = 60_000, killAfterMs = 10_000, graceMs = 3_000, maxOutputBytes = 2 * 1024 * 1024, sweepMs = 2_000 } = options; + const kill: Kill = options.kill ?? ((pid, signal) => { process.kill(pid, signal); }); + const results: StepResult[] = []; + // Groups not yet known to be empty. A group leaves as soon as a probe finds it empty, because its id may + // then be reused by an unrelated process; nothing is ever signalled once it has left. + const groups = new Set<number>(); + const live = new Map<number, Live>(); + let failed = false; + let interrupted: { signal: string; code: number } | undefined; + let killTimer: NodeJS.Timeout | undefined; + + const groupAlive = (group: number) => { + try { kill(-group, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === 'EPERM'; } + }; + /** Signal a recorded group, probing it first; an empty group is retired instead. */ + const signalGroup = (group: number, signal: 'SIGTERM' | 'SIGKILL') => { + if (!groups.has(group) || !validPid(group)) return; + if (!groupAlive(group)) { groups.delete(group); return; } + try { kill(-group, signal); } catch { /* gone between probe and signal */ } + }; + const stopStep = (pid: number, step: Live, force: boolean) => { + const plan = stopAction(process.platform, step.exited, pid, force); + if (plan?.kind === 'group') signalGroup(pid, plan.signal); + else if (plan?.kind === 'command') spawnSync(plan.command, plan.args, { stdio: 'ignore', windowsHide: true }); + }; + /** TERM, a short bound, KILL, a short bound; retire the group once it is confirmed empty. */ + const sweepGroup = async (group: number) => { + signalGroup(group, 'SIGTERM'); + for (const end = Date.now() + sweepMs; groups.has(group) && Date.now() < end;) { if (groupAlive(group)) await sleep(25); else groups.delete(group); } + signalGroup(group, 'SIGKILL'); + for (const end = Date.now() + sweepMs; groups.has(group) && Date.now() < end;) { if (groupAlive(group)) await sleep(25); else groups.delete(group); } + }; + const escalate = () => { + clearTimeout(killTimer); killTimer = undefined; + for (const [pid, step] of live) { step.signalled = true; stopStep(pid, step, true); } + for (const step of [...live.values()]) step.force('Did not stop in time; killed and abandoned.\n'); + }; + const beginStop = () => { + for (const [pid, step] of live) { + // A leader that has exited on its own is not ours to call stopped, but its group may still be running. + if (!step.exited && step.child.exitCode === null && step.child.signalCode === null) step.signalled = true; + stopStep(pid, step, false); + } + // Not unref'd: steps are still running, and the run must outlast them. + killTimer ??= setTimeout(escalate, killAfterMs); + }; + const onSignal = (signal: string) => { + if (interrupted) { escalate(); return; } + interrupted = { signal, code: 128 + (SIGNAL_NUMBER[signal] ?? 0) }; failed = true; + for (const step of live.values()) step.dump(); + beginStop(); + }; + const handlers = (['SIGINT', 'SIGTERM', 'SIGHUP'] as const).map(signal => [signal, () => onSignal(signal)] as const); + for (const [signal, handler] of handlers) process.on(signal, handler); + // `test:all | head` closes our output: stop rather than die with groups running. + const onStdoutError = (error: NodeJS.ErrnoException) => { if (error.code === 'EPIPE') onSignal('SIGPIPE'); }; + process.stdout.on('error', onStdoutError); + // A crash or process.exit must not orphan a group either. + const onExit = () => { + for (const pid of [...groups]) signalGroup(pid, 'SIGKILL'); + for (const [pid, step] of live) stopStep(pid, step, true); + }; + process.on('exit', onExit); + const heartbeat = setInterval(() => { + const names = [...live.values()].map(step => `${step.label} (${stamp((performance.now() - step.started) / 1000)})`); + if (names.length) console.log(`still running: ${names.join('; ')}`); + }, heartbeatMs); + + const runStep = (lane: Lane, step: Step) => new Promise<boolean>(resolve => { + const started = performance.now(); + const label = `${lane.name}: ${step.label}`; + console.log(`start ${label}`); + const tail = new Tail(maxOutputBytes); + const niced = step.lowPriority && process.platform !== 'win32'; + const child = spawn(niced ? 'nice' : step.command, niced ? ['-n', '10', step.command, ...step.args] : step.args, { + stdio: ['ignore', 'pipe', 'pipe'], detached: detachesSteps(process.platform), windowsHide: true, env: { ...process.env, ...step.env }, + }); + const pid = child.pid; + let settled = false; + let exit: { code: number | null; signal: NodeJS.Signals | null } | undefined; + let grace: NodeJS.Timeout | undefined; + const entry: Live = { + label, started, child, exited: false, signalled: false, printed: false, + dump: () => { entry.printed = true; print(label, `${tail.text()}Interrupted before it ended.\n`, false); }, + force: note => { child.stdout?.destroy(); child.stderr?.destroy(); finish(exit?.code === 0, note); }, + }; + if (pid) { live.set(pid, entry); if (detachesSteps(process.platform)) groups.add(pid); } + child.stdout?.on('data', chunk => tail.push(chunk)); + child.stderr?.on('data', chunk => tail.push(chunk)); + child.stdout?.on('error', () => {}); + child.stderr?.on('error', () => {}); + // ENOENT emits error and then close; the first word wins. + const finish = (ok: boolean, note = '') => { + if (settled) return; + settled = true; clearTimeout(grace); + if (pid) { + live.delete(pid); + if (!live.size) { clearTimeout(killTimer); killTimer = undefined; } + } + const seconds = (performance.now() - started) / 1000; + // Only a step the runner stopped is "stopped"; one that fails on its own is a failure, whenever. + const status = ok ? 'passed' : entry.signalled ? 'stopped' : 'failed'; + if (status === 'failed' && !failed) { failed = true; beginStop(); } + if ((status === 'passed' || status === 'failed') && !entry.printed) print(label, tail.text() + note, ok); + console.log(`${status} ${label} (${stamp(seconds)})`); + results.push({ lane: lane.name, label: step.label, seconds, status }); + // Sweep the group now that its leader is gone and the pipes are closed, so a descendant (and a Setup + // port it holds) cannot outlive the step, and the group id is retired while it is still ours. + void (pid ? sweepGroup(pid) : Promise.resolve()).then(() => resolve(ok)); + }; + child.on('error', error => finish(false, `Could not start: ${error.message}\n`)); + child.on('exit', (code, signal) => { + exit = { code, signal }; entry.exited = true; + // A leftover process holding our pipes must not keep the step open for ever. + grace = setTimeout(() => entry.force('A leftover process held its output open; abandoned.\n'), graceMs); + }); + child.on('close', (code, signal) => finish(code === 0, code === 0 ? '' : `Exited with ${signal ?? `code ${code}`}\n`)); + }); + + try { + await Promise.all(lanes.map(async lane => { + for (const step of lane.steps) { + if (failed) { results.push({ lane: lane.name, label: step.label, seconds: 0, status: 'stopped' }); continue; } + if (!await runStep(lane, step)) break; + } + })); + } finally { + clearInterval(heartbeat); clearTimeout(killTimer); + // Only groups not yet confirmed empty are left: each step's own group was swept when it ended. + await Promise.all([...groups].map(sweepGroup)); + for (const [signal, handler] of handlers) process.off(signal, handler); + process.stdout.off('error', onStdoutError); + process.stdout.on('error', () => {}); // a late EPIPE while exiting is not a crash + process.off('exit', onExit); + } + console.log('\nStep timings'); + for (const r of results) console.log(` ${r.status.padEnd(7)} ${stamp(r.seconds).padStart(7)} ${r.lane}: ${r.label}`); + if (interrupted) throw new LanesError(`Portable check interrupted by ${interrupted.signal}`, interrupted.code); + if (failed) throw new LanesError('Portable check failed', 1); + return results; +} diff --git a/scripts/test-plan.ts b/scripts/test-plan.ts new file mode 100644 index 0000000..040e1b4 --- /dev/null +++ b/scripts/test-plan.ts @@ -0,0 +1,69 @@ +/** The portable check groups, shared by CI (`scripts/ci.ts`) and the local + * runner (`scripts/test.ts`) so they cannot drift apart. Nothing here weakens a + * check: it only decides which groups may run side by side. + * + * The backend files that acquire target-derived Setup coordination ports stay in + * one serial `--test-concurrency=1` invocation (see `scripts/ci-backend.ts`). It is + * a chain of requests, each starting a worker thread, with a few deliberate + * deadline waits, so it is bound by latency rather than by the number of cores. No + * other group acquires those ports (checked with a probe on the acquisition call), + * so the other groups run beside it rather than before it. */ +import { mkdirSync, readdirSync, rmSync } from 'node:fs'; +import { resolve } from 'node:path'; +import { availableParallelism } from 'node:os'; +import { backendTestCommands, nativeOnlyTests } from './ci-backend.ts'; +import type { Lane } from './test-lanes.ts'; + +export const testFiles = (dir: string) => readdirSync(dir).filter(f => f.endsWith('.test.ts')).sort().map(f => `${dir}/${f}`); + +/** Node's compile cache keeps V8's compiled code for each source file it loads and + * checks it against the source's hash, so a changed file is recompiled, never + * served stale. Every test file runs in its own process and the managed-step tests + * start a worker per request, all loading the same modules: with the cache they + * compile each module once. Entries are keyed by file name and the fixtures run + * from fresh temporary folders, so a cache kept across runs only grows (about + * 30 MB a run); each run starts from an empty one instead. It sits in the ignored + * dependency folder, never in tracked or packaged paths. A missing or unwritable + * folder only turns the cache off. */ +export function freshCompileCache(root = process.cwd()): Record<string, string> { + const directory = resolve(root, 'node_modules/.cache/agent-progress-compile'); + try { + rmSync(directory, { recursive: true, force: true }); + mkdirSync(directory, { recursive: true }); + } catch { + console.log('Compile cache disabled: node_modules/.cache/agent-progress-compile could not be prepared; tests run without it.'); + return {}; + } + return { NODE_COMPILE_CACHE: directory }; +} + +export function portableLanes(options: { fenced: boolean; env?: Record<string, string>; cpus?: number; environment?: NodeJS.ProcessEnv }): Lane[] { + const env = options.env ?? {}; + const backend = testFiles('tests/backend').filter(f => !nativeOnlyTests.includes(f.split('/').at(-1)!)); + const [parallel, serial] = backendTestCommands(backend, options.environment ?? process.env); + // The serial group's chain keeps about two cores busy (its main thread and the + // workers it starts). Leave them free so its timing assertions keep their + // headroom, and run this lane under `nice` as well. + const workers = `--test-concurrency=${Math.max(1, (options.cpus ?? availableParallelism()) - 2)}`; + const withWorkers = (args: string[]) => [...args.slice(0, 2), workers, ...args.slice(2)]; + const node = (label: string, args: string[]) => ({ label, command: 'node', args, env }); + const types = [ + { label: 'root typecheck', command: 'bun', args: ['run', 'typecheck'], env }, + { label: 'UI typecheck', command: './node_modules/.bin/tsc', args: ['-p', 'ui/tsconfig.json', '--noEmit'], env }, + ]; + const rest = [ + node('backend tests (parallel group)', withWorkers(parallel)), + node('browser-model and automation tests', withWorkers(['--experimental-strip-types', '--test', ...testFiles('tests/browser'), ...testFiles('tests/automation')])), + ]; + // Beside the serial group, the other lane yields cores to it. + const yielding = [...types, ...rest].map(step => ({ ...step, lowPriority: true })); + return options.fenced + ? [ + { name: 'port-bound backend', steps: [node('backend tests (serial group, Setup ports)', serial)] }, + { name: 'everything else', steps: yielding }, + ] + : [ + { name: 'types', steps: types }, + { name: 'tests', steps: rest }, + ]; +} diff --git a/scripts/test.ts b/scripts/test.ts new file mode 100644 index 0000000..3e1e2ea --- /dev/null +++ b/scripts/test.ts @@ -0,0 +1,23 @@ +/** Local portable test runner. Build the generated entries first: the package + * scripts `test:all` and `test:fast` do. It never packages or starts a native + * runtime, and it does not replace `scripts/ci.ts` for a pull request. + * + * node --experimental-strip-types scripts/test.ts every portable group + * node --experimental-strip-types scripts/test.ts --fast the same without the serial Setup-port group */ +import { mkdirSync } from 'node:fs'; +import { nativeOnlyTests } from './ci-backend.ts'; +import { LanesError, runLanes } from './test-lanes.ts'; +import { freshCompileCache, portableLanes } from './test-plan.ts'; + +const fast = process.argv.includes('--fast'); +mkdirSync('/tmp/opencode', { recursive: true }); +console.log(`Native-only tests NOT RUN: ${nativeOnlyTests.join(', ')}`); +if (fast) console.log('Fast loop: the serial Setup-port backend group is skipped. Run `bun run test:all` or CI before a pull request.'); +const started = performance.now(); +try { + await runLanes(portableLanes({ fenced: !fast, env: freshCompileCache() })); + console.log(`\nAll portable groups passed in ${((performance.now() - started) / 1000).toFixed(1)}s${fast ? ' (fast loop, not the full set)' : ''}.`); +} catch (error) { + console.error(error instanceof Error ? error.message : error); + process.exit(error instanceof LanesError ? error.exitCode : 1); +} diff --git a/tests/automation/ci.test.ts b/tests/automation/ci.test.ts index ad0266c..dc719e7 100644 --- a/tests/automation/ci.test.ts +++ b/tests/automation/ci.test.ts @@ -1,15 +1,16 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, readdirSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; +import { tmpdir, availableParallelism } from 'node:os'; import { join, resolve } from 'node:path'; import { spawnSync } from 'node:child_process'; -import { backendTestCommands } from '../../scripts/ci-backend.ts'; +import { backendTestCommands, nativeOnlyTests } from '../../scripts/ci-backend.ts'; +import { freshCompileCache, portableLanes } from '../../scripts/test-plan.ts'; import { outputs } from '../../scripts/build-all.ts'; test('package scripts that consume runtime entries build before invoking their readers',()=>{ const {scripts}=JSON.parse(readFileSync('package.json','utf8')); - for(const name of ['test:backend','package','verify:package','prepare:probe','setup','check']) + for(const name of ['test:backend','test:all','test:fast','package','verify:package','prepare:probe','setup','check']) assert.equal(scripts[name].split('&&')[0].trim(),'bun run build:all',`${name} must build before its readers`); }); @@ -44,7 +45,7 @@ test('Windows service tests have an explicit same-job backend build prerequisite test('portable backend groups isolate coordination ports without omitting or repeating tests',()=>{ const files=readdirSync('tests/backend').filter(f=>f.endsWith('.test.ts')).map(f=>`tests/backend/${f}`); - const [parallel,serial]=backendTestCommands(files); + const [parallel,serial]=backendTestCommands(files,{}); assert.deepEqual(parallel.slice(0,2),['--experimental-strip-types','--test']); assert.deepEqual(serial.slice(0,3),['--experimental-strip-types','--test','--test-concurrency=1']); assert.deepEqual([...parallel.slice(2),...serial.slice(3)].sort(),files.sort()); @@ -55,7 +56,77 @@ test('portable backend groups isolate coordination ports without omitting or rep 'setup-suggestions.test.ts','windows-service.test.ts', ]); const source=readFileSync('scripts/ci.ts','utf8'); - assert.match(source,/for \(const args of backendTestCommands\([^\n]+\)\) run\('node',args\)/); + assert.match(source,/await runLanes\(portableLanes\(\{ fenced: true, env: freshCompileCache\(\) \}\)\)/); +}); + +test('portable lanes run every portable file once, keep the port-bound group serial and alone, and the fast loop drops only that group, on any core count',()=>{ + const names=(dir:string)=>readdirSync(dir).filter(f=>f.endsWith('.test.ts')).map(f=>`${dir}/${f}`).sort(); + const native=new Set(nativeOnlyTests); + const backend=names('tests/backend').filter(f=>!native.has(f.split('/').at(-1)!)); + const every=(lanes:ReturnType<typeof portableLanes>)=>lanes.flatMap(l=>l.steps).filter(s=>s.command==='node'); + const files=(steps:{args:string[]}[])=>steps.flatMap(s=>s.args.filter(a=>a.endsWith('.test.ts'))).sort(); + // On one to three cores the other lane's worker count is also 1, so the serial group + // cannot be told apart by its --test-concurrency=1; it is the sole step of its own lane. + for(const cpus of [1,2,3,4,24]){ + const at=`on ${cpus} cpus`; + const full=portableLanes({fenced:true,cpus,environment:{}}),fast=portableLanes({fenced:false,cpus,environment:{}}); + assert.deepEqual(files(every(full)),[...backend,...names('tests/browser'),...names('tests/automation')].sort(),at); + assert.equal(new Set(files(every(full))).size,files(every(full)).length,`no file runs twice ${at}`); + const serialLanes=full.filter(l=>l.name==='port-bound backend'); + assert.equal(serialLanes.length,1,at);assert.equal(serialLanes[0].steps.length,1,`the port-bound group shares its lane with nothing that could take a port ${at}`); + const serial=serialLanes[0].steps[0]; + assert.ok(serial.args.includes('--test-concurrency=1'),at); + assert.deepEqual(serial.args.slice(0,3),backendTestCommands(backend,{})[1].slice(0,3),at); + assert.deepEqual(files([serial]).map(f=>f.split('/').at(-1)),backendTestCommands(backend,{})[1].slice(3).map(f=>f.split('/').at(-1)).sort(),at); + assert.ok(!serial.lowPriority,`the serial group never yields cores ${at}`); + const others=full.filter(l=>l!==serialLanes[0]).flatMap(l=>l.steps); + assert.ok(others.every(s=>s.lowPriority),`the lane beside it yields cores to it ${at}`); + // Every other test step is bounded by an explicit worker count: the cores minus two, never below one. + const workers=Math.max(1,cpus-2); + for(const step of others.filter(s=>s.command==='node'))assert.ok(step.args.includes(`--test-concurrency=${workers}`),`${step.label} ${at}`); + assert.deepEqual(files(every(fast)),files(every(full)).filter(f=>!files([serial]).includes(f)),at); + assert.equal(fast.some(l=>l.steps.some(s=>s.args.includes('--test-concurrency=1')&&files([s]).some(f=>files([serial]).includes(f)))),false,`the fast loop has no serial group ${at}`); + for(const lanes of [full,fast]){ + const labels=lanes.flatMap(l=>l.steps).map(s=>s.label); + assert.ok(labels.includes('root typecheck')&&labels.includes('UI typecheck'),`both typechecks stay in every run ${at}`); + } + } + // Without a core count the host's is used. + assert.deepEqual(portableLanes({fenced:true,environment:{}}),portableLanes({fenced:true,cpus:availableParallelism(),environment:{}})); +}); + +test('a file that takes Setup ports only when CP_BUILT_SERVICE=1 runs in the serial group in that configuration and only there',()=>{ + const names=readdirSync('tests/backend').filter(f=>f.endsWith('.test.ts')).map(f=>`tests/backend/${f}`); + const opted='tests/backend/plan-cleanup-service.test.ts'; + const [parallelOff,serialOff]=backendTestCommands(names,{}); + assert.ok(parallelOff.includes(opted)&&!serialOff.includes(opted),'without the opt-in it stays parallel: it takes no port'); + const [parallelOn,serialOn]=backendTestCommands(names,{CP_BUILT_SERVICE:'1'}); + assert.ok(serialOn.includes(opted)&&!parallelOn.includes(opted),'with the opt-in its built service takes writer slots'); + assert.deepEqual([...parallelOn.slice(2),...serialOn.slice(3)].sort(),names.sort(),'still no file omitted or repeated'); + assert.ok(!backendTestCommands(names,{CP_BUILT_SERVICE:'0'})[1].includes(opted),'only 1 opts in'); + const plan=(environment:NodeJS.ProcessEnv)=>portableLanes({fenced:true,cpus:4,environment}).find(l=>l.name==='port-bound backend')!.steps[0].args; + assert.ok(plan({CP_BUILT_SERVICE:'1'}).includes(opted)&&!plan({}).includes(opted)); + const rest=(environment:NodeJS.ProcessEnv)=>portableLanes({fenced:true,cpus:4,environment}).filter(l=>l.name!=='port-bound backend').flatMap(l=>l.steps).flatMap(s=>s.args); + assert.ok(!rest({CP_BUILT_SERVICE:'1'}).includes(opted),'the lane beside the serial group never holds it'); +}); + +test('every step shares one compile cache folder that starts each run empty and stays out of tracked paths',()=>{ + const root=mkdtempSync(join(tmpdir(),'portable-cache-')); + try { + const stale=join(root,'node_modules','.cache','agent-progress-compile','stale-entry'); + mkdirSync(join(root,'node_modules','.cache','agent-progress-compile'),{recursive:true});writeFileSync(stale,'left by an earlier run'); + const env=freshCompileCache(root); + assert.equal(env.NODE_COMPILE_CACHE,join(root,'node_modules','.cache','agent-progress-compile')); + assert.deepEqual(readdirSync(env.NODE_COMPILE_CACHE),[],'an earlier run leaves nothing behind'); + for(const lanes of [portableLanes({fenced:true,env}),portableLanes({fenced:false,env})]) + assert.deepEqual(new Set(lanes.flatMap(l=>l.steps).map(s=>s.env?.NODE_COMPILE_CACHE)),new Set([env.NODE_COMPILE_CACHE]),'every step, typechecks included, gets the folder'); + // Without a cache folder, plans carry none: the plan tests above never touch a live cache. + assert.ok(portableLanes({fenced:true}).flatMap(l=>l.steps).every(s=>!s.env?.NODE_COMPILE_CACHE)); + assert.equal(spawnSync('git',['check-ignore','-q',join('node_modules','.cache','agent-progress-compile','x')]).status,0,'git ignores the folder'); + // An unusable location turns the cache off instead of failing the run. + writeFileSync(join(root,'blocked'),'a file where a folder is needed'); + assert.deepEqual(freshCompileCache(join(root,'blocked')),{}); + } finally {rmSync(root,{recursive:true,force:true});} }); test('actual portable CLI refuses nonfresh artifacts before entry reads or checks, preserving archives',()=>{ diff --git a/tests/automation/release.test.ts b/tests/automation/release.test.ts index 3b9d706..4a1223a 100644 --- a/tests/automation/release.test.ts +++ b/tests/automation/release.test.ts @@ -314,7 +314,9 @@ test('workflow keeps PR read-only, exact same-run artifact join and version seri assert(!text.includes('pull_request_target'));assert(!text.includes('secrets.')); assert.match(text,/permissions:\n contents: read/);assert.match(text,/publish:\n(?: name: [^\n]+\n)? needs: \[portable, windows-native\]/); assert.match(text,/windows-native:\n(?: name: [^\n]+\n)? runs-on: windows-2025/); - assert.match(text,/--experimental-strip-types --test --test-concurrency=1 tests\/backend\/windows-platform\.test\.ts tests\/backend\/windows-service\.test\.ts/); + // Both native files still run, each in its own serial runner, as the same unprivileged principal. + assert.match(text,/\$runs = @\('windows-platform', 'windows-service'\)/); + assert.match(text,/--experimental-strip-types --test --test-concurrency=1 tests\/backend\/\$\(\$run\.File\)\.test\.ts/); assert.match(text,/git fetch --no-tags origin tag v1\.1\.1/); assert.match(text,/name: Upload sanitized Windows migration trace\n if: always\(\)/); assert.match(text,/name: windows-migration-trace\n path: \$\{\{ runner.temp \}\}\/windows-migration-trace\.jsonl/); diff --git a/tests/automation/test-lanes.test.ts b/tests/automation/test-lanes.test.ts new file mode 100644 index 0000000..696e53c --- /dev/null +++ b/tests/automation/test-lanes.test.ts @@ -0,0 +1,410 @@ +import { test, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtempSync, writeFileSync, readFileSync, readdirSync, existsSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { spawn, spawnSync, type ChildProcess } from 'node:child_process'; +import * as lanes from '../../scripts/test-lanes.ts'; + +// The runner is POSIX-first: its process groups and the catchable SIGINT, SIGHUP and SIGTERM these tests send +// do not exist on Windows, where ChildProcess.kill() cannot deliver them. The stop-command test below runs everywhere. +const posixOnly = { skip: process.platform === 'win32' && 'process groups and catchable signals are POSIX-only' }; +const moduleUrl = JSON.stringify(pathToFileURL(resolve('scripts/test-lanes.ts')).href); +const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)); +// The harness's own process group, found once: a recorded pid must never lead to a signal for it. If `ps` cannot +// run (no binary, no permission) the result has no stdout, and the group is simply unknown. +function lookupGroup(run: typeof spawnSync = spawnSync, platform: NodeJS.Platform = process.platform): number | undefined { + if (platform === 'win32') return undefined; + const group = Number(run('ps', ['-o', 'pgid=', '-p', String(process.pid)], { encoding: 'utf8' })?.stdout?.trim()); + return Number.isSafeInteger(group) && group > 1 ? group : undefined; +} +const ownGroup = lookupGroup(); +/** A pid read back from a fixture file, or undefined for anything that is not a whole number above 1 that is + * neither the harness, its parent nor its group: an empty file is Number('') === 0, which is the whole group. */ +function safePid(text: string): number | undefined { + if (!/^[0-9]+$/.test(text.trim())) return undefined; + const pid = Number(text.trim()); + return Number.isSafeInteger(pid) && pid > 1 && pid !== process.pid && pid !== process.ppid && pid !== ownGroup ? pid : undefined; +} +type Send = (pid: number, signal: NodeJS.Signals) => void; +type Command = (command: string, args: string[]) => void; +const runCommand: Command = (command, args) => { spawnSync(command, args, { stdio: 'ignore' }); }; +/** Stop a fixture process and, on POSIX, the group it leads. With the harness's own group unknown no group signal is + * sent at all, only one to the validated pid itself: it could otherwise be the harness's group. */ +function killTree(pid: number | undefined, harness: { group: number | undefined } = { group: ownGroup }, send: Send = (target, signal) => { process.kill(target, signal); }, platform: NodeJS.Platform = process.platform, command: Command = runCommand) { + if (pid === undefined || safePid(String(pid)) === undefined) return; + if (platform === 'win32') { command('taskkill', ['/T', '/F', '/PID', String(pid)]); return; } + if (harness.group !== undefined && pid !== harness.group) { try { send(-pid, 'SIGKILL'); } catch { /* not a group leader */ } } + try { send(pid, 'SIGKILL'); } catch { /* gone */ } +} +const launched = new Set<ChildProcess>(); +after(() => { for (const child of launched) if (child.pid) killTree(child.pid); }); +const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +async function until(condition: () => boolean, ms = 10_000) { + for (const end = Date.now() + ms; Date.now() < end;) { if (condition()) return true; await sleep(25); } + return condition(); +} + +/** One disposable folder holding a step program whose behaviour comes from its environment: + * `ignore` ignores SIGTERM, `hang` runs for ever, `life=N` runs N ms, `code=N` exits with N, + * `grandchild` starts a same-group child that ignores SIGTERM and hangs, `session=...` starts a + * descendant in its own session (outside the step's group) that holds the step's pipes with the + * given modes, `print` and `flood` write output. Each process records its pid under ROOT. */ +function fixture() { + const root = mkdtempSync(join(tmpdir(), 'portable-lanes-')); + writeFileSync(join(root, 'child.cjs'), ` +const fs = require('node:fs'), cp = require('node:child_process'); +const { ROOT, NAME, MODE = '' } = process.env; +const modes = MODE.split(','); +const value = key => (modes.find(m => m.startsWith(key + '=')) ?? '').split('=').slice(1).join('=') || undefined; +if (modes.includes('ignore')) process.on('SIGTERM', () => {}); +fs.writeFileSync(ROOT + '/' + NAME + '.pid.tmp', String(process.pid)); +fs.renameSync(ROOT + '/' + NAME + '.pid.tmp', ROOT + '/' + NAME + '.pid'); +const again = (suffix, mode, options = {}) => cp.spawn(process.execPath, [__filename], { env: { ...process.env, NAME: NAME + '-' + suffix, MODE: mode }, stdio: ['ignore', 'inherit', 'inherit'], ...options }); +if (modes.includes('grandchild')) again('grandchild', 'ignore,hang'); +if (value('session')) again('session', value('session').replaceAll('+', ','), { detached: true }); +if (modes.includes('print')) console.log('PRINTED-BY-' + NAME); +if (modes.includes('flood')) console.log('x'.repeat(5000) + 'END'); +if (modes.includes('hang')) setInterval(() => {}, 1000); +if (value('life')) setTimeout(() => process.exit(Number(value('code') ?? 0)), Number(value('life'))); +else if (!modes.includes('hang')) process.exit(Number(value('code') ?? 0)); +`); + const step = (label: string, mode: string) => + `{label:${JSON.stringify(label)},command:process.execPath,args:[${JSON.stringify(join(root, 'child.cjs'))}],env:{ROOT:${JSON.stringify(root)},NAME:${JSON.stringify(label)},MODE:${JSON.stringify(mode)}}}`; + const pid = (name: string) => (existsSync(join(root, name + '.pid')) ? safePid(readFileSync(join(root, name + '.pid'), 'utf8')) : undefined); + // Every fixture process records its pid here: stop whatever a failed test left running, then delete the files. + const dispose = () => { + if (!existsSync(root)) return; + for (const name of readdirSync(root)) if (name.endsWith('.pid')) killTree(safePid(readFileSync(join(root, name), 'utf8'))); + rmSync(root, { recursive: true, force: true }); + }; + return { root, step, pid, dispose }; +} + +function launch(script: string, env: Record<string, string> = {}) { + const child = spawn(process.execPath, ['--experimental-strip-types', script], { env: { ...process.env, GITHUB_ACTIONS: '', ...env }, stdio: ['ignore', 'pipe', 'pipe'] }); + launched.add(child); + let out = ''; + child.stdout.on('data', c => { out += c; }); + child.stderr.on('data', c => { out += c; }); + const exited = new Promise<number | null>(done => child.on('close', code => done(code))); + return { child, output: () => out, exited }; +} + +/** A runner script. `${steps}` is written as real code so each test lists its lanes plainly. */ +function program(f: ReturnType<typeof fixture>, lanesCode: (s: (label: string, mode: string) => string) => string, options = '{}') { + const file = join(f.root, 'run.ts'); + writeFileSync(file, `import * as lanes from ${moduleUrl}; +try { await lanes.runLanes(${lanesCode(f.step)}, ${options}); console.log('RUN-OK'); } +catch (error) { console.log('REJECTED ' + (error as Error).message); process.exit((error as { exitCode?: number }).exitCode ?? 1); }`); + return file; +} +const bounded = async <T>(promise: Promise<T>, ms: number) => Promise.race([promise, sleep(ms).then(() => 'hung' as const)]); + +for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143], ['SIGHUP', 129]] as const) { + test(`${signal} stops every step, keeps what they wrote and exits ${code}`, posixOnly, async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'print,hang')}]},{name:'b',steps:[${s('two', 'print,hang')}]}]`)); + assert.ok(await until(() => f.pid('one') !== undefined && f.pid('two') !== undefined), 'both steps started'); + await sleep(300); + const pids = [f.pid('one')!, f.pid('two')!]; + run.child.kill(signal); + assert.equal(await bounded(run.exited, 15_000), code, run.output()); + assert.match(run.output(), new RegExp(`REJECTED Portable check interrupted by ${signal}`)); + assert.match(run.output(), /PRINTED-BY-one/); assert.match(run.output(), /PRINTED-BY-two/); + assert.match(run.output(), /Interrupted before it ended/); + for (const pid of pids) assert.ok(await until(() => !alive(pid), 5000), `step ${pid} outlives the runner`); + } finally { f.dispose(); } + }); +} + +test('a grandchild that ignores SIGTERM and a descendant that holds the pipes from its own session do not hold the runner', posixOnly, async () => { + const f = fixture(); + let session: number | undefined; + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'ignore,hang,grandchild,session=hang')}]}]`, '{killAfterMs:1500}')); + assert.ok(await until(() => ['one', 'one-grandchild', 'one-session'].every(n => f.pid(n) !== undefined)), 'processes started'); + await sleep(300); + session = f.pid('one-session'); + const group = [f.pid('one')!, f.pid('one-grandchild')!]; + const started = Date.now(); + run.child.kill('SIGTERM'); + assert.equal(await bounded(run.exited, 15_000), 143, run.output()); + assert.ok(Date.now() - started < 12_000, 'bounded exit'); + for (const pid of group) assert.ok(await until(() => !alive(pid), 5000), `${pid} outlives the runner`); + } finally { if (session && alive(session)) process.kill(session, 'SIGKILL'); f.dispose(); } +}); + +test('a leader that exits 0 leaving a same-group descendant on the pipes does not leave the descendant running when the runner returns', posixOnly, async () => { + const f = fixture(); + try { + // The leader exits at once; its grandchild (same group, ignores SIGTERM) holds the pipes. The grace period + // abandons the pipes, and the step passes, but the group is still alive. + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'grandchild')}]}]`, '{graceMs:400,sweepMs:600}')); + assert.ok(await until(() => f.pid('one-grandchild') !== undefined)); + const descendant = f.pid('one-grandchild')!; + assert.equal(await bounded(run.exited, 15_000), 0, run.output()); + assert.match(run.output(), /^passed a: one/m); + assert.ok(await until(() => !alive(descendant), 3000), 'the descendant outlives a passing run'); + } finally { f.dispose(); } +}); + +test('an interrupt during the grace period, which ends before the kill timer, still stops the descendant of a leader that already exited', posixOnly, async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'grandchild')}]}]`, '{graceMs:1500,killAfterMs:30000,sweepMs:600}')); + assert.ok(await until(() => f.pid('one-grandchild') !== undefined)); + const descendant = f.pid('one-grandchild')!; + await sleep(300); + assert.ok(alive(descendant), 'the grace period is still running'); + run.child.kill('SIGTERM'); + assert.equal(await bounded(run.exited, 15_000), 143, run.output()); + assert.ok(await until(() => !alive(descendant), 3000), 'the descendant outlives the interrupted run'); + } finally { f.dispose(); } +}); + +test('a repeated SIGINT is not swallowed: it kills steps that ignore the first one', posixOnly, async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'ignore,hang,grandchild')}]}]`, '{killAfterMs:60000}')); + assert.ok(await until(() => f.pid('one') !== undefined && f.pid('one-grandchild') !== undefined)); + await sleep(300); + const pids = [f.pid('one')!, f.pid('one-grandchild')!]; + run.child.kill('SIGINT'); + await sleep(400); + assert.ok(alive(pids[0]), 'the first signal alone does not stop a step that ignores it'); + run.child.kill('SIGINT'); + assert.equal(await bounded(run.exited, 10_000), 130, run.output()); + for (const pid of pids) assert.ok(await until(() => !alive(pid), 5000), `${pid} outlives the runner`); + } finally { f.dispose(); } +}); + +test('a closed output pipe stops the steps instead of orphaning them', posixOnly, async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'ignore,hang')}]}]`, '{heartbeatMs:100,killAfterMs:1000}')); + assert.ok(await until(() => f.pid('one') !== undefined)); + const pid = f.pid('one')!; + run.child.stdout!.destroy(); + assert.notEqual(await bounded(run.exited, 15_000), 'hung', 'the runner exits'); + assert.ok(await until(() => !alive(pid), 5000), 'the step outlives the runner'); + } finally { f.dispose(); } +}); + +test('a crash of the runner still kills every group it started', posixOnly, async () => { + const f = fixture(); + try { + const file = join(f.root, 'crash.ts'); + writeFileSync(file, `import {runLanes} from ${moduleUrl}; +const pending = runLanes([{name:'a',steps:[${f.step('one', 'ignore,hang')}]}]).catch(() => {}); +setTimeout(() => { throw new Error('boom'); }, 600); +await pending;`); + const run = launch(file); + assert.ok(await until(() => f.pid('one') !== undefined)); + const pid = f.pid('one')!; + assert.notEqual(await bounded(run.exited, 15_000), 0); + assert.ok(await until(() => !alive(pid), 5000), 'the step outlives the crashed runner'); + } finally { f.dispose(); } +}); + +test('a step that cannot start is reported once', async () => { + const f = fixture(); + try { + const run = launch(program(f, () => `[{name:'a',steps:[{label:'missing',command:'definitely-not-a-command-xyz',args:[]}]}]`)); + assert.equal(await bounded(run.exited, 15_000), 1, run.output()); + const rows = run.output().split('\n').filter(l => /^(passed|failed|stopped) a: missing/.test(l)); + assert.equal(rows.length, 1, run.output()); + assert.match(rows[0], /^failed/); + assert.equal(run.output().split('\n').filter(l => /^\s+(passed|failed|stopped)\s+[\d.]+s\s+a: missing/.test(l)).length, 1); + assert.match(run.output(), /Could not start/); + } finally { f.dispose(); } +}); + +test('a step that fails on its own after the first failure is a failure with its output, not a stopped step', async () => { + const f = fixture(); + try { + // "early" has exited with 4 but a descendant in another session holds its pipes for 1.5 s, + // so its close arrives after "first" has failed. The runner never signalled it. + const run = launch(program(f, s => `[{name:'a',steps:[${s('first', 'life=700,code=3')}]},{name:'b',steps:[${s('early', 'print,code=4,session=life=1500')}]}]`)); + assert.equal(await bounded(run.exited, 15_000), 1, run.output()); + assert.match(run.output(), /^failed a: first/m); + assert.match(run.output(), /^failed b: early/m); + assert.match(run.output(), /PRINTED-BY-early/); + assert.match(run.output(), /^\s+failed\s+[\d.]+s\s+b: early/m); + } finally { f.dispose(); } +}); + +test('a step the runner stopped is "stopped" and prints nothing, even if it exits non-zero in reply', async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('first', 'life=500,code=3')}]},{name:'b',steps:[${s('victim', 'print,hang')}]}]`)); + assert.equal(await bounded(run.exited, 15_000), 1, run.output()); + assert.match(run.output(), /^failed a: first/m); + assert.match(run.output(), /^stopped b: victim/m); + assert.doesNotMatch(run.output(), /PRINTED-BY-victim/); + } finally { f.dispose(); } +}); + +test('the runner names the steps still running about every heartbeat', async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('slow', 'life=900')}]}]`, '{heartbeatMs:150}')); + assert.equal(await bounded(run.exited, 15_000), 0, run.output()); + assert.match(run.output(), /still running: a: slow \(\d+\.\ds\)/); + } finally { f.dispose(); } +}); + +test('a step keeps only the tail of its output and says what was dropped', async () => { + const f = fixture(); + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('noisy', 'flood,code=1')}]}]`, '{maxOutputBytes:1000}')); + assert.equal(await bounded(run.exited, 15_000), 1, run.output()); + assert.match(run.output(), /\[\d+ bytes of earlier output dropped\]/); + assert.match(run.output(), /xEND/); + assert.ok((run.output().match(/x/g) ?? []).length < 1500, 'the dropped bytes are not printed'); + } finally { f.dispose(); } +}); + +test('a pass whose leftover process holds the pipes is abandoned after the grace period, not waited for', posixOnly, async () => { + const f = fixture(); + let session: number | undefined; + try { + const run = launch(program(f, s => `[{name:'a',steps:[${s('one', 'print,session=hang')}]}]`, '{graceMs:500}')); + assert.ok(await until(() => f.pid('one-session') !== undefined)); + session = f.pid('one-session'); + assert.equal(await bounded(run.exited, 10_000), 0, run.output()); + assert.match(run.output(), /^passed a: one/m); + assert.match(run.output(), /held its output open/); + } finally { if (session && alive(session)) process.kill(session, 'SIGKILL'); f.dispose(); } +}); + +test('a failed lookup of the harness group leaves it unknown, the module still loads, and cleanup then sends no group signal', () => { + const failed = (() => ({ pid: 0, output: null, stdout: null, stderr: null, status: null, signal: null, error: Object.assign(new Error('spawn ps ENOENT'), { code: 'ENOENT' }) })) as unknown as typeof spawnSync; + assert.equal(lookupGroup(failed, 'linux'), undefined); + assert.equal(lookupGroup((() => undefined) as unknown as typeof spawnSync, 'linux'), undefined); + assert.equal(lookupGroup((() => ({ stdout: '' })) as unknown as typeof spawnSync, 'linux'), undefined, 'an empty answer is not group 0'); + assert.equal(lookupGroup((() => ({ stdout: ' 4321\n' })) as unknown as typeof spawnSync, 'linux'), 4321); + assert.equal(lookupGroup(failed, 'win32'), undefined); + // Every call below names its platform and injects both the signal and the command: none can reach a real kill or taskkill. + const noCommand: Command = (name) => { assert.fail(`${name} must not run on this platform`); }; + const noSignal: Send = () => { assert.fail('no signal may be sent on this platform'); }; + const sent: number[] = []; + killTree(4242, { group: undefined }, pid => { sent.push(pid); }, 'linux', noCommand); + assert.deepEqual(sent, [4242], 'only the validated pid itself, never -4242'); + killTree(0, { group: undefined }, pid => { sent.push(pid); }, 'linux', noCommand); killTree(process.pid, { group: undefined }, pid => { sent.push(pid); }, 'linux', noCommand); + assert.deepEqual(sent, [4242], 'an unsafe pid is not signalled at all'); + const known: number[] = []; + killTree(4242, { group: 777 }, pid => { known.push(pid); }, 'linux', noCommand); + assert.deepEqual(known, [-4242, 4242], 'with the group known a leader is stopped as a group too'); + killTree(777, { group: 777 }, pid => { known.push(pid); }, 'linux', noCommand); + assert.deepEqual(known, [-4242, 4242, 777], 'but never the harness group itself'); + const commands: [string, string[]][] = []; + killTree(4242, { group: 777 }, noSignal, 'win32', (name, args) => { commands.push([name, args]); }); + assert.deepEqual(commands, [['taskkill', ['/T', '/F', '/PID', '4242']]], 'on Windows a safe pid goes to taskkill, through the injected runner only'); + killTree(0, { group: undefined }, noSignal, 'win32', (name, args) => { commands.push([name, args]); }); + assert.equal(commands.length, 1, 'and an unsafe pid to nothing'); +}); + +test('an empty or garbage pid file is ignored by the fixture cleanup and the harness survives', async () => { + const f = fixture(); + const sleeper = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { stdio: 'ignore', detached: process.platform !== 'win32' }); + try { + for (const [name, text] of Object.entries({ empty: '', blank: ' \n', zero: '0', init: '1', word: 'abc', negative: '-5', fraction: '2.5', harness: String(process.pid), parent: String(process.ppid) })) + writeFileSync(join(f.root, `${name}.pid`), text); + writeFileSync(join(f.root, 'real.pid'), String(sleeper.pid)); + for (const text of ['', ' ', '0', '1', 'abc', '-5', '2.5', String(process.pid), String(process.ppid)]) assert.equal(safePid(text), undefined, JSON.stringify(text)); + assert.equal(f.pid('empty'), undefined, 'a half-written file is not pid 0'); + f.dispose(); + assert.ok(await until(() => !alive(sleeper.pid!), 5000), 'the recorded fixture process is stopped'); + assert.ok(alive(process.pid), 'the harness is still here'); + assert.ok(alive(process.ppid), 'so is its parent'); + } finally { killTree(sleeper.pid); f.dispose(); } +}); + +test('the runner signals only a whole number above 1 that is not itself or its parent, and Windows stops only a child that has not exited', () => { + for (const bad of [0, 1, -1, -3, 1.5, NaN, Infinity, '12', null, undefined, process.pid, process.ppid]) assert.equal(lanes.validPid(bad), false, String(bad)); + assert.equal(lanes.validPid(4242), true); + assert.equal(lanes.stopAction('win32', true, 4242, false), undefined, 'an exited PID may belong to someone else now'); + assert.deepEqual(lanes.stopAction('win32', false, 4242, true), { kind: 'command', command: 'taskkill', args: ['/T', '/F', '/PID', '4242'] }); + assert.deepEqual(lanes.stopAction('linux', true, 4242, false), { kind: 'group', group: -4242, signal: 'SIGTERM' }, 'POSIX groups are probed before any signal, not skipped here'); + assert.equal(lanes.stopAction('linux', false, 0, false), undefined); + assert.equal(lanes.stopAction('win32', false, process.pid, true), undefined); +}); + +test('a group is retired as soon as its step is swept and nothing is sent to it afterwards, even if its id is reused', posixOnly, async () => { + const f = fixture(); + try { + const file = join(f.root, 'retire.ts'); + writeFileSync(file, `import * as lanes from ${moduleUrl}; +const calls: string[] = []; +const retired = new Set<number>(); +// Once a group answered ESRCH it is retired; any later call to that id stands for an unrelated process that reused it. +const kill = (pid: number, signal: NodeJS.Signals | 0) => { + const group = Math.abs(pid); + if (retired.has(group)) { calls.push(group + ' AFTER-RETIRED ' + signal); return; } + try { process.kill(pid, signal); calls.push(group + ' ' + signal + ' ok'); } + catch (error) { const code = (error as NodeJS.ErrnoException).code; calls.push(group + ' ' + signal + ' ' + code); if (code === 'ESRCH') retired.add(group); throw error; } +}; +await lanes.runLanes([{name:'a',steps:[${f.step('one', 'code=0')},${f.step('two', 'grandchild')}]}], {graceMs:300,sweepMs:800,kill}); +console.log('CALLS ' + JSON.stringify(calls));`); + const run = launch(file); + assert.equal(await bounded(run.exited, 20_000), 0, run.output()); + const calls: string[] = JSON.parse(/CALLS (.*)/.exec(run.output())?.[1] ?? '[]'); + const one = f.pid('one')!, two = f.pid('two')!; + const of = (group: number) => calls.filter(c => c.startsWith(group + ' ')); + assert.ok(calls.length > 0, 'the runner reports its probes and signals through the injected function'); + assert.equal(calls.filter(c => c.includes('AFTER-RETIRED')).length, 0, calls.join('; ')); + assert.deepEqual(of(one), [`${one} 0 ESRCH`], 'an empty group is probed once and retired without a signal'); + assert.ok(of(two).some(c => c.endsWith('SIGTERM ok')) && of(two).some(c => c.endsWith('SIGKILL ok')), 'a stubborn descendant gets TERM then KILL'); + assert.equal(of(two).at(-1), `${two} 0 ESRCH`, 'and the group is confirmed empty'); + assert.ok(calls.findIndex(c => c.startsWith(two + ' ')) > calls.findIndex(c => c.startsWith(one + ' ')) , 'the first step is swept before the next one starts'); + for (const c of calls) assert.ok(Number(c.split(' ')[0]) > 1, c); + } finally { f.dispose(); } +}); + +test('steps are stopped with a process group on POSIX and with taskkill /T /F on Windows, and only POSIX detaches them', () => { + assert.deepEqual(lanes.stopPlan('linux', 4242, false), { kind: 'group', group: -4242, signal: 'SIGTERM' }); + assert.deepEqual(lanes.stopPlan('darwin', 4242, true), { kind: 'group', group: -4242, signal: 'SIGKILL' }); + for (const force of [false, true]) assert.deepEqual(lanes.stopPlan('win32', 4242, force), { kind: 'command', command: 'taskkill', args: ['/T', '/F', '/PID', '4242'] }); + assert.equal(lanes.detachesSteps('linux'), true); + assert.equal(lanes.detachesSteps('darwin'), true); + assert.equal(lanes.detachesSteps('win32'), false); +}); + +test('lane runner starts a yielding step at lower priority and an ordinary one at the usual priority', posixOnly, async () => { + const f = fixture(); + try { + const file = join(f.root, 'priority.ts'); + writeFileSync(file, `import {runLanes} from ${moduleUrl}; +const show=(label:string,lowPriority?:boolean)=>({label,command:process.execPath,args:['-e',"console.log('PRIORITY '+require('node:os').getPriority())"],lowPriority}); +await runLanes([{name:'a',steps:[show('usual')]},{name:'b',steps:[show('yielding',true)]}]);`); + const run = launch(file); + assert.equal(await bounded(run.exited, 20_000), 0, run.output()); + const seen = (label: string) => Number(new RegExp(`=== ${label} ===\\nPRIORITY (-?\\d+)`).exec(run.output())?.[1]); + assert.ok(seen('b: yielding') > seen('a: usual'), 'the yielding step has the larger niceness'); + } finally { f.dispose(); } +}); + +test('lane runner stops every lane at the first failure and reports it without interleaving', async () => { + const f = fixture(); + try { + const file = join(f.root, 'first-failure.ts'); + writeFileSync(file, `import {runLanes} from ${moduleUrl}; +const node=(label:string,code:string)=>({label,command:process.execPath,args:['-e',code]}); +try{await runLanes([ + {name:'slow',steps:[node('hangs',"setTimeout(()=>{},60000)"),node('never starts',"console.log('LATE-STEP')")]}, + {name:'fails',steps:[node('breaks',"console.log('FAIL-OUTPUT');process.exit(3)")]}, + {name:'ok',steps:[node('passes',"console.log('PASS-OUTPUT')"),node('skipped after failure',"setTimeout(()=>console.log('LATE-STEP'),5000)")]}, +]);}catch(error){console.log('REJECTED '+(error as Error).message);process.exit(1);}`); + const started = performance.now(); + const run = launch(file); + assert.equal(await bounded(run.exited, 20_000), 1); + assert.ok(performance.now() - started < 15_000, 'the hanging lane is stopped, not waited for'); + assert.match(run.output(), /FAIL-OUTPUT/); assert.match(run.output(), /Exited with code 3/); assert.match(run.output(), /REJECTED Portable check failed/); + assert.doesNotMatch(run.output(), /LATE-STEP/); + assert.match(run.output(), /stopped\s+[\d.]+s\s+slow: hangs/); + assert.match(run.output(), /failed\s+[\d.]+s\s+fails: breaks/); + } finally { f.dispose(); } +}); diff --git a/tests/automation/workflow-triggers.test.ts b/tests/automation/workflow-triggers.test.ts index ca4fd91..6756787 100644 --- a/tests/automation/workflow-triggers.test.ts +++ b/tests/automation/workflow-triggers.test.ts @@ -197,7 +197,18 @@ test('Windows selects fast PR/push checks and full release, weekly and manual jo const windows = source.split('\n windows-native:\n')[1].split('\n publish:\n')[0]; assert.ok(windows.includes("AP_WINDOWS_FULL: ${{ needs.gate.outputs.windows_full == 'true' && '1' || '0' }}")); assert.match(windows, /name: Fetch released Windows migration fixture\n if: env.AP_WINDOWS_FULL == '1'\n run: git fetch --no-tags origin tag v1\.1\.1/); - assert.match(windows, /--test-concurrency=1 tests\/backend\/windows-platform\.test\.ts tests\/backend\/windows-service\.test\.ts/); + assert.match(windows, /\$runs = @\('windows-platform', 'windows-service'\)/); + assert.match(windows, /--test-concurrency=1 tests\/backend\/\$\(\$run\.File\)\.test\.ts/); + // Each file runs under Start-Process -Wait, which waits for the whole process tree, inside its own thread job. + assert.match(windows, /Start-ThreadJob[^\n]*-ScriptBlock \{/); + assert.match(windows, /-WindowStyle Hidden -Wait -PassThru -RedirectStandardOutput \$run\.Output -RedirectStandardError \$run\.Errors -ErrorAction Stop/); + // The secondary logon service refuses a second simultaneous start once; only that refusal is retried. + assert.match(windows, /\$_\.Exception\.Message -notmatch 'already running'\) \{ throw \}/); + assert.match(windows, /\$attempt -ge 30/); + assert.ok(!windows.includes('WaitForExit'), 'a bare process wait would not wait for what the process started'); + assert.match(windows, /\$null = \$runs\.Job \| Wait-Job/); + assert.match(windows, /Receive-Job -Job \$run\.Job -ErrorAction Stop/); + assert.match(windows, /Where-Object \{ \$_\.ExitCode -ne 0 \}/); const root = mkdtempSync(join(tmpdir(), 'workflow-windows-')); const git = (...args: string[]) => { diff --git a/tsconfig.json b/tsconfig.json index a1645ee..8e75031 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,5 +10,5 @@ "types": ["node"], "lib": ["ES2023", "DOM"] }, - "include": ["shared/**/*.ts", "plugin/**/*.ts", "service/**/*.ts", "setup/**/*.ts", "tests/backend/**/*.ts", "tests/fixtures/**/*.ts", "scripts/cli-probe.ts", "scripts/backend-evidence.ts", "scripts/package*.ts", "scripts/verify*package.ts", "scripts/ci.ts", "scripts/release.ts", "tests/automation/**/*.ts"] + "include": ["shared/**/*.ts", "plugin/**/*.ts", "service/**/*.ts", "setup/**/*.ts", "tests/backend/**/*.ts", "tests/fixtures/**/*.ts", "scripts/cli-probe.ts", "scripts/backend-evidence.ts", "scripts/package*.ts", "scripts/verify*package.ts", "scripts/ci.ts", "scripts/test*.ts", "scripts/release.ts", "tests/automation/**/*.ts"] } From 530dffc1b543db7e69de913ddbc0bef557a61689 Mon Sep 17 00:00:00 2001 From: Lucas <35551999+Phototonic@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:04:37 +1100 Subject: [PATCH 11/11] chore(release): 1.5.2 (#171) Archive the 1.5.0, 1.5.1 and 1.5.2 OpenSpec changes in that order, bump the version to 1.5.2, and add the 1.5.2 release notes and changelog entry. --- CHANGELOG.md | 24 +- .../2026-11-18-release-1-5-0}/design.md | 0 .../2026-11-18-release-1-5-0}/proposal.md | 0 .../specs/closed-plan-tidy/spec.md | 0 .../specs/dependency-map-arrow-state/spec.md | 0 .../dependency-map-view-controls/spec.md | 0 .../device-remembered-view-state/spec.md | 0 .../specs/incomplete-count-indicator/spec.md | 0 .../specs/interface-localization/spec.md | 0 .../specs/native-extension-updates/spec.md | 0 .../specs/needs-you-inbox/spec.md | 0 .../specs/phone-progress-surfaces/spec.md | 0 .../specs/plan-mirroring-guidance/spec.md | 0 .../specs/progress-surface-hierarchy/spec.md | 0 .../specs/release-built-outputs/spec.md | 0 .../specs/session-progress-context/spec.md | 0 .../specs/subagent-loss-notices/spec.md | 0 .../windows-setup-responsiveness/spec.md | 0 .../2026-11-18-release-1-5-0}/tasks.md | 16 +- .../2026-11-18-release-1-5-1}/design.md | 0 .../2026-11-18-release-1-5-1}/proposal.md | 0 .../specs/active-plan-cleanup/spec.md | 0 .../specs/closed-plan-tidy/spec.md | 2 +- .../dependency-map-view-controls/spec.md | 4 +- .../specs/incomplete-count-indicator/spec.md | 4 +- .../large-library-responsiveness/spec.md | 0 .../specs/needs-you-inbox/spec.md | 12 +- .../specs/plan-mirroring-guidance/spec.md | 0 .../specs/plan-selection-actions/spec.md | 0 .../2026-11-18-release-1-5-1}/tasks.md | 76 ++-- .../2026-11-19-release-1-5-2}/design.md | 0 .../2026-11-19-release-1-5-2}/proposal.md | 0 .../specs/closed-plan-tidy/spec.md | 0 .../delegation-intent-visibility/spec.md | 0 .../large-library-responsiveness/spec.md | 0 .../specs/plan-mirroring-guidance/spec.md | 0 .../specs/plan-selection-actions/spec.md | 0 .../2026-11-19-release-1-5-2}/tasks.md | 12 +- openspec/specs/active-plan-cleanup/spec.md | 142 +++++++ openspec/specs/closed-plan-tidy/spec.md | 359 ++++++++++++++++++ .../delegation-intent-visibility/spec.md | 32 ++ .../specs/dependency-map-arrow-state/spec.md | 8 +- .../dependency-map-view-controls/spec.md | 109 ++++++ .../device-remembered-view-state/spec.md | 58 +++ .../specs/incomplete-count-indicator/spec.md | 98 +++++ openspec/specs/interface-localization/spec.md | 39 +- .../large-library-responsiveness/spec.md | 168 ++++++++ .../specs/native-extension-updates/spec.md | 9 +- openspec/specs/needs-you-inbox/spec.md | 178 ++++++++- .../specs/phone-progress-surfaces/spec.md | 25 ++ .../specs/plan-mirroring-guidance/spec.md | 225 +++++++++++ openspec/specs/plan-selection-actions/spec.md | 211 ++++++++++ .../specs/progress-surface-hierarchy/spec.md | 105 +++++ openspec/specs/release-built-outputs/spec.md | 102 +++++ .../specs/session-progress-context/spec.md | 8 +- openspec/specs/subagent-loss-notices/spec.md | 10 +- .../windows-setup-responsiveness/spec.md | 48 +++ package.json | 2 +- release-notes/1.5.2.md | 19 + shared/release.ts | 2 +- 60 files changed, 2010 insertions(+), 97 deletions(-) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/design.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/proposal.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/closed-plan-tidy/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/dependency-map-arrow-state/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/dependency-map-view-controls/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/device-remembered-view-state/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/incomplete-count-indicator/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/interface-localization/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/native-extension-updates/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/needs-you-inbox/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/phone-progress-surfaces/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/plan-mirroring-guidance/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/progress-surface-hierarchy/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/release-built-outputs/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/session-progress-context/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/subagent-loss-notices/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/specs/windows-setup-responsiveness/spec.md (100%) rename openspec/changes/{release-1-5-0 => archive/2026-11-18-release-1-5-0}/tasks.md (96%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/design.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/proposal.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/active-plan-cleanup/spec.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/closed-plan-tidy/spec.md (92%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/dependency-map-view-controls/spec.md (89%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/incomplete-count-indicator/spec.md (77%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/large-library-responsiveness/spec.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/needs-you-inbox/spec.md (68%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/plan-mirroring-guidance/spec.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/specs/plan-selection-actions/spec.md (100%) rename openspec/changes/{release-1-5-1 => archive/2026-11-18-release-1-5-1}/tasks.md (78%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/design.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/proposal.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/specs/closed-plan-tidy/spec.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/specs/delegation-intent-visibility/spec.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/specs/large-library-responsiveness/spec.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/specs/plan-mirroring-guidance/spec.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/specs/plan-selection-actions/spec.md (100%) rename openspec/changes/{release-1-5-2 => archive/2026-11-19-release-1-5-2}/tasks.md (94%) create mode 100644 openspec/specs/active-plan-cleanup/spec.md create mode 100644 openspec/specs/closed-plan-tidy/spec.md create mode 100644 openspec/specs/dependency-map-view-controls/spec.md create mode 100644 openspec/specs/device-remembered-view-state/spec.md create mode 100644 openspec/specs/incomplete-count-indicator/spec.md create mode 100644 openspec/specs/large-library-responsiveness/spec.md create mode 100644 openspec/specs/plan-mirroring-guidance/spec.md create mode 100644 openspec/specs/plan-selection-actions/spec.md create mode 100644 openspec/specs/progress-surface-hierarchy/spec.md create mode 100644 openspec/specs/release-built-outputs/spec.md create mode 100644 release-notes/1.5.2.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 33ffd88..69d32a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to this project are documented in this file. The format is b ## [Unreleased] +## [1.5.2] - 2026-11-19 + +Cleanup follow-ups from the 1.5.1 review and a companion system prompt section that stays identical across requests, so it no longer defeats a provider's prompt cache. The minimum host remains OpenChamber 2.7.1. Protocol and schema stay at 2. + +### Changed + +- The companion's system prompt section holds only the fixed activation guidance and is byte-identical on every request where it is present. The one-request hint after a dispatch or plan write, the sub-agent resume capsule and the delegation refusal note keep their text and eligibility but are delivered after the cacheable prefix: as a text part after a user message, or at the end of the last tool result of a tool message, never on the Code Mode `execute` wrapper's result or a non-text result, and otherwise on the next request with a valid carrier. A delivered note stays in the same place on later requests built from the same history, keyed per session and bounded to 128 sessions, 256 carriers and 128 KiB of note text per session; notes due together are joined in a fixed order, a capsule or refusal is delivered again when its text changed or its last carrier is gone, and one fixed line clears a refusal that no longer applies. Every path that removes the section removes the added notes. Providers that drop plugin system sections now also receive these notes. Cache hit rates were not measured; tests assert the byte-for-byte prefix (#165, #167; reported in #161). +- Companion inline and packaged guidance tells an agent to clear a task's dependency block against the plan's current prerequisites, read before a handoff and when a prerequisite finishes: a prerequisite the plan no longer lists no longer holds the task, and a skipped prerequisite that is still listed counts as unfinished. Decision, review and external blockers are left alone, and the guidance stays advisory (#162). +- Coordinator refusal guidance validates a pending or reserved delegation receipt against its dispatch and declared tasks before inferring that cleanup retired it, and reports incomplete guidance when the check fails. Cancellation receipts, bound receipts and the explicit-link recovery are read as before (#162). +- `docs/ui.md` and `docs/contracts.md` state when chosen plans are checked by `/v1/search-state` point lookup, when loaded rows or a list scan are used instead, and which revision a retry compares against (#162). +- The large-library gate bounds each timed window by request and reply offsets read in the browser evaluation that starts and stops it, counts cadence, list starts and both inbox forms by the requests sent inside it, and shows run reads per window as an informational row. It records how an artifact attributed its traffic, compares the list-carried inbox form on its own, and reports a budget it cannot compare as unverified with exit status 2 instead of passing it. QA tooling only; no shipped behaviour changes (#166). +- The `release-1-5-2` OpenSpec change records the proposal, design and tasks (#160). The 1.5.0, 1.5.1 and 1.5.2 changes are archived in that order with their task lists reconciled, the 1.5.1 deltas corrected to keep the scenario names and requirement lengths the specs hold, and a Purpose written for each of the ten capabilities the first two archives created; the third creates none. +- Portable tests run faster, locally and in CI, with no test removed or relaxed. The serial backend group that takes Setup coordination ports runs beside a second lane (both typechecks, the parallel backend group, and the browser-model and automation tests) instead of before them, in one `--test-concurrency=1` invocation that nothing else joins; the second lane has its worker count capped at cores minus two and runs under `nice`. With `CP_BUILT_SERVICE=1`, the one file that takes ports moves into the serial group. New `bun run test:fast` (everything except the serial port-bound group) and `bun run test:all` (everything portable CI tests except packaging and the rebuild comparison) share one plan with CI through a POSIX-first runner whose stop path on Windows is best effort and was not run there. Node's compile cache, emptied at the start of each run, serves every step. The Linux jobs install the ZIP tools only when the image lacks them, and the Windows job starts its two native test files as two processes at once. The Linux test step fell from about 305 s to about 150 to 230 s in CI (#170). + +### Fixed + +- Tidy and Select all result lines separate plans that were skipped (refused as changed, closed, reused or not found, store busy, left out of the view or never sent after Stop) from plans whose request got no valid answer and may have been applied, in English, Russian and Simplified Chinese with plural rules. Undo still restores only validated receipts; Try again recounts skipped and unconfirmed plans together, or sends the restore again for the remainder after a partial Undo (#163). +- A bulk run that ends after an account, store or binding change the frame observed, including a switch away and back, no longer resets caches, changes the selection, closes the opened plan or shows a result on the board then shown; a validated Delete receipt still removes the review marker of the account and store the run started in. The busy state belongs to the request that set it, so an observed switch releases it and a late answer cannot complete, release or reset a newer run. Cleanup controls follow the latest health reply the controller accepted, whichever remembered list is shown, and a failed list read applies its health facts in both directions (#164). +- A count that finishes in the background, a run's progress and the end of a run with its result line repaint as background data and wait while a control is held, so a press on Stop or a click on another control is not lost; a refresh no longer expires a result that has not been painted yet. A deferred cleanup focus move is decided when it is applied and dropped if focus has moved to another control (#168). +- Tidy and Select all counts taken from a plan list read in more than one page say that plans may have been missed, on the count line and on the deletion step; a single-page list and rows chosen one by one stay exact, and Try again stays exact only when it found every plan it names. A search freshness reply certifies only the result page it was asked about by number, and only when it covered every plan that page shows; a page opened by Load more starts unchecked; a cleanup in the frame retires freshness replies in flight; and a plan a reply shows gone leaves the selection whichever page is shown. Under Select all, a plan taken out by a receipt or a reply carries the cleanup generation that took it out, so a plan restored elsewhere is counted again while a deselected plan stays out until its row is clicked or Select all is pressed again (#169). + ## [1.5.1] - 2026-11-18 Full-page responsiveness with large libraries, visible Tidy and multi-select cleanup, and map and count fixes. The minimum host remains OpenChamber 2.7.1. Protocol and schema stay at 2. @@ -346,7 +367,8 @@ The first major release: a calmer, at-a-glance progress experience with an inter Baseline before automated releases; see the repository history. -[Unreleased]: https://github.com/Phototonic/openchamber-progress/compare/v1.5.1...HEAD +[Unreleased]: https://github.com/Phototonic/openchamber-progress/compare/v1.5.2...HEAD +[1.5.2]: https://github.com/Phototonic/openchamber-progress/compare/v1.5.1...v1.5.2 [1.5.1]: https://github.com/Phototonic/openchamber-progress/compare/v1.5.0...v1.5.1 [1.5.0]: https://github.com/Phototonic/openchamber-progress/compare/v1.4.1...v1.5.0 [1.4.1]: https://github.com/Phototonic/openchamber-progress/compare/v1.4.0...v1.4.1 diff --git a/openspec/changes/release-1-5-0/design.md b/openspec/changes/archive/2026-11-18-release-1-5-0/design.md similarity index 100% rename from openspec/changes/release-1-5-0/design.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/design.md diff --git a/openspec/changes/release-1-5-0/proposal.md b/openspec/changes/archive/2026-11-18-release-1-5-0/proposal.md similarity index 100% rename from openspec/changes/release-1-5-0/proposal.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/proposal.md diff --git a/openspec/changes/release-1-5-0/specs/closed-plan-tidy/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/closed-plan-tidy/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/closed-plan-tidy/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/closed-plan-tidy/spec.md diff --git a/openspec/changes/release-1-5-0/specs/dependency-map-arrow-state/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/dependency-map-arrow-state/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/dependency-map-arrow-state/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/dependency-map-arrow-state/spec.md diff --git a/openspec/changes/release-1-5-0/specs/dependency-map-view-controls/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/dependency-map-view-controls/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/dependency-map-view-controls/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/dependency-map-view-controls/spec.md diff --git a/openspec/changes/release-1-5-0/specs/device-remembered-view-state/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/device-remembered-view-state/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/device-remembered-view-state/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/device-remembered-view-state/spec.md diff --git a/openspec/changes/release-1-5-0/specs/incomplete-count-indicator/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/incomplete-count-indicator/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/incomplete-count-indicator/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/incomplete-count-indicator/spec.md diff --git a/openspec/changes/release-1-5-0/specs/interface-localization/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/interface-localization/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/interface-localization/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/interface-localization/spec.md diff --git a/openspec/changes/release-1-5-0/specs/native-extension-updates/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/native-extension-updates/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/native-extension-updates/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/native-extension-updates/spec.md diff --git a/openspec/changes/release-1-5-0/specs/needs-you-inbox/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/needs-you-inbox/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/needs-you-inbox/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/needs-you-inbox/spec.md diff --git a/openspec/changes/release-1-5-0/specs/phone-progress-surfaces/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/phone-progress-surfaces/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/phone-progress-surfaces/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/phone-progress-surfaces/spec.md diff --git a/openspec/changes/release-1-5-0/specs/plan-mirroring-guidance/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/plan-mirroring-guidance/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/plan-mirroring-guidance/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/plan-mirroring-guidance/spec.md diff --git a/openspec/changes/release-1-5-0/specs/progress-surface-hierarchy/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/progress-surface-hierarchy/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/progress-surface-hierarchy/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/progress-surface-hierarchy/spec.md diff --git a/openspec/changes/release-1-5-0/specs/release-built-outputs/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/release-built-outputs/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/release-built-outputs/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/release-built-outputs/spec.md diff --git a/openspec/changes/release-1-5-0/specs/session-progress-context/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/session-progress-context/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/session-progress-context/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/session-progress-context/spec.md diff --git a/openspec/changes/release-1-5-0/specs/subagent-loss-notices/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/subagent-loss-notices/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/subagent-loss-notices/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/subagent-loss-notices/spec.md diff --git a/openspec/changes/release-1-5-0/specs/windows-setup-responsiveness/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-0/specs/windows-setup-responsiveness/spec.md similarity index 100% rename from openspec/changes/release-1-5-0/specs/windows-setup-responsiveness/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/specs/windows-setup-responsiveness/spec.md diff --git a/openspec/changes/release-1-5-0/tasks.md b/openspec/changes/archive/2026-11-18-release-1-5-0/tasks.md similarity index 96% rename from openspec/changes/release-1-5-0/tasks.md rename to openspec/changes/archive/2026-11-18-release-1-5-0/tasks.md index 426e0d7..66bc852 100644 --- a/openspec/changes/release-1-5-0/tasks.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-0/tasks.md @@ -68,8 +68,8 @@ Each numbered group is one pull request into the development branch. It carries ## 10. Joined verification -- [ ] 10.1 After the groups above have merged, run one rendered journey across rail, board, Work Status and Setup on the development branch at desktop width and 390 px in three languages, covering the main-session rule, scopes, actions, hide, bulk archive with Undo, the indicator and the More panels, with keyboard-only passes. -- [ ] 10.2 Run portable CI in a fresh full-history disposable checkout with a cleared environment for each pull request and for the joined branch, and review each public diff for private data. +- [x] 10.1 After the groups above have merged, run one rendered journey across rail, board, Work Status and Setup on the development branch at desktop width and 390 px in three languages, covering the main-session rule, scopes, actions, hide, bulk archive with Undo, the indicator and the More panels, with keyboard-only passes. +- [x] 10.2 Run portable CI in a fresh full-history disposable checkout with a cleared environment for each pull request and for the joined branch, and review each public diff for private data. ## 11. Plan mirroring guidance @@ -95,9 +95,9 @@ Each numbered group is one pull request into the development branch. It carries ## Deferred acceptance and out-of-scope follow-up -- [ ] Physical-phone and native-host acceptance of the new surfaces. Emulated and synthetic-host evidence does not establish them. -- [ ] A host capability to open a session with a drafted reply. Requested upstream; not part of this change. -- [ ] Live confirmation that an agent on a provider that drops plugin system text mirrors a plan unprompted. Delivery is verified here; model compliance is not, and needs the owner's own session. -- [ ] A request to the Claude Code provider project to forward plugin-added system sections, and a plugin-facing per-session instruction entry in the host API. Not part of this change. -- [ ] Release preparation (version, changelog, notes) and promotion to the distribution branch follow the release policy as changed by group 12, after this change is accepted. That promotion is the first real use of the promotion command; the release preparer rehearses it in a disposable clone first. -- [ ] A required check on the distribution branch, so that a pull request with failing checks cannot be merged. It is a repository setting, not part of this change. +- [ ] Physical-phone and native-host acceptance of the new surfaces. Emulated and synthetic-host evidence does not establish them. Deferred: it needs the owner's own devices and hosts, and the later release changes carry the same item forward. +- [ ] A host capability to open a session with a drafted reply. Requested upstream; not part of this change. Out of scope. +- [ ] Live confirmation that an agent on a provider that drops plugin system text mirrors a plan unprompted. Delivery is verified here; model compliance is not, and needs the owner's own session. Deferred. +- [ ] A request to the Claude Code provider project to forward plugin-added system sections, and a plugin-facing per-session instruction entry in the host API. Not part of this change. Out of scope. +- [x] Release preparation (version, changelog, notes) and promotion to the distribution branch follow the release policy as changed by group 12, after this change is accepted. That promotion is the first real use of the promotion command; the release preparer rehearses it in a disposable clone first. Shipped as Agent Progress 1.5.0. +- [ ] A required check on the distribution branch, so that a pull request with failing checks cannot be merged. It is a repository setting, not part of this change. Out of scope. diff --git a/openspec/changes/release-1-5-1/design.md b/openspec/changes/archive/2026-11-18-release-1-5-1/design.md similarity index 100% rename from openspec/changes/release-1-5-1/design.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/design.md diff --git a/openspec/changes/release-1-5-1/proposal.md b/openspec/changes/archive/2026-11-18-release-1-5-1/proposal.md similarity index 100% rename from openspec/changes/release-1-5-1/proposal.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/proposal.md diff --git a/openspec/changes/release-1-5-1/specs/active-plan-cleanup/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/active-plan-cleanup/spec.md similarity index 100% rename from openspec/changes/release-1-5-1/specs/active-plan-cleanup/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/active-plan-cleanup/spec.md diff --git a/openspec/changes/release-1-5-1/specs/closed-plan-tidy/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/closed-plan-tidy/spec.md similarity index 92% rename from openspec/changes/release-1-5-1/specs/closed-plan-tidy/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/closed-plan-tidy/spec.md index a688b17..344b06e 100644 --- a/openspec/changes/release-1-5-1/specs/closed-plan-tidy/spec.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/closed-plan-tidy/spec.md @@ -113,7 +113,7 @@ Opening Tidy SHALL show an inline panel, not a modal, whose one short line state ### Requirement: Honest result with undo -A run SHALL show one progress line with how many of the total are done and a Stop control. Its result SHALL be one line stating how many plans were archived or deleted and how many were skipped, and SHALL stay until the next action or refresh, not a timer. After Archive the result SHALL offer Undo, which restores each plan this run archived through the existing restore route. A deletion result MUST NOT offer Undo. Archive and Undo MUST NOT change a plan's lifecycle, counts or history. A plan SHALL be reported as done only when its receipt was validated, and a refused or unconfirmed plan MUST NOT be retried automatically. +A run SHALL show a progress line of plans done, and Stop. Its result SHALL be one line counting plans archived or deleted and plans skipped, kept until the next action or refresh, not a timer. After Archive it SHALL offer Undo, restoring each plan it archived through the restore route; a deletion result MUST NOT offer Undo. Archive and Undo MUST NOT change a plan's lifecycle, counts or history. A plan SHALL be reported done only with its validated receipt; none SHALL be retried automatically. #### Scenario: All archived - **WHEN** 128 plans are archived diff --git a/openspec/changes/release-1-5-1/specs/dependency-map-view-controls/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/dependency-map-view-controls/spec.md similarity index 89% rename from openspec/changes/release-1-5-1/specs/dependency-map-view-controls/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/dependency-map-view-controls/spec.md index ffea8e7..b1b36b7 100644 --- a/openspec/changes/release-1-5-1/specs/dependency-map-view-controls/spec.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/dependency-map-view-controls/spec.md @@ -2,7 +2,7 @@ ### Requirement: Opening view fits the plan only when readable -Once per reading, the map SHALL open showing the whole plan when the fit-all scale is at least the readability threshold of 70%. Otherwise it SHALL open at a readable zoom of 80% on current work. A coarse pointer SHALL keep its existing full-size opening zoom. Fit SHALL always show the whole plan. Opening MUST NOT select a task, move focus or repeat on polls. On a fine pointer the rail's map frame SHALL be at least 320 CSS pixels tall and SHALL grow with the plan's content at the readable zoom up to 60% of the rail's visible height. +Once per reading, the map SHALL open on the whole plan when its fit-all scale is at least the 70% readability threshold, else at a readable 80% zoom on current work. A coarse pointer SHALL keep its full-size opening zoom. Fit SHALL always show the whole plan. Opening MUST NOT select a task, move focus or repeat on polls. On a fine pointer the rail's map frame SHALL be at least 320 CSS pixels tall and grow with the plan's content at the readable zoom up to 60% of the rail's visible height. #### Scenario: Plan fits readably - **WHEN** the whole plan fits the frame at 70% or more @@ -41,7 +41,7 @@ Once per reading, the map SHALL open showing the whole plan when the fit-all sca - **WHEN** 60% of the rail's visible height is less than 320 CSS pixels - **THEN** the map frame is 320 CSS pixels tall -#### Scenario: Board and coarse-pointer frame height +#### Scenario: Frame height - **WHEN** the plan's content is shorter than the frame's maximum on the board, or the pointer is coarse on either surface - **THEN** the frame shrinks to the content, up to 64% of the viewport height on the board with a fine pointer and up to 300 CSS pixels with a coarse pointer diff --git a/openspec/changes/release-1-5-1/specs/incomplete-count-indicator/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/incomplete-count-indicator/spec.md similarity index 77% rename from openspec/changes/release-1-5-1/specs/incomplete-count-indicator/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/incomplete-count-indicator/spec.md index bb8d9d1..6691a94 100644 --- a/openspec/changes/release-1-5-1/specs/incomplete-count-indicator/spec.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/incomplete-count-indicator/spec.md @@ -2,7 +2,7 @@ ### Requirement: Possibly low counts are never shown as exact -A positive count that an active reason can raise SHALL carry a plus mark directly after the number, in all three languages, whether or not the indicator is dismissed. A plus mark MUST NOT appear on zero, and MUST NOT appear on a count that no active reason can raise. A zero count SHALL have no badge. A count MUST NOT be shown as an exact positive number, and a zero MUST NOT be presented as a verified empty result, unless its own coverage is complete. When it cannot be shown that a reason leaves a count unaffected, that count SHALL stay marked. +A positive count that an active reason can raise SHALL carry a plus mark directly after the number, in all three languages, dismissed or not. A plus mark MUST NOT appear on zero or on a count that no active reason can raise, and a zero count SHALL have no badge. A count MUST NOT be shown as an exact positive number, nor a zero as a verified empty result, unless its own coverage is complete. When it cannot be shown that a reason leaves a count unaffected, that count SHALL stay marked. #### Scenario: Partial Needs you count - **WHEN** five items are known and some plans of the scope are unchecked @@ -17,7 +17,7 @@ A positive count that an active reason can raise SHALL carry a plus mark directl - **THEN** only the first two rows show a count and the third shows no badge - **AND** a row whose plan's items were fully read shows its number without a plus mark, while a row whose plan may have more shows the plus -#### Scenario: Sub-agent counts with incomplete recorded history +#### Scenario: Partial sub-agent count - **WHEN** recorded history is only partly reconciled, while the host's current session list is complete and every recorded child is loaded - **THEN** the finished, failed, interrupted and unknown counts that are positive carry the plus mark - **AND** the running and waiting counts do not, because every currently active child is either recorded or listed by the host diff --git a/openspec/changes/release-1-5-1/specs/large-library-responsiveness/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/large-library-responsiveness/spec.md similarity index 100% rename from openspec/changes/release-1-5-1/specs/large-library-responsiveness/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/large-library-responsiveness/spec.md diff --git a/openspec/changes/release-1-5-1/specs/needs-you-inbox/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/needs-you-inbox/spec.md similarity index 68% rename from openspec/changes/release-1-5-1/specs/needs-you-inbox/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/needs-you-inbox/spec.md index 91d3e50..8ee7169 100644 --- a/openspec/changes/release-1-5-1/specs/needs-you-inbox/spec.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/needs-you-inbox/spec.md @@ -2,7 +2,7 @@ ### Requirement: Honest bounded inbox reads -Inbox reads SHALL be read-only, bounded and continuable through every eligible task. A positive count SHALL be shown as exact only with complete coverage of what it counts and otherwise SHALL carry a plus mark. A zero count MUST NOT carry a plus mark or a badge; while coverage is incomplete it SHALL show no number and MUST NOT be presented as a verified empty result. This rule SHALL govern every Needs you count on every surface and scope, including the count on each board plan row. Continuation MAY run automatically within the existing per-window bounds, at most one window per existing refresh cycle and a fixed number per traversal. Refresh SHALL add no polling loop, per-task polling, notification or inference. +Inbox reads SHALL be read-only, bounded and continuable through every eligible task. On every surface and scope, including each board plan row, a positive Needs you count SHALL be exact only with complete coverage of what it counts and otherwise carry a plus mark. A zero count MUST NOT carry a plus mark or a badge; while coverage is incomplete it SHALL show no number and MUST NOT be presented as a verified empty result. #### Scenario: Eligible task beyond the first read window - **WHEN** bounded traversal has found some items and has not reached an eligible task yet @@ -32,3 +32,13 @@ Inbox reads SHALL be read-only, bounded and continuable through every eligible t #### Scenario: Hidden frame - **WHEN** a frame is hidden while its inbox is incomplete - **THEN** it requests no continuation and discards any reply still in flight + +## ADDED Requirements + +### Requirement: Automatic inbox continuation adds no polling + +Continuation MAY run automatically within the existing per-window bounds, at most one window per existing refresh cycle and a fixed number per traversal. Refresh SHALL add no polling loop, per-task polling, notification or inference. + +#### Scenario: Refresh of an incomplete inbox +- **WHEN** a refresh runs while the inbox is incomplete +- **THEN** it starts no polling loop, per-task polling, notification or inference beyond the bounded continuation diff --git a/openspec/changes/release-1-5-1/specs/plan-mirroring-guidance/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/plan-mirroring-guidance/spec.md similarity index 100% rename from openspec/changes/release-1-5-1/specs/plan-mirroring-guidance/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/plan-mirroring-guidance/spec.md diff --git a/openspec/changes/release-1-5-1/specs/plan-selection-actions/spec.md b/openspec/changes/archive/2026-11-18-release-1-5-1/specs/plan-selection-actions/spec.md similarity index 100% rename from openspec/changes/release-1-5-1/specs/plan-selection-actions/spec.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/specs/plan-selection-actions/spec.md diff --git a/openspec/changes/release-1-5-1/tasks.md b/openspec/changes/archive/2026-11-18-release-1-5-1/tasks.md similarity index 78% rename from openspec/changes/release-1-5-1/tasks.md rename to openspec/changes/archive/2026-11-18-release-1-5-1/tasks.md index 76f9965..811e4b0 100644 --- a/openspec/changes/release-1-5-1/tasks.md +++ b/openspec/changes/archive/2026-11-18-release-1-5-1/tasks.md @@ -4,65 +4,65 @@ Each numbered group is one pull request into the development branch. It carries ## 1. Full page responsiveness and list scrolling -- [ ] 1.1 Add a measuring driver for the synthetic large library described in the design: seeded through the production write path into a disposable store, served by the real service to source-built guests in an isolated Chromium. It records long tasks, frame gaps, root replacements, element counts and request counts for idle, plan selection, map drag, wheel pan, keyboard zoom and a real-mouse scrollbar drag on page and rail, and writes sanitized results with no request bodies or identities. Run it on the unchanged 1.5.0 source and record the baseline; confirm it reproduces the design's baseline within normal variance before changing behaviour. -- [ ] 1.2 Derive the board's shown plans, order, grouping, locations, filter choices and selection once per change of their inputs, with an index for session and project lookups and a path for unrestricted filters that builds no choice list. Cover the inputs that must invalidate it (list read, live sessions, projects and worktrees, binding and source trust, filters, view, search run, language) and the duplicate-identifier and worktree placement cases with tests that compare against direct evaluation. -- [ ] 1.3 Group visible and count-authoritative Needs you rows by plan once per change of the held inbox, device-hidden set, store and binding, and read each plan row's count from that grouping, applying the count rule of group 3 (no badge for zero; a plus only when that plan's own items may not be fully read). Test equality with direct evaluation, including hidden items and the first-window authority during a recheck. -- [ ] 1.4 Stop rebuilding when a background invalidation leaves every painted input equal, and keep the plan list's scroll container connected across background paints, updating its rows in place. Keep immediate replacement on store, account, binding and board-reading changes, and add no gesture-based paint deferral. Background repaints go through the background invalidation lane. -- [ ] 1.5 Rendered checks at desktop width and 390 px: the scrollbar drag across refreshes with a release inside and outside the frame and a reported change during the drag; keyboard listbox navigation, focus and fold state through refreshes; the existing board, search and large-plan drivers unchanged. Assert unchanged request cadence and no new timer. -- [ ] 1.6 Run the measuring driver after the change, three runs, and compare with every budget in the design. Report each figure beside its baseline. On a miss, stop and raise a design amendment. Update the controller, full-page and QA-harness sections of `docs/ui.md`. +- [x] 1.1 Add a measuring driver for the synthetic large library described in the design: seeded through the production write path into a disposable store, served by the real service to source-built guests in an isolated Chromium. It records long tasks, frame gaps, root replacements, element counts and request counts for idle, plan selection, map drag, wheel pan, keyboard zoom and a real-mouse scrollbar drag on page and rail, and writes sanitized results with no request bodies or identities. Run it on the unchanged 1.5.0 source and record the baseline; confirm it reproduces the design's baseline within normal variance before changing behaviour. +- [x] 1.2 Derive the board's shown plans, order, grouping, locations, filter choices and selection once per change of their inputs, with an index for session and project lookups and a path for unrestricted filters that builds no choice list. Cover the inputs that must invalidate it (list read, live sessions, projects and worktrees, binding and source trust, filters, view, search run, language) and the duplicate-identifier and worktree placement cases with tests that compare against direct evaluation. +- [x] 1.3 Group visible and count-authoritative Needs you rows by plan once per change of the held inbox, device-hidden set, store and binding, and read each plan row's count from that grouping, applying the count rule of group 3 (no badge for zero; a plus only when that plan's own items may not be fully read). Test equality with direct evaluation, including hidden items and the first-window authority during a recheck. +- [x] 1.4 Stop rebuilding when a background invalidation leaves every painted input equal, and keep the plan list's scroll container connected across background paints, updating its rows in place. Keep immediate replacement on store, account, binding and board-reading changes, and add no gesture-based paint deferral. Background repaints go through the background invalidation lane. +- [x] 1.5 Rendered checks at desktop width and 390 px: the scrollbar drag across refreshes with a release inside and outside the frame and a reported change during the drag; keyboard listbox navigation, focus and fold state through refreshes; the existing board, search and large-plan drivers unchanged. Assert unchanged request cadence and no new timer. +- [x] 1.6 Run the measuring driver after the change, three runs, and compare with every budget in the design. Report each figure beside its baseline. On a miss, stop and raise a design amendment. Update the controller, full-page and QA-harness sections of `docs/ui.md`. ## 2. Map: rail height, Focus current work, short help -- [ ] 2.1 Give the rail frame its fine-pointer height rule: the plan's content at the readable zoom, with the 320-pixel floor and the cap at 60% of the rail's visible height. Keep the board rule and the coarse-pointer cap. Re-run the opening-view checks for the reference plans, since the frame height feeds the fit-all scale. -- [ ] 2.2 Restore the Focus current work button after Fit with its existing name, action and announcement in three languages; keep the bar on one row at 390 px and the 44-pixel targets on a coarse pointer. -- [ ] 2.3 Shorten the help text to keys, arrow meanings and the touch line, keeping the filters and shown-task count. Keep the arrow explanation required by the arrow-state capability. Review Russian and Chinese by reading. -- [ ] 2.4 Update map tests and rendered drivers: frame height on short and tall rails with small and large plans, the button by pointer, keyboard and touch with its single announcement and unchanged selection, focus and filters, help without its own scrollbar at 390 px in three languages, accessibility-tree names, 200% and 400% reflow, and the phone map driver. Update the Dependency map section and hooks list of `docs/ui.md`. +- [x] 2.1 Give the rail frame its fine-pointer height rule: the plan's content at the readable zoom, with the 320-pixel floor and the cap at 60% of the rail's visible height. Keep the board rule and the coarse-pointer cap. Re-run the opening-view checks for the reference plans, since the frame height feeds the fit-all scale. +- [x] 2.2 Restore the Focus current work button after Fit with its existing name, action and announcement in three languages; keep the bar on one row at 390 px and the 44-pixel targets on a coarse pointer. +- [x] 2.3 Shorten the help text to keys, arrow meanings and the touch line, keeping the filters and shown-task count. Keep the arrow explanation required by the arrow-state capability. Review Russian and Chinese by reading. +- [x] 2.4 Update map tests and rendered drivers: frame height on short and tall rails with small and large plans, the button by pointer, keyboard and touch with its single announcement and unchanged selection, focus and filters, help without its own scrollbar at 390 px in three languages, accessibility-tree names, 200% and 400% reflow, and the phone map driver. Update the Dependency map section and hooks list of `docs/ui.md`. ## 3. Counts: a plus only where it can matter -- [ ] 3.1 Apply the rule to the Needs you line, its other-plans link and other-blocked count, and Work Status: no plus and no number for an incomplete zero, no statement that nothing needs the user until the read is complete. -- [ ] 3.2 Mark sub-agent summary counts and the records total by the reasons that can raise each, as tabled in the design; keep a count marked where a reason cannot be shown to leave it unaffected. Record the per-count reasons in `docs/ui.md`. -- [ ] 3.3 Update the inbox, sub-agent, incomplete-count and Work Status tests and their rendered drivers in three languages at desktop width and 390 px, including accessible names of counts. Correct the "0+" statements in `docs/ui.md` and the count-qualification section of `docs/contracts.md`. +- [x] 3.1 Apply the rule to the Needs you line, its other-plans link and other-blocked count, and Work Status: no plus and no number for an incomplete zero, no statement that nothing needs the user until the read is complete. +- [x] 3.2 Mark sub-agent summary counts and the records total by the reasons that can raise each, as tabled in the design; keep a count marked where a reason cannot be shown to leave it unaffected. Record the per-count reasons in `docs/ui.md`. +- [x] 3.3 Update the inbox, sub-agent, incomplete-count and Work Status tests and their rendered drivers in three languages at desktop width and 390 px, including accessible names of counts. Correct the "0+" statements in `docs/ui.md` and the count-qualification section of `docs/contracts.md`. ## 4. Active-plan cleanup contract -- [ ] 4.1 Accept the in-progress acknowledgement on archive and delete, refuse it on restore and on closed plans, allow restore of an archived plan of any lifecycle, include the acknowledgement in the replay identity, and advertise the separate capability fact. Leave the cleanup storage format, guards, receipts and error codes unchanged. -- [ ] 4.2 Test with real authenticated requests against a disposable store: every row of the design's request table; stale revision and generation; replay and reused operation; delete with staged structure; and, through the production write path after an archive, a restore and a delete, each report operation named in the design, including reopen, a retried earlier report, delegation and handoff. Assert unchanged revision, tasks and history on refusal. -- [ ] 4.3 Test the read side for an archived and a deleted in-progress plan: ordinary lists, the session list, Needs you, resume briefs and waiting-delegation views; an earlier guest's request shapes; an older writer fenced by the guards; the previous service on a store that holds an archived in-progress plan. -- [ ] 4.4 Update the closed-plan cleanup section of `docs/contracts.md` as the design lists, and the capability list in `docs/backend.md`. Run the cleanup, Windows-relevant and portable backend suites. +- [x] 4.1 Accept the in-progress acknowledgement on archive and delete, refuse it on restore and on closed plans, allow restore of an archived plan of any lifecycle, include the acknowledgement in the replay identity, and advertise the separate capability fact. Leave the cleanup storage format, guards, receipts and error codes unchanged. +- [x] 4.2 Test with real authenticated requests against a disposable store: every row of the design's request table; stale revision and generation; replay and reused operation; delete with staged structure; and, through the production write path after an archive, a restore and a delete, each report operation named in the design, including reopen, a retried earlier report, delegation and handoff. Assert unchanged revision, tasks and history on refusal. +- [x] 4.3 Test the read side for an archived and a deleted in-progress plan: ordinary lists, the session list, Needs you, resume briefs and waiting-delegation views; an earlier guest's request shapes; an older writer fenced by the guards; the previous service on a store that holds an archived in-progress plan. +- [x] 4.4 Update the closed-plan cleanup section of `docs/contracts.md` as the design lists, and the capability list in `docs/backend.md`. Run the cleanup, Windows-relevant and portable backend suites. ## 5. Tidy on the full page -- [ ] 5.1 Add the Tidy button to the board bar and remove the bulk archive entry from the More menu on both surfaces. Show it during search and filtering and with nothing eligible; keep it absent without the cleanup capability. -- [ ] 5.2 Build the bounded target scan over the existing list and search reads with its ceiling, cancellation and retirement, feeding no ordinary cache; state the count, the over-the-ceiling case, the scan-limit case with Check more continuing from where the scan stopped, and the nothing-in-scope case. -- [ ] 5.3 Replace the per-plan confirmation list with the one-line panel, the Archive action and the two-step Delete permanently with its collapsed disclosure; keep focus, Enter and Escape rules. Current plans offer Archive and Delete permanently; Archived plans offer only Delete permanently. -- [ ] 5.4 Extend the run engine: closed plans including failed, archive and delete, the per-confirmation ceiling, progress with Stop, skipped and unconfirmed plans, context-change stop, one reconciliation read, the result line, Undo for archive only and Try again for the remainder. Never send the in-progress acknowledgement. -- [ ] 5.5 Test against the real cleanup service fixture: scope with and without search and filters, plans beyond the loaded list, failed plans included, in-progress plans untouched, a plan reopened before its request, Stop, partial failure, receipt-bound Undo, no Undo after delete, capability absent, and unchanged lifecycle and history after archive and Undo. Rendered checks at desktop width and 390 px in three languages with keyboard-only passes and accessibility-tree assertions. Measure and report the run time for 500 plans on the fixture. Update the closed-plan cleanup and full-page sections and the hooks list of `docs/ui.md`, and the bulk composition paragraph of `docs/contracts.md`. +- [x] 5.1 Add the Tidy button to the board bar and remove the bulk archive entry from the More menu on both surfaces. Show it during search and filtering and with nothing eligible; keep it absent without the cleanup capability. +- [x] 5.2 Build the bounded target scan over the existing list and search reads with its ceiling, cancellation and retirement, feeding no ordinary cache; state the count, the over-the-ceiling case, the scan-limit case with Check more continuing from where the scan stopped, and the nothing-in-scope case. +- [x] 5.3 Replace the per-plan confirmation list with the one-line panel, the Archive action and the two-step Delete permanently with its collapsed disclosure; keep focus, Enter and Escape rules. Current plans offer Archive and Delete permanently; Archived plans offer only Delete permanently. +- [x] 5.4 Extend the run engine: closed plans including failed, archive and delete, the per-confirmation ceiling, progress with Stop, skipped and unconfirmed plans, context-change stop, one reconciliation read, the result line, Undo for archive only and Try again for the remainder. Never send the in-progress acknowledgement. +- [x] 5.5 Test against the real cleanup service fixture: scope with and without search and filters, plans beyond the loaded list, failed plans included, in-progress plans untouched, a plan reopened before its request, Stop, partial failure, receipt-bound Undo, no Undo after delete, capability absent, and unchanged lifecycle and history after archive and Undo. Rendered checks at desktop width and 390 px in three languages with keyboard-only passes and accessibility-tree assertions. Measure and report the run time for 500 plans on the fixture. Update the closed-plan cleanup and full-page sections and the hooks list of `docs/ui.md`, and the bulk composition paragraph of `docs/contracts.md`. ## 6. Multi-select and in-progress plans -- [ ] 6.1 Add Select mode to the plan rows and to plan results while searching, with selected state, keyboard toggling, the selected-count bar, Clear, and the narrow-width row view; keep the selection through refreshes and clear it when the board reading changes. -- [ ] 6.2 Add Select all as a rule over the current search and filters with deselection of loaded rows, and the plus-marked count until the scan has counted. -- [ ] 6.3 Offer Archive and Delete permanently in Current plans and Restore and Delete permanently in Archived plans through the run engine. State the in-progress count in the confirmation's line, send the acknowledgement only for those plans and only when the capability is advertised, and say how many are left out otherwise. Offer Restore and Delete permanently in More for an archived plan of any lifecycle. -- [ ] 6.4 Test against the real service: mixed selections archived, restored through Undo and deleted; a selected plan reported to before its request; capability absent; no acknowledgement on any closed plan or from Tidy; selection lifetime. Rendered checks at desktop width and 390 px in three languages, keyboard-only and accessibility-tree assertions, and a report sent through the production write path to an archived, a restored and a deleted in-progress plan. Update `docs/ui.md` and `docs/contracts.md`. +- [x] 6.1 Add Select mode to the plan rows and to plan results while searching, with selected state, keyboard toggling, the selected-count bar, Clear, and the narrow-width row view; keep the selection through refreshes and clear it when the board reading changes. +- [x] 6.2 Add Select all as a rule over the current search and filters with deselection of loaded rows, and the plus-marked count until the scan has counted. +- [x] 6.3 Offer Archive and Delete permanently in Current plans and Restore and Delete permanently in Archived plans through the run engine. State the in-progress count in the confirmation's line, send the acknowledgement only for those plans and only when the capability is advertised, and say how many are left out otherwise. Offer Restore and Delete permanently in More for an archived plan of any lifecycle. +- [x] 6.4 Test against the real service: mixed selections archived, restored through Undo and deleted; a selected plan reported to before its request; capability absent; no acknowledgement on any closed plan or from Tidy; selection lifetime. Rendered checks at desktop width and 390 px in three languages, keyboard-only and accessibility-tree assertions, and a report sent through the production write path to an archived, a restored and a deleted in-progress plan. Update `docs/ui.md` and `docs/contracts.md`. ## 7. Companion guidance -- [ ] 7.1 Add the sentence to the skill beside its closed-plan statement, keep the tool description within its tested limits, and update the active-tool section of `docs/contracts.md`. -- [ ] 7.2 Judge it by reading, not phrase search: given only the companion's text, record what a coordinator does after `closed` then a refused reopen, and after `not-found`, and confirm the ordinary reopen case is unchanged. +- [x] 7.1 Add the sentence to the skill beside its closed-plan statement, keep the tool description within its tested limits, and update the active-tool section of `docs/contracts.md`. +- [x] 7.2 Judge it by reading, not phrase search: given only the companion's text, record what a coordinator does after `closed` then a refused reopen, and after `not-found`, and confirm the ordinary reopen case is unchanged. ## 8. Joined verification and release -- [ ] 8.1 After the groups above have merged, run one rendered journey on the development branch across rail, board and Work Status at desktop width and 390 px in three languages: a large library idle and during map gestures, list scrolling, Tidy archive with Undo and delete, a mixed selection, the map bar and help, and the counts, with a keyboard-only pass. -- [ ] 8.2 Run the measuring driver on the joined branch and compare with the budgets again. Compare a larger real library locally with the same method; commit none of its data, counts or logs, and delete the copy afterwards. -- [ ] 8.3 Run portable CI in a fresh full-history disposable checkout with a cleared environment, and review every public diff for private data. -- [ ] 8.4 Prepare the release: version 1.5.1 in the package and the release constant, the changelog entry and curated release notes, then the promotion to the distribution branch and its host gates as the contributor guide describes. The nine generated outputs are built and committed by the promotion only. -- [ ] 8.5 Archive the 1.5.0 change before archiving this one, because this change modifies capabilities that change introduced. +- [ ] 8.1 After the groups above have merged, run one rendered journey on the development branch across rail, board and Work Status at desktop width and 390 px in three languages: a large library idle and during map gestures, list scrolling, Tidy archive with Undo and delete, a mixed selection, the map bar and help, and the counts, with a keyboard-only pass. Deferred: it was not run as one joined journey. The rendered Tidy, selection, map and count drivers ran with each pull request, and the 1.5.2 change repeats a joined journey for Tidy and selection (its task 7.1). +- [x] 8.2 Run the measuring driver on the joined branch and compare with the budgets again. Compare a larger real library locally with the same method; commit none of its data, counts or logs, and delete the copy afterwards. +- [x] 8.3 Run portable CI in a fresh full-history disposable checkout with a cleared environment, and review every public diff for private data. +- [x] 8.4 Prepare the release: version 1.5.1 in the package and the release constant, the changelog entry and curated release notes, then the promotion to the distribution branch and its host gates as the contributor guide describes. The nine generated outputs are built and committed by the promotion only. +- [x] 8.5 Archive the 1.5.0 change before archiving this one, because this change modifies capabilities that change introduced. Done in the 1.5.2 release pull request, which archives the 1.5.0 change and then this one. ## Deferred acceptance and out-of-scope follow-up -- [ ] Physical-phone and native-host acceptance of the changed surfaces. Emulated and synthetic-host evidence does not establish them. -- [ ] Map zoom by wheel or trackpad pinch. It changes the documented wheel and browser-zoom contract and needs its own proposal. -- [ ] Narrowing which plans a recording gap qualifies, so history counts on unaffected plans lose their plus. It needs the service to record what a gap touched. -- [ ] Retaining the map's own DOM across background paints, considered only if the responsiveness gate is missed. -- [ ] A cleanup action for a visible in-progress plan in the per-plan More menu or on the rail. +- [ ] Physical-phone and native-host acceptance of the changed surfaces. Emulated and synthetic-host evidence does not establish them. Deferred: it needs the owner's own devices and hosts, and the 1.5.2 change carries the same item forward. +- [ ] Map zoom by wheel or trackpad pinch. It changes the documented wheel and browser-zoom contract and needs its own proposal. Out of scope. +- [ ] Narrowing which plans a recording gap qualifies, so history counts on unaffected plans lose their plus. It needs the service to record what a gap touched. Deferred. +- [ ] Retaining the map's own DOM across background paints, considered only if the responsiveness gate is missed. Not needed: every budget passed, so it was never considered. +- [ ] A cleanup action for a visible in-progress plan in the per-plan More menu or on the rail. Out of scope. diff --git a/openspec/changes/release-1-5-2/design.md b/openspec/changes/archive/2026-11-19-release-1-5-2/design.md similarity index 100% rename from openspec/changes/release-1-5-2/design.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/design.md diff --git a/openspec/changes/release-1-5-2/proposal.md b/openspec/changes/archive/2026-11-19-release-1-5-2/proposal.md similarity index 100% rename from openspec/changes/release-1-5-2/proposal.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/proposal.md diff --git a/openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md b/openspec/changes/archive/2026-11-19-release-1-5-2/specs/closed-plan-tidy/spec.md similarity index 100% rename from openspec/changes/release-1-5-2/specs/closed-plan-tidy/spec.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/specs/closed-plan-tidy/spec.md diff --git a/openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md b/openspec/changes/archive/2026-11-19-release-1-5-2/specs/delegation-intent-visibility/spec.md similarity index 100% rename from openspec/changes/release-1-5-2/specs/delegation-intent-visibility/spec.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/specs/delegation-intent-visibility/spec.md diff --git a/openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md b/openspec/changes/archive/2026-11-19-release-1-5-2/specs/large-library-responsiveness/spec.md similarity index 100% rename from openspec/changes/release-1-5-2/specs/large-library-responsiveness/spec.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/specs/large-library-responsiveness/spec.md diff --git a/openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md b/openspec/changes/archive/2026-11-19-release-1-5-2/specs/plan-mirroring-guidance/spec.md similarity index 100% rename from openspec/changes/release-1-5-2/specs/plan-mirroring-guidance/spec.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/specs/plan-mirroring-guidance/spec.md diff --git a/openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md b/openspec/changes/archive/2026-11-19-release-1-5-2/specs/plan-selection-actions/spec.md similarity index 100% rename from openspec/changes/release-1-5-2/specs/plan-selection-actions/spec.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/specs/plan-selection-actions/spec.md diff --git a/openspec/changes/release-1-5-2/tasks.md b/openspec/changes/archive/2026-11-19-release-1-5-2/tasks.md similarity index 94% rename from openspec/changes/release-1-5-2/tasks.md rename to openspec/changes/archive/2026-11-19-release-1-5-2/tasks.md index a090f5b..e93ed2e 100644 --- a/openspec/changes/release-1-5-2/tasks.md +++ b/openspec/changes/archive/2026-11-19-release-1-5-2/tasks.md @@ -57,12 +57,12 @@ Each numbered group is one pull request into the development branch. It carries ## 7. Joined verification and release -- [ ] 7.1 After groups 1 to 6 and 8 have merged, run one rendered journey on the development branch at desktop width and 390 px: Tidy and a mixed selection with archive, Undo and delete; a search selection across two result pages with a plan archived from another frame; the result line with skipped and unconfirmed plans in three languages; and a keyboard-only pass through count, run, Stop and result. -- [ ] 7.2 Run the measuring driver on the joined branch and the gate against a baseline recorded with the same driver. Report every row, including any reported as unverified and the informational run-read row. The gate passes. Commit no measurement. -- [ ] 7.3 Run portable CI in a fresh full-history disposable checkout with a cleared environment, and review every public diff for private data. -- [ ] 7.4 Prepare the release in one pull request into the development branch: version 1.5.2 in the package and the release constant, the changelog entry and curated release notes. This pull request is not documentation-only for CI: release notes and the changelog feed the release scripts, and tests read `openspec/changes/archive/`. -- [ ] 7.5 In the same pull request, reconcile the task lists of the 1.5.0 change, the 1.5.1 change and this one: tick each task whose work shipped, and leave a task that did not happen unticked with a note saying whether it is deferred, superseded or out of scope. -- [ ] 7.6 In the same pull request, archive the 1.5.0 change, then the 1.5.1 change, then this one, in that order, because each later change modifies capabilities the earlier ones introduced. Never use `--skip-specs` or `--no-validate`. A rehearsal showed what this pull request must correct in the 1.5.1 change's deltas before archiving that change. First, restore the two scenario names that the 1.5.0 specs hold and two of its modified requirements dropped, either by putting the old name on the new content or by keeping the old scenario beside the renamed one. Second, shorten or split the four requirement texts that would exceed 500 characters once in the specs, keeping their meaning and their scenarios. That includes the result requirement at 628 characters, although this change replaces it in the third archive: strict validation runs after the second archive too. After each archive, write the purpose of every capability it created, ten in all, and validate the specs strictly. That validation reports nothing after each of the three archives. If an archive refuses any other delta, correct the delta. +- [ ] 7.1 After groups 1 to 6 and 8 have merged, run one rendered journey on the development branch at desktop width and 390 px: Tidy and a mixed selection with archive, Undo and delete; a search selection across two result pages with a plan archived from another frame; the result line with skipped and unconfirmed plans in three languages; and a keyboard-only pass through count, run, Stop and result. Partly run, not ticked: on the merged tree the source-built rendered drivers for Tidy (224 checks) and for selection (116 checks) passed at 1280 and 390 px in English, Russian and Simplified Chinese, covering Tidy, a mixed selection with archive, Undo and delete, the result line, Stop and the keyboard-only passes. Not run as a rendered journey: a search selection across two result pages with a plan archived from another frame, and a result line holding both skipped and unconfirmed plans, because no current rendered driver covers them (the search driver predates 1.5.0 and fails on the development branch). The controller and copy tests cover both. Deferred. +- [x] 7.2 Run the measuring driver on the joined branch and the gate against a baseline recorded with the same driver. Report every row, including any reported as unverified and the informational run-read row. The gate passes. Commit no measurement. Done on the merged tree: a baseline recorded with the final driver against the 1.5.0 interface (page idle long tasks 6,099 ms, five list starts in the idle window), three source-built candidates each run alone, and the gate: exit 0, 27 rows, 26 passed, one informational run-read row, none unverified or failed. No measurement is committed. +- [x] 7.3 Run portable CI in a fresh full-history disposable checkout with a cleared environment, and review every public diff for private data. Done on the merged and archived tree: portable CI in a fresh full-history clone with a cleared environment passed, and the public diff against the development branch was reviewed for private data. +- [x] 7.4 Prepare the release in one pull request into the development branch: version 1.5.2 in the package and the release constant, the changelog entry and curated release notes. This pull request is not documentation-only for CI: release notes and the changelog feed the release scripts, and tests read `openspec/changes/archive/`. +- [x] 7.5 In the same pull request, reconcile the task lists of the 1.5.0 change, the 1.5.1 change and this one: tick each task whose work shipped, and leave a task that did not happen unticked with a note saying whether it is deferred, superseded or out of scope. +- [x] 7.6 In the same pull request, archive the 1.5.0 change, then the 1.5.1 change, then this one, in that order, because each later change modifies capabilities the earlier ones introduced. Never use `--skip-specs` or `--no-validate`. A rehearsal showed what this pull request must correct in the 1.5.1 change's deltas before archiving that change. First, restore the two scenario names that the 1.5.0 specs hold and two of its modified requirements dropped, either by putting the old name on the new content or by keeping the old scenario beside the renamed one. Second, shorten or split the four requirement texts that would exceed 500 characters once in the specs, keeping their meaning and their scenarios. That includes the result requirement at 628 characters, although this change replaces it in the third archive: strict validation runs after the second archive too. After each archive, write the purpose of every capability it created, ten in all, and validate the specs strictly. That validation reports nothing after each of the three archives. If an archive refuses any other delta, correct the delta. ## 9. Faster test suites diff --git a/openspec/specs/active-plan-cleanup/spec.md b/openspec/specs/active-plan-cleanup/spec.md new file mode 100644 index 0000000..534bc89 --- /dev/null +++ b/openspec/specs/active-plan-cleanup/spec.md @@ -0,0 +1,142 @@ +# active-plan-cleanup Specification + +## Purpose +Let the service archive or delete a plan that is still in progress only on an explicit acknowledgement, keep its revision checks and receipts unchanged, and make reports to a removed plan fail closed. + +## Requirements + +### Requirement: An in-progress plan is archived or deleted only with an explicit acknowledgement + +The archive and delete routes SHALL accept an in-progress plan only when the request carries the literal in-progress acknowledgement beside its existing fields. Without it, an in-progress plan SHALL be refused with the existing `closed` conflict, exactly as before. A request that carries it for a plan that is not in progress SHALL be refused with `closed`. Delete SHALL still require its own literal confirmation. + +#### Scenario: Archive with the acknowledgement +- **WHEN** an archive request with the acknowledgement names an in-progress plan at its current progress revision and cleanup generation +- **THEN** the plan becomes archived, its cleanup generation advances by one and a receipt is returned +- **AND** its lifecycle, tasks, counts, progress revision and history are unchanged + +#### Scenario: Archive or delete without the acknowledgement +- **WHEN** a request without the acknowledgement names an in-progress plan +- **THEN** it is refused with `closed` and nothing changes + +#### Scenario: Delete an in-progress plan +- **WHEN** a delete request carries both the confirmation and the acknowledgement for an in-progress plan +- **THEN** the plan's stored content is removed as for a closed plan and a receipt with the deleted state is returned +- **AND** the same request without the confirmation is refused as invalid + +#### Scenario: Acknowledgement on a closed plan +- **WHEN** a request carries the acknowledgement for a finished, cancelled or failed plan +- **THEN** it is refused with `closed` and nothing changes + +### Requirement: Restore accepts an archived plan of any lifecycle + +Restore SHALL accept an archived plan whatever its lifecycle, SHALL leave that lifecycle unchanged and SHALL refuse a request that carries the acknowledgement field. + +#### Scenario: Restore an archived in-progress plan +- **WHEN** a restore request names an archived plan whose lifecycle is in progress +- **THEN** the plan becomes visible and in progress again with its cleanup generation advanced by one + +#### Scenario: Restore with the acknowledgement +- **WHEN** a restore request carries the acknowledgement field +- **THEN** it is refused as invalid and nothing changes + +### Requirement: Revision checks and receipts are unchanged + +Every cleanup request SHALL stay bound to the store, source, plan, progress revision and cleanup generation it names, and a stale value SHALL be refused with `conflict` without changing anything. Only the latest identical request SHALL replay its receipt. The acknowledgement SHALL be part of the request's identity for replay. Receipt shape, error codes and statuses MUST NOT change, and no request SHALL name more than one plan. + +#### Scenario: The plan was reported to after confirmation +- **WHEN** an agent's report advances the plan's revision between confirmation and the request +- **THEN** the request is refused with `conflict` and the plan is neither archived nor deleted + +#### Scenario: The plan finished after confirmation +- **WHEN** a plan confirmed as in progress is finished before the request arrives +- **THEN** the request is refused with `conflict` because its revision is stale + +#### Scenario: Replay +- **WHEN** the latest request is sent again unchanged +- **THEN** its original receipt is returned and the cleanup generation does not advance again + +#### Scenario: Reused operation with a different acknowledgement +- **WHEN** the latest operation identifier is reused with the acknowledgement added or removed +- **THEN** the request is refused with `operation-reused` + +### Requirement: The capability is advertised separately + +A ready service that accepts the acknowledgement SHALL advertise it in health as its own additive fact, and the existing cleanup capability SHALL keep its value and meaning. A guest SHALL send the acknowledgement only when the fact is advertised. + +#### Scenario: Earlier guest +- **WHEN** a guest from the previous release uses the newer service +- **THEN** its archive, restore and delete requests behave as before and an in-progress plan is still refused + +#### Scenario: Earlier service +- **WHEN** a newer guest uses a service that does not advertise the fact +- **THEN** it sends no acknowledgement, leaves in-progress plans out of the action and says how many it left out + +### Requirement: Reports to an archived plan are refused until it is restored + +While a plan of any lifecycle is archived, every report operation on it SHALL be refused with `closed` before receipt replay and SHALL store nothing. Reading it SHALL still work. The service MUST NOT restore a plan because a report arrived. After the plan is restored, reports SHALL be accepted again at its unchanged revision. + +#### Scenario: Agent reports progress to an archived in-progress plan +- **WHEN** the plan's main session reports a task change after the plan was archived +- **THEN** the report is refused with `closed`, the plan's revision, tasks and history are unchanged and the plan stays archived + +#### Scenario: Reopen is refused +- **WHEN** the main session sends a revision with reopen to an archived plan +- **THEN** it is refused with `closed` + +#### Scenario: Retried earlier report +- **WHEN** a report that was acknowledged before the archive is sent again +- **THEN** it is refused with `closed` and its earlier receipt is not replayed + +#### Scenario: Sub-agent handoff or delegation +- **WHEN** a sub-agent hands off, or the main session declares or links a delegation, for an archived plan +- **THEN** the operation is refused with `closed` and no task is assigned or changed + +#### Scenario: Restored +- **WHEN** the person restores the plan and the agent reports at the plan's current revision +- **THEN** the report is accepted and the revision advances by one + +### Requirement: Reports to a deleted plan are refused and its identifier is never reused + +After a plan of any lifecycle is deleted, every report operation naming it SHALL be refused with `not-found`, including a start with the same identifier. Deleting an in-progress plan SHALL remove the same stored content as deleting a closed plan, including staged uploads, and SHALL keep the tombstone. Deletion MUST NOT be presented as secure erasure. + +#### Scenario: Agent reports to a deleted plan +- **WHEN** the main session reports a change to a plan the person deleted +- **THEN** the report is refused with `not-found` and nothing is stored + +#### Scenario: Starting again under the same identifier +- **WHEN** an agent starts a plan with the deleted plan's identifier +- **THEN** the start is refused with `not-found` +- **AND** a start with a new identifier creates an independent plan + +#### Scenario: Staged structure in flight +- **WHEN** an in-progress plan with staged but uncommitted structure is deleted +- **THEN** the staged chunks are removed and a later commit of that upload is refused with `not-found` + +### Requirement: An archived or deleted in-progress plan stops supplying current work + +An archived or deleted in-progress plan SHALL leave ordinary plan lists, featured-plan choices, Needs you, resume briefs and waiting-delegation views under the rules that already apply to archived and deleted plans. A delegation declared before the action MUST NOT bind afterwards. Recorded sub-agent runs SHALL remain. + +#### Scenario: Needs you +- **WHEN** an in-progress plan with a decision blocker reported by its top-level main session is archived +- **THEN** the item leaves Needs you and its counts on the next read +- **AND** restoring the plan brings the item back + +#### Scenario: Rail and Work Status +- **WHEN** the only plan of a session is archived while in progress +- **THEN** the rail and Work Status for that session show no plan, not the archived one + +#### Scenario: Pending delegation +- **WHEN** a sub-agent is dispatched after its plan was archived or deleted with a delegation still waiting +- **THEN** no task is assigned or changed and the existing delegation refusal applies + +### Requirement: Older writers and services stay safe + +The persistent store guards SHALL fence writes to an archived or deleted plan whatever its lifecycle, including from writers loaded before the action and from older releases. The cleanup storage format MUST NOT change. + +#### Scenario: Older writer +- **WHEN** a writer from an earlier release attempts a report to an archived in-progress plan +- **THEN** the write is aborted and nothing is stored + +#### Scenario: Older service after a rollback +- **WHEN** the previous release's service runs on a store that holds an archived in-progress plan +- **THEN** the plan stays readable and archived, a restore is refused with `closed`, and no data is lost diff --git a/openspec/specs/closed-plan-tidy/spec.md b/openspec/specs/closed-plan-tidy/spec.md new file mode 100644 index 0000000..4692c1a --- /dev/null +++ b/openspec/specs/closed-plan-tidy/spec.md @@ -0,0 +1,359 @@ +# closed-plan-tidy Specification + +## Purpose +Let a person clean up closed plans in bulk with an explicit confirmation, an honest per-plan result and receipt-bound undo, while every plan keeps its own revision and generation checks. + +## Requirements + +### Requirement: Explicit confirmation before any request + +Opening Tidy SHALL show an inline panel, not a modal, whose one short line states how many plans are in scope and whose buttons name the action and the count. It MUST NOT list plan titles. Cancel SHALL have initial focus, Enter MUST NOT confirm by default and Escape SHALL cancel. No archive, restore or delete request SHALL be sent on opening or cancelling. The deletion step SHALL keep what deletion removes and keeps reachable in one collapsed disclosure. + +#### Scenario: Cancel +- **WHEN** the user opens the panel and presses Escape or Cancel +- **THEN** no cleanup request is sent and focus returns to the Tidy button + +#### Scenario: Confirm +- **WHEN** the user activates the archive button +- **THEN** each plan in scope is archived through the existing per-plan archive route, bound to the progress revision and cleanup generation captured for it, one request at a time + +#### Scenario: Counting plans that are not loaded +- **WHEN** the scope reaches beyond the loaded list +- **THEN** the panel shows that it is counting, sends only reads, and can be cancelled before the count arrives + +#### Scenario: More than one run covers +- **WHEN** at least 1,000 matching plans are collected and more remain +- **THEN** the line says it covers the first 1,000 of more, and the rest can be done by using Tidy again + +#### Scenario: Scan limit reached first +- **WHEN** the scan reaches its 2,000-plan limit having collected fewer than 1,000 matching plans +- **THEN** the line states the number actually found and that more plans weren't checked, without claiming more matches exist, and offers Check more + +#### Scenario: Check more continues past checked plans +- **WHEN** the user chooses Check more after the scan limit +- **THEN** the scan continues from where it stopped in the same reading, reading up to 2,000 further plans and adding their matches to the count, never re-reading plans it already checked +- **AND** a change of store, account, binding, view, search or filters discards the continuation, so the next scan starts from the beginning + +#### Scenario: Deletion details +- **WHEN** the user expands the disclosure in the deletion step +- **THEN** it states that stored tasks, history and the document copy are removed, the original file is kept, and deletion is not secure erasure + +#### Scenario: Context changes mid-run +- **WHEN** the frame observes a change of the store, account, binding or board reading while requests remain +- **THEN** no further request is sent and no plan is reported as done without its validated receipt +- **AND** after a change of board reading in the same account, store and binding the run shows no result line and sends its one reconciliation read when it ends + +#### Scenario: Account, store or binding changes mid-run +- **WHEN** the frame observes a change of the account, store or binding while requests remain +- **THEN** the board shown after the change shows no result of that run and is not changed by it + +### Requirement: Honest result with undo + +A run SHALL show one progress line with how many of the total are done, and Stop. Its result SHALL be one line, kept until the next action or refresh, not a timer. After Archive it SHALL offer Undo, which restores each plan this run archived through the restore route; a deletion result MUST NOT offer Undo. Archive and Undo MUST NOT change a plan's lifecycle, counts or history. A plan SHALL be reported as done only when its receipt was validated, and no plan SHALL be retried automatically. + +#### Scenario: All archived +- **WHEN** 128 plans are archived +- **THEN** one line says 128 plans were archived and offers Undo, and the plans leave the current list after one authoritative re-read + +#### Scenario: Partial failure +- **WHEN** two of 128 plans were refused as changed +- **THEN** the line says 126 of 128 were archived and two were skipped, with a way to try again for the plans that remain +- **AND** the skipped plans are not retried automatically and are not reported as archived + +#### Scenario: Stop +- **WHEN** the user chooses Stop during a run +- **THEN** no further request is sent after the one in flight, and the result states how many were done before stopping + +#### Scenario: Undo +- **WHEN** the user chooses Undo +- **THEN** each plan this run archived is restored with its lifecycle unchanged, bound to the cleanup generation its archive returned +- **AND** a plan that changed since is left as it is and reported + +#### Scenario: Deleted +- **WHEN** 128 plans are deleted +- **THEN** one line says 128 plans were deleted and no Undo is offered + +#### Scenario: Keyboard and announcement +- **WHEN** a run starts and completes +- **THEN** its start and its result are each announced once, individual plans are not announced, and Stop and Undo are reachable by keyboard without moving focus unexpectedly + +### Requirement: Tidy is always available on the full page + +The full page SHALL show one Tidy button beside search and Filters whenever it shows a plan library and the service supports cleanup. The button MUST NOT be hidden because a search or filter is set or because nothing is eligible. The rail and the More menu on either surface MUST NOT hold a bulk archive entry. + +#### Scenario: While searching or filtering +- **WHEN** a search is shown or a project, worktree or session filter is set +- **THEN** the Tidy button is still shown and usable + +#### Scenario: Nothing to tidy +- **WHEN** Tidy is opened and no closed plan is in scope +- **THEN** one line says there are no closed plans here, no action is offered and nothing is sent + +#### Scenario: Service without cleanup +- **WHEN** the service does not advertise the cleanup capability +- **THEN** the Tidy button is absent, as the other cleanup actions are + +#### Scenario: Rail and More +- **WHEN** the rail or the More menu of the rail or board is opened +- **THEN** neither offers a bulk archive entry, and per-plan Archive, Restore and Delete permanently remain for the plan shown + +#### Scenario: Phone width and keyboard +- **WHEN** the full page is 390 CSS pixels wide, or operated by keyboard +- **THEN** the Tidy button is reachable in the bar without horizontal overflow, has an accessible name and is at least 44 CSS pixels on a coarse pointer + +### Requirement: Tidy covers every closed plan in the board's scope + +Tidy SHALL act on closed plans only: finished, cancelled and failed. It MUST NOT act on an in-progress plan. Its scope SHALL be the closed plans matching the current search and filters, or every closed plan of the current view when none are set, including plans that are not loaded. In Current plans it covers unarchived plans; in Archived plans it covers archived ones. + +#### Scenario: No search or filter +- **WHEN** Tidy is opened in Current plans with no search or filter and the library holds finished, cancelled, failed and in-progress plans +- **THEN** the panel counts every unarchived finished, cancelled and failed plan and no in-progress plan + +#### Scenario: Filtered +- **WHEN** a project filter is set +- **THEN** the panel counts only that project's closed plans and says the count is of matching plans + +#### Scenario: Searching +- **WHEN** a search is shown +- **THEN** the panel counts the closed plans among that search's matching plans, including matches not shown yet + +#### Scenario: Plans that are not loaded +- **WHEN** older plans were not loaded into the list +- **THEN** opening Tidy reads their identities through a bounded scan before stating the count, and they are included + +#### Scenario: A plan reopens before the run +- **WHEN** a plan counted as closed is reopened by its agent before its request is sent +- **THEN** its request is refused as changed, the plan is skipped and it is reported as not done + +### Requirement: Tidy archives or deletes permanently + +The Tidy panel SHALL offer Archive and Delete permanently for the plans in scope in Current plans, and Delete permanently only in Archived plans. Archive SHALL be undoable. Delete permanently SHALL require its own confirmation step and MUST NOT offer Undo or imply secure erasure. + +#### Scenario: Archive +- **WHEN** the user chooses Archive for 128 closed plans +- **THEN** those plans are archived through the per-plan archive route and the result offers Undo + +#### Scenario: Delete permanently +- **WHEN** the user chooses Delete permanently +- **THEN** a second step states the count and that it cannot be undone, and only its own button starts deleting + +#### Scenario: Archived plans +- **WHEN** Tidy is opened in Archived plans +- **THEN** it offers Delete permanently for the archived closed plans in scope and no Archive action + +### Requirement: A bulk count is exact only when its read can show it + +A Tidy or Select all count taken from the loaded plan list SHALL be stated as exact only when that list was read in a single page. Otherwise the confirmation SHALL say that some plans may have been missed, on its first step and on the deletion step. A count of rows explicitly chosen from that list SHALL stay exact. A Try again recount from a list read in several pages SHALL stay exact only when it found every plan it names. The qualification MUST NOT add a read. + +#### Scenario: List read in several pages +- **WHEN** Tidy is opened on a complete list of 120 plans that was read in three pages +- **THEN** the count line states the number found and that some plans may have been missed +- **AND** no request is sent to produce the count + +#### Scenario: List read in one page +- **WHEN** Tidy is opened on a complete list of 30 plans that was read in one page +- **THEN** the count line states the number without qualification + +#### Scenario: Select all on a multi-page list +- **WHEN** Select all is active on a complete list read in several pages and an action is opened +- **THEN** the confirmation says that some plans may have been missed + +#### Scenario: Explicitly chosen rows +- **WHEN** three rows are chosen one by one on a complete list read in several pages and an action is opened +- **THEN** the confirmation states three plans without qualification + +#### Scenario: Chosen rows counted by a scan +- **WHEN** rows are chosen in a searched or truncated scope, where the count runs through a scan +- **THEN** the scan's existing qualification and Check more rules apply unchanged, also on an older service, whose list scan cannot vouch for what crossed its cursor + +#### Scenario: Try again finds every named plan +- **WHEN** Try again is chosen after a partial run on a complete list that was read in several pages, and every remaining plan is among the loaded rows +- **THEN** the recount states those plans without qualification + +#### Scenario: Try again does not find a named plan +- **WHEN** Try again is chosen on a complete list that was read in several pages, and a remaining plan is not among the loaded rows +- **THEN** the recount states the plans it found and that some plans may have been missed, because that read cannot show whether the plan left the view or was missed +- **AND** no request is sent to look for it + +#### Scenario: Try again on a list read in one page +- **WHEN** Try again is chosen on a complete list that was read in one page, and a remaining plan is not among its rows +- **THEN** the recount states the plans it found without qualification + +#### Scenario: Deletion step +- **WHEN** Delete permanently is chosen from a qualified count +- **THEN** the deletion step repeats that some plans may have been missed + +### Requirement: A bulk run completes only into the account and store it ran in + +A bulk run SHALL capture the integration account and the store and binding identity when it starts. When it finishes after the frame observed a change of either, even one that has since changed back, it SHALL drop its own state and MUST NOT reset caches, change the selection, close the opened plan or show a result on the board shown then. A validated Delete receipt SHALL still remove the device review marker captured for its plan in the account and store the run started in. + +#### Scenario: Account switched while a request is held +- **WHEN** the integration account changes while a bulk archive request is held, a plan is opened and selected on the new board, and the held request then answers +- **THEN** the new board keeps its opened plan, its selection and its loaded list, and shows no result line +- **AND** the plans of the earlier run that were never sent stay unsent + +#### Scenario: Same identifiers in the new store +- **WHEN** the board shown after the change holds a selected plan with the same source and plan identifier as a target of the earlier run +- **THEN** that plan stays selected and is not treated as archived, restored or deleted + +#### Scenario: Account switched away and back while a request is held +- **WHEN** the integration account changes and changes back while a bulk archive request is held, a plan is opened on the board shown, no newer run is started, and the held request then answers +- **THEN** that board keeps its opened plan, its selection and its loaded list, and shows no result line + +#### Scenario: Delete receipt arrives after the switch +- **WHEN** the integration account changes while a bulk delete request is held, and the request then answers with a valid receipt +- **THEN** the review marker stored for that plan under the account and store the run started in is removed +- **AND** the markers of other plans, and of the same plan identifier under another account, stay + +#### Scenario: Board scope changed in the same account and store +- **WHEN** only the board's filters or search changed while the run was in flight +- **THEN** the run stops after the request in flight, shows no result line and sends its one reconciliation read when it ends, as the interface did before this change + +#### Scenario: Store changed during a run without the frame observing it +- **WHEN** the store changes with no account change while a bulk run has the list reads paused +- **THEN** the run ends on the board it started on, and the list read that follows it adopts the new store and clears that board, as before this change + +#### Scenario: Store change observed after a board change resumed list reads +- **WHEN** the board's filters change while a bulk request is held, so list reads resume, a list reply then shows that the store changed, and the held request answers +- **THEN** the board shown keeps its loaded list and its selection, and shows no result of that run + +### Requirement: Cleanup support follows the service's latest answer + +Cleanup controls SHALL follow the cleanup facts of the latest health reply the frame accepted, whichever list is shown. Showing a remembered list scope MUST NOT bring back cleanup support, or in-progress cleanup support, that a later health reply withdrew, and MUST NOT hide support that a later health reply granted. A health reply is accepted when the refresh that read it settles, whether its list read completed or failed. + +#### Scenario: Switching back to a remembered view +- **WHEN** Current plans was read with cleanup support, Archived plans then observes a service without it, and the person switches back to Current plans while its new read is pending +- **THEN** Tidy and Select stay absent while the remembered list is shown + +#### Scenario: Loss observed on a failed read +- **WHEN** a refresh receives a health reply without cleanup support and then fails to read the plans, and the person changes to a scope the frame remembers +- **THEN** the remembered list is shown without cleanup controls + +#### Scenario: Support returns +- **WHEN** a later health reply offers cleanup again +- **THEN** the controls return with that reply, not earlier + +#### Scenario: Support granted after a view was remembered +- **WHEN** one view of Current plans was last read while the service offered no cleanup, a later refresh in another view of Current plans, such as the same list under a session filter, accepts a health reply that offers it, and the person switches back to the first view while its new read is pending +- **THEN** Tidy and Select are offered while the remembered list of the first view is shown + +### Requirement: Background cleanup updates do not interrupt the person + +A count that finishes by itself, including its failure and the end of a Check more continuation, SHALL repaint as background data, so it waits while a control is held or a picker is open. Explicit actions SHALL still repaint at once, and the change MUST NOT add a timer or defer freshness beyond the existing held-control and open-picker rules. + +#### Scenario: Count finishes during a press +- **WHEN** a count finishes between pointer down and pointer up on an unrelated control such as Filters +- **THEN** the control is not replaced before its click, the click takes effect and the count line appears on the next paint + +#### Scenario: Explicit action during a count +- **WHEN** the person presses Cancel or Check more while a count is running +- **THEN** the panel repaints at once, as before this change + +### Requirement: A deferred cleanup focus move is decided when it is applied + +A focus move that cleanup deferred SHALL be applied only if, at the paint that applies it, focus is still on the control the move was queued from, or is on no control because that control was removed. If the person has focused anything else, inside the cleanup panel or outside it, the move SHALL be dropped and MUST NOT be kept for a later paint. A move denied because another frame has focus SHALL stay dropped. + +#### Scenario: Focus moved before Tidy returns +- **WHEN** a run ends while Stop has focus, the Tidy button is absent during the reconciliation read, and the person focuses Search before that read finishes +- **THEN** focus stays in Search when the Tidy button reappears, and on every later paint + +#### Scenario: Focus moved to Undo before Tidy returns +- **WHEN** a run ends while Stop has focus, the result line offers Undo while the Tidy button is absent during the reconciliation read, and the person focuses Undo before that read finishes +- **THEN** focus stays on Undo for as long as Undo is shown, also when the Tidy button reappears +- **AND** the dropped move to the Tidy button is not applied later, also after the result expires and Undo is removed + +#### Scenario: Focus lost with the removed control +- **WHEN** a run ends while Stop has focus and the person focuses nothing else +- **THEN** focus moves to the Tidy button when it reappears + +#### Scenario: Count finishes after focus moved +- **WHEN** a count finishes after the person moved focus from Cancel to Search, and its repaint was delayed by a held control +- **THEN** focus stays in Search + +### Requirement: An account or store switch releases pending cleanup controls + +After the frame observes a change of the integration account or of the store and binding, cleanup controls on the board shown SHALL be usable without waiting for a cleanup request sent before the change. That request's late answer MUST NOT complete, release or otherwise change a cleanup action started after the change. This SHALL hold for a single-plan request as for a bulk run, and when the account or store changed and changed back before the answer. + +#### Scenario: Tidy after a switch +- **WHEN** the account changes while a cleanup request is held, and the person opens Tidy on the new board before that request answers +- **THEN** Tidy opens and counts + +#### Scenario: Store change observed during a single-plan request +- **WHEN** a single-plan cleanup request is held and a list reply shows that the store changed +- **THEN** cleanup controls on the board shown after that reply are usable before the held request answers + +#### Scenario: Late answer during a newer run +- **WHEN** the earlier request answers while a run started on the new board is in flight +- **THEN** the newer run stays pending until its own requests finish and cannot be confirmed a second time + +#### Scenario: Single-plan request held across a switch +- **WHEN** a single-plan cleanup request is held, the account changes, a Tidy run is started on the new board, and the held request then answers +- **THEN** the Tidy run completes and shows its own result +- **AND** the late answer shows no message and resets nothing on the new board + +#### Scenario: Switched away and back +- **WHEN** the account changes and changes back while a cleanup request is held, a new run is started, and the held request then answers +- **THEN** the late answer neither completes nor releases the new run + +### Requirement: A run's own updates do not replace a held control + +A progress update of a bulk run, and the repaint at its end with the result line and the selection changes its receipts cause, SHALL repaint as background data, so they wait while a control is held or a picker is open. The run itself, the release of its busy state, its cache invalidation and its reconciliation read MUST NOT wait for the repaint. A refresh MUST NOT expire a result that has not been painted yet. + +#### Scenario: Stop pressed while a plan is confirmed +- **WHEN** a plan's receipt arrives between pointer down and pointer up on Stop, and requests remain +- **THEN** Stop is not replaced before its click, and the run stops after the request in flight + +#### Scenario: Last reply arrives during a press +- **WHEN** the run's last reply arrives between pointer down and pointer up on an unrelated control +- **THEN** that control is not replaced while it is held, and the result line appears on the next paint +- **AND** the reconciliation read is sent without waiting for that paint +- **AND** a held control of the board whose data the run invalidated, such as Filters, stays in place and ignores that click, as after any cache reset + +#### Scenario: Hold lasts past the next refresh +- **WHEN** the run's last reply arrives while a control is held or a picker is open, and the hold lasts past the next refresh +- **THEN** that refresh does not expire the result, and the result line, with Undo after an archive, appears on the paint after the hold ends +- **AND** the refresh after that paint expires it, as before this change + +#### Scenario: Progress still advances +- **WHEN** no control is held and no picker is open during a run +- **THEN** the progress line follows the completed count, and the result line appears when the run ends, as before this change + +### Requirement: The result separates skipped plans from unconfirmed ones + +The result line SHALL state how many plans were archived, restored or deleted, how many were skipped and, separately, how many could not be confirmed and may have been applied. A plan whose request was attempted and received no valid answer SHALL be reported as unconfirmed, never as skipped. A plan the run did not attempt MUST NOT be reported as unconfirmed. Undo SHALL restore only plans with a validated archive receipt. + +#### Scenario: Reply lost +- **WHEN** the reply to one of 128 archive requests is lost or times out and the other 127 are archived +- **THEN** the line says 127 of 128 were archived and that one could not be confirmed and may have been archived +- **AND** that plan is not reported as skipped, is not reported as archived and is not retried automatically + +#### Scenario: Skipped and unconfirmed together +- **WHEN** one plan was refused as changed and the replies for two others were lost +- **THEN** the line states the archived count, one skipped and two that could not be confirmed, in one sentence + +#### Scenario: Stopped before sending +- **WHEN** the run is stopped with plans not yet sent +- **THEN** those plans count as skipped, never as unconfirmed + +#### Scenario: Attempt that failed before reaching the service +- **WHEN** the run attempts a plan's request and it fails while being prepared or handed over, before the service could receive it +- **THEN** the plan is reported as unconfirmed, because the run cannot tell this failure from a lost reply + +#### Scenario: Unconfirmed plans and Undo +- **WHEN** Undo is chosen after a run with unconfirmed plans +- **THEN** only the plans with a validated archive receipt are restored +- **AND** an unconfirmed plan that was in fact archived is not restored by Undo; it can be restored on its own once an Archived plans list or search shows it + +#### Scenario: Try again after unconfirmed plans +- **WHEN** Try again is chosen after an archive, a deletion or a restore of selected plans that left skipped and unconfirmed plans +- **THEN** both are recounted under the existing retry rules before a new confirmation, and a plan that has left the view is left out + +#### Scenario: Try again after a partial Undo +- **WHEN** Undo restored some plans, others were skipped or could not be confirmed, and Try again is chosen +- **THEN** the restore is sent again for exactly those remaining plans, each still bound to the revision and cleanup generation its archive receipt returned, without a recount in the view shown +- **AND** a plan whose earlier restore was in fact applied is confirmed as restored from the receipt the service saved for that same request, and is not restored twice +- **AND** a plan that another cleanup changed since is refused, left as it is and reported as skipped + +#### Scenario: Three languages +- **WHEN** the result line is shown in English, Russian or Simplified Chinese +- **THEN** it distinguishes skipped from unconfirmed plans in that language, as whole sentences with its plural forms diff --git a/openspec/specs/delegation-intent-visibility/spec.md b/openspec/specs/delegation-intent-visibility/spec.md index 61c7fa7..2645cf5 100644 --- a/openspec/specs/delegation-intent-visibility/spec.md +++ b/openspec/specs/delegation-intent-visibility/spec.md @@ -32,3 +32,35 @@ The next eligible coordinator context SHALL expose a genuine delegation refusal - **WHEN** the tool is restricted or disposition evidence cannot be established within its bounds - **THEN** no permission is expanded and no successful binding is asserted - **AND** the limitation is explicit rather than an inferred absence of conflicts + +### Requirement: Refusal guidance rests on validated receipt evidence + +Before coordinator guidance infers from a delegation receipt that cleanup retired a waiting delegation, a pending or reserved receipt SHALL be checked as the per-plan reader checks it: pending names no dispatch, reserved names one, and both name at least one task. A receipt that fails MUST NOT produce a refusal; it SHALL make the guidance incomplete, as other unreadable evidence does. Other receipts SHALL be read as before. The check MUST NOT change a receipt, the store or any reply. + +#### Scenario: Reserved without a dispatch +- **WHEN** a restored plan's latest delegation receipt says reserved and names no dispatch, and its intent is gone +- **THEN** coordinator guidance reports no `closed` refusal for it and is marked incomplete + +#### Scenario: Pending with a dispatch +- **WHEN** a restored plan's latest delegation receipt says pending and names a dispatch +- **THEN** coordinator guidance reports no refusal for it and is marked incomplete + +#### Scenario: Pending or reserved with no tasks +- **WHEN** a restored plan's latest delegation receipt says pending or reserved and declares no task, and its intent is gone +- **THEN** coordinator guidance reports no refusal for it and is marked incomplete + +#### Scenario: Cancellation receipts are read as before +- **WHEN** a plan's latest delegation receipt is a cancellation, either the empty declaration that cancelled or the earlier declaration it retired, which keeps its tasks +- **THEN** coordinator guidance reads it as before this change: it reports no refusal for it and is not marked incomplete because of it + +#### Scenario: Well-formed receipt after restore +- **WHEN** a restored plan's latest delegation receipt is pending without a dispatch, or reserved with one, names at least one task, its intent was retired by cleanup, and its declared tasks have not been verifiably recovered since +- **THEN** coordinator guidance reports the `closed` refusal as before + +#### Scenario: Well-formed receipt whose tasks were recovered +- **WHEN** that same well-formed receipt is still the latest, and the plan's current assignment shows its declared tasks were explicitly linked since +- **THEN** coordinator guidance reports no refusal for it, as before this change + +#### Scenario: Both readers agree +- **WHEN** the per-plan reader rejects a pending or reserved receipt because its dispatch disagrees with its state +- **THEN** coordinator guidance does not present that same receipt as complete evidence diff --git a/openspec/specs/dependency-map-arrow-state/spec.md b/openspec/specs/dependency-map-arrow-state/spec.md index a47090d..00d0220 100644 --- a/openspec/specs/dependency-map-arrow-state/spec.md +++ b/openspec/specs/dependency-map-arrow-state/spec.md @@ -126,16 +126,16 @@ Selection-chain arrows SHALL keep chain colour, emphasis and visual priority whi ### Requirement: Arrow meaning has a textual equivalent -Arrows SHALL remain decorative and absent from accessible names and focus order. Map help SHALL explain working beads, blocked bars, skipped dashes and quiet done arrows, including that looping motion means reported work, not progress. A current waiting task's inspector SHALL summarize working and explicitly blocked direct prerequisites without new motion announcements. +Arrows SHALL remain decorative and absent from accessible names and focus order. The map's help-and-filters control SHALL explain working beads, blocked bars, skipped dashes and quiet done arrows in plain words, including that looping motion means work in progress as reported, not progress made. A current waiting task's selected-task summary SHALL count its in-progress and blocked direct prerequisites without new motion announcements. #### Scenario: Waiting-task summary - **WHEN** a selected pending task on an eligible picture has three unfinished direct recorded prerequisites, one working, one blocked and one pending -- **THEN** the inspector communicates “Waiting on 3 unfinished recorded prerequisites: 1 reported working, 1 explicitly blocked.” +- **THEN** the summary states that it waits on three earlier tasks, one in progress and one blocked - **AND** counts include prerequisites hidden by filters, count each direct task once, exclude transitive/group relationships, omit zero subcounts and preserve singular wording #### Scenario: Skipped prerequisite - **WHEN** the waiting task also has a skipped prerequisite -- **THEN** the inspector preserves the skipped-work warning alongside any working/blocked summary +- **THEN** the summary preserves the skipped-work warning alongside any in-progress/blocked count #### Scenario: Unavailable guidance - **WHEN** the picture loses current guidance or the plan closes @@ -145,7 +145,7 @@ Arrows SHALL remain decorative and absent from accessible names and focus order. #### Scenario: Accessible navigation and silence - **WHEN** motion starts, stops or changes phase during a repaint - **THEN** card accessible names, keyboard navigation, focus and the map live region do not change because of motion -- **AND** keyboard users can read the arrow key through the existing Map help disclosure and use the ordinary list alternative +- **AND** keyboard users can read the arrow key through the help-and-filters control and use the ordinary list alternative ### Requirement: Expensive maps have a deterministic static fallback diff --git a/openspec/specs/dependency-map-view-controls/spec.md b/openspec/specs/dependency-map-view-controls/spec.md new file mode 100644 index 0000000..d947cda --- /dev/null +++ b/openspec/specs/dependency-map-view-controls/spec.md @@ -0,0 +1,109 @@ +# dependency-map-view-controls Specification + +## Purpose +Open the dependency map at a readable view of the plan's current work and keep its controls, navigation and cards simple, without changing how the map is panned, zoomed or read by keyboard and touch. + +## Requirements + +### Requirement: Opening view fits the plan only when readable + +Once per reading, the map SHALL open on the whole plan when its fit-all scale is at least the 70% readability threshold, else at a readable 80% zoom on current work. A coarse pointer SHALL keep its full-size opening zoom. Fit SHALL always show the whole plan. Opening MUST NOT select a task, move focus or repeat on polls. On a fine pointer the rail's map frame SHALL be at least 320 CSS pixels tall and grow with the plan's content at the readable zoom up to 60% of the rail's visible height. + +#### Scenario: Plan fits readably +- **WHEN** the whole plan fits the frame at 70% or more +- **THEN** every card is visible on opening + +#### Scenario: Plan too large to fit readably +- **WHEN** the whole plan would need less than 70% +- **THEN** the map opens at the readable zoom on in-progress and Needs you cards with their direct neighbours, or on the first such card in stored order when that group does not fit +- **AND** cards cut by the frame edge remain partly visible and a quiet hint states that Fit shows all tasks with their count + +#### Scenario: No current work +- **WHEN** the plan is closed or has no in-progress, Needs you or ready card +- **THEN** the map opens on the whole plan + +#### Scenario: Standard rail +- **WHEN** a plan with at least two dependency columns opens in a rail between 360 and 400 CSS pixels wide +- **THEN** it opens on current work at the readable zoom rather than a whole-plan view below the threshold + +#### Scenario: Large plans +- **WHEN** the 100-task and 980-task reference plans open on the rail and board +- **THEN** they open on current work within the existing large-plan load and interaction budgets, and Fit still shows the whole plan + +#### Scenario: Small plan on the rail +- **WHEN** a plan with one or two rows of tasks is shown on a rail 900 CSS pixels tall with a fine pointer +- **THEN** the map frame is 320 CSS pixels tall + +#### Scenario: Larger plan on the rail +- **WHEN** a plan whose content at the readable zoom is between 320 CSS pixels and 60% of the rail's visible height is shown with a fine pointer +- **THEN** the map frame is as tall as that content + +#### Scenario: Large plan on the rail +- **WHEN** a plan whose content at the readable zoom is taller than 60% of the rail is shown on a rail 900 CSS pixels tall with a fine pointer +- **THEN** the map frame is 540 CSS pixels tall + +#### Scenario: Short rail +- **WHEN** 60% of the rail's visible height is less than 320 CSS pixels +- **THEN** the map frame is 320 CSS pixels tall + +#### Scenario: Frame height +- **WHEN** the plan's content is shorter than the frame's maximum on the board, or the pointer is coarse on either surface +- **THEN** the frame shrinks to the content, up to 64% of the viewport height on the board with a fine pointer and up to 300 CSS pixels with a coarse pointer + +### Requirement: One help-and-filters control + +The map bar SHALL hold the Map | List switch, zoom out, zoom in, Fit, Focus current work and one help-and-filters control. That control SHALL contain the map keys, what the arrows mean, Show all / Unfinished, the group filter and the shown-task count. Its help text SHALL be short: one line of keys, at most two lines on arrows, and one touch line on a coarse pointer. Help, filters and counts MUST NOT appear as separate default rows. + +#### Scenario: Filter active +- **WHEN** a task or group filter hides tasks +- **THEN** the control shows a mark, and one line states how many of the plan's tasks are shown with a Clear action + +#### Scenario: Help by keyboard +- **WHEN** a keyboard user opens the control +- **THEN** the keys, relationship meanings and filters are reachable in Tab order, and Escape closes it and returns focus to the control + +#### Scenario: Help is scannable +- **WHEN** the control is opened in a frame 390 CSS pixels wide in English, Russian or Simplified Chinese +- **THEN** its whole content is visible without a scrollbar of its own +- **AND** it still explains beads, bars, dashes and quiet arrows in words, including that moving beads mean work in progress as reported and not progress made + +#### Scenario: Zoom feedback +- **WHEN** the user zooms +- **THEN** the zoom percentage shows briefly and is announced once, without a permanent readout + +### Requirement: Navigation is preserved + +Dragging, wheel and trackpad panning, pinch zoom, touch taps and every existing map key SHALL keep working. The bar SHALL offer Focus current work, which frames the same current work as the opening view and MUST NOT select a task, move focus or change filters. The pan buttons MAY stay removed because drag and keys cover them. No essential action SHALL depend on a gesture alone. + +#### Scenario: Keyboard only +- **WHEN** a keyboard user focuses the map +- **THEN** it is one Tab stop, arrow keys move between cards, bracket keys follow prerequisites and dependents, plus and minus zoom, and the fit key fits the plan + +#### Scenario: Touch +- **WHEN** a touch user pans with one finger or pinches with two on a coarse pointer +- **THEN** the map pans or zooms as before, and zoom, Fit and Focus current work remain available as labelled 44 CSS pixel buttons + +#### Scenario: Back to current work +- **WHEN** the user has panned away or chosen Fit and then activates Focus current work +- **THEN** the map frames in-progress and Needs you cards with their direct neighbours at the readable zoom, or the whole plan when there is no current work +- **AND** the selection, focus and filters are unchanged and the move is announced once + +#### Scenario: Focus current work in three languages +- **WHEN** the map bar is shown in English, Russian or Simplified Chinese at 390 CSS pixels +- **THEN** the button has its translated accessible name and the bar's tools stay on one row + +### Requirement: Compact card and selected-task summary + +A card SHALL show its state in plain words, the literal title on up to two lines, and the running sub-agent's name when proven. A blocked task that is a Needs you item SHALL read as needing the user; any other blocked task SHALL read as blocked. Selecting a card SHALL open a compact summary with state, what it waits on, what it unlocks, its reported blocker text and a verified Open session for its running sub-agent. + +#### Scenario: Needs you card +- **WHEN** a task is blocked with a decision the top-level main session reported +- **THEN** its card and accessible name say it needs the user + +#### Scenario: Sub-agent blocker card +- **WHEN** a task is blocked with a decision that a sub-agent reported +- **THEN** its card says blocked, and its summary still shows the reported reason and next action + +#### Scenario: Region and card names +- **WHEN** a screen reader reaches the map +- **THEN** the region name states the plan title, task count and counts by state, and each card name states title, state, what it waits on and how many tasks it unlocks diff --git a/openspec/specs/device-remembered-view-state/spec.md b/openspec/specs/device-remembered-view-state/spec.md new file mode 100644 index 0000000..ffcda20 --- /dev/null +++ b/openspec/specs/device-remembered-view-state/spec.md @@ -0,0 +1,58 @@ +# device-remembered-view-state Specification + +## Purpose +Remember a small, fixed set of view choices on the device, with honest failure when storage is unavailable, and never let a saved choice change reported data or another store or account. + +## Requirements + +### Requirement: Exactly three view states are remembered per device + +The extension SHALL remember on the device only these view states: hidden Needs you items, whether Needs you is collapsed or expanded on the rail and on the board, and dismissal of the incomplete-count indicator. Every other disclosure, filter, map position, selection and panel SHALL stay unstored, apart from the existing language choice and History review points. + +#### Scenario: Reload +- **WHEN** the user expands Needs you on the rail, hides one item and dismisses the indicator, then reloads +- **THEN** Needs you is expanded, the item stays hidden and the indicator stays dismissed while its reasons are unchanged + +#### Scenario: Defaults +- **WHEN** no state is saved +- **THEN** Needs you is collapsed on the rail and expanded on the board, nothing is hidden and the indicator is shown when needed + +#### Scenario: Other reading state +- **WHEN** the user changes a map filter, zoom, selection or an opened item and reloads +- **THEN** none of those is restored + +### Requirement: Device storage only, with honest failure + +These states SHALL be saved only in host device storage, only when the host advertises it, as versioned bounded records. They MUST NOT be saved in instance, server or browser storage. A failed or malformed read SHALL fall back to the defaults without repairing the record, and a failed write MUST NOT be presented as saved. + +#### Scenario: Host without device storage +- **WHEN** the host does not advertise device storage +- **THEN** no device request is sent, collapse and dismissal last only for the frame, and Hide is not offered + +#### Scenario: Write fails +- **WHEN** saving a hidden item fails +- **THEN** the item is shown again with one plain line and a retry, and it is not reported as hidden + +#### Scenario: Malformed record +- **WHEN** a saved record has an unknown version or shape +- **THEN** the defaults apply and the record is not overwritten until the user makes a new choice + +#### Scenario: Bounded hidden list +- **WHEN** hidden entries reach their limit, or a complete read shows an entry's task no longer matches +- **THEN** the oldest or stale entries are removed, which can only make an item visible again + +### Requirement: Saved view state never changes reported data or other contexts + +Saving or reading these states MUST NOT change progress, start a progress read or affect another device. Hidden-item records SHALL be bound to their store, source, plan and task. Other open frames SHALL converge on their next existing refresh, with no cross-frame channel. + +#### Scenario: Another store +- **WHEN** the device connects to a different store that has a task with the same plan and task identifiers +- **THEN** that task is not hidden + +#### Scenario: Second frame +- **WHEN** an item is hidden on the rail while the board is open +- **THEN** the board reflects it after its next existing refresh, without an extra poll or message + +#### Scenario: People sharing a profile +- **WHEN** two people use the same browser profile and installation +- **THEN** they share these states, and the documentation says so rather than promising per-person isolation diff --git a/openspec/specs/incomplete-count-indicator/spec.md b/openspec/specs/incomplete-count-indicator/spec.md new file mode 100644 index 0000000..29cea40 --- /dev/null +++ b/openspec/specs/incomplete-count-indicator/spec.md @@ -0,0 +1,98 @@ +# incomplete-count-indicator Specification + +## Purpose +Show every count that may be low through one calm indicator, never presenting a possibly low count as exact, while keeping the reasons and limits available to support. + +## Requirements + +### Requirement: One calm indicator for possibly incomplete counts + +When any count on the rail or board may be low, the surface SHALL show exactly one neutral indicator, last in its content, with one sentence. It SHALL replace the Partial cue and every coverage, truncation, traversal, history-partial, not-checked and not-loaded notice. It MUST NOT use warning colour and MUST NOT state limit numbers. + +#### Scenario: Several reasons at once +- **WHEN** older history is partly loaded, the host lists more sub-agents than are checked and some plans are unchecked +- **THEN** one indicator appears with one sentence, not one notice per reason + +#### Scenario: Nothing incomplete +- **WHEN** every count on the surface is complete +- **THEN** no indicator is shown + +#### Scenario: Expanded +- **WHEN** the user expands the indicator +- **THEN** one further sentence appears, with Load more when more can be loaded +- **AND** Load more requests one further bounded read and reports a failure in one line with a retry + +#### Scenario: Screen reader +- **WHEN** the indicator appears or its expanded state changes +- **THEN** it is exposed as a named, expandable control, and its appearance is announced politely at most once per refresh + +### Requirement: Possibly low counts are never shown as exact + +A positive count that an active reason can raise SHALL carry a plus mark directly after the number, in all three languages, dismissed or not. A plus mark MUST NOT appear on zero or on a count that no active reason can raise, and a zero count SHALL have no badge. A count MUST NOT be shown as an exact positive number, nor a zero as a verified empty result, unless its own coverage is complete. When it cannot be shown that a reason leaves a count unaffected, that count SHALL stay marked. + +#### Scenario: Partial Needs you count +- **WHEN** five items are known and some plans of the scope are unchecked +- **THEN** the line reads five-plus, and the longest wait reads as a lower bound + +#### Scenario: Incomplete zero +- **WHEN** no item is known yet and some plans of the scope are unchecked +- **THEN** no number and no plus mark are shown, the surface does not say that nothing needs the user, and the incomplete-count indicator is available + +#### Scenario: Plan rows on the board +- **WHEN** the Needs you read is incomplete and the board lists plans with two, one and no known items +- **THEN** only the first two rows show a count and the third shows no badge +- **AND** a row whose plan's items were fully read shows its number without a plus mark, while a row whose plan may have more shows the plus + +#### Scenario: Partial sub-agent count +- **WHEN** recorded history is only partly reconciled, while the host's current session list is complete and every recorded child is loaded +- **THEN** the finished, failed, interrupted and unknown counts that are positive carry the plus mark +- **AND** the running and waiting counts do not, because every currently active child is either recorded or listed by the host + +#### Scenario: Sub-agent counts with incomplete current activity +- **WHEN** the host's session list is cut short or unavailable while recorded history is complete +- **THEN** the running and waiting counts that are positive carry the plus mark and the completed counts do not + +#### Scenario: Work Status +- **WHEN** the selected session's Needs you count is zero and the read is incomplete +- **THEN** Work Status shows no Needs you part, not a zero with a plus mark + +#### Scenario: Dismissed indicator +- **WHEN** the user has dismissed the indicator +- **THEN** affected counts keep their plus mark + +### Requirement: Dismissal is remembered until the reasons change + +The indicator SHALL be dismissible. Dismissal SHALL be remembered on the device until the set of reasons changes, then the indicator SHALL show again. A recording gap that needs attention SHALL be a reason of its own for each detection. + +#### Scenario: Same reasons after reload +- **WHEN** the indicator was dismissed and the same reasons hold after a reload +- **THEN** it stays dismissed + +#### Scenario: New reason +- **WHEN** a reason starts that was not active at dismissal, including a newer recording gap +- **THEN** the indicator shows again + +#### Scenario: Recording gap while dismissing +- **WHEN** the indicator is dismissed while a recording gap needing attention is among its reasons +- **THEN** its expanded text names the gap, and dismissal also sends the existing store-wide acknowledgement +- **AND** a refused or failed acknowledgement leaves the indicator shown and says so + +### Requirement: States that change what the user can do keep their own line + +A failed or stale read, recording being off, and a plan from another OpenCode install MUST NOT be folded into the indicator. A failed read SHALL always be shown, SHALL NOT be dismissible and SHALL offer a retry. + +#### Scenario: Failed read +- **WHEN** the latest read failed +- **THEN** a separate line states the time of the last successful update and offers a retry, whatever the indicator's state + +#### Scenario: Recording off +- **WHEN** recording is off +- **THEN** a separate line says new progress is not saved and links to Setup + +### Requirement: Limits and reasons stay available for support + +The numeric limits and the kinds of active reasons SHALL NOT appear in default visible text. They SHALL be listed in Advanced details and in the support summary's appended lines. + +#### Scenario: Support request +- **WHEN** a user with possibly incomplete counts copies the support summary +- **THEN** it names each active reason by a fixed word and states this build's limits diff --git a/openspec/specs/interface-localization/spec.md b/openspec/specs/interface-localization/spec.md index 19c6186..e180acf 100644 --- a/openspec/specs/interface-localization/spec.md +++ b/openspec/specs/interface-localization/spec.md @@ -29,20 +29,24 @@ The extension SHALL offer automatic, English, Russian and Simplified Chinese mod ### Requirement: Accessible switch outside plan content -The side panel and full-screen page SHALL show a compact Language / "Язык" / "语言" control in the lower utility area next to Setup and Details when those sections are present. The control SHALL remain available without a plan, before setup is complete and during loading errors. Work Status SHALL apply the shared choice without its own switch. The names English, "Русский" and "简体中文" SHALL be displayed in their own languages, without flags. +The side panel and full-screen page SHALL offer the language choice as a Language / "Язык" / "语言" entry of the More menu, opening a single-choice list of automatic, English, "Русский" and "简体中文". The entry SHALL remain available without a plan, before setup is complete and during loading errors. Work Status SHALL apply the shared choice without its own switch. Language names SHALL be displayed in their own languages, without flags. #### Scenario: Extension not yet set up - **WHEN** the user opens the side panel or page before setup is complete -- **THEN** the language control is present outside the setup form and does not require a successful progress read +- **THEN** the More menu and its Language entry are present outside the setup form and do not require a successful progress read #### Scenario: Empty or unavailable content - **WHEN** no session is selected, no plans exist or reading progress has failed -- **THEN** the language control remains in the panel and page utility area +- **THEN** the Language entry remains in the panel's and page's More menu #### Scenario: Compact view - **WHEN** Work Status is displayed - **THEN** its interface uses the shared selected language but contains no separate language switch +#### Scenario: Choosing in the menu +- **WHEN** the user picks a language from the list with the keyboard +- **THEN** the chosen entry shows as selected and keeps focus, and the list is not closed by an external language update + ### Requirement: Save the choice in the device profile The extension SHALL save one shared language choice in device-scoped storage for the profile, runtime and extension installation. The choice SHALL survive closing a view and reloading. It SHALL be independent of the plan, session, project, progress source and integration account. The extension MUST NOT save the language in shared server storage or promise isolation between people using the same profile. @@ -57,12 +61,12 @@ The extension SHALL save one shared language choice in device-scoped storage for ### Requirement: Behavior without device storage support -If the host does not support device storage, the extension SHALL follow the OpenChamber language and explain that saving and manual selection are unavailable. The language control SHALL remain visible with an accessible explanation. The extension MUST NOT create a temporary manual choice for an individual view, send unsupported device storage requests or fall back to shared server storage. +If the host does not support device storage, the extension SHALL follow the OpenChamber language and explain that saving and manual selection are unavailable. The Language entry SHALL remain in the More menu with its choices disabled and one accessible line of explanation. The extension MUST NOT create a temporary manual choice for an individual view, send unsupported device storage requests or fall back to shared server storage. #### Scenario: Host does not advertise support - **WHEN** the host does not report device storage support - **THEN** all three views use automatic mode -- **AND** the panel and page explain why manual selection is unavailable without making device storage requests or writing a server setting +- **AND** the panel's and page's Language list shows its choices disabled with one line saying the interface follows the OpenChamber language, without making device storage requests or writing a server setting ### Requirement: Save failures do not look like a successful choice @@ -239,3 +243,28 @@ A language change SHALL preserve the selected plan, tab, filters, search text, t - **WHEN** the user selects a language with the keyboard or the language changes from another view - **THEN** a local choice keeps focus on the switch and an external update does not move focus from the current element - **AND** accessible names and the document language match the displayed translation, without translated controls causing horizontal overflow in a narrow panel + +### Requirement: Plain-language visible copy in three languages + +Default visible text and accessible names SHALL use plain words and one sentence per notice, in English, Russian and Simplified Chinese changed together. Internal terms for source, store, revision, coverage, binding, capture, reported, contribution, companion and observation MUST NOT appear there; they MAY appear in Advanced details, the support summary and Setup's disclosure. Text an agent wrote SHALL be shown literally and never translated or reworded. + +#### Scenario: Internal terms +- **WHEN** the rail, board, Work Status and Setup are rendered in their default states in each language +- **THEN** no visible string or accessible name contains a listed internal term or its Russian or Chinese catalog equivalent +- **AND** state words read as in progress, blocked, waiting on earlier tasks and done + +#### Scenario: Same change, three languages +- **WHEN** a pull request adds or rewords an extension-owned string +- **THEN** the English, Russian and Simplified Chinese catalogs change together, keeping their established product terms + +#### Scenario: Counts and plurals +- **WHEN** a count of 1, 2, 5, 11 or 21 is shown, with or without a plus mark +- **THEN** the string is built whole with the language's plural rule, the plus mark follows the number without a space, and no fragment is concatenated around the number + +#### Scenario: Agent text +- **WHEN** a task title, reason or next action written by an agent is shown, including inside a copied reply +- **THEN** it appears unchanged, as text only, with only the surrounding extension-owned words translated + +#### Scenario: Narrow widths +- **WHEN** the longest strings of the new components render at 390 CSS pixels on the rail and 280 CSS pixels in Work Status in each language +- **THEN** they wrap without horizontal overflow and without truncating a control's name diff --git a/openspec/specs/large-library-responsiveness/spec.md b/openspec/specs/large-library-responsiveness/spec.md new file mode 100644 index 0000000..622027b --- /dev/null +++ b/openspec/specs/large-library-responsiveness/spec.md @@ -0,0 +1,168 @@ +# large-library-responsiveness Specification + +## Purpose +Keep the full page responsive and its plan list scrollable with a large plan library, without changing the facts shown, the read routes or the polling cadence. + +## Requirements + +### Requirement: The full page stays responsive with a large library + +With the reference library of 500 loaded plans, a background refresh on the full page SHALL stay within the release budget. A refresh that changes nothing shown MUST NOT rebuild the page, and the work of one refresh MUST NOT grow with the number of plan rows multiplied by the number of held Needs you items. The rail SHALL stay as responsive as before. + +#### Scenario: Idle page with nothing reported +- **WHEN** the full page shows the reference library with a 60-task map open and no report arrives for 16 seconds +- **THEN** main-thread tasks longer than 50 ms total at most 1,000 ms and none is longer than 250 ms + +#### Scenario: Selecting another plan +- **WHEN** the user selects another loaded plan whose detail is not cached +- **THEN** its complete detail and map are shown within 1,500 ms + +#### Scenario: Small library +- **WHEN** the full page shows a library of about ten plans with the same map +- **THEN** no main-thread task longer than 50 ms occurs while idle, as before the change + +#### Scenario: Rail +- **WHEN** the rail shows the same map over the reference library, idle or during a map gesture +- **THEN** no main-thread task longer than 50 ms occurs and the 99th-percentile frame gap is at most 50 ms + +#### Scenario: Budget missed +- **WHEN** a measured figure exceeds its budget after the change +- **THEN** the figure is reported with the baseline and the change is not released as meeting this requirement until the design is amended + +### Requirement: Map gestures are not stalled by refreshes + +On the full page, dragging, wheel panning and zooming the map SHALL stay smooth while background refreshes run. A refresh that does not change the selected plan's picture MUST NOT end the gesture, move the view or recompute the layout. + +#### Scenario: Dragging the map +- **WHEN** the user drags the map with 150 pointer moves across several refreshes on the reference library +- **THEN** the 99th-percentile frame gap is at most 150 ms and main-thread tasks longer than 50 ms total at most 1,000 ms + +#### Scenario: Wheel panning +- **WHEN** the user pans with 120 wheel events across several refreshes +- **THEN** the 99th-percentile frame gap is at most 150 ms + +#### Scenario: Keyboard zoom +- **WHEN** the user zooms with thirty key presses +- **THEN** no main-thread task is longer than 250 ms and the view ends at the zoom the keys asked for + +### Requirement: Scrolling the plan list survives refreshes + +The plan list's scroll container SHALL remain the same connected element across background refreshes, so a scrollbar drag, wheel or touch scroll in progress continues. Freshness MUST NOT be deferred without bound to protect a gesture, and a change of store, account, binding or board reading SHALL still replace the list at once. + +#### Scenario: Dragging the scrollbar across refreshes +- **WHEN** the user drags the plan list's scrollbar with a mouse for longer than two refresh cycles on a list taller than its frame +- **THEN** the list follows the pointer for the whole drag and reaches at least 90% of the distance the same drag reaches with refreshes paused + +#### Scenario: Release outside the frame +- **WHEN** the mouse button is released outside the frame +- **THEN** the drag ends and the next refresh paints normally + +#### Scenario: A plan changes during the drag +- **WHEN** a plan's reported progress changes while the scrollbar is being dragged +- **THEN** its row shows the new state without ending the drag + +#### Scenario: Authority changes during the drag +- **WHEN** the store, account, binding or board reading changes during the drag +- **THEN** the retired list is replaced at once and none of its rows stays actionable + +### Requirement: Faster painting shows the same facts + +Reused derived results SHALL give the same shown plans, order, grouping, selection, filter choices and per-plan Needs you counts as direct evaluation, and SHALL be recomputed whenever an input they depend on changes. They MUST NOT be keyed on the progress revision alone. Duplicate-identifier ambiguity, source trust and worktree placement rules MUST NOT be weakened. + +#### Scenario: Equal results +- **WHEN** the fixture library is painted with reused results and evaluated directly +- **THEN** the shown plans, their order and groups, the selection and each plan's Needs you count are identical + +#### Scenario: Live membership changes without a new report +- **WHEN** a session or worktree appears or disappears while no plan revision changes +- **THEN** the affected plans move to their new project or worktree group on the next paint + +#### Scenario: Other inputs change +- **WHEN** the binding or source trust, a filter, the current or archived view, the search run or the interface language changes +- **THEN** the next paint shows the plans, groups, choices and labels for the new value + +#### Scenario: An item is hidden on this device +- **WHEN** the user hides a Needs you item +- **THEN** that plan's row count drops on the next paint + +#### Scenario: Same identifier in two sources +- **WHEN** two sources hold plans or sessions with equal identifiers +- **THEN** each plan keeps its own source's placement and neither borrows the other's session title or project + +### Requirement: No new polling or larger reads + +The change MUST NOT add a timer, a polling loop, a route or a service capability, and MUST NOT raise the number or size of reads a refresh sends. + +#### Scenario: Idle traffic +- **WHEN** the full page idles on the reference library +- **THEN** each refresh sends no more than ten list pages, one health read, one inbox window and one runs page, as before the change + +#### Scenario: Hidden frame +- **WHEN** the frame is hidden +- **THEN** it sends nothing and paints nothing, as before the change + +### Requirement: Idle traffic is counted by when and in what order it was sent + +The release gate's idle-traffic comparison SHALL count only requests sent inside the timed window, taken from the request log in the order they were sent. List pages and inbox requests SHALL be kept with the refresh whose first list page precedes them. Run reads SHALL be counted per window and shown as not compared per refresh, because the log cannot show which refresh caused one. Health reads SHALL be judged by cadence only. These checks change no shipped behaviour. + +#### Scenario: Request logged after the window ends +- **WHEN** a first-page list request is logged after the timed window stopped and before the driver read its logs +- **THEN** it is not counted as a list start of that window and does not close the refresh that was still open + +#### Scenario: Run read sent after the next refresh started +- **WHEN** a run read is sent after the next refresh's first list page, as the automatic follow-up of a run reconciliation can be +- **THEN** it is counted in the window's run-read count, which the artifact records +- **AND** it adds nothing to either refresh's per-refresh figures and is not lost with the final open refresh + +#### Scenario: Run read before the window's first list start +- **WHEN** a run read is sent inside the window before the window's first list page, because the refreshes around it started before the window +- **THEN** it is counted in the window's run-read count and is not dropped + +#### Scenario: Health read before its list page +- **WHEN** a refresh reads health before its first list page +- **THEN** that health read is not added to the previous refresh's traffic + +#### Scenario: Inbox request across a window edge +- **WHEN** a standalone inbox request is sent before the window and answered inside it, and another is sent inside the window and answered after it +- **THEN** only the second is counted in the window's inbox split, by when it was sent +- **AND** per-refresh verdicts still rest on complete refreshes: a request of the refresh left open at the window's end changes no per-refresh verdict, like that refresh's list pages + +#### Scenario: Reply-ordered attribution is caught +- **WHEN** attribution is changed to follow the order replies arrived +- **THEN** a unit test fails + +### Requirement: The gate reports what it cannot compare + +An artifact SHALL record how it attributed traffic and SHALL keep the wall-clock split of both inbox request forms. The gate SHALL compare the inbox form carried by the list read on its own as well as in the combined figure. A budget the gate cannot compare SHALL be reported as unverified and MUST NOT be reported as passed. That includes a per-refresh budget whose baseline and candidate figures do not rest on the same denominator. + +#### Scenario: Older artifact that bucketed replies +- **WHEN** the baseline artifact was produced by a driver that attributed replies instead of requests +- **THEN** the gate names the difference and does not treat the two as equivalent complete samples + +#### Scenario: Window with one list start +- **WHEN** an idle window holds a single list start, so no refresh completed inside it +- **THEN** the artifact still carries the wall-clock split of both inbox forms, and the form carried by the list read is still compared per list start +- **AND** no per-refresh budget is compared between that artifact's wall-clock figure and another artifact's complete refreshes + +#### Scenario: Extra boundary request on the standalone form +- **WHEN** a baseline counts one more standalone inbox request than list starts, and a candidate adds one inbox window carried by the list read +- **THEN** the comparison of the form carried by the list read fails + +#### Scenario: No comparable baseline +- **WHEN** the baseline, or all but one candidate, lacks the inbox split +- **THEN** the combined inbox budget is reported as unverified, the gate reports neither a pass nor a failed budget for it, and it exits unsuccessfully naming that state +- **AND** the comparisons that can be made still run + +#### Scenario: Mixed denominators +- **WHEN** the baseline completed no refresh inside its window, so its list-page figure rests on wall-clock counts, and the candidates' figures rest on complete refreshes +- **THEN** the per-refresh budgets are reported as unverified and the gate exits unsuccessfully naming that state +- **AND** a candidate that reads eleven list pages per refresh is not passed against a wall-clock baseline figure of nineteen + +#### Scenario: Per-refresh run-read budget +- **WHEN** the gate compares a baseline and candidates in the current artifact format +- **THEN** it shows each window's run-read count beside its list starts as a row that is not compared, and that row alone does not change the exit status +- **AND** it does not judge those counts as a budget + +#### Scenario: Wrong denominator is caught +- **WHEN** the gate divides by health replies where it should divide by list starts +- **THEN** a unit test fails diff --git a/openspec/specs/native-extension-updates/spec.md b/openspec/specs/native-extension-updates/spec.md index 36d7c97..dae8e8d 100644 --- a/openspec/specs/native-extension-updates/spec.md +++ b/openspec/specs/native-extension-updates/spec.md @@ -71,13 +71,18 @@ Acceptance SHALL exercise actual OpenChamber web 2.7.1 Git installation, automat ### Requirement: Accurate source and update instructions -README and Setup SHALL describe only behavior supported by measured installer/update evidence: default-branch/main selection, explicit `#main` and `#dev`, fixed release tags, and manual folder/ZIP replacement. They SHALL explain that host offers are version-based rather than commit/byte-based, and SHALL NOT promise a README custom-scheme install button or untested platform behavior. +README and Setup SHALL describe only behavior supported by measured installer/update evidence: default-branch/main selection, explicit `#main`, fixed release tags, and manual folder/ZIP replacement. They SHALL state that the development branch is source only and not installable. They SHALL explain that host offers are version-based rather than commit/byte-based, and SHALL NOT promise a README custom-scheme install button or untested platform behavior. #### Scenario: Branch and tag selection -- **WHEN** disposable default, explicit-main, development-branch and tag installations are checked after their refs diverge +- **WHEN** disposable default, explicit-main and tag installations are checked after their refs diverge - **THEN** each follows its selected ref rather than another branch or the newest tag - **AND** a same-version byte/commit change is not described as sufficient for an automatic host Update offer +#### Scenario: Ref without built entries +- **WHEN** a disposable installation or update selects a ref that carries no built entries, as the development branch does +- **THEN** the installer refuses it and a previous installation keeps its files +- **AND** README and Setup do not offer `#dev` + #### Scenario: Folder or ZIP installation - **WHEN** a folder or ZIP install is listed and update checking runs - **THEN** it has no Git update offer diff --git a/openspec/specs/needs-you-inbox/spec.md b/openspec/specs/needs-you-inbox/spec.md index 877c547..098829b 100644 --- a/openspec/specs/needs-you-inbox/spec.md +++ b/openspec/specs/needs-you-inbox/spec.md @@ -7,42 +7,188 @@ Bring reported decision and review blockers across active plans into one bounded ### Requirement: Source-wide reported attention -The inbox SHALL enumerate each explicitly blocked task once across active visible plans of the verified source. Valid current decision/review categories SHALL count as Needs you. Remaining categories, missing/unknown annotations and unusable annotations SHALL appear separately as Also blocked with honest labels. Closed, archived, deleted, group and unverified-source records MUST NOT enter either group. +The inbox SHALL enumerate each explicitly blocked task once across active visible plans of the verified source. A task SHALL count as Needs you only when its valid current category is decision or review and it meets the main-session membership requirement. Every other eligible blocked task SHALL be counted apart as other blocked work, with honest labels. Closed, archived, deleted, group and unverified-source records MUST NOT enter either group. #### Scenario: Mixed plans and categories - **WHEN** several active plans report decision, review, external, dependency, other and unclassified blockers -- **THEN** only decision/review tasks contribute to the Needs you count and all other eligible blocked tasks appear in Also blocked +- **THEN** only decision/review tasks that meet main-session membership contribute to the Needs you count, and all other eligible blocked tasks are counted as other blocked work - **AND** equal task or plan identifiers in different sources do not collide or leak across the verified binding #### Scenario: No person-facing blockers -- **WHEN** a complete verified read contains no decision/review blockers -- **THEN** the inbox clearly states that no reported items need the user, even if Also blocked contains tasks +- **WHEN** a complete verified read contains no Needs you item +- **THEN** the board states that nothing needs the user and the rail shows no Needs you line, even if other blocked work exists - **AND** a failed, unsupported or incomplete read is not presented as a verified empty result ### Requirement: Honest bounded inbox reads -Inbox reads SHALL be read-only, bounded and continuable through every eligible task. Coverage and counts SHALL distinguish complete data from partial, gapped, stale or unavailable data. Refresh SHALL reuse existing scheduling without extra polling loops, per-task polling, notifications or inference. +Inbox reads SHALL be read-only, bounded and continuable through every eligible task. On every surface and scope, including each board plan row, a positive Needs you count SHALL be exact only with complete coverage of what it counts and otherwise carry a plus mark. A zero count MUST NOT carry a plus mark or a badge; while coverage is incomplete it SHALL show no number and MUST NOT be presented as a verified empty result. #### Scenario: Eligible task beyond the first read window -- **WHEN** bounded traversal has not reached an eligible task yet -- **THEN** the UI discloses incomplete coverage and permits continuation to that task -- **AND** it does not claim a complete zero, lose the task at a page boundary or display it twice +- **WHEN** bounded traversal has found some items and has not reached an eligible task yet +- **THEN** the count carries a plus mark, the incomplete-count indicator is available and continuation reaches that task automatically or through Load more +- **AND** the UI does not claim a complete zero, lose the task at a window boundary or display it twice + +#### Scenario: Nothing found yet +- **WHEN** bounded traversal has found no item and has not covered every eligible plan +- **THEN** the Needs you line shows no number and no plus mark, and does not state that nothing needs the user +- **AND** the incomplete-count indicator is available and continuation proceeds as for a positive count + +#### Scenario: Plan rows +- **WHEN** the board lists plans while the traversal is incomplete +- **THEN** a row shows a Needs you count only when its plan has at least one known item +- **AND** the count carries a plus mark only when that plan's own items may not be fully read #### Scenario: Source or revision changes - **WHEN** identity changes or a pinned record changes during continuation -- **THEN** stale requests/results are retired or the continuation visibly restarts -- **AND** no cross-revision detail is silently assembled +- **THEN** stale requests/results are retired or the traversal restarts +- **AND** no cross-revision detail is silently assembled and the count is not exact until a traversal completes again + +#### Scenario: Automatic continuation stays bounded +- **WHEN** the inbox is incomplete in a visible frame across several successful refreshes +- **THEN** each refresh sends at most one inbox request, and automatic continuation stops at its fixed per-traversal window limit +- **AND** further windows load only on an explicit Load more, one window per activation + +#### Scenario: Hidden frame +- **WHEN** a frame is hidden while its inbox is incomplete +- **THEN** it requests no continuation and discards any reply still in flight ### Requirement: Reported details and safe navigation -Each row SHALL identify plan/task, reported reason, next action and history-derived waiting time when available. Unknown values SHALL remain unknown. Selecting a row SHALL open and reveal the current task in a clearly labelled reading without changing status, authority, host session or draft. Work Status SHALL expose a discoverable count entry into the compact panel inbox. +Each item SHALL be one line naming the task, its kind and its history-derived waiting time, with the plan named in the all-plans scope. Opening an item SHALL show its reported reason and next action literally and in place, without changing status, authority, host session or draft. Unknown values SHALL remain unknown. Work Status SHALL show the selected session's Needs you count and open the panel from it. #### Scenario: Read a waiting task -- **WHEN** the user selects an inbox row -- **THEN** its source-qualified plan/task is revalidated and brought into view, or removal/unavailability is explained +- **WHEN** the user opens an inbox item +- **THEN** its kind, waiting time and the agent's own reason and next action appear inside the list, with one item open at a time - **AND** exact, lower-bound and unavailable waiting time retain their existing reported-history meanings +- **AND** when the plan shown is that item's plan, its task is selected on the map or revealed in the list without a separate pinned reading + +#### Scenario: An opened item changes or leaves +- **WHEN** a later read no longer contains the opened item, or its details changed +- **THEN** the opened item closes or shows the current details, and the removal is not presented as the user's action #### Scenario: Accessible phone-width inbox -- **WHEN** the inbox is used with keyboard, touch, English/Russian, light/dark or a phone-width layout -- **THEN** group labels, empty/error states and actions remain readable and operable with visible focus -- **AND** no control mutates a task from the inbox +- **WHEN** the inbox is used with keyboard, touch, English, Russian or Simplified Chinese, light/dark or a phone-width layout +- **THEN** the line, items, empty and error states and actions remain readable and operable with visible focus +- **AND** Escape closes an opened item and returns focus to its line, and no control mutates a task from the inbox + +### Requirement: Only a plan's main session supplies Needs you items + +A blocked task SHALL be a Needs you item only when the session that reported its current blocker details is the plan's main session and that session is recorded as top-level, with no parent session. A task failing this, or whose main session's parent status is unknown, MUST NOT be shown or counted as needing the user on any surface. It SHALL remain a blocked task with its reported details on its task in the list and the map. + +#### Scenario: Sub-agent reports a decision on its assigned task +- **WHEN** a sub-agent reports its assigned task blocked with a decision or review category, directly or together with its final handoff +- **THEN** the task is not listed or counted as Needs you +- **AND** it stays blocked on its task row and map card with its reason and next action, and is counted as other blocked work + +#### Scenario: Sub-agent owns the plan +- **WHEN** a session that has a parent session started the plan and reports a decision blocker addressed to its parent +- **THEN** no task of that plan is a Needs you item while that session remains its main session + +#### Scenario: Main session reports for a sub-agent +- **WHEN** a top-level main session reports a decision or review blocker on a sub-agent's task, including as a relay attributed to that sub-agent +- **THEN** the task is a Needs you item + +#### Scenario: Details change hands +- **WHEN** a sub-agent replaces blocker details that the main session wrote +- **THEN** the task leaves Needs you on the next accepted read and stays blocked +- **AND** it returns only when the main session reports its details again + +#### Scenario: Blockers stored before the upgrade +- **WHEN** a store already holds decision or review blockers that sub-agents reported +- **THEN** they are classified by this rule on the first read, without rewriting, migrating or deleting any stored record +- **AND** they remain visible as blocked tasks with their details + +#### Scenario: Service cannot supply the main-session fact +- **WHEN** inbox rows arrive without the main session's top-level fact +- **THEN** Needs you is reported unavailable rather than classified without it or shown as empty + +#### Scenario: Waiting sub-agent sessions +- **WHEN** the host shows a sub-agent session waiting on a question or permission +- **THEN** that session is counted only on the sub-agents line and adds nothing to the Needs you count + +### Requirement: Default scope is the current session or selected plan + +On the rail and Work Status the inbox SHALL default to the plans of the current session, including plans that session helps with. On the board it SHALL default to the selected plan. All plans SHALL be an explicit secondary scope. The list MUST NOT switch scope by itself. + +#### Scenario: This session has nothing but other plans do +- **WHEN** the default scope has no Needs you item and other plans in the verified source do +- **THEN** the surface shows nothing waiting in this scope and a quiet link naming how many items wait in other plans +- **AND** the list changes to all plans only when the user chooses it + +#### Scenario: All plans +- **WHEN** the user selects the all-plans scope +- **THEN** every Needs you item of the verified source is listed with its plan name, with the same counts and plus-mark rules + +#### Scenario: Session plan list is incomplete +- **WHEN** the session's own plan list was not fully loaded +- **THEN** the session-scoped count carries a plus mark rather than reading as exact + +### Requirement: Compact Needs you presentation + +The inbox SHALL be the same component on rail and board, placed below the map or list. Collapsed, it SHALL be one line with the count and the longest wait. Expanded, it SHALL show one line per item. Other blocked work SHALL appear only as a quiet count, never as a default list. The rail SHALL start collapsed and the board expanded unless a saved device state says otherwise. + +#### Scenario: Collapsed line +- **WHEN** two items in scope need the user and the longest has waited 17 hours +- **THEN** one line states that two need the user and that the oldest has waited 17 hours, as a button exposing its expanded state + +#### Scenario: Nothing in scope on the rail +- **WHEN** a complete read finds nothing needing the user in the rail's scope and no item in other plans +- **THEN** the rail shows no Needs you line at all + +#### Scenario: Other blocked work +- **WHEN** four further tasks in scope are blocked without being Needs you items +- **THEN** the expanded list shows one quiet count for them, and selecting it points to those tasks in the plan shown + +#### Scenario: Read failed +- **WHEN** the inbox cannot be read +- **THEN** one plain line says it could not be checked and offers a retry, never an empty state + +### Requirement: Open session and Copy reply never resolve an item + +An opened item SHALL offer Open session, which asks the host to open the plan's main session, and Copy reply, which copies a short reply frame naming the task and plan. Neither action SHALL send a message, change a task, mark an item resolved or remove it. An item SHALL leave only when a later report changes it. + +#### Scenario: Open session +- **WHEN** the user chooses Open session for an item whose main session the host lists for the verified source +- **THEN** the host is asked to open that session and nothing is sent, drafted or reported + +#### Scenario: Session cannot be opened +- **WHEN** the main session is not listed by the host or the open gate does not hold +- **THEN** Open session is not offered, one plain line says why, and Copy reply remains + +#### Scenario: Copy reply +- **WHEN** the user chooses Copy reply +- **THEN** the clipboard receives the reply frame with the agent's task and plan titles unchanged, and the control confirms only after the clipboard accepts +- **AND** on a clipboard failure the same text is shown for manual selection + +#### Scenario: After acting +- **WHEN** the user has opened the session or copied a reply and no new report has arrived +- **THEN** the item is still listed and counted + +### Requirement: Hide an item on this device until its reported state changes + +An opened item SHALL offer Hide where device storage is supported. A hidden item SHALL be excluded from the list and count on that device until its reported blocker details change, then return by itself. Hiding MUST NOT change any reported data or other devices. The number hidden SHALL stay visible with a way to show and unhide them. + +#### Scenario: Hide and undo +- **WHEN** the user hides an item +- **THEN** the count drops at once, a line says it is hidden until the task changes and offers Undo, and the change is announced once + +#### Scenario: Reported state changes +- **WHEN** the main session reports new details for a hidden task +- **THEN** the task is listed and counted again without user action +- **AND** an unrelated report on the same plan does not unhide it + +#### Scenario: Hidden items stay reachable +- **WHEN** one or more items are hidden +- **THEN** the expanded list and the More menu state how many are hidden and let the user show and unhide them + +#### Scenario: Device storage unsupported +- **WHEN** the host does not advertise device storage +- **THEN** Hide is not offered and no item is hidden + +### Requirement: Automatic inbox continuation adds no polling + +Continuation MAY run automatically within the existing per-window bounds, at most one window per existing refresh cycle and a fixed number per traversal. Refresh SHALL add no polling loop, per-task polling, notification or inference. + +#### Scenario: Refresh of an incomplete inbox +- **WHEN** a refresh runs while the inbox is incomplete +- **THEN** it starts no polling loop, per-task polling, notification or inference beyond the bounded continuation diff --git a/openspec/specs/phone-progress-surfaces/spec.md b/openspec/specs/phone-progress-surfaces/spec.md index ce3540c..08791ec 100644 --- a/openspec/specs/phone-progress-surfaces/spec.md +++ b/openspec/specs/phone-progress-surfaces/spec.md @@ -45,3 +45,28 @@ Phone reads SHALL retain the existing source/account/runtime/session retirement - **WHEN** the host replays the same session item after Show current session - **THEN** the existing frame-local reset contract remains in force - **AND** the actual phone limitation and tested versions are documented without a visibility-based workaround + +### Requirement: Simple-by-default surfaces at phone width + +At about 390 CSS pixels with a coarse pointer, the rail and board SHALL keep the same order in one column: header, progress, Map or List, Needs you, the sub-agents line and the incomplete-count indicator. The Map | List switch and the map tools SHALL stay on one row. Every new control SHALL be at least 44 CSS pixels and usable without hover or long press. + +#### Scenario: Map on a phone +- **WHEN** a plan with prerequisites opens on a phone-width rail +- **THEN** the map is the first content under the progress bar, in a frame no taller than 300 CSS pixels, with zoom, Fit and help-and-filters reachable by tap +- **AND** the page scrolls normally from everything around the map + +#### Scenario: Needs you and its actions +- **WHEN** the user expands Needs you and opens an item at phone width in English, Russian or Simplified Chinese +- **THEN** the line, items, scope switch and Open session, Copy reply and Hide are operable by tap with visible focus and no horizontal overflow + +#### Scenario: More, Tidy and the indicator +- **WHEN** the user opens More, confirms a bulk archive, uses Undo, or expands and dismisses the indicator at phone width +- **THEN** every step is reachable by tap and keyboard, panels offer a visible Back, and essential actions stay above the keyboard and safe-area insets + +#### Scenario: Narrow board +- **WHEN** the board is narrower than 820 CSS pixels +- **THEN** the plan list becomes the header's plan picker and the rest follows the rail order + +#### Scenario: Emulation is not device acceptance +- **WHEN** these layouts are verified in an emulated narrow touch browser +- **THEN** the evidence is recorded as emulation, not physical-phone acceptance diff --git a/openspec/specs/plan-mirroring-guidance/spec.md b/openspec/specs/plan-mirroring-guidance/spec.md new file mode 100644 index 0000000..ac8baff --- /dev/null +++ b/openspec/specs/plan-mirroring-guidance/spec.md @@ -0,0 +1,225 @@ +# plan-mirroring-guidance Specification + +## Purpose +Tell agents when to mirror their plan into Agent Progress and how to report it, through guidance that survives truncation and providers that drop plugin system text, and keep any hint advisory and honest. + +## Requirements + +### Requirement: Guidance leads with a short checklist of when to report + +Every guidance surface the companion provides SHALL open with the same short positive checklist: start the mirror when a plan is ready for execution, with its real tasks and prerequisites; declare or link a sub-agent's tasks before dispatching it; mark a task as working when work on it starts; finish, cancel or fail the plan explicitly. Prohibitions and operation detail SHALL follow the checklist. + +#### Scenario: Description opening +- **WHEN** an agent is shown the report tool +- **THEN** the description opens with the four checklist steps, each naming the operation it uses +- **AND** no prohibition precedes them + +#### Scenario: Other surfaces +- **WHEN** the companion adds its section to a session context, or an agent loads the skill +- **THEN** that text opens with the same checklist + +#### Scenario: Skill listing +- **WHEN** a host lists skills by name and one-line description only +- **THEN** the line says when to load the skill: on writing, receiving or coordinating a plan, and before dispatching sub-agents + +### Requirement: The tool description survives truncation + +The report tool's description and the context section SHALL each be shorter than in the previous release. The checklist and one valid start example SHALL fit inside the smallest description limit recorded for a supported client. Detail removed from the description SHALL remain available in the skill, which the description SHALL name. + +#### Scenario: A client cuts long descriptions +- **WHEN** a client truncates the description at the smallest limit recorded for a supported client +- **THEN** the whole checklist and one valid start example with a prerequisite remain inside the kept part + +#### Scenario: Detail stays reachable +- **WHEN** an agent needs delegation, staging or handoff rules that left the description +- **THEN** the skill states them and the description says where to find them + +### Requirement: Guidance reaches the agent without custom instructions + +With the companion installed and recording on, an agent whose session exposes the report tool SHALL receive the checklist and conditional hints from the companion alone. No project instruction file, user-authored skill, agent prompt or orchestrator prompt SHALL be needed. A session whose report tool is hidden or restricted SHALL receive neither. + +#### Scenario: No instructions mention Agent Progress +- **WHEN** the session's instruction files, skills and agent prompt never mention Agent Progress +- **THEN** the checklist and the hints are still delivered + +#### Scenario: Report tool hidden or recording off +- **WHEN** the session's effective tools exclude the report tool, the source is unverified or recording is off +- **THEN** no section and no note is added and tool results are unchanged + +### Requirement: Delivery does not depend on forwarded system text + +Delivery MUST NOT depend on the model provider forwarding text that a plugin adds to the system prompt. The checklist SHALL travel in the tool description, and a conditional hint SHALL also travel as a short fixed note appended to the result of an observed call. The existing context section SHALL still be added for providers that forward it. + +#### Scenario: Provider forwards only tool definitions and tool results +- **WHEN** a coordinator's provider rebuilds the system prompt and shows tools under a host-prefixed name +- **AND** the coordinator completes a sub-agent dispatch while recording is on +- **THEN** the checklist is in the report tool's description as the model sees it +- **AND** the dispatch result ends with a note asking it to start a mirror if its planned work has none, and to declare or link tasks before the next dispatch +- **AND** the note names the report tool so that it is recognisable under a host prefix + +#### Scenario: Plan write +- **WHEN** that coordinator writes or edits a recognised plan document +- **THEN** the result of that call ends with the plan note + +#### Scenario: A delegated planner wrote the plan +- **WHEN** a sub-agent writes a recognised plan document and its verified direct parent next completes a dispatch, plan write or tracker update +- **THEN** that result carries the plan note for the parent once +- **AND** for a dispatch the parent was waiting on, this is the result that returns the planner + +#### Scenario: Provider forwards system text +- **WHEN** the provider forwards plugin system text +- **THEN** the context section and its hint are delivered as before +- **AND** each of the two carriers delivers one observation at most once + +### Requirement: Plan documents are recognised where planning workflows write them + +A successful single-file write or edit SHALL raise the plan hint when its path is a Markdown file that is named `plan`, lies under a `plans` or `.plans` folder, or is the `tasks.md` or `proposal.md` of one spec change directly under `openspec/changes/`. Files written by a shell command or an unrecognised tool SHALL NOT be observed. + +#### Scenario: Spec-change task list +- **WHEN** a session writes `openspec/changes/example/tasks.md` in its own directory +- **THEN** the plan hint is raised for it and, when verified, for its direct parent + +#### Scenario: Archived or auxiliary spec files +- **WHEN** a session edits a file under `openspec/changes/archive/`, a spec delta or a design note +- **THEN** no plan hint is raised + +#### Scenario: Shell-written plan +- **WHEN** a plan file is created by a shell command +- **THEN** nothing is observed, and the checklist and the dispatch note remain the only prompts + +### Requirement: Plan paths in other worktrees of the same project are accepted + +A plan-shaped path SHALL be accepted inside the writing session's directory, or inside another directory that the host lists as the root or a worktree of that session's own project. Recognition SHALL use the path and host-reported project facts only; the companion MUST NOT read the file, its folder or repository metadata to decide. + +#### Scenario: Plan in a sibling worktree +- **WHEN** a session writes a plan file under a `plans` folder, by absolute path, into a directory the host lists as another worktree of the session's project +- **THEN** the plan hint is raised + +#### Scenario: Path outside the project +- **WHEN** the path resolves outside the session directory and outside every host-listed worktree of its project, or the host cannot list them +- **THEN** no hint is raised + +#### Scenario: Parent in another worktree +- **WHEN** the writer's verified direct parent belongs to the same project and works in another host-listed worktree of it +- **THEN** that parent is flagged once, and no other ancestor or sibling is + +### Requirement: Hints stay advisory and honest + +A checklist, section or note MUST NOT send a report, start a plan, assign or link a task, or state or imply that work started, was reviewed, was approved or finished. Observation and delivery SHALL perform no plan lookup, no document read and no store write. Only a deliberate report changes recorded progress. + +#### Scenario: Hint without a report +- **WHEN** sections and notes are delivered and the agent sends no report +- **THEN** the store holds no new plan, revision, receipt or contribution + +#### Scenario: A user adds their own reminder +- **WHEN** a user's own instructions also tell the agent to mirror plans +- **THEN** nothing conflicts: an identical repeated start returns the original receipt, a different start for a plan that already exists is refused with the current revision, and the checklist tells the agent to read first and not to repeat state that is already current + +### Requirement: Result notes leave the original call intact + +A note SHALL be fixed text chosen by the kind of observation, with no path, title, prompt, worker output or identifier. It SHALL be added only to a completed call that qualified under the existing metadata rules, after that call's original output, and MUST leave the output and structured result intact. A failed, cancelled or partial call MUST NOT be changed. + +#### Scenario: Original result preserved +- **WHEN** a note is added to a dispatch result +- **THEN** the returned child session, status and output are unchanged for the model and for run recording +- **AND** the note follows them + +#### Scenario: Failed or unrecognised call +- **WHEN** a call fails, is cancelled, is partial or does not match the recognised metadata +- **THEN** its result is not changed + +#### Scenario: Several qualifying calls in one step +- **WHEN** several qualifying calls of one session complete in the same model step +- **THEN** at most one note is added for that step + +### Requirement: Guidance explains a report refused after the person archived or deleted the plan + +The skill SHALL state in one sentence that a write refused as `closed` on a plan that was in progress, or as `not-found` on a plan the agent started, means the person archived or deleted that plan, and that the agent stops reporting to it, does not retry and does not recreate it under another identifier unless the person specifically asks for it. The guidance SHALL stay advisory and MUST NOT change any tool input, validation, reply or size limit. + +#### Scenario: Archived while in progress +- **WHEN** an agent holding only the companion's text receives `closed` for a change to a plan it was reporting, and then `closed` again for a reopen +- **THEN** the guidance leads it to stop reporting to that plan and continue its work, without retrying and without starting a replacement plan + +#### Scenario: Deleted +- **WHEN** an agent receives `not-found` for a plan it started earlier +- **THEN** the guidance leads it not to start the same plan again under a new identifier + +#### Scenario: The person asks for tracking again +- **WHEN** the person specifically asks the agent to track that work again after deleting or archiving its plan +- **THEN** the guidance allows the agent to start a new plan under a new identifier + +#### Scenario: Ordinary closed plan +- **WHEN** an agent's own plan is finished and it has real further work +- **THEN** the existing reopen guidance still applies and is not replaced by this sentence + +#### Scenario: Description limits +- **WHEN** the companion's texts are built +- **THEN** the tool description stays within its existing total limit, with the checklist and start example inside its first part + +### Requirement: Guidance clears a dependency block against the plan's current prerequisites + +The skill, the tool description and the inline guidance SHALL tell an agent that blocked a task because work moved back to its prerequisites to read the current plan before a handoff, and to unblock that task once every prerequisite it still has is done. A prerequisite the plan no longer lists MUST NOT keep it blocked; a skipped prerequisite that is still listed SHALL count as unfinished. The guidance SHALL stay advisory and MUST NOT change any tool input, validation, reply or size limit. + +#### Scenario: A revision removes one of two prerequisites +- **WHEN** an agent holding only the companion's text blocked a task on prerequisites A and B, an approved plan revision removes B as a prerequisite, and A finishes +- **THEN** the guidance leads it to set the task back to working or pending without waiting for B + +#### Scenario: A listed prerequisite was skipped +- **WHEN** a prerequisite the task still lists is skipped instead of done +- **THEN** the guidance does not lead the agent to clear the block for that reason + +#### Scenario: Before a handoff +- **WHEN** the agent is about to hand off with a task it blocked this way +- **THEN** the guidance leads it to read the current plan first and to clear the block if no listed prerequisite is unfinished + +#### Scenario: Another kind of blocker +- **WHEN** a task is blocked with a decision, review, external or other blocker +- **THEN** the guidance leaves that task and its blocker as they are + +#### Scenario: Description limits +- **WHEN** the companion's texts are built +- **THEN** the tool description stays within its existing total limit, with the checklist and start example inside its first part + +### Requirement: The companion's system prompt section stays identical across requests + +The companion's section of the system prompt SHALL contain only text that does not change within a session, and SHALL be byte-identical on every request where it is present. The one-request hint, the sub-agent resume capsule and the delegation refusal note SHALL be added after the content of the latest message, in a carrier valid for its role, with their text unchanged. A due note MUST NOT be dropped for lack of a carrier, and the stored conversation MUST NOT change. + +#### Scenario: A hint is due +- **WHEN** a dispatch or a plan-file write makes the one-request hint due and the next request is built +- **THEN** the system section is identical to the previous request's, and the hint is added after the latest message's content + +#### Scenario: Continuation after a plan-file write +- **WHEN** a plan-file write succeeds and the next request continues the tool call, so its latest message is a tool message +- **THEN** the system section is unchanged, and the hint is appended to the output of that message's last tool result, so the request stays valid for the provider + +#### Scenario: No valid carrier +- **WHEN** a note is due and the latest message has no valid carrier, such as an assistant message or the Code Mode `execute` wrapper's result +- **THEN** nothing is added on that request, and the note is added on the next request whose latest message has a valid carrier + +### Requirement: Delivered context notes stay in place on later requests + +Each note the companion delivered SHALL be added again, unchanged and in the same place, on every later request whose messages still hold its carrier while the companion remembers it. A capsule or refusal SHALL be delivered again only when its text differs from the last one delivered or that delivery's carrier is absent from the request. When a delivered refusal clears on a complete read, one fixed cleared line SHALL be delivered. Where the section is removed, every added note MUST be removed. + +#### Scenario: Later requests keep earlier notes +- **WHEN** a request carried a note and the next request is built from the same stored history with new messages after it +- **THEN** the next request repeats that message with the same note in the same place, so its messages begin with the previous request's messages byte for byte, and the stored conversation does not contain the note + +#### Scenario: A sub-agent's plan moved on +- **WHEN** a sub-agent session sends two requests and the plan's revision changed between them, or the capsule lookup timed out for the second +- **THEN** the system section is identical on both requests; after a revision change the second request carries the new capsule after its latest message, and after a timeout it adds nothing, while the earlier capsule stays where it was + +#### Scenario: A refusal appears and clears +- **WHEN** a delegation refusal note applies to one request and not to a later one +- **THEN** the system section is identical on both, the note stays where it was delivered, and after a successful, complete read with no refusal the fixed cleared line is added after the later request's latest message; a failed read adds nothing + +#### Scenario: Standing note after its carrier is gone +- **WHEN** a capsule or refusal note was delivered and a later request no longer holds that carrier, after compaction, a reverted message or an evicted carrier, and the text is unchanged +- **THEN** the current capsule or refusal is delivered again after that request's latest message + +#### Scenario: Reused tool call identifier +- **WHEN** a later turn's tool result reuses the call identifier of a tool result that carried a note +- **THEN** the newer tool result does not receive the earlier note + +#### Scenario: Section removed +- **WHEN** any path removes the section, such as capture off, the report tool unavailable, the source unverified or a failure in the hook +- **THEN** the section is absent as before, every note the companion added is removed from the request, and no new note is added diff --git a/openspec/specs/plan-selection-actions/spec.md b/openspec/specs/plan-selection-actions/spec.md new file mode 100644 index 0000000..7a73fea --- /dev/null +++ b/openspec/specs/plan-selection-actions/spec.md @@ -0,0 +1,211 @@ +# plan-selection-actions Specification + +## Purpose +Let a person select several plans on the full page, or every plan matching the current search and filters, and archive, restore or delete them together, with in-progress plans acknowledged explicitly. + +## Requirements + +### Requirement: Several plans can be selected on the full page + +The full page SHALL offer a Select mode in which plan rows, and plan results while searching, can be selected and deselected one by one by pointer or keyboard. Each row SHALL expose its name and selected state to assistive technology, with no control nested inside another. Select mode MUST NOT exist on the rail or Work Status. + +#### Scenario: Select and deselect +- **WHEN** the user enters Select mode and toggles three plan rows +- **THEN** a bar states that three are selected and offers the actions and Clear +- **AND** leaving Select mode or choosing Clear empties the selection + +#### Scenario: Keyboard and screen reader +- **WHEN** a keyboard user moves through the rows in Select mode +- **THEN** Space toggles the focused row, its selected state is exposed, and a change in the selected count is announced once per action + +#### Scenario: Phone width +- **WHEN** the full page is narrower than 820 CSS pixels, where browsing shows no plan rows +- **THEN** Select shows the plan rows for selection in place of the plan, with a way back, without horizontal overflow and with targets of at least 44 CSS pixels on a coarse pointer + +#### Scenario: Rail and Work Status +- **WHEN** the rail or Work Status is shown +- **THEN** neither offers Select mode + +### Requirement: A selection belongs to one board reading + +The selection SHALL be frame-local and SHALL survive background refreshes. It SHALL be cleared when the account, store, binding, current or archived view, filters or search change. It MUST NOT be stored. + +#### Scenario: Refresh keeps the selection +- **WHEN** a background refresh arrives while plans are selected +- **THEN** the selection and the focused row are kept +- **AND** a selected plan that left the reading is no longer counted + +#### Scenario: Reading changes +- **WHEN** the user changes a filter, runs or clears a search, or switches between Current and Archived plans +- **THEN** the selection is cleared + +#### Scenario: Reload +- **WHEN** the frame is reloaded +- **THEN** nothing is selected + +### Requirement: Every matching plan can be selected at once + +Select mode SHALL offer Select all, which selects every plan matching the current search and filters, or every plan of the current view when none are set, including plans that are not loaded. The stated count MUST NOT be presented as exact while it may be low. + +#### Scenario: Everything, with nothing set +- **WHEN** Select all is chosen with no search or filter +- **THEN** every plan of the current view is selected, including plans inside closed Finished folds and plans not loaded + +#### Scenario: Matching a filter or search +- **WHEN** Select all is chosen while a filter or search is set +- **THEN** only the matching plans are selected + +#### Scenario: Count before the scan +- **WHEN** some matching plans are not loaded and the action panel has not counted them yet +- **THEN** the selected count carries a plus mark +- **AND** opening an action counts them through a bounded scan and states the number it will act on + +#### Scenario: Deselecting after Select all +- **WHEN** the user deselects one loaded row after Select all +- **THEN** that plan is left out of the action and the count drops by one + +### Requirement: Selection actions work on plans of any status + +With at least one plan selected, the full page SHALL offer Archive and Delete permanently in Current plans, and Restore and Delete permanently in Archived plans, for plans of any status. These actions SHALL follow Tidy's confirmation, run, progress, result and Undo rules. + +#### Scenario: Archive a mixed selection +- **WHEN** the user archives 14 selected plans of which three are in progress +- **THEN** after confirming, all 14 are archived and the result offers Undo, which restores the three as in progress + +#### Scenario: Delete a selection +- **WHEN** the user chooses Delete permanently for the selected plans +- **THEN** a second step states the count and that it cannot be undone, and only its own button starts deleting + +#### Scenario: Restore in Archived plans +- **WHEN** the user selects archived plans, including one that was in progress, and chooses Restore +- **THEN** each is restored with its lifecycle unchanged and the in-progress one accepts reports again + +#### Scenario: A selected plan changes before its request +- **WHEN** an agent reports to a selected plan between confirmation and its request +- **THEN** that plan is skipped as changed and reported as not done + +### Requirement: In-progress plans in a selection are acknowledged explicitly + +When a selection includes in-progress plans, the confirmation's one line SHALL state how many and what follows. Each Archive or Delete permanently request for an in-progress plan SHALL carry the in-progress acknowledgement, and no other request SHALL carry it. Restore requests, including Undo of an archive, SHALL never carry it, whatever the plan's lifecycle. Without the service capability, in-progress plans SHALL be left out and the line SHALL say how many. + +#### Scenario: Archive warning +- **WHEN** three of 14 selected plans are in progress and the user chooses Archive +- **THEN** the confirmation states that three are still in progress and stop updating until restored + +#### Scenario: Delete warning +- **WHEN** three of 14 selected plans are in progress and the user chooses Delete permanently +- **THEN** the deletion step states that three are still in progress and that it cannot be undone + +#### Scenario: Acknowledgement only where needed +- **WHEN** the run sends its requests +- **THEN** the three requests for in-progress plans carry the acknowledgement and the eleven for closed plans do not + +#### Scenario: Restore never acknowledges +- **WHEN** the user restores a selection, or uses Undo after archiving, and it includes plans that were in progress +- **THEN** no restore request carries the acknowledgement, and each is restored with its lifecycle unchanged + +#### Scenario: Service without in-progress cleanup +- **WHEN** the service does not advertise in-progress cleanup and the selection includes three in-progress plans +- **THEN** the confirmation says three in-progress plans are left out, no request is sent for them and the others proceed + +### Requirement: An archived in-progress plan can be restored or deleted on its own + +In Archived plans, the More menu SHALL offer Restore and Delete permanently for the shown plan whatever its lifecycle. A visible in-progress plan MUST NOT get a per-plan cleanup action; it is acted on through a selection only. + +#### Scenario: Restore from More +- **WHEN** an archived in-progress plan is shown in Archived plans +- **THEN** More offers Restore plan and Delete permanently, and Restore returns it to Current plans as in progress + +#### Scenario: Visible in-progress plan +- **WHEN** an unarchived in-progress plan is shown on the rail or board +- **THEN** More offers no Archive or Delete action for it + +### Requirement: A selection follows confirmed changes during a search + +While searching, a freshness reply SHALL certify only the result page it was asked about, identified by its number in the search and not by its position among the retained pages, and only when it covered every plan that page shows when the reply arrives. Hits the search reads into a page after it was checked SHALL leave it checked. A plan that a freshness reply shows missing, deleted or moved across the archive boundary SHALL leave the selection whichever page is shown. + +#### Scenario: Load more replaces the page a reply was asked about +- **WHEN** a freshness reply for result page 2 is held, Load more drops page 1 from the retained pages and shows page 3, and the reply then arrives +- **THEN** page 3 is not treated as checked by that reply +- **AND** page 3 is checked only by a reply that covered its own plans + +#### Scenario: Hits appended while a reply is held +- **WHEN** a freshness reply for an unchecked result page is held, the search appends further hits to that same page, and the reply then arrives with every covered plan unchanged +- **THEN** the page is not counted as checked by that reply +- **AND** it counts as checked once a reply has covered the plans it then shows + +#### Scenario: Hits read after a page was checked +- **WHEN** a freshness reply has certified a result page and the running search then reads further hits into that page +- **THEN** the page stays checked: those hits were read from the service at that moment, as the hits on the first page of a search are +- **AND** the next freshness read covers the plans the page then shows + +#### Scenario: Plan confirmed gone while another page is shown +- **WHEN** a selected plan has hits on two retained pages, a freshness reply for page 2 is held, the person goes back to page 1, and the reply shows that another frame archived the plan +- **THEN** the plan's hits leave both pages and the selected count drops by one +- **AND** page 1 stays unchecked until a reply covers it + +#### Scenario: Unchanged poll +- **WHEN** a freshness reply covered every plan shown on the page it was asked about and shows them unchanged +- **THEN** the selection and the focused row are kept and the page counts as checked + +### Requirement: A cleanup in this frame retires freshness reads in flight + +When a cleanup action in this frame invalidates the search, the freshness reads the frame already sent SHALL be retired: their replies MUST NOT certify a page or change the selection. A cleanup made elsewhere that this frame has not observed retires nothing; a freshness reply that shows its effect is evidence like any other. + +#### Scenario: Reply from before a cleanup +- **WHEN** a freshness reply is held on an unchecked result page under Select all, a matching plan is archived from this frame, and the reply arrives after the run reconciled +- **THEN** the reply changes nothing: the page is not marked checked and the archived plan is not selected again + +#### Scenario: Archive made in another frame +- **WHEN** a freshness read is in flight while another frame archives a selected plan, and its reply shows the plan archived +- **THEN** the plan leaves the selection and the retained pages, as for any plan a reply shows gone + +### Requirement: Deselection and departure are kept apart + +Under Select all, a plan the person deselected and a plan a cleanup receipt took out of view SHALL be tracked separately. Both SHALL last until the person clicks the plan's row, replaces the selection with Select all or ends it. A departure SHALL also end when an Undo receipt returns the plan, a verified read lists it, or a fresh count finds it in the view at a newer cleanup generation; none of these SHALL end a deselection. A cached, unchecked page MUST NOT end a departure. + +#### Scenario: Restored elsewhere, then counted again +- **WHEN** a plan is archived from this frame under Select all, the retained search drops it, another frame restores it, and the person opens the next action +- **THEN** the count includes that plan at its current revision and cleanup generation + +#### Scenario: Deselected plan stays out +- **WHEN** the person deselected a plan under Select all and a fresh count finds that plan in the view +- **THEN** the plan is left out of the action + +#### Scenario: Deselected and departed +- **WHEN** a plan was both deselected by the person and taken out by a receipt, and an Undo receipt, a verified read or a fresh count returns it to the view +- **THEN** its departure ends and it stays out of the action as a deselected plan, until the person clicks its row or replaces the selection with Select all + +#### Scenario: Select all pressed again +- **WHEN** the person presses Select all again after deselecting plans +- **THEN** the selection is replaced and those plans are selected again, as before this change + +#### Scenario: Still archived +- **WHEN** a departed plan is still archived when the next action in Current plans is counted +- **THEN** it is not in the count + +### Requirement: A new search result page starts unchecked + +A result page opened by Load more SHALL start unchecked, whatever the state of the page shown before it, and SHALL count as checked only after a freshness reply covered its own plans. A page that shows no plan has nothing to check and MUST NOT show the checking note. + +#### Scenario: New page after a checked page +- **WHEN** Load more opens a new result page while the page shown before it was checked +- **THEN** the new page is not treated as checked until a freshness reply has covered its plans +- **AND** the note that results are being checked can show until then, with no time limit; a failed freshness read leaves the page unchecked and is reported by the existing stale indication + +#### Scenario: Load more finds nothing +- **WHEN** Load more opens a new result page and the search ends without a hit for it +- **THEN** the page shows no checking note, and no freshness read is added for it + +### Requirement: A Select all count states the plans the frame has loaded + +Under Select all, the selection bar's count SHALL be the number of selected plans the frame has loaded. It SHALL carry a plus mark only while matching plans are known not to be loaded, as before this change, and MUST NOT gain one because the list was read in several pages. The count is not a verified total of matching plans: where a list read in several pages may have missed a plan, the confirmation SHALL say so before any request. + +#### Scenario: Complete list read in several pages +- **WHEN** Select all is active on a complete list that was read in several pages +- **THEN** the selection bar states the number of selected plans the frame has loaded, without a plus +- **AND** an action opened from it says that some plans may have been missed + +#### Scenario: Matching plans not loaded +- **WHEN** Select all is active while matching plans are not loaded +- **THEN** the selected count carries a plus mark, as before this change diff --git a/openspec/specs/progress-surface-hierarchy/spec.md b/openspec/specs/progress-surface-hierarchy/spec.md new file mode 100644 index 0000000..1159a7e --- /dev/null +++ b/openspec/specs/progress-surface-hierarchy/spec.md @@ -0,0 +1,105 @@ +# progress-surface-hierarchy Specification + +## Purpose +Give the rail and board one reading order, with the map first, one More menu for secondary content, advanced facts moved out of the default view and a compact Work Status. + +## Requirements + +### Requirement: Map-first plan reading order + +The rail and board SHALL present a plan in this order: header with title, progress bar with done/total and a text legend, the Map or List view, Needs you, the sub-agents line, and the incomplete-count indicator when needed. Map SHALL be the default view whenever complete detail records a task-to-task prerequisite and List otherwise. One Map | List switch SHALL sit at the top of that view. + +#### Scenario: Plan with prerequisites +- **WHEN** a plan whose complete detail records a task-to-task prerequisite is opened on the rail or board +- **THEN** the map opens directly under the title and progress bar, ahead of Needs you and the sub-agents line + +#### Scenario: Plan without prerequisites +- **WHEN** complete detail records no task-to-task prerequisite, or the graph capability is unsupported +- **THEN** List opens and the Map | List switch stays available + +#### Scenario: Very narrow frame +- **WHEN** a frame is narrower than 320 CSS pixels +- **THEN** List is the default and Map remains selectable + +#### Scenario: Explicit choice +- **WHEN** the user selects Map or List +- **THEN** that choice holds for the reading under the existing reset rules and is not stored + +#### Scenario: Wide board +- **WHEN** the board is at least 820 CSS pixels wide +- **THEN** the plan list is a left column whose rows show each plan's Needs you count, and the selected plan follows the same order on the right + +### Requirement: One More menu for secondary content + +Each rail and board SHALL have exactly one More menu holding copy actions, Plan document, History (board), Sessions, archive actions, hidden items, Language, Setup, Troubleshooting and deletion of a closed plan. Only applicable entries SHALL appear. Language, Setup and Troubleshooting SHALL be reachable in every state, including no plan, not set up and a failed read. + +#### Scenario: Panels replace the view +- **WHEN** the user opens Plan document, History, Sessions, Setup or Troubleshooting from More +- **THEN** it opens as a panel in place of the map or list, and Back returns to the view with focus on the More button + +#### Scenario: Menu keyboard use +- **WHEN** the menu is operated with a keyboard or a coarse pointer +- **THEN** it follows menu semantics with arrow keys and type-ahead, Escape returns focus to its button, and rows are at least 44 CSS pixels high on a coarse pointer + +#### Scenario: New history +- **WHEN** this device's saved review point for the selected plan is older than the plan's current revision +- **THEN** the board's More button shows a dot with an accessible name, without an additional history read +- **AND** no dot appears without a saved review point or without device storage + +#### Scenario: Before setup or after a failed read +- **WHEN** the extension is not set up, no plan is shown, or the progress read failed +- **THEN** More still offers Language, Setup and Troubleshooting + +### Requirement: Advanced controls leave the default UI without losing facts + +The default UI MUST NOT show the Details disclosure, the reporting-health panel, footer disclosures, task view options, the participant filter, the order toggle, expand/collapse all, per-task copy, the map's own heading and count line, or scope and coverage sentences. Every diagnostic fact they showed SHALL remain reachable under Troubleshooting → Advanced details. No service data or route SHALL be removed. + +#### Scenario: Advanced details +- **WHEN** the user opens Troubleshooting and expands Advanced details +- **THEN** the plan and store identifiers, recording state, document state, live-session count, report authorship and health observations that Details and Reporting health showed are present + +#### Scenario: Support summary +- **WHEN** the user copies the support summary +- **THEN** every line it contained before this change is present with the same text, order and values +- **AND** appended lines state the active incomplete-count reasons and this build's limits using fixed vocabulary, with no plan text, identifiers or paths + +#### Scenario: Troubleshooting panel +- **WHEN** Troubleshooting opens +- **THEN** it shows one sentence, Copy support summary, Check again and collapsed Advanced details + +#### Scenario: Unfinished filter +- **WHEN** the user wants only unfinished tasks +- **THEN** Show all / Unfinished is available in the help-and-filters control for both Map and List + +### Requirement: Compact Work Status + +Work Status SHALL show at most five lines: the featured plan's title with a position picker, the progress bar with done/total, one activity line, one qualification line and Open progress. It MUST NOT show state chips, focus rows, a current-task line, sub-agent rows or a separate more-plans line, and SHALL stay within the host's maximum section height. + +#### Scenario: Active plan +- **WHEN** the featured plan is active with two running sub-agents and one Needs you item in the selected session's plans +- **THEN** the activity line states two running and one needing the user, each part only when nonzero + +#### Scenario: Sub-agent waiting for the user +- **WHEN** the host shows a sub-agent session waiting on a question or permission +- **THEN** the activity line states it as a sub-agent waiting for the user, apart from the Needs you count + +#### Scenario: Stale only when stale +- **WHEN** an active plan's last report is more than one hour old +- **THEN** the qualification line states the age of the last update +- **AND** a fresher plan shows no time, and a failed read shows its own undismissable line with a retry + +#### Scenario: Recording off or plan closed +- **WHEN** recording is off, or the featured plan is finished, cancelled or failed +- **THEN** the qualification line says recording is off, or the activity line states the plan's outcome in words + +#### Scenario: Possibly incomplete counts +- **WHEN** a sub-agent or Needs you count may be low +- **THEN** the number carries a plus mark and no indicator line is added + +#### Scenario: Narrow and translated +- **WHEN** the card is 190 CSS pixels wide in English, Russian or Simplified Chinese +- **THEN** it wraps without horizontal overflow and its content height does not exceed the host's 480 pixel section maximum + +#### Scenario: Open from the count +- **WHEN** the user selects the Needs you count or Open progress +- **THEN** the rail opens with no task payload and no host-session change, and the rail's Needs you shows in its saved state diff --git a/openspec/specs/release-built-outputs/spec.md b/openspec/specs/release-built-outputs/spec.md new file mode 100644 index 0000000..5a626ff --- /dev/null +++ b/openspec/specs/release-built-outputs/spec.md @@ -0,0 +1,102 @@ +# release-built-outputs Specification + +## Purpose +Keep the development branch to source only and build the generated runtime outputs at promotion, so the distribution branch always equals a rebuild of the source it promotes and what users install does not change. + +## Requirements + +### Requirement: The development branch carries source only + +The generated runtime outputs (the service, setup and companion entries under `build/`, the background script and the three guest bundles) SHALL NOT be tracked on the development branch or in a pull request into any branch other than the distribution branch. Git SHALL ignore them there, so a local build leaves the working tree clean. A check SHALL fail when such a revision tracks any of them. + +#### Scenario: Fresh checkout of the development branch +- **WHEN** the development branch is cloned +- **THEN** none of the generated outputs is present or tracked +- **AND** building them leaves the working tree clean + +#### Scenario: An output is committed again +- **WHEN** a pull request into the development branch tracks a generated output, whether carried over by a rebase or brought in by merging the distribution branch +- **THEN** its portable check fails and names the tracked output + +#### Scenario: Two pull requests change shared interface source +- **WHEN** two open pull requests change source that the same guest bundle is built from +- **THEN** neither contains that bundle +- **AND** merging one does not make the other conflict on a generated file + +### Requirement: Checks build outputs before reading them + +On a revision that tracks no generated output, portable checks SHALL build every generated output from that revision before any test, package, readiness or verification step reads one. A second build of the same revision SHALL produce identical bytes, and the check SHALL fail when it does not. A check that needs an output MUST fail, not skip or pass, when that output is absent. + +#### Scenario: Portable checks in a fresh checkout +- **WHEN** portable checks run in a fresh full-history checkout of a development revision with a cleared environment +- **THEN** the outputs are built first +- **AND** tests, package assembly and package verification run against that build + +#### Scenario: Build is not reproducible +- **WHEN** the second build differs from the first in any output +- **THEN** the check fails and names the output + +#### Scenario: Native Windows suite +- **WHEN** the Windows suite runs on a development revision +- **THEN** the service entry it starts was built from that revision in the same job + +#### Scenario: Documentation-only pull request +- **WHEN** a pull request changes only documentation or proposal text under the existing rule +- **THEN** its check jobs are still skipped and nothing is built + +### Requirement: Promotion commits outputs built from the promoted source + +Promotion SHALL produce one commit whose parents are the distribution branch tip and the accepted development revision, and whose tree is that development revision plus the generated outputs built from it and nothing else. The promotion command SHALL act on the local repository only: it MUST NOT push, tag or publish. It SHALL refuse, leaving no promotion commit, when a precondition fails. + +#### Scenario: First promotion after the change +- **WHEN** the development revision has removed the outputs that the distribution branch still tracks +- **THEN** the promotion commit tracks every output, built from the promoted source, with version stamps equal to the package version + +#### Scenario: A later promotion +- **WHEN** a further development revision is promoted after an earlier promotion +- **THEN** the promotion completes with no merge conflict in any generated output +- **AND** the committed outputs are those of the newly promoted source + +#### Scenario: The distribution branch holds a change the development branch lacks +- **WHEN** the promoted tree would differ from the development revision in anything other than the generated outputs +- **THEN** the command refuses and names the differing paths + +#### Scenario: Unsafe starting state +- **WHEN** the working tree has uncommitted changes, the development revision tracks an output, or the build fails +- **THEN** the command refuses and both branches are unchanged + +### Requirement: The distribution branch always matches a rebuild of its source + +Every pull request into the distribution branch and every push to it SHALL be checked strictly: all generated outputs are tracked and each equals a fresh build of that revision. A pull request into the distribution branch SHALL always run these checks, including one opened directly from the development branch. Release eligibility, validation of the exact pushed revision and publication SHALL stay as they are. + +#### Scenario: Promotion pull request +- **WHEN** the promotion commit is proposed to the distribution branch +- **THEN** the checks run on its merge result and pass only if every output equals a rebuild + +#### Scenario: Development branch proposed directly +- **WHEN** a pull request is opened from the development branch into the distribution branch +- **THEN** its checks are not skipped as a duplicate +- **AND** they fail because outputs are missing or stale + +#### Scenario: Stale or missing outputs reach the distribution branch +- **WHEN** a push to the distribution branch has an output that is missing or differs from a rebuild +- **THEN** the check fails and no release is published for that revision + +#### Scenario: Version increase reaches the distribution branch +- **WHEN** a promotion with a higher package version and its release notes is pushed +- **THEN** the existing eligibility rules read the compiled versions from that exact revision +- **AND** publication proceeds as before + +### Requirement: What users install does not change + +Git installations from the default branch, from `#main` and from a release tag, and the release ZIP assets, SHALL contain the same entries as before and SHALL need no consumer build or dependency installation. The development branch SHALL NOT be offered as an installable ref. + +#### Scenario: Install from the distribution branch after a promotion +- **WHEN** a host installs or updates from the default branch or a release tag +- **THEN** it receives the declared companion folder and the service, setup, background and guest entries +- **AND** it runs them without building + +#### Scenario: A ref without built entries is selected +- **WHEN** a host is asked to install or update from the development branch +- **THEN** the host refuses the package +- **AND** an existing installation keeps its files and state diff --git a/openspec/specs/session-progress-context/spec.md b/openspec/specs/session-progress-context/spec.md index d63a6e9..816b897 100644 --- a/openspec/specs/session-progress-context/spec.md +++ b/openspec/specs/session-progress-context/spec.md @@ -69,17 +69,17 @@ The pinned-scope label SHALL offer a visible, keyboard-accessible localized **Sh ### Requirement: Explicit empty and multiple-plan handling -The action SHALL reuse existing panel plan selection within the validated source/session result, including a valid saved choice and the normal automatic selection rule. Multiple plans SHALL remain individually selectable and visibly scoped. Failed or incomplete reads SHALL NOT be presented as an authoritative empty or complete result. +The action SHALL reuse existing panel plan selection within the validated source/session result, including a valid saved choice and the normal automatic selection rule. Multiple plans SHALL remain individually selectable and visibly scoped, with the picker stating the shown plan's position among them. Failed or incomplete reads SHALL NOT be presented as an authoritative empty or complete result. #### Scenario: Multiple reported plans - **WHEN** the target has several eligible plans -- **THEN** the existing picker exposes them with the chosen/automatic indication +- **THEN** the existing picker exposes them and states the shown plan's position, without a separate chosen-or-automatic note - **AND** no combined synthetic plan or cross-source fallback is created #### Scenario: No plans or incomplete read - **WHEN** a complete validated result is empty -- **THEN** the panel explains that no plan is reported for that session -- **AND** a failed or capped read instead explains its limitation rather than claiming no plans +- **THEN** the panel explains that the session has no plan yet +- **AND** a failed read instead explains itself, and a capped read marks its counts as possibly incomplete, rather than claiming no plans ### Requirement: Optional source-labelled host work context diff --git a/openspec/specs/subagent-loss-notices/spec.md b/openspec/specs/subagent-loss-notices/spec.md index 0497dea..62d8eaf 100644 --- a/openspec/specs/subagent-loss-notices/spec.md +++ b/openspec/specs/subagent-loss-notices/spec.md @@ -84,12 +84,12 @@ Rail and board SHALL permit an explicit acknowledgement of the observed loss seq ### Requirement: Permanent coverage disclosure independent of attention -An old or dismissed loss SHALL remain in `coverage.reasons` as `capture-loss`, keep coverage incomplete and remain in the rail/board disclosure. Their Partial badge SHALL remain visible and muted when the loss does not require attention. A section containing the loss note MUST NOT expose itself as complete merely because its attention cue was quieted. +An old or dismissed loss SHALL remain in `coverage.reasons` as `capture-loss` and keep coverage incomplete. Affected counts SHALL keep their plus mark, and the loss with its detection date SHALL stay listed in Advanced details and named in the support summary. A section containing the loss MUST NOT expose itself as complete merely because its indicator was dismissed or its attention ended. #### Scenario: Dismissal does not repair counts - **WHEN** a recent loss is acknowledged - **THEN** retained counts and run/task facts do not change -- **AND** the date, disclosure, muted Partial badge and incomplete-section marker remain +- **AND** the date, the plus marks and the incomplete-section marker remain #### Scenario: Recovery completes after loss - **WHEN** history reconciliation finishes after a recorded gap @@ -97,13 +97,13 @@ An old or dismissed loss SHALL remain in `coverage.reasons` as `capture-loss`, k ### Requirement: Surface-specific accessible presentation -Rail and board SHALL use the prerequisite inline disclosure and change the Partial badge to warning tone only for active loss attention, with a textual accessible description. Work Status SHALL offer no dismissal control and SHALL show its short loss line only for active loss attention. The UI MUST retain existing section eligibility, other note priorities, keyboard access, disclosure continuity and identity-bound focus behaviour. +Rail and board SHALL present a recording gap through the single incomplete-count indicator, in neutral tone. A gap needing attention SHALL bring a dismissed indicator back and SHALL be named in its expanded text; dismissing it then SHALL send the store-wide acknowledgement. Work Status SHALL offer no dismissal control and no separate loss line. The UI MUST retain section eligibility, keyboard access and identity-bound focus behaviour. #### Scenario: Recent, old and legacy gaps - **WHEN** an eligible section has a recent undismissed gap -- **THEN** rail and board expose warning-tone Partial and the dated notice with Dismiss warning +- **THEN** rail and board show the indicator even if it was dismissed on this device, its expanded text names the gap, and affected counts carry a plus mark - **AND WHEN** that gap ages out, is dismissed, or is a migrated unknown-date gap -- **THEN** Partial is muted, the disclosure remains and Work Status has no loss line +- **THEN** it no longer brings a dismissed indicator back, the plus marks remain and Work Status shows only the plus marks #### Scenario: A response arrives after navigation - **WHEN** a dismissal/read reply belongs to a retired store, binding, account, root or hidden/disposed visit diff --git a/openspec/specs/windows-setup-responsiveness/spec.md b/openspec/specs/windows-setup-responsiveness/spec.md index 3d94afe..62d8cdf 100644 --- a/openspec/specs/windows-setup-responsiveness/spec.md +++ b/openspec/specs/windows-setup-responsiveness/spec.md @@ -264,3 +264,51 @@ Fresh setup SHALL support explicitly chosen valid retained stores, preserving id - **WHEN** the reviewed retained store has no source for the selected canonical roots - **THEN** confirmation binds a new source identity and expectation publication precedes its idempotent registration - **AND** existing sources, data and capture remain unchanged + +### Requirement: Fresh setup is presented as grouped plain-language steps + +Fresh setup SHALL present its frozen plan as at most four named groups: create the progress folder, connect it to OpenCode, turn on recording, and check that it works. Each internal step SHALL belong to exactly one group, in frozen order. Grouping SHALL be presentation only: requests, budgets, journal, pause and resume stay per internal step. Migration SHALL keep its own step sequence, reworded only. + +#### Scenario: New store +- **WHEN** fresh setup creates a new store and source +- **THEN** four groups are shown, and the current position reads as a step of four + +#### Scenario: Retained store or reused source +- **WHEN** the frozen plan omits creation, registration or enabling steps +- **THEN** a group with no step in the plan is not shown, the total counts only shown groups, and the first group's label says an existing folder is used + +#### Scenario: Pause inside a group +- **WHEN** setup is paused or closed after one internal step of a group +- **THEN** that group shows as paused, not complete, and explicit resume continues from the next internal step + +#### Scenario: Group completion +- **WHEN** every internal step of a group is durably complete +- **THEN** the group is marked complete, and not before + +#### Scenario: Failure +- **WHEN** an internal step fails +- **THEN** its group shows the failure with the existing fixed stage and code, and the internal step name is available in the disclosure + +### Requirement: Setup review stays explicit while its details fold away + +Setup SHALL show one sentence of purpose, the grouped steps and one explicit consent line stating that the progress service runs with the user's account access. Reviewed paths, proposed identities and delivery facts SHALL sit in one disclosure that is operable before confirming. Confirmation SHALL stay bound to the same reviewed facts, and recording state SHALL stay stated at every step. + +#### Scenario: Review before starting +- **WHEN** the user reaches the review +- **THEN** the consent control is unchecked by default, the disclosure of what Setup changes can be opened before confirming, and begin is refused until consent is given + +#### Scenario: Reviewed facts change +- **WHEN** the reviewed target or facts change before confirmation +- **THEN** begin refuses stale consent exactly as before, whether or not the disclosure was opened + +#### Scenario: Recording state while running +- **WHEN** fresh setup is running before its enable step +- **THEN** one plain line says recording is not on yet, without a warning box + +#### Scenario: Recording state when stopped +- **WHEN** setup pauses, fails, is closed or completes with recording off or unknown +- **THEN** that state is shown conspicuously with its recovery action + +#### Scenario: Three languages at phone width +- **WHEN** review, running, paused, failed and complete states render in English, Russian and Simplified Chinese at phone width +- **THEN** group names, the consent line and recovery actions are readable and operable by keyboard without horizontal overflow diff --git a/package.json b/package.json index 5922356..d4566b7 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "openchamber-agent-progress-probe", - "version": "1.5.1", + "version": "1.5.2", "private": true, "license": "MIT", "type": "module", diff --git a/release-notes/1.5.2.md b/release-notes/1.5.2.md new file mode 100644 index 0000000..7ea141f --- /dev/null +++ b/release-notes/1.5.2.md @@ -0,0 +1,19 @@ +# A stable system prompt, and steadier Tidy + +## Improvements + +- **Companion: the system prompt section is now stable, so providers can keep caching your conversation.** The section used to change between requests: after a dispatch or a plan write, in a sub-agent session and after a delegation refusal. A provider's prompt cache misses from the first change onward, which a user reported as a lower cache hit rate (#161). The section is now identical on every request. The notes that vary between requests arrive after the cacheable part, on the latest message, and stay in place on later requests. Providers that drop plugin system text now receive those notes too. Tests check that each request begins with the previous one byte for byte; real cache hit rates depend on the provider and were not measured. +- **Full page: the Tidy and selection result tells skipped plans from plans it could not confirm.** A request whose reply never arrived may have been applied, so the result line now says so in English, Russian and Simplified Chinese instead of calling the plan skipped. Undo still restores only plans whose archive was confirmed. + +## Fixes + +- Full page: a Tidy or selection run that finishes after you switch account or store no longer resets or changes the board you switched to, and Tidy and Select work at once on the new board. Cleanup controls follow what the service currently offers, including after a failed list read or a switch between Current and Archived plans. +- Full page: a count, a run's progress or its result arriving in the background no longer cancels a click or a press on Stop, and a focus move Tidy queued no longer pulls focus away from a control you chose. A result you have not seen yet is no longer dropped by the next refresh. +- Full page: Tidy and Select all now say when their count may have missed plans, which can happen when the plan list was read in more than one page. A count from a single page, or from rows you chose yourself, stays exact. A selection made during a search follows plans archived, deleted or restored elsewhere, and a plan restored elsewhere is counted again by the next action. +- Reporting: when work moves back to the prerequisites of a task an agent reported blocked, agents are now told to read the current plan and clear the block once every prerequisite the task still lists is done, instead of waiting on a prerequisite the plan no longer has. Coordinator guidance no longer turns a malformed delegation receipt into a confident refusal. + +## Misc + +- Documentation: clarifies when Tidy and Select all check chosen plans one by one and which revision a retry compares against. +- Development: the large-library check counts the requests a measuring window actually sent and reports a comparison it could not make as unverified instead of passing it. +- Development: the Linux test step in CI is faster, dropping from about 5 minutes to about 2.5 to 4 minutes, with no tests removed. New `bun run test:fast` and `bun run test:all` commands run the portable checks locally. The runner is POSIX-first, and stopping it on Windows is best effort. diff --git a/shared/release.ts b/shared/release.ts index 60489a1..4c64754 100644 --- a/shared/release.ts +++ b/shared/release.ts @@ -1,2 +1,2 @@ /** Package release is independent of the frozen protocol/schema version. */ -export const RELEASE = '1.5.1'; +export const RELEASE = '1.5.2';