72 KiB
Round 2: drafts C and D
Draft C, junior seat
-
Hardest places, ranked hardest first
-
src/session.ts:336-404(drain,dropSocket,linkLost,end),comeBackUpat:303, andsrc/session/link-life.ts:17-82(LinkLife's phase plus its predicates). Link state is a four-valuePhaseplus a separatestoppedflag. Seven predicates read it:isAttached,isUp,isOver,isStopped,retrying,awaitsNextLink,refusal. On top of that,OutgoingRequests.canCarry()adds!sock.destroyed. To followcomeBackUp's!this.link.retrying() || !this.link.isUp()(:319) ordrain's twocanCarry()checks, I had to hold every phase transition at once.linkLostis order-dependent ("Read first: adisconnectedlistener may close() the session"), so a synchronous listener re-enters the session in the middle of the method. The comments resolved each line on its own. The whole state machine never became clear to me; I would need to draw it. -
src/session/outgoing-requests.ts:83-150(request,carry,attempt). The three lanes, thefor(;;)retry loop,window.release()in afinally, andpending.wait()registered beforewrite()all interact. The loop-exit comment at:118("Until the link is dropped it admits the retry straight back onto the dead socket, and the loop spins") took three rereads. TheLanedoc comment at:20-26rescued the lanes. The retry exit stayed half-opaque. -
src/session/incoming-requests.ts:103-271(handle,route,onDelivery,onMessage, plusrefusedSegmentStatusat:28). This is where the domain costs the most.data_smroutes bycarriedAs.deliver_smmight be a receipt or a message, andonDeliveryfalls through toonMessage. The status codes come as a family:ESME_RX_P_APPN,ESME_RX_T_APPN,ESME_RTHROTTLED,ESME_RINVTLVVAL,ESME_RINVESMCLASS. ThearrivedOnsocket-identity check at:111is state compared across anawait. The flow reads cleanly, but I only knew why each status was right after reading README "Receiving in depth" and "Server in depth". -
src/messages/reassembly.ts:110-206(Reassembler.collect,trim) withsrc/messages/expiring-groups.ts:70-88(weigh).weigh()can evict the group currently being added to.trimthen countsparts.size - 1for that group, because the segment just added is refused and so is not lost. The contract is split across two classes:ExpiringGroups"enforces neither max nor timeout itself", so every owner must remember to callfullortakeExpired. It resolved after reading theExpiringGroupsdoc comments. Action at a distance, but it is marked. -
src/messages/dlr.ts:157-238(messageType,receiptStatus,dlrFromPdu). A four-valueMessageTypeis derived fromesm_classbits and then from a TLV. The TLV state and the body's state take precedence over each other in different ways.statusIdfalls back toUNKNOWN, and anunmarkedPDU without both an id and a state is not a receipt. The comments cite spec sections (5.3.2.26, Appendix B) that I cannot open. The READMEDlrfield table is what finally made the output shape make sense. -
src/client.ts:219-322(bindOn,initialAttempts,keepTrying). There are two routes intoReconnectLoop: the session's own, and a second one here that builds a freshSessionper attempt. There is closure state (lastErr,settled) and abort-listener bookkeeping. The comment at:241("close() must reach the loop's stop() before its first await") depends on howSession.closeis ordered inside, in another file. It stayed partly opaque. -
src/wire/pdu.ts:84-136(resolveShortMessage,resolveBody).CodingSourcedecides whethershort_messageormessage_payloadownsdata_coding. The cases are Buffer or string, empty or not, crossed with a string TLV being present. That is four or more branches returning objects that are almost the same. TheCodingSourcedoc comment helped, but only after I had readmessageOctets()inmessage-body.ts. -
src/defs/encodings.ts:151-190(messageClassOf,messageClassEncoding,encodingByDataCoding). Bit masking over GSM 03.38 coding groups, which I had no context for.messageClassEncodinghas a//comment and a/** */comment stacked on top of it that say different things. It stayed opaque, and I would trust the tests over my reading.
-
-
The unit I'd least want to modify:
Session.linkLost,dropSocketandend(src/session.ts:366-404) together withLinkLife. They are re-entered from the transport (close, error, unreadable), fromLinkTimers.onIdle, fromcomeBackUp, fromunbindandclose, and synchronously from application listeners (disconnected,close). The correctness depends on call order and on idempotence guards (drop()returning false,end()returning false). None of that is visible at any single call site. -
Expected hard, found easy:
- The codec in
defs/types.ts: 684 lines, but it is one pattern repeated (read, size, write, all returning Results). PduFramer.- The no-throw
Resultconvention, which is applied the same way everywhere. send-sms.ts:checkOptionsis a flat chain of guards.bind-direction.ts.- The folder layout. The AGENTS.md architecture map matched the files one to one, and a one-line purpose per file made cold navigation fast.
- The codec in
-
Prose debt
- What I needed and what it cost:
- The basic domain vocabulary: ESME vs SMSC/MC, bind types, what
deliver_smdoubles as,esm_class,data_coding, UDH vssar_*,registered_delivery. There is no glossary anywhere. I rebuilt it from README "Receiving in depth", "Delivery receipts" and "Bind direction", which cost a pass over a 764-line README with a lot of jumping. - The AGENTS section "GSM 7-bit is sent unpacked", which was essential for
segmentUnitsinmessage.ts. - Many code comments cite SMPP section numbers with no summary, so they are pointers I could not follow.
- The AGENTS decision index names choices, for example "Every request leaves through one
request(), in one of three lanes", whose reasoning is indocs/decisions.md, which was out of bounds. The titles alone helped a little. - I did not open any test.
- The basic domain vocabulary: ESME vs SMSC/MC, bind types, what
- Prose that added nothing the code didn't already say:
- The seven
declarelistener lines in each emitter class. OutgoingRequests.deliver("False means nothing was") andPendingRequests.deliver, both restating their code.- README's "Everything exported" table, which repeats
index.ts. - The AGENTS Conventions paragraph about test fixtures, for reading
src/. - The 0.4.0 defect table, which is history and says nothing about the current code's structure.
- The seven
- What I needed and what it cost:
-
Scores
- Navigation: 7. It sits at "predictable": the
session/,messages/,wire/,defs/split plus the per-file map in AGENTS.md got me from a symptom to a file on the first try. It stays below 8 because concatenation logic is split three ways (concat.ts,udh.ts,reassembly.ts), refusal statuses are split betweenpdu-refusal.tsandincoming-requests.ts, andudh.tsholdsConcatReference. - Locality: 6. It is between "honest middle" and "predictable". The hard parts are marked, but
IncomingRequestsholds theSessionand calls back into it (emit,sendReturn,close,sock,linkEnd).LinkLifeis shared bySessionandOutgoingRequests.ExpiringGroupsdepends on its owners to sweep.linkLostis re-entrant through listeners. - Shape: 6. Files are small and fan-out is bounded, but some names mislead:
- The GSM7 codec is called
ascii. ExpiringGroups<true>is used as a "spent" set.linkLost()means something different inSession,OutgoingRequestsandIncomingRequests.refusal()returns anErroronLinkLifeand anErrorNameonIncomingRequests.IdleWaiters.settle()wakes waiters whatever the count reads.
- The GSM7 codec is called
- Self-sufficiency: 5. Honest middle. The comments are dense and often state invariants. But for a reader with no SMPP background, the domain terms and bare spec citations mean the README has to stay open beside
incoming-requests.ts,dlr.tsandencodings.ts. - Overall: 6. Capped at self-sufficiency plus one. The layout and conventions are clearly cared for; what costs a junior is the lifecycle state machine and the unexplained domain.
- Intrinsic difficulty: high. It is an asynchronous protocol session with reconnect, drain, windowing and reassembly under hostile input. That gets no bonus in the scores above.
- Navigation: 7. It sits at "predictable": the
SCORES nav=7 loc=6 shape=6 self=5 overall=6
Draft C, mid seat
-
Hardest places, hardest first
-
src/session.ts:303-404:Session.comeBackUp/drain/dropSocket/linkLost/end. Whether the link is alive is held in four places:LinkLife.phase, which isbinding,up,downorendedLinkLife.stoppedReconnectLoop.haltedtransport.sock.destroyed
Order matters in several spots, and only comments say so.
linkLostreadsretrying()before the drop because adisconnectedlistener may callclose().comeBackUpchecks!retrying() || !isUp()afterbind(). That only makes sense once you find thatbind()reachessession.bound(), which callslink.open()out of sight.canCarry()(outgoing-requests.ts:58) asks bothlink.isUp()andsock.destroyed, and nothing explains why both are needed. The comments helped, but I had to trace the state by hand and it is still not fully clear to me. -
src/session/outgoing-requests.ts:83-150:OutgoingRequests.request/carry/attempt. The loop incarryhas three waits: the link budget, a window slot, and the response. The window slot is released in afinally, and a retry is allowed only whenattempt.retry && link.awaitsNextLink(). You need LinkLife's phase logic in your head (link-life.ts:71-82) to see why the loop ends. The comment "the loop spins" warns about it but does not explain it. The three lanes are well documented in theLanetype's comment (line 25). This resolved, slowly. -
src/wire/pdu.ts:84-136:resolveShortMessage/resolveBody. The code decides whethershort_messageormessage_payloadownsdata_coding. An empty Buffer meansmessage_payload, and a string body gets encoded and can overwritedata_coding, but only for one of the two sources. I had no domain context and read it three times. TheCodingSourcecomment helped, and the README "Building" bullets confirmed what it is meant to do. -
src/session/incoming-requests.ts:103-271:handle/route/onMessage/refusedSegmentStatus. Adata_smbecomessubmit_smordeliver_smdepending onlinkEnd(viastandsInFor). Adeliver_smthat is not a receipt falls through toonMessage. The status codes (ESME_RX_T_APPN,ESME_RTHROTTLED,ESME_RINVTLVVAL,ESME_RINVESMCLASS) are domain rules I cannot check. The class also calls back intoSessionthroughsock,emit,sendReturnandclose. The socket-identity check after theonRequestawait was clear once the comment was read. The status choices stayed opaque; I trusted README "Receiving in depth". -
src/messages/reassembly.ts:110-206withexpiring-groups.ts:70-88:Reassembler.collect/trimandExpiringGroups.weigh. The rules are split between the two classes:- ExpiringGroups enforces neither max nor timeout, and its owners must.
set()resets weight to zero.weigh()may evict the key you are weighing.trimworks outanswered = parts.size - 1for the current group.
The comments state each rule, but I needed all of them at once. This resolved.
-
src/messages/dlr-merger.ts:105-185:DlrMerger.collect/open/spend. There are two stores (groupsandspent), andspend()is the exit for four different situations: completion, expiry, reuse and eviction. The class docblock and theseveritycomment explain it. This resolved. -
src/defs/encodings.ts:162-190:messageClassEncoding/encodingByDataCoding. This is bit-level decoding ofdata_coding. The comments say which bits are which but not the table behind them. The code is short, but it stayed opaque without the GSM 03.38 spec. -
src/client.ts:220-322:bindOn/initialAttempts/keepTrying. A secondReconnectLoopis built outside the session forfromStart.bindOndepends onclose()reachingstop()before its first await, which the comment at line 241 states. There are also two abort listeners with different lifetimes. This resolved with effort.
I did not open any tests.
-
Unit I would least want to modify: the session lifecycle cluster,
Session.linkLost/dropSocket/end/comeBackUptogether withLinkLife. Every change there interacts with the reconnect loop's own stopped flag, with the drain'scanCarry()checks before and after it waits, and with whatever an event listener does duringemit. Tests would be the only way to know a change is safe. -
Expected hard, found easy:
PduFramer- the parse path in
pduToObj/parsePdu PendingRequestsSendWindowReconnectLoopbackoff- the listener guards that stop an application listener's throw or rejection from escaping (the no-throw rule)
- the
defs/tables defs/types.ts, which is 684 lines but repetitive and predictable
The rule that nothing throws makes every call site easy to read.
-
Prose debt
- Needed:
- README "Shutdown" and "Sends and the link", to understand the lanes and the drain.
- README "Receiving in depth", for which way a
data_smgoes and the throttle statuses. - The AGENTS architecture map, which is accurate and was the best way in.
- The AGENTS decision index lines, such as "Every message is answered on arrival" and "One owner decides whether a link can carry a request". They gave intent cheaply because each is one line.
- Cost to find: low, because the map and the index point to the right places. The code's references to spec sections (e.g. "SMPP 3.4 5.2.19") assume a document I do not have.
- One false claim: AGENTS says "
wireusesdefs,messagesuseswire", butwire/pdu.ts:10importsdecodeMessageandencodeBodyfrommessages/message.ts. So wire and messages depend on each other. - Told me nothing:
- the AGENTS 0.4.0 defect table (history, not needed to read the current code)
- most of the test-convention prose in AGENTS
- the README feature bullets
- one-line docstrings that restate the method name, such as
isStoppedandget sock
- Duplicated code:
quoted()is duplicated inbind-direction.tsandsession-options.ts.collectSentandcollectReceiptare near-copies.
- Needed:
-
Scores
- Navigation: 7 (Predictable). The AGENTS file map matches the layout, and the
session//messages//wire/grouping took me straight to the right file. It falls short of 9 because answering a request is split acrossserver.handleRequest,IncomingRequests.unhandled(ESME_RALYBND) andSession.refuse. - Locality: 6 (between 5 and 7). The collaborators are small and injected. But link liveness is spread over
LinkLife,ReconnectLoop.haltedandsock.destroyed, and three comments carry order rules: "Read first", "must reach stop() before its first await", and "the loop spins".IncomingRequestsalso reaches back intoSession. - Shape: 7 (Predictable). Fan-out at each level is bounded, and the
Sessionconstructor wires seven named collaborators. Some names mislead:- the GSM codec is called
ascii(encodings.ts:45) idlemeans three different things:IdleWaiters,ExpiringGroups.idle()and theLinkTimers.idletimer- the near-synonyms
stop,end,close,release,linkLostanddropSocketblur which one is final
- the GSM codec is called
- Self-sufficiency: 7 (Predictable). Almost every non-obvious branch carries a one-line reason, often with a spec section. The lanes, the drain and the refusal statuses still needed the README open beside the code.
- Overall: 6. It is capped by Locality. The lifecycle corners are marked, but they are not contained.
The problem is hard in itself: a protocol full of peer quirks, plus async lifecycle with reconnect and drain. That gets no bonus here.
- Navigation: 7 (Predictable). The AGENTS file map matches the layout, and the
SCORES nav=7 loc=6 shape=7 self=7 overall=6
Draft C, senior seat
-
Hardest places, ranked
src/session.ts:303-404, theSessionlifecycle:comeBackUp,drain,stop,dropSocket,linkLost,end. Whether the session is still alive is spread across three places:LinkLife's phase and its separatestoppedflag,ReconnectLoop.halted, andlink.end(). To follow any one of these methods I had to hold all three.comeBackUp:319tests!retrying() || !isUp(). That only makes sense once you knowisUp()got set as a side effect: theonConnectedcallback inclient.ts:bindcallssession.bound(), which callslink.open(). The ordering is load-bearing in several places.linkLost:379has to readretrying()before the drop.end()callsdropSocket(), which is also a guard.client.ts:241says "close() must reach the loop's stop() before its first await". The comments at the call sites marked each ordering rule. None of them explained why the whole thing is split this way. It stayed expensive to read.src/session/outgoing-requests.ts:83-121,request/carry, together withsrc/session/link-life.ts:34-186.LinkLifeexposes six overlapping predicates:isAttached,isUp,isStopped,retrying,awaitsNextLinkandrefusal. The lanes mix them.messagechecksrefusal() ?? isStopped().receiptskips both checks up front and only meetsrefusal()insidebudget().linkskips everything. The loop exits on!attempt.retry || !awaitsNextLink(). The comment about it spinning helped, but I had to walk the phase transitions by hand to convince myself. TheLanedoc comment resolved what each lane is for. It did not resolve what each lane actually checks.src/messages/expiring-groups.ts:18,ExpiringGroups, withsrc/messages/reassembly.ts:110-136, 187-206,Reassembler.collect/trim. The store says outright that it enforces neither itsmaxnor its timeout itself. The owner has to checkfull, calltakeExpired(), and letweigh()evict, andweigh()can evict the very group being written. Intrim,answered = size - 1for the current key, and the refused segment has already beensetinto the group. That is an invariant spread across two files. The doc comments state the contract honestly, so it was readable, just slow.src/wire/pdu.ts:84-136,resolveShortMessage/resolveBody. Deciding which field is allowed to setdata_codinggoes throughCodingSource. An empty Buffershort_messagecounts as sourcemessage_payload. A string body rewritesdata_coding, but only when it encodes to something non-empty. Three branches return three different param shapes. TheCodingSourcedoc comment is the key, and I only understood it after going back tomessage-body.ts.src/messages/dlr-merger.ts:68-184,DlrMerger(open,spend,dropOldest). It keeps a secondExpiringGroups<true>as a tombstone set.spend()is called on completion, on expiry, on eviction and on id reuse, and each time it deletes and re-inserts the tombstone. The class doc comment explains why ("merged at most once"). I still had to trace which paths end up inspendto be sure a straggler receipt is ignored.src/client.ts:219-322,bindOn/initialAttempts/keepTrying. ForfromStartthere are twoReconnectLoops: one in the client and one inside each session.lastErrlives in a closure, andsettleis idempotent.bindOnremoves its abort listener on failure but deliberately keeps it after success, so a later abort closes a bound session. Only README ("That signal also closes the session once bound") told me that was intended rather than a leak.src/defs/encodings.ts:483-514,messageClassEncoding/encodingByDataCoding. Bit masks over coding groups I had no background in. There is an orphan//comment sitting above a/** */doc comment. The GSM 03.38 codec is namedascii, and "fall back to ASCII" (line 504) actually means GSM7. That misled me until I checked theencodingsmap.src/session/incoming-requests.ts:103-153,handle/route.arrivedOnis captured before the application'sonRequestawait and compared afterwards. Theunbindcase closes the session withAbortSignal.abort()from inside a handler that the dispatch itself is running. Both have comments, and both still needed a second read to be sure nothing re-enters.
-
Least want to modify: the
Sessionlifecycle cluster (session.ts:303-404plusLinkLife). A change to when the link counts as up, stopped or ended touchesLinkLife,ReconnectLoop,OutgoingRequests.canCarry,client.tsbindOn/bind, andIncomingRequests'sockcheck. Nothing in the types enforces the ordering, so it only lives in the comments. -
Expected hard, found easy:
PduFramer; the wire types indefs/types.ts(long but uniform); TLV read and write, including repeatable tags and keying by id; the reconnect backoff;bind-direction.ts; theResultconvention;udh.tsconcatInfo;send-sms.tsvalidation, which is a flat checklist;PendingRequests;SendWindow. -
Prose debt.
-
Documentation I needed:
- README "Reconnect" section, to know the abort listener kept alive in
bindOnis intended. - AGENTS "GSM 7-bit is sent unpacked", to trust
segmentUnitsGSM7 153 vs UCS2 134. The one-line comment atmessage.ts:13is close to enough on its own. - README "Shutdown", to learn that
drain()returning{}when!canCarry()also skips waiting on handlers. The code says "nothing is on the wire", which does not mention handlers. - The charter's decision index points at
docs/decisions.md, which I was not allowed to open. For several decisions I had only the title and had to take the rest on trust.
- README "Reconnect" section, to know the abort listener kept alive in
-
Where the charter's map is wrong:
- It says
messagesuseswire. In factwire/pdu.tsimportsmessages/message.ts(decodeMessage,encodeBody). decodeSegmentslives inreassembly.tsbut is used bysms.ts.ConcatReference, a per-session counter, lives inudh.ts.
Each of these cost a wrong turn.
- It says
-
Prose that told me nothing new:
send()'s "Sends a request and resolves with the peer's response".LinkTimers' "Keeps a quiet connection honest".PduFramer's "Cuts a byte stream into whole PDUs".- The charter's test conventions, which are irrelevant to reading
src/. - Most of the decision-index lines, which restate README behaviour.
- The 0.4.0 defect table. It is useful history but did not help me read the current code.
-
Duplicated code:
collectSentandcollectReceiptare near-copies,quoted()exists twice, and theemit/captureRejectionSymbolguards are copied betweenSessionandSmppServer.
-
-
Scores. The problem is intrinsically hard (SMPP session state, reassembly under memory caps, receipt correlation), and that gets no bonus.
- Navigation 7: near the "predictable" anchor. The
session/,messages/,wire/,defs/split and the charter's file map took me from symptom to file first try. It is held below 8 by the misplaced units above and the false import-direction claim. - Locality 6: between the 5 and 7 anchors. Link lifecycle state is split across
LinkLife,ReconnectLoopandSession, with ordering rules marked only by comments.IncomingRequestsreaches back intosession.sock,boundAsandlinkEnd. - Shape 7: at "predictable". Fan-out per level is small and most names are honest. It is held there by
asciifor the GSM codec, "fall back to ASCII",udh.tsalso holding the reference counter, and six overlapping liveness predicates onLinkLife. - Self-sufficiency 7: at "predictable". Comments cite SMPP sections and state invariants beside the code. Two behaviours (the kept abort listener, the drain skipping handlers) needed README open beside the code.
- Overall 6: a cold senior would be productive within a week and would know to fear the lifecycle cluster. The locality cost there is what holds it below 7.
- Navigation 7: near the "predictable" anchor. The
SCORES nav=7 loc=6 shape=7 self=7 overall=6
Draft C, architect seat
Comprehension panel report: Architect, inherited (draft-c, @larvit/smpp)
I opened no test file. I read every non-test source file under src/. I read defs/types.ts and defs/tlvs.ts by outline plus key sections, and commands.ts, constants.ts and errors.ts only as far as their outline.
1. Map from README and file tree only, verbatim
- Root, the entry points:
client.tshasclient();server.tshasserver()andSmppServer;session.tshasSession, the orchestrator;index.tsis the public surface. - Root, cross-cutting:
result.ts(Result),log.ts(SmppLog),error-from.ts(unknown → Error).defaults.tsI expect to hold session defaults, and I am unsure how it relates tosession/session-options.ts. defs/: the SMPP spec tables: commands, TLVs, errors, constants, encodings, wire types.wire/: the codec.pdu.tsis pduToObj/objToPdu,pdu-framer.tsturns a byte stream into PDUs,pdu-refusal.tsis PduRefusedError.session/: what a Session is made of: transport, keepalive timers, reconnect, send window, pending-request correlation, incoming and outgoing requests, bind direction, options.running-handlers.tsI guess countsonSmspromises (README: "1000 handlers", "close() waits for your handlers").idle-waiters.tsandlink-life.tsare unclear from their names.messages/: message-level logic: encode/split, UDH, concatenation, DLR parse and merge, reassembly, the inboundSmshandle, sendSms composition, ids, uuid.- Names that do not give their purpose:
retained-pdu.ts,expiring-groups.ts,unanswered-error.ts(why in messages/?),uuid.ts(why in messages/?),pdu-transport.ts(session, not wire?),link-life.ts. - README promises I expect to find: a drain that waits for handlers, then for requests.
smppTimesomewhere in messages. No store (goal 9 says it has not shipped).
2. Where the map was wrong, and what each correction cost
| Map claim | Reality | Cost |
|---|---|---|
wire/ is the codec |
The per-field codec is defs/types.ts (684 lines of read/size/write) and defs/tlvs.ts (parseTlvs/writeTlvs). wire/pdu.ts:10 imports encodeBody and decodeMessage from messages/message.ts, so wire depends on messages. AGENTS.md says the reverse ("messages uses wire"). |
High. I had to reopen defs/, and the documented dependency direction is false. |
defaults.ts holds session defaults |
It holds every option's default plus bounds (limits that are not options). |
Low. |
session-options.ts holds option types |
It also holds SessionEvents, OnRequest, SmsHandler, and the validation for client and server options (CheckableOptions includes authenticate, connectTimeout, fromStart). |
Medium. |
| One reconnect concept | client.ts:278 keepTrying runs a second, separate ReconnectLoop for fromStart. ReconnectOptions (session: connect/onConnected) and the client's reconnect (ReconnectTuning) are two shapes under one name. |
Medium. |
running-handlers.ts counts onSms promises |
Correct. | None. |
messages/ is message logic |
It is a 14-file grab-bag with 5 themes: codec helpers, receipts, bounded stores, sending, ids/errors. | Medium. |
3. Fan-out, level by level
- L0,
src/: 8 files and 4 directories. It mixes 4 entry points with 4 utilities. Acceptable. - L1:
session/: 12 files.Sessioncomposes 7 collaborators plusConcatReference.messages/: 14 files across about 5 themes.wire/: 3 files.defs/: 7 files.
- L2, inside
session.ts: about 25 members. The lifecycle cluster alone (drain/stop/dropSocket/linkLost/end) touches 6 collaborators. - Worst level:
- By count and cohesion,
messages/(14 files). - By reading cost,
session/.link-life.tshas 7 near-synonymous predicates,OutgoingRequests.canCarryis an 8th, andReconnectLoop.isStoppeda 9th.
- By count and cohesion,
4. Names
Names that mislead
encodings.ts:45asciiis the GSM 03.38 codec. The comment atencodings.ts:180says "alphabets with no codec fall back to ASCII", but the code returns'GSM7'.ExpiringGroupsenforces neither the cap nor the expiry; its own doc comment says so atexpiring-groups.ts:18.defs/is described as "spec tables" but holds most of the codec.udh.tsholds the outboundConcatReferencecounter next to UDH parsing.messages/unanswered-error.tsis used bysession/outgoing-requests.ts.
Concepts with two names
sendSmsandsubmitSmsname the same action.- GSM7 and
asciiname the same codec. - "stopped" is held twice:
LinkLife.stoppedandReconnectLoop.halted, both set bySession.stop(). smsId,message_idandbaserefer to the same id.
One name over several concepts
idle: theLinkTimersidle timeout,IdleWaiters(a count falling to zero), andExpiringGroups.idle()(stop the sweeper).release:SendWindow.releasefrees a slot,RunningHandlers.releasewakes the drain,LinkLife.releasesettles link waiters.settle: used everywhere.reconnect: the session'sReconnectOptionsand the client'sReconnectTuning.checkReconnectvalidates only the client shape.
5. What I would restructure, ranked
- Move the codec into
wire/:defs/types.tsread/write,defs/tlvs.tsparse/write, andencodeBody/decodeMessage. This makes the documented dependency direction true. - Split
messages/into inbound, outbound and receipts. Moveunanswered-errortosession/, and moveuuidout. - Collapse the link predicates in
LinkLifeinto one query per lane (for exampleadmits(lane)), absorbingcanCarryandReconnectLoop.halted. - Split
session-options.ts: event and hook types in one place, client/server option checking in another. - Renames:
ascii→gsm7,ExpiringGroups→ something that says it only holds keyed deadlines, and distinct names for theidle,releaseandsettleoverloads.
What the structure gets right
Sessionis split into collaborators, each with a one-line owner doc.Resultis used uniformly.- Comments record why at the call site (for example
link-life.ts:173,reassembly.ts:162,dlr-merger.ts:23). - The AGENTS.md file map is accurate at file level.
- Every store is bounded and says so.
6. The 3am question
Time and route, cold: about 5–10 minutes. README "Shutdown" → session.ts:267 close() → session.ts:336 drain() → incoming.idle → session/running-handlers.ts:54 RunningHandlers.run and :89 idle.
The premise does not match this code. sms.sendResp() does not exist here; a grep for it finds nothing. Every message is answered on arrival (incoming-requests.ts:233), and the drain waits for the promise the onSms handler returned to settle, not for any answer.
Likely cause: a handler whose promise has not settled. The typical case is a handler awaiting sms.sendDlr() while the peer never answers the deliver_sm: responseTimeout (30 s) is longer than shutdownTimeout (5 s). The second place to look is the phase after it: outgoing.idle → SendWindow.unfinished() (send-window.ts:82), which counts queued waiters as well as requests on the wire.
Adjacent hazard (plausible, not confirmed): session.ts:340 returns before waiting for handlers when the link cannot carry requests. A close() during a reconnect gap therefore skips the handler wait, which README step 2 says always happens. A slow onRequest hook is never counted by the drain either.
Where it rots first: the lifecycle cluster in session.ts:336-404. Its correctness depends on call order: linkLost reads retrying() before dropSocket, and end calls stop and dropSocket before the phase check. Every new link state adds a predicate to LinkLife.
Where the next two features land:
- Goal 9's store cuts across
DlrMerger,ReassemblerandExpiringGroupsinmessages/, andRunningHandlersinsession/. It has no single seam today. - A per-PDU rate limit (goal 7) becomes a fourth wait in the
OutgoingRequests.carryloop (outgoing-requests.ts:100).
7. Hardest places, ranked
src/session.ts:336-404,drain/stop/dropSocket/linkLost/end: order dependence, and the early return that skips handlers.src/session/link-life.ts:50-82, theLinkLifepredicates: phase × stopped × reconnects expressed as 7 booleans.src/session/outgoing-requests.ts:83-121,request/carry: 3 lanes and a retry loop whose own comment warns that it spins.src/session/incoming-requests.ts:103-128,IncomingRequests.handle: holds a Session back-reference, awaitsonRequest, then re-checks the socket. The session is reachable by two routes: the object and thesendReceiptclosure.src/messages/reassembly.ts:110-206,Reassembler.collect/trim: eviction by weight, with theparts - 1accounting for a segment that was refused.src/messages/dlr-merger.ts:150-173,DlrMerger.open/spend: a secondExpiringGroupsused as a set of spent ids.src/wire/pdu.ts:84-136,resolveShortMessage/resolveBody: which source'sdata_codingwins.src/client.ts:250-322,keepTrying/initialAttempts: a second reconnect mechanism.
The unit I would least want to modify: the Session lifecycle cluster, session.ts:366-404 (dropSocket/linkLost/end).
8. Scores
The problem is intrinsically hard: SMPP session lifecycle with reconnect, drain, send window and bounded reassembly. That earns no bonus.
- Navigation 7. Sits at "Predictable": the AGENTS.md map and file names took me from symptom to
RunningHandlersin minutes. It is held below 8 because the codec is split betweendefs/andwire/, andmessages/is a grab-bag. - Locality 6. Between "Honest middle" and "Predictable". The collaborators are real. It is held there by
IncomingRequestsholding aSessionback-reference, by stopped/up state spread acrossLinkLife,ReconnectLoopandtransport.sock.destroyed, and by the order-dependentend/linkLost. - Shape 6. Between the anchors. It is held there by the 14-file
messages/, aLinkLifeAPI of 9 predicates, the wire→messages import that contradicts AGENTS.md, and names that lie (ascii,ExpiringGroups,idle/releaseoverloads). - Self-sufficiency 7. Sits at "Predictable": the invariants and whys are stated beside the code. It is held below 8 because the drain's early return at
session.ts:340contradicts the README's shutdown contract, and the file map's layering claim is false. - Overall 6. Capped at 7 by the lowest dimension plus one. It sits at 6 because the hardest code (the lifecycle and the link predicates) is exactly where the order dependence lives.
SCORES nav=7 loc=6 shape=6 self=7 overall=6
Draft D, junior seat
-
Hardest places, hardest first
-
src/handled-messages.ts:92HandledMessages.offer,:125run, andsrc/sms.ts:83createSms.offercreates an object whose own closure setshandled.answered.sendRespthen takes one of two paths depending onansweredAs(sms.ts:97).- After a handler fails,
runcallssms.sendResp({ status: retryStatus })(:133). For a multipart message,answeredOnArrival()returns anerrthere and nobody reads it. - I had to trace three files to see that this is intended: the segments were already answered, so there is nothing left to refuse. No comment at
:133says so. - Still opaque: what "settle" means here, compared with
IdleWaiters.settle.
-
src/session.ts:239-323, the shutdown verbs:unbind,close,drain,finish,linkLost,dropLink.- There are six near-synonyms, plus
LinkLife.stop/drop/endunderneath them.stop()gets called twice (indrainand again infinish). unbind's return line,sent.err && !closedOnUnbind ? … : drained, needed a truth table.- Re-entrancy: an inbound
unbind(incoming-requests.ts:149) callssession.close(), which callsincoming.drain()on the same object that is still mid-route. - Doc comments helped with each piece. The overall state machine was never written down in one place.
- There are six near-synonyms, plus
-
src/outgoing-requests.ts:120refusal()and:74request(), withsrc/link-life.ts:31LinkLife.LinkLifeexposes seven predicates (isAttached,isUp,isOver,isStopped,retrying,awaitsNextLink,refusal).- Callers mix them with
canCarry()(which also checkssock.destroyed).refusal()at:129readsisStopped() && canCarry(), and its comment ("the link's own refusal names the session closed instead") only made sense once I had held all four phases in my head. - Also surprising: the phase starts at
'up'before any bind. I had to hunt throughcomeBackUpto see that'binding'exists only on reconnect.
-
src/reassembly.ts:186Reassembler.trim, withsrc/expiring-groups.ts:70ExpiringGroups.weigh.ExpiringGroupsis a store whose rules its owners enforce:set()never evicts,weigh()does,fullis only advisory, andonSweepmust calltakeExpired().trimreweighs the whole group, may evict the group it is working on, and then computesanswered = parts.size - 1for that one.- The
:199comment explains the-1. It took several rereads to see whyopen()evicts by count andtrimby weight.
-
src/pdu.ts:84resolveShortMessageand:113resolveBody.CodingSourcedecides whethershort_messageormessage_payloadgets to setdata_coding. An empty-stringshort_messageflips it to'message_payload'.- I had to hold four cases at once: Buffer vs string, empty vs not, plus the TLV text. The type comment at
:74is accurate but dense. - I had no domain context for why a body could live in two places. The README's "Where the body is" resolved that.
-
src/client.ts:253initialAttempts,:276keepTrying,:218bindOn.- This is a second use of
ReconnectLoop, separate from the oneSessionowns. It builds a freshSessionper attempt, and alastErrclosure is shared across attempts. bindOncomes with an ordering warning: "close() must reach the loop's stop() before its first await". Checking that required readingSession.close→drain→reconnectLoop.stop().- It resolved once I saw that
fromStartis the only path into this code.
- This is a second use of
-
src/dlr-merger.ts:150open,:166spend.- There are two
ExpiringGroups, and the second one (spent) is a tombstone set.spenddeletes from both, evicts the oldest tombstone, then re-adds. - The class doc (
:62-67) explains the "merged once" rule. Without it this would have stayed opaque.
- There are two
-
src/defs/encodings.ts:162messageClassEncoding,:182encodingByDataCoding,:45ascii.- Bitmask rules come from a spec I have not read. The codec named
asciiis actually the GSM 03.38 table (GSM: ascii), which misled me at first. - I took the comments on trust; I could not check them.
- Bitmask rules come from a spec I have not read. The codec named
I opened no tests.
-
-
The unit I would least want to modify:
HandledMessagestogether withcreateSms(handled-messages.ts:92-140,sms.ts:83-157). The "answered" state lives in three places:answer.donein the closure,handled.answered, andansweredOnArrival. They are updated by callbacks across two files. Whether the peer gets exactly one response depends on all three agreeing, and a mistake silently double-answers or never answers a request. -
Expected hard, found easy:
- The wire codec.
defs/types.tsis long but repetitive, and every read and write checks its range the same way. PduFramerandPduTransport.send-sms.ts:checkOptionsis a flat, ordered pipeline.sms-id.ts,concat.ts,udh.ts: small files whose names tell the truth.- The "nothing throws" rule makes every call site look the same, so I stopped needing to think about control flow.
- The wire codec.
-
Prose debt.
- Needed:
- I needed domain background: what a DLR is,
esm_class,data_coding, UDH vssar_*, and whydata_smchanges meaning with direction. None of it is insrc/. - I found it in README.md sections "Receiving in depth", "Server in depth" and "Delivery receipts". That cost reading about 780 lines to extract about 60 useful ones.
- Comments cite SMPP section numbers (e.g. "5.3.2.26", "4.6.2") that a junior cannot resolve without the spec.
- The AGENTS.md architecture list was the most valuable single piece: one line per file, and accurate.
- I needed domain background: what a DLR is,
- Told me nothing:
- Comments that restate the code:
Session.send"Sends a request and resolves with the peer's response.",client()"Connects to an SMSC and binds.",LinkTimers.clearcontext, andbindCarries's doc, which mostly repeats its three lines. - The long AGENTS.md "Conventions" paragraph on test fixtures (irrelevant to reading
src/). - The defects table: it is history, not an explanation of the current code, though it did hint at domain pitfalls.
- Comments that restate the code:
- Needed:
-
Scores (the problem's own difficulty is high: a stateful protocol with reconnect, drain and reassembly, and it gets no bonus here):
- Navigation 7. Predictable: the AGENTS.md file map plus descriptive file names got me to the right file first try for almost every question. What holds it below 8: one symptom such as "why was this refused with ESME_RTHROTTLED" is spread across
incoming-requests.ts(retryStatus,refusedSegmentStatus),handled-messages.ts(refuses) andreassembly.ts(Refusal). - Locality 5. Honest middle: liveness state in
LinkLifeis read through seven predicates from three classes.generation()is captured in closures (incoming-requests.ts:106,:253),answeredis mutated through a callback, and ordering constraints are documented only in comments (client.ts:239,session.ts:349). - Shape 6. Between 5 and 7: classes are small and fan-out is bounded, but some names mislead. The GSM codec is called
ascii, and six-plus near-synonymous teardown verbs (stop/end/drop/finish/linkLost/dropLink/clear) mark distinctions I had to work out myself. - Self-sufficiency 5. Honest middle: the code comments give terse, accurate reasons, but the domain model a newcomer needs to read them lives only in README.md and the SMPP spec, so I kept the README open the whole time.
- Overall 5. Capped at 6 by locality; I land at 5 because both locality and self-sufficiency cost me rereads on the stateful session core. The codec and message layers alone would sit near 7.
- Navigation 7. Predictable: the AGENTS.md file map plus descriptive file names got me to the right file first try for almost every question. What holds it below 8: one symptom such as "why was this refused with ESME_RTHROTTLED" is spread across
SCORES nav=7 loc=5 shape=6 self=5 overall=5
Draft D, mid seat
-
Hardest places, ranked hardest first
src/session.ts:265-362:Session.drain/finish/linkLost/dropLink/comeBackUp, read together withsrc/link-life.ts:31-135(LinkLife).- One question, "can a request go out right now?", depends on four pieces of state:
LinkLife.phase(binding/down/ended/up),LinkLife.stopped,ReconnectLoop.halted, andOutgoingRequests.canCarry(). The last one islink.isUp() && !sock.destroyed. drain()callslink.stop(), then branches oncanCarry().finish()callsstop()again, thendropLink(), thenend().comeBackUpuses!this.link.retrying()to mean "close() landed during the rebind". Hereretrying()is being used as a stand-in for "not stopped", which the name hides.- I had to trace every caller by hand to be sure
closefires exactly once anddisconnectedis never followed bycloseon the same drop. The per-method doc comments helped. Nothing ties the whole state machine together in one place; this stayed the most expensive read.
- One question, "can a request go out right now?", depends on four pieces of state:
src/outgoing-requests.ts:262-351:OutgoingRequests.request/refusal/attempt.- A
for(;;)loop holds one link-wait budget (link.hold()returns a closure) plus a window slot, and retries only whenretryOnNextLink && awaitsNextLink(). refusalline 317 (pastDrain !== true && isStopped() && canCarry()) is a three-way condition. Its comment explains why the other branch exists, not this one.attemptregisterspending.waitbeforetransport.write, and checks abort twice (inrefusaland again inattempt). The comment at line 325 resolved the second check.- The
pastDrainflag reaches here fromIncomingRequeststhroughSession.incomingFor. It is action at a distance.
- A
src/pdu.ts:84-136:resolveShortMessage/resolveBody(plusreadParamsat 249).- The
CodingSourcereturn value decides whether an encodedmessage_payloadmay overwritedata_coding. Without the domain, I had to derive why an emptyshort_messagehandsdata_codingto the TLV. TheCodingSourcedoc comment half-resolves it. readParamspassesparamNumber(params.sm_length, 0)as the length to every field'sread. It only works becausesm_lengthprecedesshort_messagein wire order. That is an order dependence stated only as the general "parameter order is wire order" warning, not at the call.
- The
src/handled-messages.ts:359-423andsrc/expiring-groups.ts:442-554:HandledMessages.offer/run/refuses, andExpiringGroups.ExpiringGroups's contract is inverted: it "enforces neither max nor timeout itself", onlyweigh()evicts,onSweepmust calltakeExpired(), andtakeOldestgoes throughdelete(which stops the timer) whiletakeExpiredgoes throughremove. Each owner (Reassembler, DlrMerger, HandledMessages) re-implements the policy.- In
HandledMessages, theansweredflag is set by a closure threaded intocreateSms.runuses an identity check (running.get(key) !== handled) to detect thatclear/sweepgot there first.refuses()has hysteresis state (atBound) and callssweep()as a side effect. - The class doc comment resolved the intent. The mechanics took rereads.
src/incoming-requests.ts:105-260together withsrc/server.ts:542-567:IncomingRequests.handle/route/onMessage/offer, andhandleRequest.- Searching for where a bind is accepted, I found
IncomingRequests.unhandledanswering binds withESME_RALYBND. The real bind handling is in server.ts, injected asonRequest, so the "application hook" slot is also the server's own bind handler. - The charter's Decisions index says this ("composes the application's onRequest after its own bind handling"), but the reader gets there only after a wrong turn.
- Link generation is checked twice by different mechanisms: inline in
handle, and as alostLinkclosure inoffer. carriedAs/standsInForrewritesdata_smdepending onlinkEnd, a mutable public field set after construction (session.linkEnd = 'smsc'in server.ts:586).
- Searching for where a bind is accepted, I found
src/reassembly.ts:425-444:Reassembler.trim.weigh()returns evicted groups, possibly including the current one.answered = parts.size - 1excludes the refused segment from the loss count.collectonly weighs incomplete groups; the completing segment is never weighed. I had to confirm that is intended.- The comments at 361 and 437 resolved it, after two reads.
src/dlr.ts:342-424:messageType/receiptStatus/dlrFromPdu.- Four message types, with
'unmarked'meaning "maybe a receipt if the body parses to both an id and a state". Status comes from TLV, then body, then UNKNOWN, andstatusIdandstatusMsgcan disagree by design. - This is domain-heavy but well commented with spec sections. README's "Delivery receipts" section closed the gap.
- Four message types, with
src/defs/encodings.ts:302-341:messageClassOf/messageClassEncoding/encodingByDataCoding.- Bit-twiddling over GSM 03.38 coding groups that I had no context for. The comments give the bit positions, so it resolves with care.
- The GSM codec object is named
ascii(line 196), which is a lying name for GSM 03.38.
-
The unit I would least want to modify: the Session link lifecycle (
Session.drain/finish/linkLost/comeBackUp) together withLinkLife.- Correctness depends on call order across three classes.
stop()must reach the loop before the first await; client.ts:239 says so from another file. closeanddisconnectedmust stay exclusive, andend()must release waiters exactly once.- Any change risks a hung
close()or a doublecloseevent, and nothing local tells you which invariant you just broke.
- Correctness depends on call order across three classes.
-
Expected hard, found easy.
- The wire codec in
defs/types.ts: repetitive, every read is range-checked, andResultis uniform. PduFramer: short, with the quadratic concern stated.- The
send-sms.tscheck pipeline: linear and flat, each refusal named. DlrMergerseverity ranking: one comment explains why wire values can't be compared.bind-direction.ts:standsInFor/bindCarriesare tiny and explained.- The UDH walk in
udh.ts. - The no-throw discipline made every call site read the same way.
- The wire codec in
-
Prose debt.
- Needed, and where I found it:
- What ESME and SMSC are. Only inferable from
LinkEnd's comment and README. - What "answered on arrival" means. README "Server in depth", roughly a 400-line scroll.
- Why
data_smflips direction. The comment in bind-direction.ts is sufficient. - How the server's bind handling composes with
onRequest. Only in the AGENTS.md Decisions index, as one line whose reasoning is in docs/decisions.md, which I was barred from. - The 134/153 segment budget. Covered both inline (message.ts:364) and in AGENTS, so it was cheap.
- Many AGENTS decision lines are pointers into a file I couldn't open. For the lifecycle ("A deliberate shutdown drains; an unusable link and an abort do not"), the one-liner was the only statement of the rule the code implements.
- The AGENTS architecture map was accurate and was the cheapest, most useful prose.
- What ESME and SMSC are. Only inferable from
- Told me nothing the code didn't already say:
Session.send's "Sends a request and resolves with the peer's response."- README's "Everything exported" table, which duplicates
index.ts. - The
defaults.tspreamble. - AGENTS "Conventions", about 30 lines on test fixtures and teardown, which are irrelevant to reading
src/. - The repeated "Injected so expiry can be exercised without a wall clock" on four options types.
- Minor drift: README types
onSmsas(sms) => Promise<void> | void; the code declares(sms) => unknown.
- Needed, and where I found it:
-
Scores. Intrinsic difficulty is high: a stateful protocol session with reconnect, drain, windowing and reassembly. It gets no bonus.
- Navigation 8. Above 7 "the layout answers where does this live":
src/is flat, file names match contents, and the AGENTS map is accurate. It stops short of 9 because server bind handling lives behind theonRequestslot, which cost one wrong turn. - Locality 6. Between 5 and 7: most units stand alone. Link liveness is split across
LinkLife.phase,stopped,ReconnectLoop.halted,canCarry()'s socket check and generation counters. Changing shutdown means holding session.ts, link-life.ts, outgoing-requests.ts and client.ts at once, andlinkEndis mutated after construction. - Shape 7. At "predictable": classes are small and fan-out is bounded per level. A few names lie:
asciifor the GSM codec,HandledMessagesfor messages still being handled,retrying()used as "not closed", andsettlemeaning different things in five classes. - Self-sufficiency 7. At 7: comments carry the why with spec section references at the hard points (receipts, UDH, data_coding bits). What is missing is the lifecycle invariant and the bind composition, which exist only as index lines pointing at a decisions file.
- Overall 6. Capped at loc+1 = 7. I place it at 6 because the hardest part, the session lifecycle, is hard both because the problem is hard and because its state is spread across files. It is neither localized nor marked as one place.
- Navigation 8. Above 7 "the layout answers where does this live":
SCORES nav=8 loc=6 shape=7 self=7 overall=6
Draft D, senior seat
-
Hardest places, hardest first
- The link lifecycle across four owners.
src/session.ts:265-362(drain,finish,linkLost,dropLink,comeBackUp),src/link-life.ts:31(LinkLife),src/reconnect-loop.ts(stop/halted) andsrc/outgoing-requests.ts:120(refusal, which usescanCarry()=link.isUp() && !sock.destroyed).- There are three "stopped" notions:
LinkLife.stopped,ReconnectLoop.halted, andphase === 'ended', which also setsstopped.drain()andfinish()each calllink.stop()andreconnectLoop?.stop(), so I had to hold the order of the calls to see which one decides thecloseevent versusdisconnected. link-life.ts:38startsphaseat'up', although'binding'exists. The first link therefore reportsisUp()before any bind, and the charter's "a bind is what makes it one" holds only for reconnected links. I worked this out myself; nothing in the code says so. The code mostly explains itself, but that one point stayed opaque.
- There are three "stopped" notions:
- Who answers a failed handler.
src/handled-messages.ts:92-140(offer,run), together withsrc/sms.ts:83-157(createSms,sendResp,answeredOnArrival) andsrc/incoming-requests.ts:252(offer).- An
answeredflag is set through a callback thatofferbuilds around ahandledconst, which that same closure refers to.SmsRoute = Omit<SmsHandlers,'answered'>and a mutableAnswerobject add further state, and thelostLinkgeneration closure is built in yet another class. - When a multipart handler fails,
run()callssendResp({status: retryStatus}). That returns anerrfromansweredOnArrival, and theerris discarded. That is how "its answer stands" comes out right, and nothing says so. README's "A handler that fails" bullet resolved it.
- An
- Reassembly eviction.
src/reassembly.ts:110(collect) and:187(trim), withsrc/expiring-groups.ts:70(weigh).weigh()can evict the group that is being weighed, sotrimcounts it asparts.size - 1answered. Thefull/unplaceablerefusals map to three statuses inrefusedSegmentStatus.ExpiringGroupsenforces its limits unevenly: onlyweighevicts, whilemaxandtimeoutfall to the owners, and I had to find that in its class docstring. The inline comments resolved it, but it took a reread.
- Building and reading the message body.
src/pdu.ts:84-136(resolveShortMessage,resolveBody) and:249(readParams).- On the write side,
CodingSourcedecides which ofshort_messageandmessage_payloadmay overwritedata_coding. An empty buffer counts as'message_payload'. I had to hold four branches at once. - On the read side,
readParamspassessm_lengthas thelengthargument to every wire type'sread. The same parameter means the TLV length indefs/types.ts. Only thecommands.tscomment on wire order hints at this coupling.
- On the write side,
- data_coding bit logic.
src/defs/encodings.ts:159-190(messageClassEncoding,encodingByDataCoding).- It is dense bit-twiddling with no context, and a
//comment sits above a separate/** */block, so I could not tell which of the two it belonged to. - Some names are wrong.
'LATIN1'is returned for 8-bit binary. The GSM codec is namedascii(:45). - The docblocks resolved most of it. The class-group comment stayed only half clear.
- It is dense bit-twiddling with no context, and a
DlrMerger's two stores.src/dlr-merger.ts:68, withspendat:166andopenat:150. TwoExpiringGroups(groupsandspent) are both mutated byspend().open()checks both, anddropOldestspends. The class docstring explained the "merged at most once" rule. I still had to trace the steps by hand.- Retrying the first bind.
src/client.ts:218-320(bindOn,initialAttempts,keepTrying). This is a secondReconnectLoopoutsideSession, with a fresh session per attempt and alastErrclosure. Correctness depends on the order in which abort listeners are added and removed, and on the comment "close() must reach the loop's stop() before its first await". The comments resolved it.
- The link lifecycle across four owners.
-
The unit I would least want to modify:
LinkLife(src/link-life.ts).Session,OutgoingRequests(isUp,awaitsNextLink,refusal,hold) andIncomingRequests(generation) all read its phase. Itsstoppedflag duplicates the reconnect loop's, and its initial'up'is an unstated exception to its ownbindingrule. A change there reaches the drain, the queued sends and response correlation, and no single file shows all of that. -
Expected to be hard, found easy:
- The codec:
defs/types.tsis long but uniform, and every read is range-checked the same way. PduFramer,ReconnectLoopandPendingRequests.- The typing of
TlvInputsandTlvs. splitMessageand the budget per segment.- Navigation overall: the charter's one-line-per-file map matched the tree exactly.
- The codec:
-
Prose debt
- Needed, and what it cost to find:
- README "Receiving in depth" and "Shutdown", to learn the half-bound hysteresis, the five-minute handler cutoff, and what happens when a handler fails after answering. Finding them was cheap, but they sit in a user document, not beside
HandledMessages. - The rationale for the link-life decisions. AGENTS.md only indexes it ("One owner decides whether a link can carry a request…") and I was not allowed to open
docs/decisions.md, so the initial-'up'question stayed open. - I opened no tests.
- README "Receiving in depth" and "Shutdown", to learn the half-bound hysteresis, the five-minute handler cutoff, and what happens when a handler fails after answering. Finding them was cheap, but they sit in a user document, not beside
- Told me nothing the code did not already say:
session.ts:203"Sends a request and resolves with the peer's response".- The getter docstrings on
boundAsandpeerInterfaceVersion. UnansweredError's docstring, which restates its message.retryStatus's docstring.- The idle-timeout rationale, written twice (
defaults.ts:13andclient.ts:193). checkSessionOptions's docstring describes one case,maxOutstanding: 0, not the function, which misleads slightly.- AGENTS.md's 0.4.0 defect table and its long test-fixture paragraph cost reading time and did not help with
src/.
- Small duplication noticed:
collectSentinsend-sms.tsandcollectReceiptinsms.ts, andquoted()in bothsession-options.tsandbind-direction.ts.
- Needed, and what it cost to find:
-
Scores
Dimension Score Anchor and cause Navigation 8 Between 7 and 9. The Architecture map and truthful file names took me from symptom to file first try every time. The lifecycle behaviour spread over Session,LinkLifeandReconnectLoopis what keeps it from 9.Locality 6 Between 5 and 7. Most collaborators are standalone, with injected nowand dependencies. But whether a link can carry a request, is stopped, or has ended is split acrossLinkLife,ReconnectLoop,OutgoingRequests.canCarryand order-dependent calls inSession, and the handled-messageansweredstate runs through closures in three files.Shape 7 Predictable. Fan-out is bounded per level and nearly every name tells the truth. The exceptions are asciifor GSM,LATIN1standing for binary, andisUp()being true before the first bind.Self-sufficiency 7 Predictable. Inline comments carry most of the "why" (SMPP section references, peer quirks). The handler bound and failure semantics needed README, and the reasoning behind the link-life decisions sits in a document I could not open. Overall 7 Predictable, within the cap of lowest dimension plus one. The hard corners are few and I know which to fear, but the lifecycle corner is spread across four files instead of sitting in one marked place. The problem is intrinsically hard: SMPP session semantics, reconnecting with no resends, a draining shutdown, and reassembly under memory bounds. The scores give no bonus for that.
SCORES nav=8 loc=6 shape=7 self=7 overall=7
Draft D, architect seat
Comprehension panel report: Architect, inherited (draft-d)
Order note: I read AGENTS.md right after README and the tree, before I had written the map down. Its architecture listing matched the map below and changed nothing in it. I opened no test files.
1. Map (README + tree only, verbatim)
Top-level areas I expected in src/:
- A. Entry points:
index.tsfor the public surface,client.tsfor connect and bind with reconnect,server.tsfor the listener, auth and close. - B. Session core:
session.tsas the hub.session-options.tsanddefaults.tsfor options.bind-direction.tsfor which commands a bind type carries. - C. Link lifecycle:
link-life.ts(up, down or ended?),link-timers.ts(enquire_link and idle),reconnect-loop.ts(backoff),pdu-transport.ts(socket to PDUs). - D. Outbound:
send-sms.ts(split and submit),outgoing-requests.ts(the request path),pending-requests.ts(seqNr correlation),send-window.ts(maxOutstanding),unanswered-error.ts. - E. Inbound:
incoming-requests.ts(dispatch),sms.ts(the onSms handle),handled-messages.ts(probably the "held while the handler runs" bound),reassembly.ts,concat.ts,udh.ts,message-body.ts. - F. Receipts:
dlr.ts(parse),dlr-merger.ts(messageDlr),sms-id.ts(hex/decimal and<base>-<n>). - G. Codec:
pdu.ts,pdu-framer.ts,pdu-refusal.ts(PduRefusedError),retained-pdu.ts(?),defs/*(spec tables). - H. Text:
message.ts(encode, split, smppTime) anddefs/encodings.ts. - I. Utilities:
result.ts,error-from.ts,log.ts,uuid.ts,idle-waiters.ts(?),expiring-groups.ts(?).
Names that did not give their purpose:
idle-waiters: idle peer or idle count?retained-pduexpiring-groups: groups of what?handled-messages: reads as "already handled".error-fromdefaultsvssession-options
README features I could not place, or that were missing:
- Goal 9's store is absent, as the README says.
- smppTime and smppDate: presumably
message.ts. - At the repo root,
MIGRATION-NOTES.mdandDESIGN.mdbesideMIGRATION.mdanddocs/decisions.md: I cannot tell their purpose apart from the others.
Where the map was wrong, and what each correction cost:
handled-messages.ts(medium cost, and it is the crux of the 3am question). I guessed "held untilsendResp()". It actually holds a message until the handler's promise settles.answeredis recorded only to decide the retry refusal.link-life.ts(medium). It is not only a state flag. It is also the queue where requests wait for the next link, with two orthogonal state variables,phaseandstopped.expiring-groups.ts(medium). It is a shared TTL store whose contract is "enforces neither max nor timeout itself" (expiring-groups.ts:18). Each of its three owners re-implements the policy differently.HandledMessagesuses it for running handlers, which are not groups.DlrMergeruses a second instance as a "spent" set.- Cheap corrections:
session-options.tsalso holdsSessionEventsand all option validation.bind-direction.tsalso holds bind-record validation (checkedBind) andundeclaredInterfaceVersion.reassembly.tsholdsdecodeSegments, whichsms.tsuses.idle-waiters.tsis "wait until a count reaches 0".retained-pdu.tscopies PDUs off the wire and weighs them.
2. Fan-out by level
- L0, repo root: 22 entries, 8 of them prose documents. Two documents I could not tell apart by name.
- L1,
src/: 36 files plusdefs/, all flat. This is the worst level. Only names and the AGENTS listing group them into the 9 areas above. Nine is bounded; 37 is not, and the directory gives no help. - L2,
defs/: 7 files, bounded and clear. - L3, units:
Sessionwires 9 collaborators and has about 15 methods.IncomingRequestsowns 3 things and reaches back intoSession.OutgoingRequestsowns 3.LinkLifehas 12 methods over 2 state variables. By method count it is the densest unit.
3. Names
One name over several concepts:
- idle means four things:
IdleWaiters: a count falls to 0.- The
LinkTimersidle timeout: a silent peer. ExpiringGroups.idle(): stop the sweeper.SendWindow.idle(): the drain.
- refusal means four things:
pdu-refusal: an unreadable PDU.LinkLife.refusal(): the session is over.OutgoingRequests.refusal(): a request cannot go out.- The reassembly
Refusal:'full' | 'unplaceable'.
- settle covers waiters, pending requests,
IdleWaiters.settleandHandledMessages.settle(), which means "wake the drain if empty". - Shutdown verbs:
stop,end,finish,drop,dropLink,linkLost,halted,isOver,isStopped.link.stop()refuses new work whilereconnectLoop.stop()halts timers: same verb, different meanings.
One concept with several names:
- "Answered":
Answer.done(sms.ts:81),Handled.answered(handled-messages.ts),answeredAsandansweredOnArrival. - Writing a response:
answer(),sendReturn(),sendResp(). - The reassembly octet cap: option
maxOctetsvsdefaults.maxReassemblyOctets. The option name does not say "reassembly", yet a sibling cap exists (maxHandledOctets). - The server's idle timeout: the literal
defaults.idleTimeout40 000 vs the client's derived2 × enquireLinkInterval. - Two date formatters,
smppDateandsmppTime.encode, inmessage.ts, with duplicated pad chains.
Misleading:
HandledMessagesmeans "being handled". The README calls them "messages being handled".ExpiringGroupsholds running handlers, which are not groups.bind-direction.tsholds more than direction.
Copies:
quoted()appears twice (session-options.ts:78,bind-direction.ts:54).collectSent(send-sms.ts:274) andcollectReceipt(sms.ts:183) are near-twins.- An inline
thrown instanceof Error ? … : new Error(String(thrown))appears three times (client.ts:89,reconnect-loop.ts:80,reconnect-loop.ts:136) instead oferrorFrom().
4. What I would restructure, ranked
- Group
src/into about 6 folders: link, outbound, inbound, receipts, codec, text. The AGENTS listing already draws those lines, so this only moves the map from a document into the layout. - Give the shutdown/link vocabulary one owner.
- Collapse
LinkLife.phaseandstoppedinto one state enum. - Rename so that "stop" means one thing everywhere.
- Move
OutgoingRequests.refusal'spastDrain && isStopped && canCarrycondition (outgoing-requests.ts:129) behind oneLinkLifepredicate.
- Collapse
- Make
ExpiringGroupsenforce its own policy, or split it into a TTL store and a set. Today three owners re-implement "full", weight and sweep, and its sweeper interval equals its timeout. So expiry is lazy by up to 2× (expiring-groups.ts:60): the README's "five minutes" handler cap is really 5–10 minutes when no traffic arrives. That is a plausible claim drift; I derived it from the code and have not verified it. - Merge the "answered" state into one place, so
sms.tsandHandledMessagesstop tracking the same fact. - Use
errorFrom()everywhere.reconnect-loop.ts:80runsString(thrown)inside the.catchthat is meant to contain an application throw.errorFrom's own comment saysString()can throw.- If it does,
void this.run()rejects unhandled andattemptingstaystrue, which wedges the loop. The trigger is a null-prototype object thrown from an application-suppliedReconnectOptions.connectoronConnected, reachable becauseSessionis publicly constructible. - I call this plausible, not verified.
What the structure gets right:
- Files are small (all under 420 lines).
- Every file name maps to one noun that also appears in
Session's fields. Sessionreads as a table of contents.- Imports point one way.
- Hard-rule-1 result types are uniform.
- Comments carry the WHY at the line: spec section numbers, peer quirks, past defects.
defs/is clean.PduFramer,PendingRequests,SendWindowandReconnectLoopeach fit in the head alone.
5. The 3am question
Symptom: during a graceful shutdown the session hangs until shutdownTimeout, although the application called sendResp() on every message.
Path, cold, about 2–3 minutes: Session.close → drain (session.ts:265) → this.incoming.drain(...) (session.ts:274) → IncomingRequests.drain (incoming-requests.ts:163) → HandledMessages.idle (handled-messages.ts:111).
The unit is HandledMessages.run (handled-messages.ts:125). The entry is deleted at :138 only after await this.handle() returns. sendResp() only flips handled.answered, and the drain never reads it.
So the peer's handler has not returned. The likely cause is that it is awaiting sms.sendDlr(). That call waits for every deliver_sm_resp, up to responseTimeout, which defaults to 30 s, longer than the 5 s shutdown. It can also wait without bound behind a full send window, because sendDlr passes no signal.
This is designed behaviour: the OnSms type doc, README lines 108 and 389, and the AGENTS decision all say it. The fix is on the caller's side (return the handler, or fire-and-forget the receipt). The code states this at the type (session-options.ts:39), so no document is needed.
Where it rots first:
- The link/shutdown triangle:
Session.drain/finish/linkLost/dropLink/comeBackUpplusLinkLifeplusOutgoingRequests.refusal. Three units readLinkLifestate. Correctness depends on call order:link.stop()beforecanCarry(),drop()beforeend().IncomingRequestsalso snapshotslink.generation(). - Next,
ExpiringGroupsand its three divergent owners.
Where the next two features land:
- Goal 9's store would have to thread an interface through
Session→IncomingRequests→Reassembler/HandledMessages/DlrMerger, which is everyExpiringGroupsowner. That is the costliest seam in the code base. - A per-PDU rate-limit hook (goal 7) lands cleanly in
OutgoingRequests.requestbesideSendWindow.acquire.
6. Hardest places, ranked
session.ts:265-362:drain,finish,linkLost,dropLink,comeBackUp. Order-dependent shutdown across 4 collaborators.link-life.ts:31LinkLifeas a whole:phase×stopped, and 7 predicates with overlapping meanings.outgoing-requests.ts:74-134,requestandrefusal: the link-wait/window retry loop and thepastDrainexemption.handled-messages.ts:67-138,refuses/offer/run: hysteresis, a hidden sweeper timer, and the answered flag written fromsms.ts.expiring-groups.tsweightogether withreassembly.ts:187trim: eviction can take the current key.pdu.ts:84-136,resolveShortMessageandresolveBody: theCodingSourcerules.incoming-requests.ts:218-260,onMessageandoffer: the bound check, reassembly, answer on arrival, and generation capture.dlr.ts:216dlrFromPdu: themessageType/receiptStatusprecedence.
The unit I would least want to modify is LinkLife. Everything that decides whether a request may go out reads it, and its meaning is spread over 7 predicates.
Intrinsic difficulty: high. It is an SMPP session layer with reconnect, a send window, reassembly, receipt merging and drain semantics, and it earns no bonus for that.
7. Scores
- Navigation 7: "Predictable". The file names plus
Session's field list got me from symptom to unit in 3 hops. The flat 37-filesrc/and the misleading nameHandledMessageskeep it below 9. - Locality 6: between "honest middle" and "predictable".
LinkLifestate is read bySession,OutgoingRequestsandIncomingRequests, and shutdown correctness depends on call order.ExpiringGroupspushes its own policy onto three owners. - Shape 6: between "honest middle" and "predictable". Units are small and mostly named truthfully. But L1 has 37 ungrouped entries, and "idle", "refusal", "settle" and "stop" are each overloaded.
- Self-sufficiency 7: "Predictable". Comments at each unit state its invariants and the spec section behind them, and the 3am answer is readable at the
OnSmstype with no document open. A reader still needs the AGENTS listing to see the area grouping that the layout does not show. - Overall 6: capped by locality and shape at 6. A cold senior is productive within a week on everything except the link/shutdown triangle.
SCORES nav=7 loc=6 shape=6 self=7 overall=6