Skip to content

拆分 approval-service.ts(12,429 行)为职责模块,只搬不改 #38665

Todo

Description

@objectstack-fleet

repo:objectstack#2 · os-warren · session_01JQwxbXyLoBzNYY1U8SNPFu

Filed on the maintainer's word: split card 2 of the large-file plan.

Filing gate: ③ maintainer-directed. Source: maintainer (Warren, os-warren), os-warren's fleet project thread, 2026-11-30T01:18:13Z 「同意,立卡」 and 2026-11-30T01:18:26Z 「按照 fable的方案」, approving the large-file plan of an isolated fable analysis (measured on origin/main f5da514; prior rulings 6624258595 on #29465 and 6897467376 on #33949: a split file carries a facade ceiling, an unsplit file none, "at most a warning"; #33949 closed 11-22 with "a future split that pays for itself can be filed on its own measurement").
Grading: area:workflow · Task (no behaviour change) · Suggested-grade: p2 · reach: every approvals card · evidence: packages/plugins/plugin-approvals/src/approval-service.ts 12,429 lines at f5da514 (176 members), +2,948 in 30 days, 19 commits in the last week; open PRs #38497 (+1,432) and #38634 (+1,247) both add to it; named "next round" in ruling 6897467376.
Blocked-by: #38497, #38634

维护者速读

  • 问题:审批服务一个文件 1.2 万行,一个月涨了近 3,000 行,手上两个 PR 还各加 1,200 多行,审批相关的卡都挤在这一个文件。
  • 做什么:等这两个 PR 合并后,按职责拆成几个模块,只搬代码、不改行为,单独一个 PR。
  • 要你做什么:拆分 PR 超过 3,000 行时需您批准。

Ask

  1. First the ~2,300 lines of top-level helpers ahead of the class (refusals, row mapping, SLA) to leaf modules.
  2. Then the class bodies by concern: request lifecycle, notification, read redaction (the dev proposes the cut and names). ApprovalService keeps its public surface and delegates. Move-only: no renamed public member, no behaviour change, no new package export.
  3. Register the facade in scripts/facade-delegation-registry.json: a facades row and a ceilings row (post-split count, CEILING_MARGIN 100); a state-owning member that stays gets an exceptions row with its reason.
  4. One PR (or one per step if over 3,000 lines changed). Start from main after the blockers merge; land before another card opens a PR on the file.

Acceptance

  • The PR body maps each moved member or helper to its new file; net growth past a pure move is itemised per file.
  • Every plugin-approvals test and the approval pins elsewhere pass unchanged; the package's public declaration is unchanged.
  • scripts/check-facade-delegation-only.mjs is green with the new rows; approval-service.ts falls well below 2,000 lines.

Not here

  • Any fix or feature. packages/spec/src/contracts/approval-service.ts (the contract) is untouched.

Activity

  1. objectstack-fleet commented on Nov 30, 2026

    @objectstack-fleet
    ContributorAuthor

    triage@os-warren · os-warren · session_01JQwxbZzZ2f5mzcvJbRrRNZ

    Triage: lands in packages/plugins/plugin-approvals/src/approval-service.ts and new concern modules, move-only · area:workflow · domain:services · Task · p2 · pm:blocked · size L (one PR, move-only).
    Rationale: split card 2 of the large-file plan, maintainer-directed (「同意,立卡」「按照 fable的方案」, 2026-11-30T01:18Z, quoted in the body). A refactor is a Task; it takes p2 because every approvals card queues on this one file. It waits on the body's Blocked-by: line (PRs #38497 and #38634, which both add to the file). Routed to the area:workflow lane. Answers knock 7266133804.

  2. added
    area:workflow
    domain:server
    pm:blocked
    priority:p2
    on Nov 30, 2026
  3. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Seat note · 2026-12-01T11:33Z · ⛔ not a claim; state and labels unchanged.

    Both blockers (#38497, #38634) are closed, so this card is about to re-enter the queue. Its acceptance has the same contradiction the sibling split #38667 hit: "the package's public declaration is unchanged" and "approval-service.ts falls well below 2,000 lines" cannot both hold under the facade form (on #38667 the public signatures and docblocks alone kept engine.ts at 7,735 lines; that forced ruling 7305055957).

    Measured now: approval-service.ts is 15,275 lines (the card says 12,429) with 190 private/protected members. The two landed sibling move-only splits grew their package source past a pure move: #38889 (automation) +2,642 net, PR #38700 (knowledge) +1,785 net, mostly doubled signatures and docblocks and the facet host blocks.

    The maintainer has since ruled on #38667 (7309703845) that the automation engine's published declaration is not a customer contract, and filed the target state (state moved into its modules, no host scaffolding) as #38905. Whether this card keeps its move-only facade form or goes straight to the state-owning form is being put to the maintainer by this seat; the seat will not dispatch it under the current acceptance until that answer is recorded here.

  4. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Maintainer ruling · 2026-12-01T11:57Z · on the seat note 7309820070 (this card's acceptance holds the same contradiction as #38667's).

    The maintainer, in seat repo:objectstack@os-justin's session, verbatim: 「38665 直接做成目标形态」.

    Ruling — this card goes straight to the state-owning form; the move-only facade form is not built. It replaces the card's ask and acceptance as follows:

    1. Target. ApprovalService's state moves into the modules that own it; each module receives its few dependencies in its constructor; approval-service.ts becomes the composition root and keeps one-line delegations for its public methods. No facet host blocks, no signature or docblock written twice (one copy, on the module or on the public method). The scripts/facade-delegation-registry.json facade and exception rows are not owed (the file is not a facade); the file's line ceiling, if one is owed, is the measured end size.
    2. Contract kept. IApprovalService (packages/spec/src/contracts/approval-service.ts) and the service registered as approvals behave and type-check unchanged; the public methods the shipped skills document (e.g. ApprovalService.decide()) keep their signatures. Byte-identity of the published .d.ts is not required: private members and docblock placement may change (same reasoning as the ruling 7309703845 on 拆分 service-automation engine.ts(12,298 行)为职责模块,只搬不改 #38667 — customers author metadata and reach the service through its spec interface).
    3. Order. Step 1, no code: a state-ownership map (every field, its writers and readers) and the cluster plan, posted on this card by the seat and reviewed before code. Then one PR per cluster, target ≤ ~1,000 changed lines each, Part of #38665 (the last one Fixes), each with behaviour tests for the paths it moves; every plugin-approvals test and the approval pins elsewhere pass.
    4. Superseded: the acceptance lines "the package's public declaration is unchanged" (as byte-identity) and "approval-service.ts falls well below 2,000 lines" as a fixed number; and, for this file, the not-planned closure of refactor: move shared state out of the protocol.ts and engine.ts facades into state-owning facets, so the hot bodies left on the class can become delegations (ruling 6624345766) #30020 (state-owning facets as a standalone programme) — the maintainer's words here order it.
  5. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Claim: PM loop round 1
    Session: session_01QSeKYnrQ7UMtHofKQVjcH2
    Account: os-justin
    Branch: claude/issue-38665-approval-service-modules
    Worktree: objectstack-issue-38665
    Domain: domain:server
    Seat: repo:objectstack@os-justin
    File surface: packages/plugins/plugin-approvals/src/approval-service.ts, packages/plugins/plugin-approvals/src/ (reason: the state-owning modules the ruling 7310432861 orders; each PR names its new files in its body), scripts/query-options-erasure-baseline.json (reason: PR 0b retires this file's grandfathered row), the source-keyed pins and anchors the step-1 map §5 names — packages/core/src/security/second-object-read-exposure.pin.test.ts, scripts/adr-anchors/packages__plugins__plugin-approvals__src__approval-service.ts.json, docs/qa/platform-checklist/areas/approvals.json, packages/spec/liveness/ (reason: they key on this file's path and method names; widened in place after the step-1 map) (stop on breach; explain in the report)
    Container & model: L, mode:cloud, model: opus (dispatch-gates --tier: no path-derived mandate; floor sonnet · default opus · ceiling fable — default tier; the cluster cut is a design judgement), effort: high
    Clause-②: no
    Metadata-protocol: none
    Responsibility: n/a — not a defect card
    Thread-read: 7310432861
    Premise: holds (origin/main ac97540, 2026-12-01T11:58Z: approval-service.ts 15,275 lines, 190 private/protected members; IApprovalService at packages/spec/src/contracts/approval-service.ts:1107; blockers #38497 and #38634 closed)
    Serial constraints cleared: no in-flight claim names approval-service.ts (check-handover --inflight, 2026-12-01T11:58Z); open PR #38871 touches only flow-route.integration.test.ts in this package. Step 1 (the state-ownership map) is the seat's, posted here before any dev is dispatched. Landing: each cluster PR by its own size; a PR over 3000 changed lines is Tier H.

  6. added
    pm:dispatched
    and removed
    pm:blocked
    on Dec 1, 2026
  7. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Step 1 · state-ownership map and cluster plan · 2026-12-01T12:17Z · ordered by the ruling 7310432861; measured read-only on origin/main ac97540 by an at-tier analysis subagent (TypeScript compiler API over the file; test counts are regex). The full map follows the seat's review.

    维护者速读

    • 实测结果:审批服务几乎没有内存状态(只有 5 个可变字段,每个只被 1–2 个方法用到),真正的耦合是方法互相调用。所以按"状态归属"切不出边界,改为按调用图切成 8 个模块。调用图无环,每个模块只调用下层模块、从不回调 service,因此不需要任何 host 脚手架。
    • 若照 automation 那样做成 facade + host,会留下约 209 个回调,比 automation 的 138 个还多,证明直接做目标形态是对的。
    • 代价:约 12 个顺序 PR(每个低于 3,000 行变更,不触发 Tier H)。期间别的卡若要改 approval-service.ts,需要排在后面。
    • 要你做什么:无。若不同意下面的 PR 分组,在此回复即可。

    Seat review (verdict: the plan is sound; three changes)

    Spot-checked: scripts/query-options-erasure-baseline.json exempts 10 sites in this file (line 38); 9 test sites override a method on the instance ((svc as any).x = …, grep over the package's *.test.ts). Both hold.

    1. Premise correction accepted, ruling intent kept. The ruling's "state moves into the modules that own it" has almost no state to move here; the target is read as: modules cut along the acyclic call graph, each taking the lower modules it calls in its constructor, no host blocks, no doubled signatures or docblocks, approval-service.ts the composition root with its 38 public delegations. That is the ruling's form; no fork.
    2. PR grouping (seat's task order). The map's 20 units are grouped into PRs of at most ~1,400 moved lines (a move counts both sides, so under the 3,000-line human-merge threshold), keeping topological order: 0b (type the 10 grandfathered query-options sites — a hard prerequisite, the ratchet refuses a new file in the baseline) → 0a (shared prelude primitives) → 1+2 → 3 → 4 → 5+6 → 7+12 → 8 → 9+10 → 11 → 13 → 14 → 15 → 16+19 → 17 → 18+20. About 16 PRs; each is Part of #38665, the last Fixes. Each is dispatched only after the previous one merges (all touch approval-service.ts).
    3. Test seams are an acceptance line, not a note. Every PR that moves a method some test overrides or spies on through the service instance re-points that test at the module and adds a positive control showing the override still intercepts (an override that silently stops intercepting lets a test pass for the wrong reason). Source-keyed pins and prose anchors named in §5 move in the same PR.

    Out of scope, recorded: the durable shared state (sys_approval_request written at 17 sites in 15 methods across 4 modules, 8 of them read-modify-write on node_config_json) gets no single owner from a move; that is a behaviour change for its own card if wanted. attachTenancyPosture and actionLinkUrl have 0 callers and 0 tests (map §6): a retirement question for triage, not this card.

    Hot file: while this series runs, a card that edits approval-service.ts queues behind the PR in flight (Blocked-by: that PR), per the area lease's split rule.


    ApprovalService state map and split plan (#38665)

    Target: packages/plugins/plugin-approvals/src/approval-service.ts at origin/main ac97540
    (working tree file is byte-identical to origin/main, checked with cmp).
    Read-only analysis; nothing in the repo was edited.

    How it was measured. TypeScript compiler API (ts.createSourceFile, TypeScript 6.0.2 from
    /opt/node22/lib/node_modules) over the file: every this.<name> inside the class is classified as
    field read / assignment / container mutation (.set/.delete/.add/.push…) / method call / method
    reference, attributed to the enclosing class member (closures included). No const self = this
    alias and no this[...] dynamic access exist (0 and 0), so the AST count is complete for the class.
    this.engine.<op>('<object>', …) calls and their payload keys were extracted the same way.
    Test and caller references were measured by regex/grep (marked where so).
    Not run: tests, tsc, eslint (this checkout has no node_modules). Git churn is not
    measurable here (shallow clone, 3 commits). Scripts and raw output are in
    /tmp/claude-0/-home-user-objectstack/96353139-b75c-518e-b0e8-54f835f491d0/scratchpad/tools/
    (ast.json, ast2.json, callgraph.txt, rep1.txt, clusters.json, tests.json).

    0. Headline: the premise needs one correction

    The class holds almost no in-memory state, so "cluster by state ownership" does not decide the cut.

    Measure Value
    File 15,275 lines: prelude 1–3020 (144 top-level declarations, 33 exported), class 3021–15275
    Class members 204 methods (165 private, 0 protected, 38 public + constructor, 8 static) and 25 fields (2 static constants)
    Method body lines 8,288; comment lines inside the class 5,404 (44% of the class)
    Mutable in-memory fields 5, touched at 10 sites, each by 1–2 methods, each inside one module
    Late-bound collaborator slots (public attach* setter) 5
    Collaborators fixed in the constructor 13
    this.<field> read sites outside the constructor 394, of which 362 (92%) read engine (165), logger (118), automation (55) or clock (24)
    this.<method> call/reference sites 404

    Compare with the engine.ts attempt (105 state reads + 138 method callbacks): here the state reads
    that would need a host are 10, but the method coupling is larger. Under the 8-module cut below,
    204 of the 404 intra-class call sites (plus 5 static calls) cross a module boundary, through 74
    distinct methods.
    A facade-with-host form would therefore leave ~209 callbacks, worse than
    engine.ts. The state-owning form is still viable, because the module graph is acyclic (section 3),
    so every one of those 209 sites becomes a direct call on a constructor-injected lower module and no
    module ever calls back into the service. What is not achievable is "a few narrow dependencies" for
    the top layer: the door methods (openNodeRequest, decide, recall, …) are orchestration and
    need 6 lower modules through 54 methods at 152 call sites.

    The state that really is shared is durable: the sys_approval_request row (17 write sites in 15
    methods across 4 modules). Section 3 covers it.

    1. State inventory

    Line = declaration line. R/W = sites outside the constructor (AST). "Methods" lists every writer,
    and every reader when there are few; the full per-method list for engine/logger/clock is in
    tools/rep1.txt.

    1a. Mutable state (5 fields)

    Field Type Line Written by Read by
    strandScanCursor string | null = null 3034 inspectStrandedRequests (11619) inspectStrandedRequests (11613)
    reconcileScanCursor string | null = null 3036 reconcileMarkedApprovals (12424) reconcileMarkedApprovals (12418)
    sweepClockScheduled boolean = false 3315 noteSweepClockScheduled (3319), called by the plugin at approvals-plugin.ts:557 judgeOpening (7098)
    schemaReadVerdicts WeakMap<object, Promise<boolean>> 3045 authorizeSchemaRead (.set, 15211) authorizeSchemaRead (15208)
    platformAdminStandings WeakMap<object, Map<string, Promise<boolean>>> 3047 platformAdminStanding (.set, 3815) platformAdminStanding (3808)

    Module-level mutable state in the same file: REQUEST_VISIBILITY (2965) and SLOT_LABELS (2991),
    both WeakMap<ApprovalService, …> written once per instance in the constructor (3127, 3130) and
    read by the exported requestVisibilitySourceOf / slotLabelSourceOf.

    1b. Late-bound collaborators (constructor option, replaceable through a public setter)

    Field Type Line Written by Read sites / methods
    automation ApprovalResumeSurface? 3025 ctor 3089, attachAutomation 3302 55 sites in 27 methods (table 1d)
    messaging ApprovalMessagingSurface? 3026 ctor 3090, attachMessaging 3324 3 sites, notify only
    tenancyPosture () => string | undefined 3038 ctor 3093, attachTenancyPosture 3183 3: orgScopeDeps 3280, organizationWallStands 3582, recipientContext 13360
    fieldVisibility FieldVisibilitySource? 3039 ctor 3094, attachFieldVisibility 3192 3: servedFields 3246, subjectNamesFor 13316, freeTextMayMatchSnapshot 13695
    objectReadAdmission ObjectReadAdmissionSource? 3041 attachObjectReadAdmission 3203 only (not a constructor option) 1: admittedTargetObjects

    1c. Collaborators fixed in the constructor (never reassigned)

    Field Type Line Read sites / methods
    engine ApprovalEngine (readonly) 3022 165 sites in 98 methods. All durable writes go through it (section 3)
    clock ApprovalClock (readonly) 3023 24 sites in 24 methods
    logger ApprovalServiceOptions['logger'] (readonly) 3024 118 sites in 63 methods
    publicBaseUrl string (not readonly, but only the ctor assigns it, 3091) 3027 3: notify, actionLinkUrl, approvalsInboxLink
    getConsoleUrl ConsolePageComposer? (readonly) 3037 2: notify, approvalsInboxLink
    messageTranslator () => ValidationMessageTranslator | undefined 3043 1: userFacingRefusal
    i18nServiceSource () => ReaderLabelI18n | undefined 3049 2: userFacingRefusal, readerLabels
    positionLabelSource (name) => Promise<string | undefined> 3051 2 sites, notePositionLabels
    ownershipQueues () => ApproverQueueSource | undefined 3053 1: queueSource
    workCalendar () => Pick<IWorkCalendarService,'addWorkingHours'> | undefined 3055 1: slaDeadline
    recordReaderVisibleObjects ReadonlySet<string> (readonly) 3063 1: recordReaderTierOn
    recordOrgResolver RecordOrganizationResolver (readonly; built in ctor 3080, memoizes per object) 3071 3: attributedMirrorContext ×2, openNodeRequestBody 7787
    pendingApproverReads PendingApproverReadGrantSource (readonly; built in ctor 3081 with closures over isOverrideActor, callerAccountEmail) 3076 1: pendingApproverReadGrants

    Static constants: SERVED_TEXT_SCOPE_CAP = 5_000 (13775, used by servedTextArms),
    APPROVER_INDEX_CAP = 10_000 (13953, used by organizationAdministrators, approverRequestIds,
    visibleRequestIds, addRecordReaderVisibleIds).

    1d. Field reads per proposed module (read sites; /W = writes outside the constructor)

    Field actors directory runs display reader judge doors recovery
    engine 4 13 2 17 32 35 44 18
    logger 1 18 9 9 10 35 16 20
    clock · 1 · · 1 5 14 3
    automation · · 31/W1 · 1 10 1 12
    tenancyPosture 1/W1 1 · 1 · · · ·
    fieldVisibility · · · 2/W1 1 · · ·
    i18nServiceSource · · · 1 · · 1 ·
    recordOrgResolver · · · · · 2 1 ·
    every other field one module only (see 1a–1c)

    2. Clustering

    Because 1a is trivial, the modules below are cut on (a) the call graph, so that the module graph is
    a DAG, and (b) which durable rows a module writes. Eight top-level modules; the maintainer asked
    for 3–7. Merging actors into directory gives 7, but they share no state and no call, so I kept
    them apart. Line counts: "span" = class lines including the doc comment above each member;
    "prelude" = top-level helpers referenced by that module alone (transitively) that move with it.

    # Module (proposed file) Methods Body Span + prelude Public methods Depends on
    1 ApprovalActors (approval-actors.ts) 13 226 419 18 attachTenancyPosture none
    2 ApproverDirectory (approver-directory.ts) 28 1,083 1,642 268 none none
    3 ApprovalRuns (approval-runs.ts) 24 519 996 53 attachAutomation none
    4 ApprovalDisplay + notifier (approval-display.ts, approval-notifier.ts) 32 686 1,170 97 localizeActionRows, attachFieldVisibility, attachObjectReadAdmission, attachMessaging, actionLinkUrl none (notifier → display, 2 sites)
    5 ApprovalRequestReader (approval-request-reader.ts, approval-visibility.ts) 33 953 1,626 406 listRequests, countRequests, getRequest, getRecordLock, getRecordLocks, listActions, authorizeFileRead, authorizeSchemaRead, rebuildApproverIndex, pendingApproverReadGrants actors, display, runs
    6 ApprovalJudge (status-mirror.ts, approval-judge.ts) 32 1,324 1,964 532 noteSweepClockScheduled display, directory, runs, reader
    7 Doors (approval-opening.ts, approval-decisions.ts, approval-tokens.ts, approval-escalation.ts) 31 2,564 3,038 199 openNodeRequest, decideNode, decide, recall, sendBack, resubmit, reassign, remind, requestInfo, comment, issueActionTokens, peekActionToken, redeemActionToken, handleActionPage, runEscalations all six below it
    8 ApprovalRecovery (approval-recovery.ts) 10 849 1,258 400 inspectStrandedRequests, continueRestoredRun, reconcileMarkedApprovals, releaseDeadRunRequests, cancelForDeletedRecord reader, judge, runs, display

    Left on the composition root: the constructor (140 lines today), the two WeakMap registrations,
    and 38 one-line delegations. Shared by two or more modules and not owned by any: 1,149 prelude
    lines in 41 declarations (SYSTEM_CTX, uid, parseJson, actingUserId, recordedActor,
    stampOf, rowFromRequest, pendingSlateOf, RUN_STATUS_LIVENESS, ApprovalResumeSurface, …).

    Module 1 — ApprovalActors (who the caller is)

    • Owns: platformAdminStandings (cache). Collaborators: engine, tenancyPosture, workCalendar, logger.
    • Methods: isOverrideActor 3493, organizationWallStands 3581, resolveActor 3674, callerHasEmail 3715, callerAccountEmail 3726, excludedSubmitterSlots 3746, submitterSlots 3762, actingCaller 3777, platformAdminStanding 3805, takenSlot 3844, attachTenancyPosture 3182; plus the SLA clock slaDeadline 11388 and projectWorkingTimeDue 11427 (a 43-line leaf read by reader, opening and escalation; it can equally be its own function module).
    • Serves: every door (resolveActor ×8, takenSlot ×5, isOverrideActor ×9 across modules, actingCaller ×6); 37 inbound call sites through 10 methods.
    • Depends on: nothing.

    Module 2 — ApproverDirectory (who a slot expands to)

    • Owns: no state. Collaborators: engine, clock, logger, tenancyPosture, ownershipQueues.
    • Methods (holders, a leaf): expandTeamUsers 4562, teamIsProvablyOutsideOrg, readTeamRow, dropMembersProvablyOutsideOrg, businessUnitOrgScope, businessUnitMemberScope, expandBusinessUnitUsers 4832, businessUnitIsLive, queueSource, expandQueueUsers, expandPositionUsers 5180, organizationAdministrators 5231, expandMembershipTierUsers, readHoldersToCompletion, readRowsToCompletion, lookupManager 5395, managerIsProvablyOutsideOrg, reassignTargetRefusal 10839.
    • Methods (resolver, calls holders at 11 sites): expandApprovers 3895, warnPlatformSlotNotOpened, resolveApproverSpec 4029, warnExpansionFailed, resolveExpressionApprovers 4350, applyOooDelegation 5484, namesNoAccount, lookupActiveDelegation 5577, orgScopeDeps 3277, directoryOrgFor 3289.
    • Serves (6 methods, 15 sites): expandApprovers (4, from openNodeRequestBody and decideNode), organizationAdministrators (3), reassignTargetRefusal (3), expandPositionUsers (3), businessUnitIsLive (1), readTeamRow (1).
    • Depends on: nothing.

    Module 3 — ApprovalRuns (the automation gateway)

    • Owns: the automation slot (31 of its 55 read sites). Writes the strand journal into sys_approval_request.node_config_json (journalStrandedContinuation 11801).
    • Methods: attachAutomation 3301, flowPackageOf 5051, requestFlowSlot 5075, requestFlow 5109, requestFlowKey 5125, stepRunsInArmedBody 4986, serviceResume 8894, statics resumeCodeOf/resumeStatusOf/resumeRefusalOf/recognisedRefusal/parentStrandReport 8928–9008, assertRunResumable 9090, missingRunCapability 9155, resumeRecordedOutcome 9237, journalStrandedContinuation 11790, batchAboveItem 9816, resumeBatchOfRecalledItem 9851, cancelRunsOfVoidedRequest 10128, voidedRunChain 10184, assertReviseEdge 10513, expectedPauseNode 12056, runHasEnded 14956, ranArmedBody 14974.
    • Serves: 29 inbound sites through 20 methods (doors 22 sites / 15 methods; recovery 3; judge 2; reader 2).
    • Depends on: nothing.

    Module 4 — ApprovalDisplay and ApprovalNotifier

    • Display owns: the fieldVisibility and objectReadAdmission slots. Collaborators: engine, logger, i18nServiceSource, positionLabelSource, tenancyPosture.
    • Display methods: servedSubjectFields 3219, servedFields 3238, redactPayloads 3267, resolveDisplayField 12835, statics titleCandidates/pickTitle/titleAsServed, resolveUserNames 12880, readUserNames, slotLabels 12937, slateLabels, actionRow 12990, resolveLookupFields 13047, servesPayloadDisplayTarget 13085, admittedTargetObjects 13120, resolveFieldLabels, resolveSubjectDisplays, titlesAsServed, objectLabelOf 13261, subjectNamesFor 13293, recipientContext, enrichRows 13402, readerLabels 14404, localizeActionRows 15042, notePositionLabels 15122, attachFieldVisibility, attachObjectReadAdmission.
    • Notifier owns: the messaging slot, publicBaseUrl, getConsoleUrl. Methods: notify 3339, attachMessaging 3323, actionLinkUrl 10967, approvalsInboxLink 11157, notifyDecisionOutcome 9491. Calls display at 2 sites (subjectNamesFor, objectLabelOf).
    • Serves: 66 inbound sites through 18 methods; the big ones are actionRow ×20 and notify ×17.

    Module 5 — ApprovalRequestReader (read side, visibility, approver index)

    • Owns: schemaReadVerdicts (cache), recordReaderVisibleObjects, pendingApproverReads. Sole writer of sys_approval_approver (syncApproverIndex 13550/13553, rebuildApproverIndex 13611/13623).
    • Methods (visibility + index, depends on actors only): syncApproverIndex 13535, rebuildApproverIndex 13566, approverRequestIds 13970, approverIndexWhere, participantProbes 14026, visibleRequestIds 14106, addRecordReaderVisibleIds, recordReaderTierOn, applyVisibility, requestRowForCaller 14566, refuseUnreadableRequest 14613, authorizeSchemaRead 15205, servesAnyRequest 15240, pendingApproverReadGrants 3177.
    • Methods (queries): freeTextMayMatchSnapshot, buildRequestWhere 13709, servedTextArms, recordsTitledWith, listRequests 14320, countRequests 14415, readBackRequest 14476, getRecordLocks 14519, getRequest 14545, getRecordLock 14664, loadRequest 14681, loadPendingRow 3448, assertLatestForRun 10555, attachDecisionProgress, attachViewers, attachFlowSteps, attachFlowRoute, listActions 14978, authorizeFileRead 15155.
    • Depends on: actors (isOverrideActor ×4, actingCaller ×4, projectWorkingTimeDue ×2), display (11 methods, 17 sites: enrichRows, readerLabels, servedSubjectFields, redactPayloads, resolveUserNames, localizeActionRows, objectLabelOf, servedFields, resolveDisplayField, 2 statics), runs (requestFlow, runHasEnded).
    • Serves: 36 inbound sites through 8 methods: readBackRequest ×10, syncApproverIndex ×11, loadPendingRow ×6, refuseUnreadableRequest ×3, assertLatestForRun ×3, getRequest, visibleRequestIds, approverRequestIds.

    Module 6 — ApprovalJudge (status mirror, run reading, verdict, opening check)

    • Owns: sweepClockScheduled; shares the recordOrgResolver instance with opening. Sole writer of the subject record's status field (mirrorStatusField 5735). Writes marks on sys_approval_request (keepRunsRead 6536, abandonApproval 6661, clearMarks 6865, noteLaterStepNotOpened 6987, voidRefusedOpening 7208) and 3 timeline rows.
    • Methods: one contiguous block, 5701–7564: mirror (mirrorStatusField 5701, closesOnApprovalOutcome, holdsBackDecision, reportRefusedMirror 7239, mirroredStatusValue, closedValuesOf, abandonedValueOnClosingField, approvalWroteHeldValue, attributedMirrorContext, hasTimelineLine); run reading (readCarryingRun 6088, laterStepNotOpenedOn, waitingRun, readApprovalRun, placeApprovalRun, keepRunsRead, runsReadAtOpening); verdict (judgeApprovalAfterDoor 5845, abandonApproval 6653, cancelStoppedRun, reportFlowNotContinued, clearMarks, clearEarlierMarks, refuseAbandonedContinuation, deciderOf, noteLaterStepNotOpened); opening check (judgeOpening 7025, openingRootFlow, openingCalleeFlow, isFirstRequestOfApproval, voidRefusedOpening), plus noteSweepClockScheduled 3318.
    • Depends on (11 sites): display actionRow ×3, notifier notify ×3, directory organizationAdministrators ×2, runs voidedRunChain, flowPackageOf, reader syncApproverIndex.
    • Serves: 33 inbound sites through 12 methods: judgeApprovalAfterDoor ×11, mirrorStatusField ×7, clearMarks ×3, clearEarlierMarks ×3, holdsBackDecision ×2, and 7 used once by opening/recovery.

    Module 7 — Doors (use cases)

    • Owns: no in-memory state. Writes: the only sys_approval_request insert (8161), 7 of its updates, 15 sys_approval_action inserts, both sys_approval_token writes (11001, 11070).
    • Opening: openNodeRequest 7638, openNodeRequestBody 7725 (665 lines, the largest method), loadLiveRecord 7584, snapshotRecord 12817, platformAdminApproverRefusal 5003, namesPlatformAdminApprover 4969.
    • Decisions: isApprovalSatisfied 8399, assertDecisionOutputsMatchDeclarations 8444, decisionOutputValueRefusal 8522, decideNode 8562, assertAttachmentsUploadedByCaller 9026, decide 9340, decideAndResume 9368; recall 9585, userFacingRefusal 3612, sendBack 10240, resubmit 10413; reassign 10580, assertReassignTargetResolves, assertReassignTargetIsNotSubmitter, remind 10875, requestInfo 11208, comment 11248.
    • Tokens: issueActionTokens 10983, resolveActionToken, peekActionToken, redeemActionToken 11063, handleActionPage 11122, personForTokenSlot.
    • Escalation: runEscalations 11306, escalateRequest 12672.
    • Depends on (152 sites, 54 methods): display+notifier 40 sites (actionRow ×15, notify ×14, slateLabels ×4, …), reader 30 (readBackRequest ×10, syncApproverIndex ×8, loadPendingRow ×6, …), judge 24 (judgeApprovalAfterDoor ×8, mirrorStatusField ×6, …), actors 23, runs 22, directory 13. Exact list in tools/clusters.json.
    • Tokens and escalation sit above decisions (redeemActionToken → decide, escalateRequest → decideAndResume).

    Module 8 — ApprovalRecovery (sweeps and repair)

    • Owns: strandScanCursor, reconcileScanCursor. Writes sys_approval_request at 12514 (endApprovalOfDeletedRecord), 12644 (abandonForDeadRun), 10031 (cancelForDeletedRecord) and 2 timeline rows.
    • Methods: inspectStrandedRequests 11569, resolveRecordedContinuation 11851, continueRestoredRun 12198, reconcileMarkedApprovals 12395, recordIsGone, endApprovalOfDeletedRecord, endApprovalsOfDeletedRecord, releaseDeadRunRequests 12570, abandonForDeadRun 12627, cancelForDeletedRecord 9971.
    • Depends on (17 sites): judge (judgeApprovalAfterDoor ×3, clearMarks ×3, refuseAbandonedContinuation, mirrorStatusField, clearEarlierMarks), reader (assertLatestForRun, syncApproverIndex ×2), runs (expectedPauseNode, resumeRecordedOutcome, cancelRunsOfVoidedRequest), display (actionRow ×2). Nothing depends on it.

    3. Cross-cluster hot spots

    3a. In-memory fields read by several modules

    Field Readers outside the owner Proposed owner and accessor
    automation (late-bound; the plugin attaches it at approvals-plugin.ts:750, after registerService at :483) 24 of 55 sites: judge 10 (readCarryingRun 6101, placeApprovalRun 6378, runsReadAtOpening 6573/6596, cancelStoppedRun 6783/6797, judgeOpening 7095/7096, openingRootFlow 7125, openingCalleeFlow 7152), recovery 12 (inspectStrandedRequests ×6, continueRestoredRun ×4, releaseDeadRunRequests ×2), doors 1 (recall 9705), reader 1 (attachFlowSteps 14833) A one-field slot built in the root (attach(surface), get()), written only by attachAutomation. ApprovalRuns gets the slot; judge, recovery and reader get the read-only thunk () => ApprovalResumeSurface | undefined, the same shape six collaborators already have (workCalendar, ownershipQueues, …). Each consumer keeps its own typeof x?.getRun !== 'function' test, so the move is textual. recall's one site becomes runs.cancelRun(runId, reason). Narrower typing is possible per module: judge uses getRun, suspensionOf, cancelRun, getActionDescriptor, getFlow, getRunFlow, getFlowSlot(s), flowSlotKey; recovery uses hasSuspendedRun, getRun, inspectConsumedSuspension, suspensionOf; reader uses getFlow.
    tenancyPosture 3 readers in 3 modules (actors 3582, directory 3280, display 13360) Already a thunk. attachTenancyPosture has 0 callers anywhere in the repo (grep over ts/tsx/md/mdx). Either keep it and use the same slot pattern, or the maintainer rules it removable and the constructor thunk is passed to the three modules directly.
    fieldVisibility reader 1 (freeTextMayMatchSnapshot 13695) Display owns the slot. Move freeTextMayMatchSnapshot (21 lines, one caller: buildRequestWhere) into display so it has a single reader module, or expose display.fieldVisibility().
    i18nServiceSource doors 1 (userFacingRefusal 3632), display 1 (readerLabels 14407) Immutable thunk; inject into both. Not state.
    recordOrgResolver judge 2 (7554, 7560), doors 1 (7787) Build once in the root and inject the same instance into the mirror and opening, so its per-object memo stays single.
    engine, logger, clock all modules (165 / 118 / 24 sites) One immutable { engine, clock, logger } object passed to every constructor.

    The five mutable fields in 1a are not hot spots: each has one owner and no outside reader, except
    sweepClockScheduled, whose writer is a public method the plugin calls and whose only reader is
    judgeOpening; it lives with the opening check and the facade's noteSweepClockScheduled()
    delegates to it.

    3b. Durable state written by several modules (the real shared state)

    Object Write sites Writers by module
    sys_approval_request 16 updates + 1 insert, in 15 methods doors 7+1 (openNodeRequestBody 8161 insert; decideNode 8816, 8846; recall 9661; sendBack 10294, 10347; reassign 10682; escalateRequest 12743), judge 5 (6536, 6661, 6865, 6987, 7208), recovery 3 (10031, 12514, 12644), runs 1 (11801)
    sys_approval_action 20 inserts, every row built by actionRow doors 15, judge 3 (6722, 7213, 7264), recovery 2 (10021, 12632)
    sys_approval_approver 2 deletes + 2 inserts reader only (syncApproverIndex, rebuildApproverIndex); 11 syncApproverIndex call sites from doors 8, recovery 2, judge 1
    sys_approval_token 1 insert, 1 update doors/tokens only
    subject record (status field) 1 update (5735) judge only (mirrorStatusField, 7 callers in 3 modules)

    By column, the request row splits into two groups that do not follow module lines:

    • slate and status (status, pending_approvers, pending_approver_labels, completed_at,
      cancel_reason): 10 sites in 8 methods across judge (voidRefusedOpening), doors
      (decideNode ×2, recall, sendBack ×2, reassign, escalateRequest) and recovery
      (cancelForDeletedRecord, abandonForDeadRun). All eight, and the inserting
      openNodeRequestBody, then call syncApproverIndex.
    • node_config_json (run-read marks, abandoned mark, later-step note, strand journal, decision
      outputs): keepRunsRead, abandonApproval, noteLaterStepNotOpened,
      journalStrandedContinuation, endApprovalOfDeletedRecord, plus conditional spreads in
      decideNode (8816, 8846) and reassign (10682): 8 sites in 4 modules (judge 3, doors 3, runs 1,
      recovery 1), each a read-modify-write of one JSON column. unjudged_since is written at 3 sites
      in 2 modules (clearMarks 6865; decideNode 8848, sendBack 10297).

    Proposal: the move PRs leave these writes where they are (each module keeps calling engine.update).
    Giving the row one owner (RequestStore.writeSlate(row, patch) that also syncs the index, and
    patchNodeConfig(id, fn)) is a behaviour change with its own concurrency questions and belongs in a
    later card. Until then no module can truthfully be said to own the request row.

    3c. Cycles

    Measured on the 8-module cut and on the 20-unit PR order: 0 mutual module pairs, 0 forward call
    sites
    in topological order. Four placements are what keep it acyclic; a cut by method theme would
    create each of these cycles:

    1. namesNoAccount → reassignTargetRefusal → expandPositionUsers: reassignTargetRefusal (10839)
      sits among the reassign code but must live in the directory, or directory ↔ doors is a cycle.
    2. resumeRecordedOutcome → journalStrandedContinuation and continueRestoredRun → resumeRecordedOutcome: journalStrandedContinuation (11790) and expectedPauseNode (12056) sit
      among the recovery code but must live in runs, or runs ↔ recovery is a cycle.
    3. cancelForDeletedRecord → endApprovalsOfDeletedRecord and reconcileMarkedApprovals → endApprovalOfDeletedRecord: cancelForDeletedRecord (9971) goes to recovery, so doors and
      recovery stay independent siblings.
    4. loadPendingRow (3448) and assertLatestForRun (10555) go to the reader; escalateRequest → decideAndResume and redeemActionToken → decide put escalation and tokens above decisions.

    4. Construction order and lifecycle

    Constructor-only injection is enough; no setter injection between modules is needed.

    core        = { engine, clock, logger }
    automation  = slot(opts.automation); tenancy = slot(opts.tenancyPosture); fieldVis = slot(opts.fieldVisibility)
    recordOrg   = createRecordOrganizationResolver(engine)
    actors      = new ApprovalActors(core, { tenancy, workCalendar })
    holders     = new ApproverHolders(core, { ownershipQueues })
    resolver    = new ApproverResolver(core, { tenancy, holders })
    runs        = new ApprovalRuns(core, { automation })
    display     = new ApprovalDisplay(core, { fieldVis, objectReadAdmission, i18nServiceSource, positionLabelSource, tenancy })
    notifier    = new ApprovalNotifier(core, { messaging, publicBaseUrl, getConsoleUrl, display })
    visibility  = new ApprovalVisibility(core, { recordReaderVisibleObjects, actors })       // builds pendingApproverReads from actors
    reader      = new ApprovalRequestReader(core, { automation, actors, display, runs, visibility })
    mirror      = new StatusMirror(core, { recordOrg, holders, display, notifier })
    judge       = new ApprovalJudge(core, { automation, mirror, runs, holders, display, notifier, visibility })
    recovery    = new ApprovalRecovery(core, { automation, runs, reader, visibility, mirror, judge, display })
    opening     = new ApprovalOpening(core, { recordOrg, actors, holders, resolver, runs, display, notifier, visibility, mirror, judge })
    decisions   = new ApprovalDecisions(core, { messageTranslator, i18nServiceSource, actors, holders, resolver, runs, display, notifier, visibility, reader, mirror, judge })
    tokens      = new ApprovalTokens(core, { reader, notifier, decisions })
    escalation  = new ApprovalEscalation(core, { actors, holders, display, notifier, visibility, decisions })
    SLOT_LABELS.set(this, …display.slotLabels);  REQUEST_VISIBILITY.set(this, …actors + visibility)
    

    Lifecycle:

    • The service has no lifecycle of its own. No setInterval/setTimeout/subscription and no
      start/stop in approval-service.ts (grep: 0 hits). The plugin owns it: start() builds the
      service (approvals-plugin.ts:279), calls attachFieldVisibility (:372),
      attachObjectReadAdmission (:398), attachMessaging (:496), attachAutomation (:750);
      destroy() (:779) cancels the job and unbinds hooks. None of that changes.
    • Sweep job (ESCALATION_JOB_NAME, every ESCALATION_SCAN_INTERVAL_MS = 5 min, plus one boot
      run): approvals-plugin.ts:528–552 calls runEscalations, releaseDeadRunRequests,
      inspectStrandedRequests, reconcileMarkedApprovals under Promise.allSettled, then
      noteSweepClockScheduled (:557). After the split the four legs land in escalation (1) and
      recovery (3); they already run concurrently with each other and with user doors, so the split
      adds no new interleaving.
    • Cursors are per process, never persisted, and each belongs to one method ("a restart costs a
      repeat, never a miss", 3029–3033). A second ApprovalRecovery instance would restart the walk;
      the root must build exactly one.
    • Caches: platformAdminStandings and schemaReadVerdicts are WeakMaps keyed by the request
      context object, so they need no invalidation and no teardown; they hold a per-request memo only
      if every caller reaches the same module instance (one ApprovalActors, one visibility module).
      recordOrgResolver memoizes for the service's lifetime. PendingApproverReadGrantSource
      memoizes per context and engine write epoch.
    • Late attach: automation and messaging may be absent for the whole life of the service
      (no automation engine, no messaging service); every module must keep reading the slot at call
      time, never capture its value in a constructor.

    5. PR order

    "Moved" = class span plus exclusive prelude helpers. A move shows in a diff as −N/+N, so the
    changed-line count is about twice "moved", plus the rewiring of call sites (this.x( →
    this.<module>.x() listed as "sites". Only 6 of 20 units stay under 1,000 changed lines counted
    that way; 15 of 20 stay under 1,000 moved lines. Order is topological: each unit calls only units
    above it in the table (measured, 0 forward sites), so no unit ever calls back into the service.

    Two prerequisites, no method moves:

    • PR 0a — shared primitives. Move the 43 prelude declarations used by two or more units
      (1,163 lines: SYSTEM_CTX, uid, parseJson, actingUserId, recordedActor, stampOf,
      rowFromRequest, pendingSlateOf, RUN_STATUS_LIVENESS, ApprovalResumeSurface, …) into one or
      two leaf files; approval-service.ts re-exports the exported ones (besides ApprovalService, files
      in the package import 24 other names from it, e.g. SLA_ACTOR_ID, RUN_STATUS_LIVENESS,
      ApprovalNodeAutoOutcome; index.ts re-exports 12 types). Over 1,000 lines;
      split by topic (rows and actors / run liveness and strand types) if the limit is firm.
    • PR 0b — the query-options ratchet. scripts/query-options-erasure-baseline.json:38
      grandfathers 10 erasure sites for this file, and the ratchet fails on any file added to the
      baseline (check-query-options-erasure-ratchet.mjs:268–276). Moving a counted site into a new file
      goes red. Either type those sites first or get a ruling. My AST heuristic located 3 of them
      (lookupManager 5397, lookupActiveDelegation 5585, loadLiveRecord 7586); the other 7 are not
      located (eslint not runnable here).
    PR Unit → file Methods Moved Sites rewired (in/out) Depends on Existing tests on its paths Gap
    1 actors + SLA clock → approval-actors.ts 13 437 37 / 0 — approval-service.test.ts (calls resolveActor :6033, actingCaller :6103/:6355; spies isOverrideActor :5663), approval-actor-impersonation, admin-exemption-retired, agent-account-not-an-administrator.integration, platform-admin-approver-34218, approval-positions-name-authority, approval-tenant-positions-name-authority, exclude-submitter.integration, approval-service-sla-calendar-clock (SLA) No test names platformAdminStanding; the per-context memo is not pinned as far as grep shows. attachTenancyPosture: 0 tests, 0 callers
    2 holders → approver-holders.ts 18 848 22 / 0 — business-unit-hierarchy-complete.integration, business-unit-holders-complete.integration, member-tier-holders-complete.integration, team-position-holders-complete.integration (all four call privates directly), business-unit-member-org-screen, team-member-org-screen, team-approver-org-screen, manager-approver-org-screen, manager-org-screen-parity.contract (:239, :263), approver-cross-org.integration reassignTargetRefusal, readRowsToCompletion, dropMembersProvablyOutsideOrg never named; reached through doors only
    3 resolver → approver-resolver.ts 10 1,062 4 / 11 2 same four holders-complete files (resolveApproverSpec, resolveExpressionApprovers), ooo-delegation-organization, sys-approval-delegation-*.test, approver-org-scope, no-approver-note, submitter-exclusion-note, admin-rescue-named-slate.integration none found
    4 runs → approval-runs.ts 24 1,049 29 / 0 — approval-restart-resume, resume-failure-refusal, deleted-flow-decision-refusal, hook-refusal-after-decision, decision-strand-envelope, recall-strand-discriminator, subflow-hosted-approval-strand, batch-item-recall-resumes-batch, run-status-liveness, approval-revise (calls expectedPauseNode, flowPackageOf, requestFlowKey :894–897), approval-reconciler-37767.integration (overrides resumeRecordedOutcome :556) voidedRunChain, cancelRunsOfVoidedRequest, batchAboveItem, missingRunCapability never named in a test
    5 display → approval-display.ts 27 953 48 / 0 — approval-list-display-labels.integration, reader-locale-display-labels.integration, reader-locale-labels(-data-door), display-label-backfill.integration, implicit-reference-target-lookup + lookup-field-reference-carrier + payload-display-target-exposure (call resolveLookupFields / enrichRows directly), lookup-target-title-reader-fls.integration, lookup-target-title-row-access.integration, approval-payload-masked-field, approval-payload-redaction, actor-lookups-hold-ids.integration localizeActionRows: no direct test call (reached via listActions and the plugin middleware; not verified)
    6 notifier → approval-notifier.ts 5 314 20 / 2 5 approval-notification-body.integration, approval-notification-keyed-text.integration, approval-requested-notification.integration, approval-requested-slack-dm.integration, approval-email-notification.integration, approval-decision-outcome-notification.integration, notification-subject-title-per-recipient.integration, remind-notified-per-person.integration actionLinkUrl: 0 tests, 0 callers
    7 visibility + approver index → approval-visibility.ts 14 719 24 / 6 1 approval-service.test.ts :5654–5685 (spies participantProbes, isOverrideActor, servesAnyRequest; calls visibleRequestIds), request-read-gate.integration, request-child-read-gate.integration, request-read-waiting-on-caller.integration, record-reader-visibility, record-reader-opt-in.integration, pending-approver-read-grant.integration, sys-approval-request-viewer.conformance syncApproverIndex never named in a test
    8 reader → approval-request-reader.ts 19 1,065 20 / 31 1, 4, 5, 7 approval-service.test.ts (getRequest ×81, listRequests ×43, listActions ×29, countRequests ×14), record-lock-read.integration (getRecordLock ×38, getRecordLocks ×21), approval-free-text-scope, approval-inbox-search-display-text.integration, flow-route.integration, sys-approval-request-attached-on-read attachDecisionProgress, attachFlowRoute never named
    9 status mirror → status-mirror.ts 10 569 14 / 3 2, 5, 6 status-mirror-cascade / -envelope / -declared-values / -abandoned-closed-value / -closing-field-refusal (.integration), approval-mirror-unfinished-readings, save-notice-approval-round-trip.integration none of its 10 methods is named in a test; all coverage is through doors
    10 run reading → approval-run-reading.ts 7 1,061 (626 + 435 prelude) 5 / 0 — approval-outcome-when-over-37767.integration, approval-hold-37767.integration, request-root-run.integration, later-step-original-submitter.integration the RunsRead prelude helpers (runsReadAfter, keptAsEnded, …) have no unit test; not verified whether another file covers them
    11 verdict → approval-judge.ts 9 595 19 / 13 2, 4, 5, 6, 9, 10 approval-hold-37767.integration and approval-reconciler-37767.integration (both replace judgeApprovalAfterDoor on the instance, :203–205 and :264–266), approval-closed-states-37766.integration, approval-outcome-when-over-37767.integration only judgeApprovalAfterDoor is named in any test
    12 opening check → same file or approval-opening-gate.ts 6 246 3 / 3 4, 5, 7 approval-opening-check.test, approval-opening-check-37766.integration, approval-opening-refusal.test, 6 files calling noteSweepClockScheduled none found
    13 recovery: strands → approval-recovery.ts 3 1,078 (747 + 331 prelude) 0 / 6 4, 8, 11 stranded-request-inspection (inspectStrandedRequests ×43, cursor :854), stranded-run-repairability, restored-approval-continuation (continueRestoredRun ×26; calls resolveRecordedContinuation :556–583), stranded-resubmit-second-door (:361, :379) none found
    14 recovery: sweeps and deleted records → same file 7 580 0 / 11 4, 5, 7, 9, 11 approval-reconciler-37767.integration (reconcileMarkedApprovals ×98, cursor and limit :484–529), approval-service.test.ts (releaseDeadRunRequests ×13), record-delete-cancel.integration, action-locale-data-door.integration cancelForDeletedRecord: 4 direct calls in 2 files; its hook path (lifecycle-hooks.ts) not verified
    15 opening → approval-opening.ts 6 957 0 / 31 1–7, 9–12 51 files call openNodeRequest (435 calls): approval-service.test.ts ×294, approval-node, approval-node-degradation, team-member-org-screen, team-approver-org-screen, exclude-submitter.integration, admin-rescue-named-slate.integration, approval-snapshot-credential-mask none found
    16 decide → approval-decisions.ts 7 714 3 / 25 1–9, 11 approval-service.test.ts (decideNode ×126, decide ×27), approval-override-audit, approval-actor-impersonation, approval-reject-wording-35021, decision-attachments-uploaded-by-caller.integration, platform-admin-approver-34218 none found
    17 recall, send back, resubmit → same file 4 572 0 / 50 1, 4–9, 11 approval-revise (sendBack ×26, resubmit ×18, recall ×9), recall-refusal-user-copy (×13), recall-strand-discriminator, batch-item-recall-resumes-batch, restored-approval-continuation none found
    18 reassign, remind, request info, comment → same file 6 462 0 / 33 1, 2, 5–8, 16 approval-service.test.ts (reassign ×39, remind ×14, comment ×14, requestInfo ×7), exclude-submitter.integration, approval-override-audit, reminder-action-link-at-rest.integration, actor-lookups-hold-ids.integration requestInfo is the thinnest: 12 calls in 6 files
    19 tokens → approval-tokens.ts 6 269 0 / 5 6, 8, 16 action-page-member.integration (issueActionTokens ×26, handleActionPage ×25), approval-token-internal-hash.integration, sys-approval-token-generic-door.integration, subject-title-reader-fls.integration none found
    20 escalation → approval-escalation.ts 2 251 0 / 11 1, 2, 5–7, 16 approval-service-sla-calendar-clock (runEscalations ×17), approval-service.test.ts (×18), platform-admin-approver-34218, plugin-shutdown-cancels-escalation-job none found

    Test counts are regex counts of .method( in the 142 *.test.ts files of the package (95 of them
    name ApprovalService; 53,630 test lines; approval-service.test.ts alone is 7,406). They show
    which files exercise a path, not line coverage. 114 of the 165 private methods are never named in
    any test file, so a regression in one shows up only as a failing door test.

    After PR 20 the facade should be the constructor, two WeakMap registrations and 38 delegations;
    my estimate is 600–800 lines (not measured).

    Each move PR also has to update, in the same PR:

    • Source-keyed pins that name this file and a method.
      approver-address-readers.test.ts (READERS :90–101 and SLOT_SITES keys approval-service.ts · <method> · <text>; 21 references) for PRs 1, 3, 5, 7, 8, 11, 16, 17, 18, 19;
      packages/core/src/security/second-object-read-exposure.pin.test.ts:182–187 (file path,
      servesPayloadDisplayTarget, and the literal this.servesPayloadDisplayTarget() for PR 5;
      text-field-html-outlets.pin.test.ts:75 (census of files touching HTML) for PR 19;
      scripts/adr-anchors/packages__plugins__plugin-approvals__src__approval-service.ts.json
      (ADR-0157 and ADR-0042 must stay referenced in the anchored file; the invariant text names
      ApprovalService.slaDeadline) for PRs 1 and 20.
    • Tests that reach a private member through the instance. At least 23 private methods in 15
      test files, about 47 sites (regex): 9 instance overrides, 3 vi.spyOn, the rest direct calls.
    • Prose anchors approval-service.ts#<method>: 20 in
      docs/qa/platform-checklist/areas/approvals.json, 3 in packages/spec/liveness/*.json. Whether a
      gate validates them was not verified.

    6. Risks, and what contradicts the premise

    1. State ownership does not determine the cut (contradicts the premise as stated). 5 mutable
      fields, 10 sites, no field shared between modules. The scaffolding risk in this class is method
      coupling: 209 cross-module call sites over 74 methods. A facade-with-host form would be worse
      here than on engine.ts. The state-owning form works because the graph is a DAG, and only if PRs
      land in topological order.
    2. "A few narrow dependencies" holds for six modules and fails for the doors. actors,
      directory, runs, display have none; reader 3; judge 4; recovery 4. The door units need 6 modules
      through 54 methods at 152 sites (recall/sendBack/resubmit alone: 50 sites). That is the
      honest shape of an orchestration layer; narrowing it would mean redesigning the lower modules'
      interfaces, which is not a move.
    3. The PR size target is not reachable per cluster. Clusters are 437–3,237 moved lines; 44% of
      the class is comments that must travel with the code. Counting both sides of a move, 6 of 20
      units fit in 1,000 changed lines; counting moved lines, 15 of 20. The five over are PRs 3, 4, 8,
      10, 13 (1,049–1,078 each) and PR 0a (1,163).
    4. The durable row has no single owner and the split will not give it one (3b): 17 write sites
      to sys_approval_request in 4 modules, 8 of them read-modify-write on node_config_json.
    5. Test seams silently vanish. (svc as any).judgeApprovalAfterDoor = …
      (approval-hold-37767.integration.test.ts:203, approval-reconciler-37767.integration.test.ts:264),
      (svc as any).organizationAdministrators = … (reconciler :395, :551;
      status-mirror-closing-field-refusal :185), (svc as any).resumeRecordedOutcome = … (reconciler
      :556) and the three vi.spyOn(svc as any, …) in approval-service.test.ts :5655–5685 intercept
      internal calls. After a move the assignment still succeeds and intercepts nothing, so a test can
      keep passing for the wrong reason. Each must be re-pointed at the owning module in the PR that
      moves the method, and that PR should show the test failing when the seam is removed.
    6. Gates keyed on this file path (section 5 list) plus the query-options ratchet, which refuses
      new baseline files outright (PR 0b).
    7. Late-bound slots must be read at call time. A module that captures automation or
      messaging in its constructor would see undefined forever, because the plugin attaches both
      after constructing the service. 36 test files call attachAutomation after construction, so
      this would fail loudly, but only for paths those tests reach.
    8. Log strings and doc links. Three log lines name ApprovalService.resolveLookupFields /
      ApprovalService.enrichRows (13059, 13091, 13139) and
      lookup-field-reference-carrier.test.ts:78 asserts one; keep the strings verbatim. The file has
      390 {@link …} tags; those pointing at moved members will dangle (no gate found; not verified).
    9. Two public methods have no caller and no test: attachTenancyPosture, actionLinkUrl
      (grep over ts/tsx/md/mdx). They are public on an exported class, so they stay as delegations
      unless the maintainer rules otherwise. decideNode, openNodeRequest, issueActionTokens and 19
      other public methods are outside IApprovalService (16 members) but are called by the plugin,
      approval-node.ts, lifecycle-hooks.ts, plugin-sharing, service-storage or tests; all 38 public
      methods must remain.
    10. Not verified: nothing was executed (no node_modules), so "pure move keeps tests green" is
      an inference from the AST, not a result. Churn on this file and overlap with open PRs could not
      be measured (shallow clone); a 15k-line file split across 22 PRs will conflict with any
      concurrent change to it, so the window should be short and announced.
  8. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Seat note · 2026-12-01T12:59Z · acknowledging triage's notice 7311900364 (maintainer Warren, 2026-12-01T12:51Z, 「全部同意」 on 「拆分一类的优化任务排在其他 p1 p2 后面,除非严重影响车队效率,需要立刻分拆的」; skill text #38912). This split does not qualify for the exception.

  9. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2
    os-dev-report

    {
      "issue": 38665,
      "status": "done",
      "branch": "claude/issue-38665-approval-service-modules",
      "pr": "https://github.com/objectstack-ai/objectstack/pull/38921",
      "session": "session_01QSeKYnrQ7UMtHofKQVjcH2",
      "premise_still_valid": true,
      "summary": "PR 0b (draft #38921, Part of #38665, no method moves). The baseline row claimed 10 sites but the ratchet itself measured 4 on origin/main ac97540f75 ('erasure count fell 10 -> 4'); a single-rule ESLint pass with the grandfathering lifted located them: lookupManager 5397, lookupActiveDelegation 5585, loadLiveRecord 7586 (`} as any)` -> `} satisfies EngineQueryOptions)`) and the request-list query 14370 (`const findOpts: any` -> `const findOpts: EngineQueryOptions`). All four bags type-check unchanged against EngineQueryOptions, so no key mismatch and no behaviour question; the approval-service.ts row is removed from scripts/query-options-erasure-baseline.json (not lowered), so the file is now under pnpm lint's rule and later module files start at zero. Head 16186f6967, 3 commits.",
      "tests": "HEAD 16186f6967. `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2` under os-verify-lock: VERDICT command-exit 0; 'Test Files 142 passed (142)', 'Tests 2256 passed (2256)'. Typing-only, no tested behaviour changed: no new test, no ablation. Reverse verification: planted `direction: 'desc'` in the lookupManager bag and in the list query's orderBy -> `tsc --noEmit` exit 2 with two TS2353 at approval-service.ts(5398) and (14359) ('direction' does not exist in type ...); restored with `git restore --source=HEAD --staged --worktree`, porcelain empty. Published-output check: package built from base and head sources -> index.js/index.mjs/index.d.ts/index.d.mts byte-identical, only index.js.map/index.mjs.map differ (embedded source text); dist is in files[] so a patch changeset is owed (not skip-changeset).",
      "gates": "Local, on HEAD 16186f6967, exit captured before any pipe: `pnpm --filter @objectstack/plugin-approvals typecheck` exit 0 (VERDICT command-exit 0; check:test-typecheck OK); `pnpm check:query-options-erasure` exit 0 ('25 unswept non-test site(s) in 11 file(s), none new'; 'baseline key set verified against ac97540: no files added'); `npx eslint --no-inline-config packages/plugins/plugin-approvals/src/approval-service.ts` exit 0, 0 problems; dependency closure `pnpm turbo run build --filter='@objectstack/plugin-approvals^...' --concurrency=2` exit 0 (40/40 tasks). `node scripts/pm/dispatch-gates.mjs --ran FILE --repo objectstack-ai/objectstack` exit 0: 'Run reconciliation - 76 derived, 74 run, 2 NOT-MEASURED, 0 UNRUN'. The 74 all exit 0. NOT MEASURED: `pnpm check:dual-build-cjs-loads` exit 3 and `pnpm check:i18n` exit 3, both PREREQUISITE NOT MET (full workspace build absent; only the plugin-approvals closure was built) -> CI Lint & Repo Gates. check:platform-checklist not owed (no export renamed or deleted). PR check-runs: not yet read at report time (CI convergence is the seat's).",
      "mcp_calls": "0",
      "api_writes": "3 REST writes via the fleet-write relay: POST /repos/objectstack-ai/objectstack/pulls (draft) + POST /repos/objectstack-ai/objectstack/issues/38921/assignees (os-justin), one pr_create stroke, read-back 'identical'; POST /repos/objectstack-ai/objectstack/issues/38665/comments (this os-dev-report via post-stamped.mjs). Plus git push (not REST): the branch probe and 3 commit pushes.",
      "classifier_refusals": [],
      "open_questions": [],
      "security_findings": "none",
      "out_of_scope_findings": [
        "carrier: none - noted, not filed: scripts/query-options-erasure-baseline.json keeps a row for packages/runtime/src/http-dispatcher.ts at 1 although the ratchet reads it clean ('baselined file is clean/gone (was 1)'); headroom for one new erasure until `--update` drops it; outside this claim's file surface, left untouched; in PR Acceptance notes."
      ],
      "deviations": "(1) The order said 10 sites; there were 4 (ratchet measurement) - all typed, row removed. (2) One gate loop was auto-moved to the background by the harness at its 600s cap; stopped at once with TaskStop and re-run in foreground chunks, the two ratchets and check:comment-mask-corpus (213.8s) re-run singly - all exit 0. (3) Baseline row removed by hand rather than `--update`, because --update would also drop the http-dispatcher.ts row outside the file surface.",
      "files_changed": [
        "packages/plugins/plugin-approvals/src/approval-service.ts (+5/-5)",
        "scripts/query-options-erasure-baseline.json (-1)",
        ".changeset/38665-approval-query-options-typed.md (new, patch, @objectstack/plugin-approvals)"
      ],
      "line_budget": "21 changed lines (+15/-6) across 3 files, under the 3000 threshold and the ruling's ~1,000 per PR",
      "worktree": "objectstack-issue-38665 removed after the PR opened (node_modules deleted, git worktree remove exit 0); work lives on origin/claude/issue-38665-approval-service-modules @ 16186f6967"
    }
  10. objectstack-fleet commented on Dec 1, 2026

    @objectstack-fleet
    ContributorAuthor

    repo:objectstack@os-justin · os-justin · session_01QSeKYnrQ7UMtHofKQVjcH2

    Series ledger · 2026-12-01T14:10Z · PR 0b landed: PR #38921 merged (Part of #38665; L1 ACCEPT 7313079240). Four any erasures typed, the file's row is out of the query-options baseline, so later module files start at zero.

    Claim stood down here: pm:dispatched → pm:queue, assignee cleared, no dev in flight. By the maintainer's split ruling (relayed in 7311900364), this series ranks after the other p1/p2 cards; it is re-claimed for PR 0a (shared prelude primitives) when the seat's pick reaches it, and each later PR follows the step-1 comment's order. Nothing is lost: the ruling 7310432861, the map and the PR grouping on this card stand, and the branch name in the claim is reused per PR as each new claim states. Checked now: no open p1/p2 card names packages/plugins/plugin-approvals/src/approval-service.ts in its body (#38691 names automation files; #37770 names the spec contract approval-service.ts, not this file).

  11. added
    pm:queue
    and removed
    pm:dispatched
    on Dec 1, 2026
  12. objectstack-fleet commented on Dec 3, 2026

    @objectstack-fleet
    ContributorAuthor

    triage@hotlong · hotlong · session_01Q4EjjMnyLqJdzuktEmRPXH

    Triage: re-read 2026-12-03T14:33Z at os-bill's request on mailbox #39280. area:workflow · domain:server · Task · p2 · pm:queue, grade unchanged.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:workflowdomain:serverpm:queuepriority:p2

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions