harness-reflex 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The decisions every orchestrated capability asks its host for.
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * Four capabilities now share one orchestration layer (prune, stagnation,
7
+ * correction, closing), and each of them asks its host the same handful of
8
+ * questions: what policy is in force, which counters may move, how one abandoned
9
+ * plan is recorded, how one plan is billed. Before this module, each `Host*Port`
10
+ * re-declared that surface in its own words. The declarations agreed, but
11
+ * nothing *made* them agree — a fourth capability would have been the fourth copy,
12
+ * and a divergence between two ports meant to be the same would have had nowhere
13
+ * to be caught.
14
+ *
15
+ * The shared surface is stated once, here. It is deliberately split into two
16
+ * interfaces rather than one, because the corpus of four ports showed the two
17
+ * halves have different reach:
18
+ *
19
+ * | Interface | Members | Who extends it |
20
+ * |---|---|---|
21
+ * | {@link HostDecisionPort} | `policy`, `budget`, `clock`/`now`, `serves` | **all four** |
22
+ * | {@link HostBillingPort} | `skip`, `chargeJudgment`, `conclude` | the three that bill the same way |
23
+ *
24
+ * ## Why the billing channels are a second interface
25
+ *
26
+ * The judgment capabilities (stagnation, correction, closing) record an abandoned
27
+ * plan as "reason + the judgment it cost" and bill an applied plan as "record +
28
+ * applied + the judgment it rode on". All three are literally the same two calls,
29
+ * so they share {@link HostBillingPort}.
30
+ *
31
+ * Pruning is **not** one of them, and this is the finding that stopped this batch
32
+ * from collapsing everything into one interface. Its two billing channels are
33
+ * genuinely wider:
34
+ *
35
+ * - `skip(reason, detail, judgment?)` — the `detail` is not a charge. It carries
36
+ * the payload diagnostics (`digest`, `floored`, `floorMissed`, the segment
37
+ * counts) that make *"why was nothing pruned"* answerable. Those fields are the
38
+ * reason the pruning audit trail exists at all.
39
+ * - `conclude(plan, applied, costs, judgment?, locator?)` — `costs` carries the
40
+ * four size columns and the retained locator, i.e. every number that makes a
41
+ * claimed saving *verifiable*. Collapsing it into the judgment-capability shape
42
+ * would silently drop them.
43
+ *
44
+ * Fitting pruning to the common shape would therefore have required either
45
+ * deleting audit fields or making the base `skip(reason, x?: unknown)`, which
46
+ * buys nothing: every caller would cast, and the one place a wrong answer is a
47
+ * model-visible regression would be the place the type stopped helping. Both were
48
+ * rejected. Pruning extends only {@link HostDecisionPort}, states its two wider
49
+ * channels in its own interface, and the divergence is documented there.
50
+ *
51
+ * ## The judgment is bought, not fetched
52
+ *
53
+ * A port never hands over a backend. It answers **one purchase at a time** —
54
+ * {@link HostJudgmentPort#buy} for the stagnation verdict (bought by both the
55
+ * stagnation and the correction capability, which ask the same question of the
56
+ * same service), `classify`/`verify` for closing's two-request judgment, and
57
+ * `judge(payload)` for pruning's reduction.
58
+ *
59
+ * The distinction matters because a port that exposes `backend()` forces every
60
+ * caller to re-implement the purchase: the memo key, the budget check, the
61
+ * local/remote latency split, and the billing. Those four are the shared layer's
62
+ * — {@link ../judge.runJudgment} and each capability's own accounting — and they
63
+ * are stated once. A host answers only "what did the service say, and how long
64
+ * did it wait".
65
+ *
66
+ * ### One buy is one request; one charge may be several buys
67
+ *
68
+ * The unit of `buy` is the *request*, not the bill. The closing check buys twice
69
+ * from one capability — a classification of the turn's sentences, then a
70
+ * verification of the claims that classification accepted — but bills them as a
71
+ * single {@link JudgmentCost} against the single slot the turn budget granted.
72
+ * That fold is the shared layer's (`orchestrateClosing`), which is exactly why
73
+ * the closing port must not be collapsing the two requests into one method: the
74
+ * latency split and the token sum belong where the charge is built. For the
75
+ * stagnation verdict one buy is one request and one charge.
76
+ *
77
+ * @module core/orchestrate-host
78
+ */
79
+ export {};
80
+ //# sourceMappingURL=orchestrate-host.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orchestrate-host.js","sourceRoot":"","sources":["../../src/core/orchestrate-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6EG","sourcesContent":["/**\n * The decisions every orchestrated capability asks its host for.\n *\n * ## Why this exists\n *\n * Four capabilities now share one orchestration layer (prune, stagnation,\n * correction, closing), and each of them asks its host the same handful of\n * questions: what policy is in force, which counters may move, how one abandoned\n * plan is recorded, how one plan is billed. Before this module, each `Host*Port`\n * re-declared that surface in its own words. The declarations agreed, but\n * nothing *made* them agree — a fourth capability would have been the fourth copy,\n * and a divergence between two ports meant to be the same would have had nowhere\n * to be caught.\n *\n * The shared surface is stated once, here. It is deliberately split into two\n * interfaces rather than one, because the corpus of four ports showed the two\n * halves have different reach:\n *\n * | Interface | Members | Who extends it |\n * |---|---|---|\n * | {@link HostDecisionPort} | `policy`, `budget`, `clock`/`now`, `serves` | **all four** |\n * | {@link HostBillingPort} | `skip`, `chargeJudgment`, `conclude` | the three that bill the same way |\n *\n * ## Why the billing channels are a second interface\n *\n * The judgment capabilities (stagnation, correction, closing) record an abandoned\n * plan as \"reason + the judgment it cost\" and bill an applied plan as \"record +\n * applied + the judgment it rode on\". All three are literally the same two calls,\n * so they share {@link HostBillingPort}.\n *\n * Pruning is **not** one of them, and this is the finding that stopped this batch\n * from collapsing everything into one interface. Its two billing channels are\n * genuinely wider:\n *\n * - `skip(reason, detail, judgment?)` — the `detail` is not a charge. It carries\n * the payload diagnostics (`digest`, `floored`, `floorMissed`, the segment\n * counts) that make *\"why was nothing pruned\"* answerable. Those fields are the\n * reason the pruning audit trail exists at all.\n * - `conclude(plan, applied, costs, judgment?, locator?)` — `costs` carries the\n * four size columns and the retained locator, i.e. every number that makes a\n * claimed saving *verifiable*. Collapsing it into the judgment-capability shape\n * would silently drop them.\n *\n * Fitting pruning to the common shape would therefore have required either\n * deleting audit fields or making the base `skip(reason, x?: unknown)`, which\n * buys nothing: every caller would cast, and the one place a wrong answer is a\n * model-visible regression would be the place the type stopped helping. Both were\n * rejected. Pruning extends only {@link HostDecisionPort}, states its two wider\n * channels in its own interface, and the divergence is documented there.\n *\n * ## The judgment is bought, not fetched\n *\n * A port never hands over a backend. It answers **one purchase at a time** —\n * {@link HostJudgmentPort#buy} for the stagnation verdict (bought by both the\n * stagnation and the correction capability, which ask the same question of the\n * same service), `classify`/`verify` for closing's two-request judgment, and\n * `judge(payload)` for pruning's reduction.\n *\n * The distinction matters because a port that exposes `backend()` forces every\n * caller to re-implement the purchase: the memo key, the budget check, the\n * local/remote latency split, and the billing. Those four are the shared layer's\n * — {@link ../judge.runJudgment} and each capability's own accounting — and they\n * are stated once. A host answers only \"what did the service say, and how long\n * did it wait\".\n *\n * ### One buy is one request; one charge may be several buys\n *\n * The unit of `buy` is the *request*, not the bill. The closing check buys twice\n * from one capability — a classification of the turn's sentences, then a\n * verification of the claims that classification accepted — but bills them as a\n * single {@link JudgmentCost} against the single slot the turn budget granted.\n * That fold is the shared layer's (`orchestrateClosing`), which is exactly why\n * the closing port must not be collapsing the two requests into one method: the\n * latency split and the token sum belong where the charge is built. For the\n * stagnation verdict one buy is one request and one charge.\n *\n * @module core/orchestrate-host\n */\n\nimport type { ActionStep, StagnationCheckResponse } from '../backend/types.js';\nimport type { ClockPort } from '../ports/clock.js';\nimport type { BudgetState, PolicySnapshot } from './policy.js';\n\n/**\n * The charge of one judgment, as every capability bills it.\n *\n * Stated here rather than in one capability's module because all of them record\n * the same five columns, and the fifth (`judgeTokens`) is the one a host that\n * forgot it would quietly under-report.\n */\nexport interface JudgmentCost {\n readonly judgments: number;\n readonly memoHits: number;\n readonly localLatencyMs: number;\n readonly remoteLatencyMs: number;\n readonly judgeTokens: number;\n}\n\n/**\n * One judgment request: the window, plus the question it is put to.\n *\n * This is the whole of what a host is asked for when a judgment is bought. It is\n * a value rather than a port because the host's only job is \"ask the service and\n * report what it said, latency included\" — the memo key, the budget check, the\n * latency split and the charge stay with the caller that owns the counters.\n */\nexport interface JudgmentStep {\n /** Why the run is judged, when the caller knows (a wait question). */\n readonly goal: string | undefined;\n /** The observed steps to judge, oldest first. */\n readonly history: readonly ActionStep[];\n}\n\n/**\n * Where in the run one judgment is being made.\n *\n * This is the value the four capabilities used to each spell their own accessor\n * for (`position()`, `location()`, `turn()`, and two bare state reads). They\n * disagreed because a port should not answer it: every host has these two\n * numbers, every host means the same thing by them, and a judgment is *about*\n * one place. So the place travels with the judgment — never through the port.\n */\nexport interface JudgmentPosition {\n /** The turn this judgment belongs to. */\n turn: number;\n /** The step this judgment belongs to. */\n step: number;\n}\n\n/**\n * The counters every judgment capability keeps, positioned at where it decides.\n *\n * The place is part of the state for the three capabilities whose state *is* the\n * host's running record (the same object the trigger windows are kept in): the\n * audit detail, the retention request and the verdict memo all quote it, so one\n * source keeps them in step. The closing check is the exception, and the\n * exception is the finding: its turn is the boundary it was asked at, which can\n * be a turn no step has recorded yet, so it arrives as an input of that decision\n * instead (see `orchestrateClosing`).\n */\nexport interface JudgmentState extends BudgetState, JudgmentPosition {}\n\n/**\n * What a capability that buys exactly one judgment asks its host for.\n *\n * The shape is one method over one value: the window and the question put to it\n * ({@link JudgmentStep}). The host answers what the service said, latency\n * included; the purchase around it — budget, memo, latency split, charge — is\n * the shared layer's.\n *\n * A capability that buys *differently* still states its buys in this form, one\n * member per request: closing answers `classify` and `verify`, pruning answers\n * `judge`. The rule is that a port states the purchases it makes and never the\n * transport behind them.\n *\n * @typeParam Answer - what this capability's service returns for one request.\n */\nexport interface HostJudgmentPort<Answer> {\n /**\n * Buy one judgment about one step.\n * @param step - the window to judge and the question it is asked in.\n * @returns the service's answer, carrying the latency the split is measured on.\n */\n buy(step: JudgmentStep): Promise<Answer>;\n}\n\n/**\n * What every orchestrated decision asks its host, whatever it decides.\n *\n * These four are the ones no capability can answer alone and no capability\n * answers differently: the policy is the host's resolved config, the counters are\n * the host's storage, the clock is the host's wall time, and the switch is the\n * host's.\n *\n * @typeParam State - the counters this decision spends from. Must extend\n * {@link BudgetState}, because the shared budget rules mutate it through one.\n */\nexport interface HostDecisionPort<State extends BudgetState = BudgetState> {\n /** The resolved policy in force right now (re-read per decision). */\n policy(): PolicySnapshot;\n /**\n * The counters this decision spends from and books against.\n *\n * The shared layer mutates them in place through `core/policy`; a host that\n * stores its counters elsewhere hands over the object it wants mutated and\n * nothing else has to know where they live.\n */\n budget(): State;\n /** The clock, for the local-latency split. */\n clock(): ClockPort;\n /** Whether the decision applies at all (master switch on, capability not off). */\n serves(): boolean;\n}\n\n/**\n * The three accounting channels the judgment capabilities share.\n *\n * Extended by stagnation, correction and closing. See the module documentation\n * for why pruning is not one of them.\n *\n * @typeParam Charge - the judgment charge this capability bills.\n * @typeParam Record - the plan this capability records when it acts.\n */\nexport interface HostBillingPort<Charge = JudgmentCost, Record = unknown> {\n /**\n * Record one abandoned plan by reason.\n *\n * The charge is passed in because the record has to say what the refusal cost:\n * a paid \"not this\" and a free \"budget spent\" are different answers, and a skip\n * that reported both as free would understate the turn.\n */\n skip(reason: string, charge?: Charge): void;\n /**\n * Bill one judgment whose plan was abandoned after it was really made.\n *\n * A refusal before the judgment is bought costs nothing and is never billed\n * here. One that refused *after* it ran did spend, so hiding it would understate\n * what the turn cost.\n */\n chargeJudgment(charge: Charge): void;\n /**\n * Record one applied or observed plan.\n *\n * This is the one place a plan is billed: `plans` +1, `applied` +1 when it really\n * took effect, and every column of the charge.\n *\n * @param plan - what the capability decided.\n * @param applied - whether active mode executed it.\n * @param charge - the judgment this decision rode on.\n */\n conclude(plan: Record, applied: boolean, charge: Charge): void;\n}\n"]}
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The shared orchestration of the stagnation decision.
3
+ *
4
+ * Like {@link ./orchestrate}, this module owns *when and in what order* a
5
+ * decision is made, and none of the host facts the decision is made of. It was
6
+ * lifted in behaviour from the DSH engine's `toolCall` and `preStep` branches so
7
+ * that a second host can reuse them, and each of the two hooks is a function over
8
+ * a port:
9
+ *
10
+ * ```
11
+ * tools/pre-execute
12
+ * downstream first, always
13
+ * → off / own tool / aborted → hand the downstream decision back
14
+ * → [the window: recorded steps + this call, waits removed]
15
+ * → a wait shape already classified this turn → wait-query, nothing asked
16
+ * → the cheap trigger (repetition / failing retry / oscillation)
17
+ * → a handle-shaped repetition promoted to a wait question
18
+ * → not suspicious, or already refused → hand it back
19
+ * → already intervened on this episode → duplicate-intervention
20
+ * → the turn's action allowance is spent → intervention-cap
21
+ * → buy a judgment (memo first, budgets inside)
22
+ * → not useful → charge it, record why, hand it back
23
+ * → latch the refusal, latch the episode, book the action, conclude
24
+ * → deny *only* when the downstream decision was an allow
25
+ *
26
+ * agent/pre-step
27
+ * downstream first, always
28
+ * → off / aborted / not `enter` → hand the downstream decision back
29
+ * → nothing observed → nothing to correct
30
+ * → the last observation was a wait → wait-query / wait-query-unjudged
31
+ * → already intervened / no allowance → duplicate-intervention / cap
32
+ * → the cheap trigger over the progress-only window
33
+ * → buy a judgment → not useful → charge it, record why, hand it back
34
+ * → latch the correction, book the action, conclude
35
+ * → append the correction to the admitted messages (active only)
36
+ * ```
37
+ *
38
+ * ## What is shared and what is not
39
+ *
40
+ * Shared here: both orders, every skip reason, the budget rules
41
+ * (`actionWithinBudget`, `bookAction`, the judgment memo), the latch semantics,
42
+ * the shape of the audit detail, and the rule that decides whether a refusal may
43
+ * be *added* at all.
44
+ *
45
+ * *Not* shared here: the window itself (the host records steps and hands over an
46
+ * array), the call identity a repetition is measured on (the host's signature
47
+ * algorithm), what counts as a legitimate wait (the host's tool list and argument
48
+ * shape), how a correction is attached to a step or a refusal delivered (the
49
+ * host's message and decision types), and the operator-facing wording of either.
50
+ *
51
+ * ## Why the host supplies the window, not a store
52
+ *
53
+ * The DSH engine keeps its window in the agent's own bookkeeping and hands the
54
+ * shared layer a value; a host that derives the window from a persisted log would
55
+ * hand over a different value. Both are legal, and neither has to teach the
56
+ * shared layer how it stores anything. The only thing the shared layer mutates is
57
+ * the counters it is given, through {@link BudgetState}.
58
+ *
59
+ * ## The safety property this module states
60
+ *
61
+ * A refusal may only ever be *added on top of an allow* — {@link mayAddDecision},
62
+ * one place, one rule. A host that returned something stricter is never
63
+ * overwritten, because the harness would otherwise be able to turn a host's
64
+ * conservative decision into a weaker one.
65
+ *
66
+ * @module core/orchestrate-stagnation
67
+ */
68
+ import type { StagnationCheckResponse } from '../backend/types.js';
69
+ import type { HostBillingPort, HostDecisionPort, HostJudgmentPort } from './orchestrate-host.js';
70
+ import { type ObservedStep, type StagnationSuspicion, type VerdictMemoState } from './judge.js';
71
+ /** The capability every decision in this module belongs to. */
72
+ export declare const STAGNATION_CAPABILITY: "stagnation";
73
+ /** What one orchestrated decision turned out to be. */
74
+ export type StagnationAction = 'allow' | 'deny' | 'pass-through';
75
+ /**
76
+ * The window a stagnation trigger and its judgment are measured on.
77
+ *
78
+ * A wait query is not progress the run can be repeating: an identically repeated
79
+ * status/result query of the same background job is the sanctioned way to wait,
80
+ * so those steps are dropped before the repetition, failure and oscillation
81
+ * triggers read the window. Genuine calls on either side of a wait stay adjacent
82
+ * instead of being separated by it, which keeps a real loop visible while a run
83
+ * is waiting.
84
+ * @param steps - observed steps, oldest first.
85
+ * @returns the steps that count as progress.
86
+ */
87
+ export declare function progressSteps(steps: readonly ObservedStep[]): readonly ObservedStep[];
88
+ /**
89
+ * Whether an action may be added on top of the decision the rest of the
90
+ * waterfall already made.
91
+ *
92
+ * This is the permission-monotonicity rule, in one place: a `deny` may be added
93
+ * only to an `allow`. An approval in flight, a denial carrying its own structured
94
+ * error identity, or a cancellation is information the Host attached, and
95
+ * overwriting any of it would drop that information or relax the decision.
96
+ * @param downstreamKind - the kind of the downstream decision.
97
+ * @returns whether the shared layer may add a refusal.
98
+ */
99
+ export declare function mayAddDecision(downstreamKind: string): boolean;
100
+ /**
101
+ * The trigger for a repetition of a *wait-shaped* call.
102
+ *
103
+ * The host's tool list only decides that this repetition is worth asking about;
104
+ * it does not pass or refuse anything by itself.
105
+ * @param shape - the wait shape the host recognised.
106
+ * @param repeats - how many times the identity already occurred.
107
+ * @returns the promoted trigger.
108
+ */
109
+ export declare function waitTrigger(shape: string, repeats: number): StagnationSuspicion;
110
+ /** The judgment cost of one decision, as the host bills it. */
111
+ export interface JudgedCharge {
112
+ readonly judgments: number;
113
+ readonly memoHits: number;
114
+ readonly localLatencyMs: number;
115
+ readonly remoteLatencyMs: number;
116
+ readonly judgeTokens: number;
117
+ }
118
+ /** One planned stagnation decision, as the host records it. */
119
+ export interface StagnationPlanRecord {
120
+ readonly capability: typeof STAGNATION_CAPABILITY;
121
+ readonly action: 'deny-call' | 'corrective-context';
122
+ readonly reason: string;
123
+ feedback: string;
124
+ readonly detail: Record<string, unknown>;
125
+ }
126
+ /** What one refusal or correction was built from. */
127
+ export interface StagnationFeedbackFacts {
128
+ readonly tool: string;
129
+ readonly suspicion: StagnationSuspicion;
130
+ readonly verdict: StagnationCheckResponse;
131
+ }
132
+ /**
133
+ * The counters one decision spends from and books against.
134
+ *
135
+ * The verdict cache is part of the budget state because a cached answer is what
136
+ * makes a second question in the same turn free: the shared layer reads it
137
+ * through here rather than keeping a second copy.
138
+ */
139
+ export interface StagnationState extends VerdictMemoState {
140
+ verdictTurn: number;
141
+ verdictKey: string;
142
+ verdict?: StagnationCheckResponse;
143
+ }
144
+ /**
145
+ * Everything the shared layer cannot know by itself.
146
+ *
147
+ * {@link HostDecisionPort} answers the part every capability asks — policy,
148
+ * counters, clock, switch, and the three billing channels — so this interface
149
+ * states only what a *refusal or correction* additionally needs.
150
+ */
151
+ export interface HostStagnationPort<Decision, Corrected> extends HostDecisionPort<StagnationState>, HostBillingPort<JudgedCharge, StagnationPlanRecord>, HostJudgmentPort<StagnationCheckResponse> {
152
+ /** Name of the call being decided, for the record and the wording. */
153
+ toolName(): string;
154
+ /** The recorded window, oldest first, *without* the call about to run. */
155
+ window(): readonly ObservedStep[];
156
+ /** The step the call about to run would append, without committing it. */
157
+ pendingStep(): ObservedStep;
158
+ /** The identity this decision is about. */
159
+ signature(): string;
160
+ /**
161
+ * The cheap trigger over one window.
162
+ *
163
+ * `PolicySnapshot` carries the repetition threshold and the confidence floor —
164
+ * the two numbers the *budget* rules are stated in — but the failure threshold
165
+ * and the window size are trigger parameters, and the host owns their values.
166
+ * Keeping them here is what keeps one policy type for every capability.
167
+ */
168
+ suspicion(steps: readonly ObservedStep[]): StagnationSuspicion;
169
+ /** The progress-only window a pre-step corrects against. */
170
+ progressWindow(): readonly ObservedStep[];
171
+ /** Whether this identity was already intervened on this turn. */
172
+ alreadyIntervened(): boolean;
173
+ /** Whether this identity was already refused this turn. */
174
+ alreadyDenied(): boolean;
175
+ /**
176
+ * Whether the signature of a step was already classified as a wait.
177
+ *
178
+ * The pre-step hook needs it to tell "a poll the run already had answered" from
179
+ * "a poll this turn never judged" — two different skip reasons, and the second
180
+ * one is not a stagnation episode at all.
181
+ */
182
+ wasClassifiedAsWait(signature: string): boolean;
183
+ /** Latch this identity as refused. */
184
+ latchDenied(): void;
185
+ /** Latch this identity as an episode already acted on. */
186
+ latchIntervened(): void;
187
+ /** The decision to hand back when nothing is done. */
188
+ passThrough(): Decision;
189
+ /** Build the refusal, once the decision is to apply one. */
190
+ deny(feedback: string): Decision;
191
+ /** Append the correction to the admitted messages, once the decision is to apply one. */
192
+ correct(feedback: string): Corrected;
193
+ /** Word the refusal handed to the model. */
194
+ denyFeedback(facts: StagnationFeedbackFacts): string;
195
+ /** Word the corrective context attached to a step. */
196
+ contextFeedback(facts: StagnationFeedbackFacts): string;
197
+ }
198
+ /** The outcome of one orchestrated decision. */
199
+ export interface StagnationOutcome<Decision> {
200
+ /** What the host should return to its caller. */
201
+ readonly result: Decision;
202
+ /** What the decision was. */
203
+ readonly action: StagnationAction;
204
+ }
205
+ /**
206
+ * `tools/pre-execute`: refuse a call the run is repeating.
207
+ *
208
+ * The host calls this **after** its own `next()`, and hands over what that
209
+ * returned: the downstream decision is the first fact the decision is about, and
210
+ * a refusal may only ever be added to an allow.
211
+ *
212
+ * @param invocation - the downstream decision, the signal, and the window facts.
213
+ * @param port - everything that is the host's to answer.
214
+ * @returns the decision the Host dispatches on.
215
+ */
216
+ export declare function orchestrateStagnationPre<Decision, Corrected>(invocation: {
217
+ /** Kind of the decision the rest of the waterfall made. */
218
+ readonly downstreamKind: string;
219
+ /** The call's abort signal, if it has one. */
220
+ readonly signal?: AbortSignal;
221
+ /**
222
+ * The window the judgment is about, when a wait question needs one.
223
+ *
224
+ * Defaults to the progress-only window. A host that annotates its polls
225
+ * supplies the annotated list here, because *how* a poll is labelled is the
226
+ * host's business and the shared layer only asks the question.
227
+ */
228
+ judgeSteps?: () => readonly ObservedStep[];
229
+ /** The question a promoted wait asks, or nothing for an ordinary repetition. */
230
+ waitQuestion?: () => string | undefined;
231
+ /** Whether this wait shape was already classified this turn. */
232
+ waitClassified?: () => boolean;
233
+ /** Latch the wait shape as classified. */
234
+ latchWait?: () => void;
235
+ /** The wait handle shape, so the trigger can name it. */
236
+ waitShape?: () => {
237
+ readonly shape: string;
238
+ readonly repeats: number;
239
+ } | undefined;
240
+ /** Record that this call was refused, so its result is not judged as evidence. */
241
+ noteRefused?: () => void;
242
+ }, port: HostStagnationPort<Decision, Corrected>): Promise<StagnationOutcome<Decision>>;
243
+ /**
244
+ * `agent/pre-step`: attach the correction to the step after a loop repeated
245
+ * itself.
246
+ *
247
+ * The host calls this **after** its own `next()`. A step the rest of the
248
+ * waterfall rejected, or a step whose turn is being cancelled, is not corrected.
249
+ *
250
+ * @param invocation - the downstream decision and the signal.
251
+ * @param port - everything that is the host's to answer.
252
+ * @returns the decision the loop enters with.
253
+ */
254
+ export declare function orchestrateStagnationStep<Decision, Corrected>(invocation: {
255
+ /** Kind of the decision the rest of the waterfall made. */
256
+ readonly downstreamKind: string;
257
+ /** The step's abort signal, if it has one. */
258
+ readonly signal?: AbortSignal;
259
+ }, port: HostStagnationPort<Decision, Corrected>): Promise<StagnationOutcome<Decision | Corrected>>;
@@ -0,0 +1,270 @@
1
+ import { judgmentCharge, runJudgment } from './judge.js';
2
+ import { actionWithinBudget, bookAction, modeOf } from './policy.js';
3
+ /** The capability every decision in this module belongs to. */
4
+ export const STAGNATION_CAPABILITY = 'stagnation';
5
+ /**
6
+ * The window a stagnation trigger and its judgment are measured on.
7
+ *
8
+ * A wait query is not progress the run can be repeating: an identically repeated
9
+ * status/result query of the same background job is the sanctioned way to wait,
10
+ * so those steps are dropped before the repetition, failure and oscillation
11
+ * triggers read the window. Genuine calls on either side of a wait stay adjacent
12
+ * instead of being separated by it, which keeps a real loop visible while a run
13
+ * is waiting.
14
+ * @param steps - observed steps, oldest first.
15
+ * @returns the steps that count as progress.
16
+ */
17
+ export function progressSteps(steps) {
18
+ return steps.some((step) => step.wait === true) ? steps.filter((step) => step.wait !== true) : steps;
19
+ }
20
+ /**
21
+ * Whether an action may be added on top of the decision the rest of the
22
+ * waterfall already made.
23
+ *
24
+ * This is the permission-monotonicity rule, in one place: a `deny` may be added
25
+ * only to an `allow`. An approval in flight, a denial carrying its own structured
26
+ * error identity, or a cancellation is information the Host attached, and
27
+ * overwriting any of it would drop that information or relax the decision.
28
+ * @param downstreamKind - the kind of the downstream decision.
29
+ * @returns whether the shared layer may add a refusal.
30
+ */
31
+ export function mayAddDecision(downstreamKind) {
32
+ return downstreamKind === 'allow';
33
+ }
34
+ /**
35
+ * The trigger for a repetition of a *wait-shaped* call.
36
+ *
37
+ * The host's tool list only decides that this repetition is worth asking about;
38
+ * it does not pass or refuse anything by itself.
39
+ * @param shape - the wait shape the host recognised.
40
+ * @param repeats - how many times the identity already occurred.
41
+ * @returns the promoted trigger.
42
+ */
43
+ export function waitTrigger(shape, repeats) {
44
+ return {
45
+ suspicious: true,
46
+ pattern: 'repetition',
47
+ note: `wait-suspect ${shape} repeated ${repeats}x`,
48
+ repeats
49
+ };
50
+ }
51
+ /**
52
+ * The charge of one judgment, through the core's own billing rule.
53
+ * @param outcome - the judgment's outcome.
54
+ * @param started - clock reading at hook entry.
55
+ * @param now - clock reading now.
56
+ * @returns the charge the host records.
57
+ */
58
+ function chargeOf(outcome, started, now) {
59
+ return judgmentCharge(outcome, started, now);
60
+ }
61
+ /**
62
+ * The detail every stagnation record carries.
63
+ * @param suspicion - the cheap-path trigger.
64
+ * @param verdict - what System 1 answered.
65
+ * @param state - the deciding state, for turn and step.
66
+ * @param step - the step the decision belongs to.
67
+ * @returns the audit fields.
68
+ */
69
+ function detailOf(suspicion, verdict, turn, step) {
70
+ return {
71
+ pattern: String(verdict.patternType ?? suspicion.pattern ?? 'unknown'),
72
+ confidence: verdict.confidence,
73
+ repeats: suspicion.repeats,
74
+ turn,
75
+ step
76
+ };
77
+ }
78
+ /**
79
+ * `tools/pre-execute`: refuse a call the run is repeating.
80
+ *
81
+ * The host calls this **after** its own `next()`, and hands over what that
82
+ * returned: the downstream decision is the first fact the decision is about, and
83
+ * a refusal may only ever be added to an allow.
84
+ *
85
+ * @param invocation - the downstream decision, the signal, and the window facts.
86
+ * @param port - everything that is the host's to answer.
87
+ * @returns the decision the Host dispatches on.
88
+ */
89
+ export async function orchestrateStagnationPre(invocation, port) {
90
+ const { signal } = invocation;
91
+ const passThrough = () => ({ result: port.passThrough(), action: 'pass-through' });
92
+ const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);
93
+ if (mode === 'off' || !port.serves())
94
+ return passThrough();
95
+ if (signal?.aborted === true)
96
+ return passThrough();
97
+ const policy = port.policy();
98
+ const pending = port.pendingStep();
99
+ // The call about to run is part of its own window: three identical calls are a
100
+ // repetition at the moment the third one is proposed, and the judgment has to
101
+ // see all three.
102
+ const allWindow = [...port.window(), pending];
103
+ const window = progressSteps(allWindow);
104
+ const signalValue = invocation.waitShape?.();
105
+ // A wait-suspect call this turn already classified is answered by that verdict
106
+ // rather than re-asked; anything else is only worth a question when it actually
107
+ // repeats (the same threshold as any other repetition).
108
+ if (signalValue !== undefined && invocation.waitClassified?.() === true) {
109
+ port.skip('wait-query');
110
+ return passThrough();
111
+ }
112
+ let suspicion = port.suspicion(window);
113
+ let waitSuspected = false;
114
+ if (signalValue !== undefined && signalValue.repeats >= policy.repeatThreshold) {
115
+ suspicion = waitTrigger(signalValue.shape, signalValue.repeats);
116
+ waitSuspected = true;
117
+ }
118
+ if (!suspicion.suspicious || port.alreadyDenied())
119
+ return passThrough();
120
+ if (port.alreadyIntervened()) {
121
+ port.skip('duplicate-intervention');
122
+ return passThrough();
123
+ }
124
+ if (!actionWithinBudget(port.budget(), policy)) {
125
+ port.skip('intervention-cap');
126
+ return passThrough();
127
+ }
128
+ // A wait question is judged on the polls themselves (each labelled with its
129
+ // place in the series, so the backend can read a wait rather than an exact
130
+ // repeat); every other question keeps the progress-only window.
131
+ const steps = waitSuspected ? (invocation.judgeSteps?.() ?? window) : window;
132
+ const started = port.clock().now();
133
+ const outcome = await runJudgment({
134
+ state: port.budget(),
135
+ policy,
136
+ buy: (step) => port.buy(step),
137
+ clock: port.clock(),
138
+ steps,
139
+ ...(waitSuspected ? { goal: invocation.waitQuestion?.() } : {}),
140
+ ...(signal === undefined ? {} : { signal })
141
+ });
142
+ const charge = chargeOf(outcome, started, port.clock().now());
143
+ // Denial is latched per signature whether or not it was applied: in observe
144
+ // mode the refusal is what would have happened, and the latch is what keeps the
145
+ // next identical attempt from being judged again in the same turn.
146
+ port.latchDenied();
147
+ if (!outcome.useful) {
148
+ if (waitSuspected)
149
+ invocation.latchWait?.();
150
+ // A budget/abort skip keeps its own reason; only a real "not stuck" answer to
151
+ // a wait question is recorded as the wait outcome.
152
+ port.chargeJudgment(charge);
153
+ port.skip(outcome.skip ?? (waitSuspected ? 'wait-query' : 'unconfirmed'), charge);
154
+ return passThrough();
155
+ }
156
+ const facts = {
157
+ tool: port.toolName(),
158
+ suspicion,
159
+ verdict: outcome.response
160
+ };
161
+ const plan = {
162
+ capability: STAGNATION_CAPABILITY,
163
+ action: 'deny-call',
164
+ reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before ${port.toolName()}`,
165
+ feedback: port.denyFeedback(facts),
166
+ detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
167
+ };
168
+ const applies = mode === 'active' && mayAddDecision(invocation.downstreamKind);
169
+ if (mode === 'active' && !applies)
170
+ port.skip('downstream-decided');
171
+ invocation.noteRefused?.();
172
+ // The episode and the action are latched in both modes: observe has to plan
173
+ // exactly what active would do — one refusal per episode, subject to the same
174
+ // turn cap — or its column would over-count the very thing it is measuring.
175
+ port.latchIntervened();
176
+ bookAction(port.budget());
177
+ port.conclude(plan, applies, charge);
178
+ return applies
179
+ ? { result: port.deny(plan.feedback), action: 'deny' }
180
+ : passThrough();
181
+ }
182
+ /**
183
+ * `agent/pre-step`: attach the correction to the step after a loop repeated
184
+ * itself.
185
+ *
186
+ * The host calls this **after** its own `next()`. A step the rest of the
187
+ * waterfall rejected, or a step whose turn is being cancelled, is not corrected.
188
+ *
189
+ * @param invocation - the downstream decision and the signal.
190
+ * @param port - everything that is the host's to answer.
191
+ * @returns the decision the loop enters with.
192
+ */
193
+ export async function orchestrateStagnationStep(invocation, port) {
194
+ const passThrough = () => ({
195
+ result: port.passThrough(),
196
+ action: 'pass-through'
197
+ });
198
+ const mode = modeOf(port.policy(), STAGNATION_CAPABILITY);
199
+ if (mode === 'off' || !port.serves())
200
+ return passThrough();
201
+ if (invocation.signal?.aborted === true || invocation.downstreamKind !== 'enter')
202
+ return passThrough();
203
+ // The last observation is read from the *raw* window, before waits are dropped:
204
+ // a wait is exactly what this branch is about, so a window that had already
205
+ // filtered it out could never recognize one. Everything after this reads the
206
+ // progress-only window.
207
+ const recorded = port.window();
208
+ const last = recorded[recorded.length - 1];
209
+ if (last === undefined)
210
+ return passThrough();
211
+ // A poll that already passed the semantic wait judgment has nothing to correct
212
+ // here: the run asked about a background job again, it did not repeat its work.
213
+ // A poll this turn never judged was not a repetition, so it is not an episode.
214
+ if (last.wait === true) {
215
+ port.skip(port.wasClassifiedAsWait(last.signature) ? 'wait-query' : 'wait-query-unjudged');
216
+ return passThrough();
217
+ }
218
+ const window = port.progressWindow();
219
+ if (port.alreadyIntervened()) {
220
+ port.skip('duplicate-intervention');
221
+ return passThrough();
222
+ }
223
+ const policy = port.policy();
224
+ if (!actionWithinBudget(port.budget(), policy)) {
225
+ port.skip('intervention-cap');
226
+ return passThrough();
227
+ }
228
+ const suspicion = port.suspicion(window);
229
+ if (!suspicion.suspicious)
230
+ return passThrough();
231
+ const started = port.clock().now();
232
+ const outcome = await runJudgment({
233
+ state: port.budget(),
234
+ policy,
235
+ buy: (step) => port.buy(step),
236
+ clock: port.clock(),
237
+ steps: window,
238
+ ...(invocation.signal === undefined ? {} : { signal: invocation.signal })
239
+ });
240
+ const charge = chargeOf(outcome, started, port.clock().now());
241
+ if (!outcome.useful) {
242
+ port.chargeJudgment(charge);
243
+ port.skip(outcome.skip ?? 'unconfirmed', charge);
244
+ return passThrough();
245
+ }
246
+ const facts = {
247
+ tool: port.toolName(),
248
+ suspicion,
249
+ verdict: outcome.response
250
+ };
251
+ const plan = {
252
+ capability: STAGNATION_CAPABILITY,
253
+ action: 'corrective-context',
254
+ reason: `System 1 confirmed ${outcome.response.patternType ?? suspicion.pattern} stagnation before step ${port.budget().step}`,
255
+ feedback: port.contextFeedback(facts),
256
+ detail: detailOf(suspicion, outcome.response, port.budget().turn, port.budget().step)
257
+ };
258
+ const applies = mode === 'active';
259
+ // The latch is mode-independent on purpose. Observe has to consume the same
260
+ // episode — one intervention per detected loop, one charge against the turn's
261
+ // cap — or its accounting would describe a run nobody could reproduce;
262
+ // installing the message is the only thing the mode gates.
263
+ port.latchIntervened();
264
+ bookAction(port.budget());
265
+ port.conclude(plan, applies, charge);
266
+ return applies
267
+ ? { result: port.correct(plan.feedback), action: 'allow' }
268
+ : passThrough();
269
+ }
270
+ //# sourceMappingURL=orchestrate-stagnation.js.map