dsh-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 (124) hide show
  1. package/README.md +20 -6
  2. package/client.js +3511 -185
  3. package/dist/attribution.d.ts +266 -0
  4. package/dist/attribution.js +238 -0
  5. package/dist/attribution.js.map +1 -0
  6. package/dist/bridge.d.ts +311 -13
  7. package/dist/bridge.js +714 -42
  8. package/dist/bridge.js.map +1 -1
  9. package/dist/client-bundle.js +4 -1
  10. package/dist/client-bundle.js.map +1 -1
  11. package/dist/command.js +10 -0
  12. package/dist/command.js.map +1 -1
  13. package/dist/config.d.ts +530 -22
  14. package/dist/config.js +808 -27
  15. package/dist/config.js.map +1 -1
  16. package/dist/delegation-dispatch.d.ts +132 -0
  17. package/dist/delegation-dispatch.js +186 -0
  18. package/dist/delegation-dispatch.js.map +1 -0
  19. package/dist/delegation-health.d.ts +131 -0
  20. package/dist/delegation-health.js +97 -0
  21. package/dist/delegation-health.js.map +1 -0
  22. package/dist/delegation.d.ts +148 -0
  23. package/dist/delegation.js +186 -0
  24. package/dist/delegation.js.map +1 -0
  25. package/dist/effort-delegation.d.ts +144 -0
  26. package/dist/effort-delegation.js +280 -0
  27. package/dist/effort-delegation.js.map +1 -0
  28. package/dist/effort.d.ts +141 -0
  29. package/dist/effort.js +251 -9
  30. package/dist/effort.js.map +1 -1
  31. package/dist/host-patch.d.ts +156 -0
  32. package/dist/host-patch.js +534 -0
  33. package/dist/host-patch.js.map +1 -0
  34. package/dist/index.d.ts +12 -3
  35. package/dist/index.js +99 -7
  36. package/dist/index.js.map +1 -1
  37. package/dist/interventions.d.ts +98 -373
  38. package/dist/interventions.js +442 -1702
  39. package/dist/interventions.js.map +1 -1
  40. package/dist/panel-api.d.ts +328 -4
  41. package/dist/panel-api.js +322 -15
  42. package/dist/panel-api.js.map +1 -1
  43. package/dist/panel-mount.d.ts +81 -22
  44. package/dist/panel-mount.js +228 -7
  45. package/dist/panel-mount.js.map +1 -1
  46. package/dist/routing.d.ts +23 -18
  47. package/dist/routing.js +471 -153
  48. package/dist/routing.js.map +1 -1
  49. package/dist/session-audit.d.ts +70 -0
  50. package/dist/session-audit.js +73 -0
  51. package/dist/session-audit.js.map +1 -1
  52. package/dist/systemone-probe.d.ts +114 -0
  53. package/dist/systemone-probe.js +383 -0
  54. package/dist/systemone-probe.js.map +1 -0
  55. package/dist/testing.d.ts +212 -7
  56. package/dist/testing.js +333 -27
  57. package/dist/testing.js.map +1 -1
  58. package/dist/tools.d.ts +109 -3
  59. package/dist/tools.js +103 -4
  60. package/dist/tools.js.map +1 -1
  61. package/dist/unconfigured-backend.d.ts +72 -0
  62. package/dist/unconfigured-backend.js +94 -0
  63. package/dist/unconfigured-backend.js.map +1 -0
  64. package/dist/vendor/harness-reflex/backend/factory.d.ts +31 -1
  65. package/dist/vendor/harness-reflex/backend/factory.js +18 -3
  66. package/dist/vendor/harness-reflex/backend/factory.js.map +1 -1
  67. package/dist/vendor/harness-reflex/backend/jev.d.ts +20 -0
  68. package/dist/vendor/harness-reflex/backend/jev.js +11 -4
  69. package/dist/vendor/harness-reflex/backend/jev.js.map +1 -1
  70. package/dist/vendor/harness-reflex/backend/simple-jev.d.ts +16 -0
  71. package/dist/vendor/harness-reflex/backend/simple-jev.js +17 -6
  72. package/dist/vendor/harness-reflex/backend/simple-jev.js.map +1 -1
  73. package/dist/vendor/harness-reflex/core/closing.d.ts +90 -0
  74. package/dist/vendor/harness-reflex/core/closing.js +111 -0
  75. package/dist/vendor/harness-reflex/core/closing.js.map +1 -0
  76. package/dist/vendor/harness-reflex/core/evidence.d.ts +119 -0
  77. package/dist/vendor/harness-reflex/core/evidence.js +209 -0
  78. package/dist/vendor/harness-reflex/core/evidence.js.map +1 -0
  79. package/dist/vendor/harness-reflex/core/judge.d.ts +221 -0
  80. package/dist/vendor/harness-reflex/core/judge.js +251 -0
  81. package/dist/vendor/harness-reflex/core/judge.js.map +1 -0
  82. package/dist/vendor/harness-reflex/core/orchestrate-closing.d.ts +237 -0
  83. package/dist/vendor/harness-reflex/core/orchestrate-closing.js +250 -0
  84. package/dist/vendor/harness-reflex/core/orchestrate-closing.js.map +1 -0
  85. package/dist/vendor/harness-reflex/core/orchestrate-correction.d.ts +209 -0
  86. package/dist/vendor/harness-reflex/core/orchestrate-correction.js +141 -0
  87. package/dist/vendor/harness-reflex/core/orchestrate-correction.js.map +1 -0
  88. package/dist/vendor/harness-reflex/core/orchestrate-host.d.ts +225 -0
  89. package/dist/vendor/harness-reflex/core/orchestrate-host.js +80 -0
  90. package/dist/vendor/harness-reflex/core/orchestrate-host.js.map +1 -0
  91. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.d.ts +259 -0
  92. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js +270 -0
  93. package/dist/vendor/harness-reflex/core/orchestrate-stagnation.js.map +1 -0
  94. package/dist/vendor/harness-reflex/core/orchestrate.d.ts +357 -0
  95. package/dist/vendor/harness-reflex/core/orchestrate.js +418 -0
  96. package/dist/vendor/harness-reflex/core/orchestrate.js.map +1 -0
  97. package/dist/vendor/harness-reflex/core/policy.d.ts +122 -0
  98. package/dist/vendor/harness-reflex/core/policy.js +102 -0
  99. package/dist/vendor/harness-reflex/core/policy.js.map +1 -0
  100. package/dist/vendor/harness-reflex/core/prune-plan.d.ts +141 -0
  101. package/dist/vendor/harness-reflex/core/prune-plan.js +390 -0
  102. package/dist/vendor/harness-reflex/core/prune-plan.js.map +1 -0
  103. package/dist/vendor/harness-reflex/core/text.d.ts +36 -0
  104. package/dist/vendor/harness-reflex/core/text.js +66 -0
  105. package/dist/vendor/harness-reflex/core/text.js.map +1 -0
  106. package/dist/vendor/harness-reflex/ports/audit.d.ts +18 -0
  107. package/dist/vendor/harness-reflex/ports/audit.js +11 -0
  108. package/dist/vendor/harness-reflex/ports/audit.js.map +1 -0
  109. package/dist/vendor/harness-reflex/ports/clock.d.ts +14 -0
  110. package/dist/vendor/harness-reflex/ports/clock.js +11 -0
  111. package/dist/vendor/harness-reflex/ports/clock.js.map +1 -0
  112. package/dist/vendor/harness-reflex/ports/decision.d.ts +75 -0
  113. package/dist/vendor/harness-reflex/ports/decision.js +2 -0
  114. package/dist/vendor/harness-reflex/ports/decision.js.map +1 -0
  115. package/dist/vendor/harness-reflex/ports/index.d.ts +14 -0
  116. package/dist/vendor/harness-reflex/ports/index.js +2 -0
  117. package/dist/vendor/harness-reflex/ports/index.js.map +1 -0
  118. package/dist/vendor/harness-reflex/ports/log.d.ts +22 -0
  119. package/dist/vendor/harness-reflex/ports/log.js +12 -0
  120. package/dist/vendor/harness-reflex/ports/log.js.map +1 -0
  121. package/dist/vendor/harness-reflex/ports/state.d.ts +46 -0
  122. package/dist/vendor/harness-reflex/ports/state.js +13 -0
  123. package/dist/vendor/harness-reflex/ports/state.js.map +1 -0
  124. package/package.json +25 -13
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effort-delegation.js","sourceRoot":"","sources":["../src/effort-delegation.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAC9C,OAAO,EAAE,yBAAyB,EAAiC,MAAM,oBAAoB,CAAC;AAE9F;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgEG;AAEH,qDAAqD;AACrD,MAAM,CAAC,MAAM,wBAAwB,GAAG,wBAAiC,CAAC;AAkD1E;;;;;;;GAOG;AACH,MAAM,UAAU,kBAAkB,CAAC,MAAqC;IACtE,IAAI,CAAC,MAAM,IAAI,OAAO,MAAM,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACxD,IAAI,OAAO,MAAM,CAAC,eAAe,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,eAAe,GAAG,CAAC,CAAC;IAClF,OAAO,MAAM,CAAC,MAAM,KAAK,UAAU,CAAC;AACtC,CAAC;AAED;;;;GAIG;AACH,SAAS,aAAa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OAAO,GAAG,IAAI,CAAC;QACjB,CAAC;QACD,IAAI,CAAC,OAAO;YAAE,OAAO;QACrB,6EAA6E;QAC7E,wCAAwC;QACxC,cAAc,CAAC,GAAG,EAAE;YAClB,IAAI,QAAQ;gBAAE,OAAO;YACrB,IAAI,CAAC;gBACH,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,SAAS,CAAC,CAAC;YACnC,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO,CAAC,IAAI,EAAE,CAAC,oDAAoD,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YACtF,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;IAEH,OAAO;QACL,IAAI,QAAQ;YACV,OAAO,QAAQ,CAAC;QAClB,CAAC;QACD,IAAI,OAAO;YACT,OAAO,OAAO,CAAC;QACjB,CAAC;QACD,OAAO;YACL,IAAI,QAAQ;gBAAE,OAAO;YACrB,QAAQ,GAAG,IAAI,CAAC;YAChB,IAAI,EAAE,CAAC;QACT,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type { Context } from '@deepseek-ai/cordis';\n\nimport { isEffortTrigger } from './effort.js';\nimport { appendEffortInheritRecord, type EffortInheritAuditRecord } from './session-audit.js';\n\n/**\n * Delegated agents cannot decide their own reasoning effort — so let them inherit.\n *\n * ## Why this exists (g-048)\n *\n * `executor.reasoning_effort: \"reflex\"` marks a deployment as adaptive: the\n * plugin decides the level per turn. For a delegated agent that decision used to\n * be taken inside the `agent/request` waterfall, and `dsh-agent-loop` refuses\n * exactly that — it fixes the step's effort during step preparation and rejects\n * any later proposal:\n *\n * agent/request proposed reasoning effort \"low\" after step preparation fixed\n * \"reflex\"; use agent.model.select() before step preparation\n *\n * The waterfall may re-route a request; it may not re-decide the effort. And\n * `agent/pre-step` cannot help either: the loop reads `model.current()` for that\n * step *before* the waterfall runs, so a `modelSelection` handed back from\n * `pre-step` is already too late. There is no host hook between \"the selection is\n * recorded\" and \"the step reads it\".\n *\n * ## What this does instead (C1)\n *\n * The marker the delegated agent would have decided on is replaced on its own\n * `model/selection` — the very log entry the loop folds to obtain `model.current()`\n * — with the level its parent session is currently using. The step then fixes a\n * concrete level, the request waterfall has nothing left to change, and the loop's\n * contract holds by construction rather than by suppressing a check.\n *\n * ## Why the rewrite is a second `model/selection` event\n *\n * The arriving event is deep-frozen (the Session snapshots and freezes every\n * payload) and the append that published it is still on the stack, so a listener\n * cannot rewrite it in place: `session append cannot reenter while another append\n * is being published`. Returning *before* the projection folds is not an option\n * either — listeners run in registration order, and the projection that serves\n * `model.current()` is registered by the agent runtime, ahead of this plugin.\n *\n * So the rewrite is committed immediately *after* the current append completes,\n * as one further `model/selection`. Only the last one counts: the selection fold\n * takes `pending` from the newest `model/selection`, which is exactly the value\n * `model.current()` returns. Nothing reads the selection in between — the driver\n * reaches its next step only after the current one has fully committed.\n *\n * Deferring also buys the ordering the parent needs. A child's selection may be\n * recorded before the parent has one, and the parent's own level may change\n * later; settling on a microtask keeps the copy current without depending on\n * which session was configured first.\n *\n * ## Boundaries\n *\n * - **Only delegated sessions.** A `delegationDepth > 0` header or a `subagent`\n * origin marks one; a main session is never touched, so the adaptive behaviour\n * its deployment asked for is bit-for-bit unchanged.\n * - **Only the marker.** `reflex`/`auto` is rewritten. A concrete level — the\n * caller's own choice — is left exactly as recorded.\n * - **`effort.enabled: false` keeps today's behaviour**, i.e. nothing happens\n * here and the interceptor clears the marker later, landing on the adapter's\n * default. Inheriting the parent's level would silently change what a switched\n * off deployment does.\n * - **No parent level, no inheritance:** the marker is removed, which is the\n * adapter's own default — the same outcome the disabled switch has, reached for\n * a different reason (recorded as such).\n *\n * @module dsh-reflex/effort-delegation\n */\n\n/** The only reason this module rewrites anything. */\nexport const DELEGATION_EFFORT_REASON = 'subagent-cannot-decide' as const;\n\n/** Structural view of the session header fields delegation is decided on. */\ninterface SessionHeaderLike {\n origin?: string;\n delegationDepth?: number;\n parentSession?: unknown;\n}\n\n/** Structural view of the selection events this module reads and writes. */\ninterface SelectionData {\n provider: string;\n model: string;\n reasoningEffort?: string;\n}\n\n/** Structural view of a live session. */\ninterface SessionLike {\n readonly id?: string;\n readonly header?: SessionHeaderLike;\n append(type: string, data: unknown): unknown;\n snapshotEvents?(): readonly { type: string; data?: any }[];\n}\n\n/** What {@link installDelegatedEffortInheritance} needs from the activation. */\nexport interface DelegatedEffortInheritanceOptions {\n /**\n * Read the live `effort.enabled` switch.\n *\n * A getter, not a value: a config-only settings save flips this without\n * remounting the plugin, and the next delegated selection must see the value\n * actually in force.\n */\n enabled: () => boolean;\n /** Resolve one session id to a live session (the parent lookup). */\n sessionById?: (id: string) => SessionLike | undefined;\n /** Diagnostic sink for non-fatal degradation (never throws). */\n warn?: (message: string) => void;\n}\n\n/** What {@link installDelegatedEffortInheritance} installed. */\nexport interface DelegatedEffortInheritance {\n /** How many delegated selections have been rewritten. */\n readonly rewrites: number;\n /** How many records have been written to child logs. */\n readonly records: number;\n /** Detach the listener; idempotent. */\n dispose(): void;\n}\n\n/**\n * Whether one session is a delegated agent's.\n *\n * `delegationDepth` is authoritative when present; `origin: 'subagent'` covers a\n * header written before depth was recorded. A main session has neither.\n * @param header - the session header, when the session has one.\n * @returns whether this session is a delegated child.\n */\nexport function isDelegatedSession(header: SessionHeaderLike | undefined): boolean {\n if (!header || typeof header !== 'object') return false;\n if (typeof header.delegationDepth === 'number') return header.delegationDepth > 0;\n return header.origin === 'subagent';\n}\n\n/**\n * Read the concrete level a selection carries.\n * @param selection - the selection to inspect.\n * @returns the level, or undefined when it carries none (or carries the marker).\n */\nfunction concreteLevel(selection: SelectionData | undefined): string | undefined {\n const effort = selection?.reasoningEffort;\n if (typeof effort !== 'string') return undefined;\n return isEffortTrigger(effort) ? undefined : effort;\n}\n\n/**\n * Fold one session's selection the way the host projection does.\n *\n * `model/selection` sets `pending`; a matching `request/header` retires it into\n * `lastUsed`. `model.current()` reads `pending ?? lastUsed`, so this is the exact\n * value the loop would fix for the next step.\n * @param session - the session to read.\n * @returns the selection in force, or undefined when none was ever recorded.\n */\nexport function currentSelectionOf(session: SessionLike | undefined): SelectionData | undefined {\n const events = session?.snapshotEvents?.() ?? [];\n let pending: SelectionData | undefined;\n let lastUsed: SelectionData | undefined;\n const same = (a: SelectionData | undefined, b: SelectionData | undefined): boolean =>\n a === b ||\n (a !== undefined &&\n b !== undefined &&\n a.provider === b.provider &&\n a.model === b.model &&\n a.reasoningEffort === b.reasoningEffort);\n for (const event of events) {\n if (event.type === 'model/selection') {\n const data = event.data as SelectionData | undefined;\n if (data && typeof data.provider === 'string' && typeof data.model === 'string') pending = data;\n continue;\n }\n if (event.type !== 'request/header') continue;\n const config = (event.data as { header?: { config?: SelectionData } } | undefined)?.header?.config;\n if (!config || typeof config.provider !== 'string' || typeof config.model !== 'string') continue;\n lastUsed = config;\n if (same(pending, config)) pending = undefined;\n }\n return pending ?? lastUsed;\n}\n\n/**\n * Build the audit record for one rewrite.\n * @param selection - the child selection that carried the marker.\n * @param requested - the marker that was there.\n * @param parentLevel - the level copied from the parent, when there was one.\n * @param parentLevel - how the parent looked up.\n * @param agentId - the delegated agent's id.\n * @param depth - the delegated agent's depth.\n * @returns the record payload.\n */\nfunction inheritRecord(\n selection: SelectionData,\n requested: string,\n parentLevel: string | undefined,\n parentState: EffortInheritAuditRecord['parentLevel'],\n agentId: string | undefined,\n depth: number | undefined\n): EffortInheritAuditRecord {\n return {\n requested,\n applied: parentLevel ?? null,\n reason: DELEGATION_EFFORT_REASON,\n ...(parentLevel === undefined ? {} : { inherited: parentLevel }),\n parentLevel: parentState,\n provider: selection.provider,\n model: selection.model,\n line:\n parentLevel === undefined\n ? `delegated agent: configured \"${requested}\", cannot decide per turn — marker removed (adapter default)`\n : `delegated agent: configured \"${requested}\", cannot decide per turn — inherited parent level \"${parentLevel}\"`,\n at: Date.now(),\n ...(agentId === undefined ? {} : { agentId }),\n ...(depth === undefined ? {} : { delegationDepth: depth })\n };\n}\n\n/**\n * Install the delegated-agent effort inheritance.\n *\n * The listener observes `model/selection` on every session and settles the\n * delegated ones off the current append, never inside it.\n * @param ctx - the plugin context whose `session/event` feed is observed.\n * @param options - live policy and the parent lookup.\n * @returns the installation handle.\n */\nexport function installDelegatedEffortInheritance(\n ctx: Context,\n options: DelegatedEffortInheritanceOptions\n): DelegatedEffortInheritance {\n let rewrites = 0;\n let records = 0;\n let disposed = false;\n\n /**\n * Rewrite one child selection, then record what happened.\n *\n * Every step is best-effort: this runs off a committed event, and an audit or\n * lookup failure must not become a failed turn.\n * @param session - the delegated agent's session.\n * @param selection - the child selection carrying the marker.\n * @param requested - the marker that was there.\n */\n const settle = (session: SessionLike, selection: SelectionData, requested: string): void => {\n if (disposed) return;\n const header = session.header;\n const parentId = header?.parentSession;\n let parentLevel: string | undefined;\n let parentState: EffortInheritAuditRecord['parentLevel'] = 'absent';\n try {\n if (parentId !== undefined && options.sessionById !== undefined) {\n const parent = options.sessionById(String(parentId));\n if (parent === undefined) parentState = 'absent';\n else {\n const level = concreteLevel(currentSelectionOf(parent));\n if (level === undefined) parentState = 'absent';\n else {\n parentLevel = level;\n parentState = 'present';\n }\n }\n }\n } catch (error) {\n // A hostile or half-built session must not swallow the rewrite itself:\n // without a readable parent the marker is removed, which is still valid.\n parentState = 'unreadable';\n parentLevel = undefined;\n options.warn?.(`dsh-reflex: could not read the parent level of a delegated agent: ${String(error)}`);\n }\n\n try {\n // A second `model/selection` is the rewrite: the fold takes `pending` from\n // the newest one, which is what the next step's `model.current()` reads.\n session.append('model/selection', {\n provider: selection.provider,\n model: selection.model,\n ...(parentLevel === undefined ? {} : { reasoningEffort: parentLevel })\n });\n rewrites += 1;\n } catch (error) {\n options.warn?.(`dsh-reflex: could not inherit a parent effort level: ${String(error)}`);\n return;\n }\n\n const record = inheritRecord(selection, requested, parentLevel, parentState, session.id, header?.delegationDepth);\n if (appendEffortInheritRecord(session, record) !== undefined) records += 1;\n };\n\n const stop = ctx.on('session/event', (session: any, event: any) => {\n if (disposed || event?.type !== 'model/selection') return;\n const data = event.data as SelectionData | undefined;\n if (!data || typeof data.provider !== 'string' || typeof data.model !== 'string') return;\n const requested = data.reasoningEffort;\n if (requested === undefined || !isEffortTrigger(requested)) return;\n if (!isDelegatedSession(session?.header)) return;\n // The disabled switch keeps its existing behaviour; the interceptor clears\n // the marker on the way out, so touching the selection here would change it.\n let enabled = true;\n try {\n enabled = options.enabled();\n } catch {\n enabled = true;\n }\n if (!enabled) return;\n // Off the current append: the log cannot be appended to while the event that\n // reported it is still being published.\n queueMicrotask(() => {\n if (disposed) return;\n try {\n settle(session, data, requested);\n } catch (error) {\n options.warn?.(`dsh-reflex: delegated effort inheritance failed: ${String(error)}`);\n }\n });\n });\n\n return {\n get rewrites(): number {\n return rewrites;\n },\n get records(): number {\n return records;\n },\n dispose(): void {\n if (disposed) return;\n disposed = true;\n stop();\n }\n };\n}\n"]}
package/dist/effort.d.ts CHANGED
@@ -58,8 +58,24 @@ export type EffortOutcome = 'supported' | 'snapped' | 'cleared' | 'unknown' | 'p
58
58
  export type EffortTriggerKind = 'request' | 'config';
59
59
  /** Characters of the turn input handed to System 1 as the question. */
60
60
  export declare const EFFORT_QUESTION_CHARS = 600;
61
+ /**
62
+ * Characters of *earlier turn* context prepended to a continuation reply.
63
+ *
64
+ * Deliberately a separate budget from {@link EFFORT_QUESTION_CHARS}: that one
65
+ * bounds how much of the current turn is shown, this one bounds how much of the
66
+ * session's history is borrowed. Raising the question budget must never widen
67
+ * the history window as a side effect, and a continuation reply's own text is
68
+ * only a few characters — the two limits answer different questions and are
69
+ * kept independent on purpose.
70
+ *
71
+ * The whole decision input of one turn is therefore bounded by
72
+ * `EFFORT_CONTEXT_CHARS + EFFORT_QUESTION_CHARS`, both constants, both known.
73
+ */
74
+ export declare const EFFORT_CONTEXT_CHARS = 400;
61
75
  /** Characters of the turn input kept in the audit surfaces. */
62
76
  export declare const EFFORT_AUDIT_TASK_CHARS = 160;
77
+ /** How many earlier turns of a session may contribute context. Fixed window. */
78
+ export declare const EFFORT_CONTEXT_TURNS = 3;
63
79
  /**
64
80
  * Scenario vocabulary of one adaptive level. The first token of every rendered
65
81
  * option is the level id, so a backend answer is parsed by prefix; the remaining
@@ -123,6 +139,26 @@ export interface EffortRequestContext {
123
139
  probe?: ReasoningProbe;
124
140
  /** Turn input captured on `agent/pre-step`. */
125
141
  task?: string;
142
+ /**
143
+ * Task text of earlier turns of this agent, oldest first.
144
+ *
145
+ * Always consulted, inside the fixed window, through
146
+ * {@link composeEffortDecisionInput} (g-063): a short prompt can continue a
147
+ * large task, and a short new instruction can name hard work, so grading text
148
+ * in isolation answers a question the user did not ask. The caller supplies
149
+ * observed turn text — never a session-log structure — keeping routing's ban on
150
+ * depending on the session module's internals intact.
151
+ */
152
+ history?: readonly EffortContextTurn[];
153
+ /**
154
+ * The level the previous decision produced for this agent (g-063).
155
+ *
156
+ * Read from the routing layer's own `lastAdaptiveEffort` fact, which existed
157
+ * since g-056 to recognise a header echo but never reached a decision. It is a
158
+ * prior, not an answer: {@link composeEffortDecisionInput} puts it on the
159
+ * decision input's opening line, and the prompt says it is to be weighed.
160
+ */
161
+ previousLevel?: string;
126
162
  agent?: EffortAgentFacts;
127
163
  turn?: number;
128
164
  step?: number;
@@ -191,6 +227,19 @@ export interface ReflexEffortStatus {
191
227
  heldForCache?: boolean;
192
228
  /** Effort ids the routed model declares; `[]` when it declares none. */
193
229
  supportedEfforts?: string[];
230
+ /**
231
+ * Characters of earlier-turn context that went into this decision; absent when
232
+ * the turn was graded on its own text (every new instruction). Present only
233
+ * for a continuation reply, and never above `EFFORT_CONTEXT_CHARS`.
234
+ */
235
+ contextChars?: number;
236
+ /** How many earlier turns that context came from, at most `EFFORT_CONTEXT_TURNS`. */
237
+ contextTurns?: number;
238
+ /**
239
+ * The level the previous decision produced, when this decision was told it
240
+ * (g-063). Absent on a session's first decision and after the prior aged out.
241
+ */
242
+ previousLevel?: string;
194
243
  }
195
244
  /** Whether a value is the adaptive trigger marker. */
196
245
  export declare function isEffortTrigger(value: string | undefined): value is EffortTrigger;
@@ -337,6 +386,85 @@ export declare function cleanEffortTaskText(task: string): CleanedEffortTask;
337
386
  * @returns matched cue words per tier, deduplicated, plus the input length.
338
387
  */
339
388
  export declare function readEffortCues(task: string): EffortCues;
389
+ /**
390
+ * Whether one turn input is a continuation reply rather than a new instruction.
391
+ *
392
+ * A continuation adds no task information of its own — "继续", "同意", "go
393
+ * ahead" — so grading its few characters in isolation answers a question the
394
+ * user did not ask. The caller decides the level from *what is being continued*
395
+ * instead; see {@link composeEffortDecisionInput}.
396
+ *
397
+ * The rule is word-level rather than one clever pattern: every token must be a
398
+ * continuation verb or filler, and at least one verb must be present. Any other
399
+ * content word — `继续实现 parser`, `go ahead and implement it` — names work this
400
+ * turn, so it is a new instruction and never a continuation. That is what keeps
401
+ * the path from widening beyond the replies it is meant for.
402
+ *
403
+ * `同意` and `按这个来` are not in {@link CUE_VOCABULARY}, so they are named here
404
+ * explicitly: without them the classifier would miss exactly the replies the
405
+ * goal is about, and they would keep being graded as if they were the whole task.
406
+ *
407
+ * @param task - the raw turn input.
408
+ * @returns whether the turn is a continuation reply.
409
+ */
410
+ export declare function isContinuationReply(task: string): boolean;
411
+ /** One earlier turn's text, as the continuation path may consult it. */
412
+ export interface EffortContextTurn {
413
+ /** That turn's captured task text, already cleaned by the caller or here. */
414
+ text: string;
415
+ }
416
+ /**
417
+ * The previous level prefix, as it appears in the decision input.
418
+ *
419
+ * A structured first line rather than a sentence: System 1 is asked which level
420
+ * a turn needs, and the level it chose last turn is a *prior* on that answer,
421
+ * not part of the task. Keeping it on its own line lets the prompt say so, and
422
+ * lets a test assert on it without parsing prose. English on both sides of the
423
+ * page for the same reason the cue vocabulary is: it is read by a backend, not
424
+ * by a user.
425
+ */
426
+ export declare const EFFORT_PREVIOUS_LEVEL_PREFIX = "[previous level:";
427
+ /**
428
+ * Render the previous level as the decision input's opening line.
429
+ * @param level - the level the previous decision produced.
430
+ * @returns e.g. `[previous level: high]`; empty when there was no previous decision.
431
+ */
432
+ export declare function formatPreviousLevelLine(level: string | undefined): string;
433
+ /**
434
+ * Compose the text one adaptive decision is graded on.
435
+ *
436
+ * **Every turn is graded on three things, in this order** (g-063):
437
+ *
438
+ * 1. the previous level, as a one-line prefix — what the last decision chose;
439
+ * 2. the recent turns, inside the same window as before;
440
+ * 3. this turn's own text, last.
441
+ *
442
+ * It used to be the other way round: a continuation reply ("继续", "同意") got the
443
+ * history and every other turn got only its own text. That split was wrong for
444
+ * the reason the continuation path was introduced for. A short prompt is not
445
+ * the same thing as a small task — "继续" may be continuing a migration — and a
446
+ * *new* instruction can be just as short ("改成这样") while the work it names is
447
+ * everything the session has been doing. Grading text in isolation therefore
448
+ * answers a question the user did not ask, whichever branch it happens in.
449
+ *
450
+ * The history is cut from its **end**: the most recent turns are the ones being
451
+ * continued, so when the window overflows the oldest text is what goes first.
452
+ *
453
+ * Every part goes through {@link cleanEffortTaskText}: the history carries the
454
+ * same architecture/proof vocabulary the current turn does, and it is exactly
455
+ * that vocabulary that P9 showed must not leak into a decision as a raw keyword.
456
+ *
457
+ * @param task - the current turn input.
458
+ * @param history - earlier turns of this session, oldest first.
459
+ * @param previousLevel - the level the previous decision produced, when known.
460
+ * @returns the text to grade, and how much history and state were actually used.
461
+ */
462
+ export declare function composeEffortDecisionInput(task: string, history?: readonly EffortContextTurn[], previousLevel?: string): {
463
+ text: string;
464
+ contextChars: number;
465
+ contextTurns: number;
466
+ previousLevel?: string;
467
+ };
340
468
  /** One tier's vote. */
341
469
  export interface EffortCueVote {
342
470
  level: AdaptiveEffortLevel;
@@ -372,12 +500,25 @@ export declare function classifyByCues(cues: EffortCues, fallback?: AdaptiveEffo
372
500
  * handed a keyword-scoring backend the exact words the cleanup had just removed
373
501
  * — the second half of the P9 regression.
374
502
  *
503
+ * g-063 adds a second neutral clause, and only when the input really opens with
504
+ * the previous level (see {@link composeEffortDecisionInput}): the line says the
505
+ * prior is there to be *considered*, and that a short reply to a larger task, or
506
+ * a new instruction inside a hard session, keeps the depth the session needs.
507
+ * Without that clause a text-reading backend can read `[previous level: high]`
508
+ * as the answer instead of as a hint.
509
+ *
375
510
  * @param task - the turn input captured before the request.
376
511
  * @param cues - its cue words (already cleaned).
377
512
  * @param efforts - effort ids the routed model declares; omitted keeps the whole ladder.
378
513
  * @returns the question and the level candidates.
379
514
  */
380
515
  export declare function buildEffortChoice(task: string, cues: EffortCues, efforts?: readonly string[]): ChoiceRequest;
516
+ /**
517
+ * Whether a decision input opens with the previous-level line.
518
+ * @param text - the composed decision input.
519
+ * @returns whether the structured prefix is present.
520
+ */
521
+ export declare function hasPreviousLevelPrefix(text: string): boolean;
381
522
  /**
382
523
  * Read the level out of one candidate option.
383
524
  * @param option - an option produced by {@link EFFORT_CHOICE_OPTIONS}.
package/dist/effort.js CHANGED
@@ -16,8 +16,24 @@ export const ADAPTIVE_EFFORT_LEVELS = ['off', 'low', 'medium', 'high'];
16
16
  export const EFFORT_TRIGGERS = ['reflex', 'auto'];
17
17
  /** Characters of the turn input handed to System 1 as the question. */
18
18
  export const EFFORT_QUESTION_CHARS = 600;
19
+ /**
20
+ * Characters of *earlier turn* context prepended to a continuation reply.
21
+ *
22
+ * Deliberately a separate budget from {@link EFFORT_QUESTION_CHARS}: that one
23
+ * bounds how much of the current turn is shown, this one bounds how much of the
24
+ * session's history is borrowed. Raising the question budget must never widen
25
+ * the history window as a side effect, and a continuation reply's own text is
26
+ * only a few characters — the two limits answer different questions and are
27
+ * kept independent on purpose.
28
+ *
29
+ * The whole decision input of one turn is therefore bounded by
30
+ * `EFFORT_CONTEXT_CHARS + EFFORT_QUESTION_CHARS`, both constants, both known.
31
+ */
32
+ export const EFFORT_CONTEXT_CHARS = 400;
19
33
  /** Characters of the turn input kept in the audit surfaces. */
20
34
  export const EFFORT_AUDIT_TASK_CHARS = 160;
35
+ /** How many earlier turns of a session may contribute context. Fixed window. */
36
+ export const EFFORT_CONTEXT_TURNS = 3;
21
37
  /**
22
38
  * Scenario vocabulary of one adaptive level. The first token of every rendered
23
39
  * option is the level id, so a backend answer is parsed by prefix; the remaining
@@ -415,6 +431,192 @@ export function readEffortCues(task) {
415
431
  }
416
432
  return cues;
417
433
  }
434
+ /** Politeness that may surround a continuation without being one. */
435
+ const CONTINUATION_FILLER = new Set([
436
+ 'ok', 'okay', 'sure', 'yes', 'yeah', 'yep', 'alright', 'right', 'fine', 'great', 'cool', 'good', 'perfect',
437
+ 'go', 'just', 'then', 'please', 'thanks', 'thank', 'you', 'on', 'ahead', 'and',
438
+ '好的', '好', '行', '可以', '没问题', '那就', '就', '嗯', '对', '是的', '收到', '谢谢', '麻烦你', '请', '吧', '来', '做', '了', '的'
439
+ ]);
440
+ /** Leading filler that may be glued to a Han verb: `那就继续`, `那就按这个来`. */
441
+ const CONTINUATION_LEAD = ['那就', '就这么'];
442
+ /**
443
+ * Multi-word English continuations. Split into tokens these are
444
+ * `go`+`ahead`, `go`+`on`, `carry`+`on`, `keep`+`going`; each word is filler or
445
+ * verb on its own, so the pair is what has to be recognised.
446
+ */
447
+ const CONTINUATION_PHRASE = /\b(?:go\s+(?:ahead|on)|carry\s+on|keep\s+going)\b/iu;
448
+ /**
449
+ * Words that *are* the continuation, as opposed to politeness around it.
450
+ *
451
+ * Agreeing — 同意, 赞成, 按这个来 — is the same act as "continue": it commits the
452
+ * session to work already described rather than describing new work.
453
+ */
454
+ const CONTINUATION_VERB = new Set([
455
+ 'continue', 'proceed', 'carry', 'keep', 'going',
456
+ '继续', '接着', '下一步', '按这个', '按这样', '就这么', '照这个', '往下', '同意', '赞成', '可以的'
457
+ ]);
458
+ /** Longest continuation verb, used to bound the prefix scan. */
459
+ const CONTINUATION_VERB_MAX = Math.max(...[...CONTINUATION_VERB].map((word) => word.length));
460
+ /** Split one reply into content-bearing pieces, dropping punctuation and spacing. */
461
+ function replyTokens(text) {
462
+ return text
463
+ .toLowerCase()
464
+ .split(/[^\p{Script=Han}a-z0-9]+/u)
465
+ .filter((token) => token.length > 0);
466
+ }
467
+ /**
468
+ * Whether one token is a continuation verb, alone or with trailing filler:
469
+ * `继续`, `继续吧`, `继续做`, `按这个来`, `go`+`ahead` handled at token level.
470
+ */
471
+ function isContinuationVerb(token) {
472
+ if (CONTINUATION_VERB.has(token))
473
+ return true;
474
+ for (const lead of CONTINUATION_LEAD) {
475
+ if (token.startsWith(lead))
476
+ return isContinuationVerb(token.slice(lead.length));
477
+ }
478
+ // A Han run may carry trailing filler ("继续吧", "那就继续吧" splits into
479
+ // "那就"+"继续吧"): match the longest known prefix whose remainder is all
480
+ // filler, one character at a time. A shorter verb must still be tried when the
481
+ // longest prefix's remainder is not filler, hence the loop rather than a return.
482
+ for (let size = Math.min(token.length, CONTINUATION_VERB_MAX); size > 0; size -= 1) {
483
+ const head = token.slice(0, size);
484
+ if (!CONTINUATION_VERB.has(head))
485
+ continue;
486
+ const rest = token.slice(size);
487
+ if (rest.length === 0)
488
+ return true;
489
+ if (!/\p{Script=Han}/u.test(rest))
490
+ continue;
491
+ if ([...rest].every((char) => CONTINUATION_FILLER.has(char)))
492
+ return true;
493
+ }
494
+ return false;
495
+ }
496
+ /**
497
+ * Whether one turn input is a continuation reply rather than a new instruction.
498
+ *
499
+ * A continuation adds no task information of its own — "继续", "同意", "go
500
+ * ahead" — so grading its few characters in isolation answers a question the
501
+ * user did not ask. The caller decides the level from *what is being continued*
502
+ * instead; see {@link composeEffortDecisionInput}.
503
+ *
504
+ * The rule is word-level rather than one clever pattern: every token must be a
505
+ * continuation verb or filler, and at least one verb must be present. Any other
506
+ * content word — `继续实现 parser`, `go ahead and implement it` — names work this
507
+ * turn, so it is a new instruction and never a continuation. That is what keeps
508
+ * the path from widening beyond the replies it is meant for.
509
+ *
510
+ * `同意` and `按这个来` are not in {@link CUE_VOCABULARY}, so they are named here
511
+ * explicitly: without them the classifier would miss exactly the replies the
512
+ * goal is about, and they would keep being graded as if they were the whole task.
513
+ *
514
+ * @param task - the raw turn input.
515
+ * @returns whether the turn is a continuation reply.
516
+ */
517
+ export function isContinuationReply(task) {
518
+ const text = cleanEffortTaskText(task).text;
519
+ if (text.length === 0)
520
+ return false;
521
+ const tokens = replyTokens(text);
522
+ if (tokens.length === 0)
523
+ return false;
524
+ // Every token must be filler or a continuation verb, and at least one must be
525
+ // a verb. Filler may sit on either side of it ("好的,继续", "继续吧,那就"), so
526
+ // the scan only has to reject a foreign word, not order the reply.
527
+ let sawVerb = CONTINUATION_PHRASE.test(text);
528
+ for (const token of tokens) {
529
+ if (isContinuationVerb(token))
530
+ sawVerb = true;
531
+ else if (!CONTINUATION_FILLER.has(token))
532
+ return false;
533
+ }
534
+ return sawVerb;
535
+ }
536
+ /**
537
+ * The previous level prefix, as it appears in the decision input.
538
+ *
539
+ * A structured first line rather than a sentence: System 1 is asked which level
540
+ * a turn needs, and the level it chose last turn is a *prior* on that answer,
541
+ * not part of the task. Keeping it on its own line lets the prompt say so, and
542
+ * lets a test assert on it without parsing prose. English on both sides of the
543
+ * page for the same reason the cue vocabulary is: it is read by a backend, not
544
+ * by a user.
545
+ */
546
+ export const EFFORT_PREVIOUS_LEVEL_PREFIX = '[previous level:';
547
+ /**
548
+ * Render the previous level as the decision input's opening line.
549
+ * @param level - the level the previous decision produced.
550
+ * @returns e.g. `[previous level: high]`; empty when there was no previous decision.
551
+ */
552
+ export function formatPreviousLevelLine(level) {
553
+ const value = (level ?? '').trim();
554
+ return value.length === 0 ? '' : `${EFFORT_PREVIOUS_LEVEL_PREFIX} ${value}]`;
555
+ }
556
+ /**
557
+ * Compose the text one adaptive decision is graded on.
558
+ *
559
+ * **Every turn is graded on three things, in this order** (g-063):
560
+ *
561
+ * 1. the previous level, as a one-line prefix — what the last decision chose;
562
+ * 2. the recent turns, inside the same window as before;
563
+ * 3. this turn's own text, last.
564
+ *
565
+ * It used to be the other way round: a continuation reply ("继续", "同意") got the
566
+ * history and every other turn got only its own text. That split was wrong for
567
+ * the reason the continuation path was introduced for. A short prompt is not
568
+ * the same thing as a small task — "继续" may be continuing a migration — and a
569
+ * *new* instruction can be just as short ("改成这样") while the work it names is
570
+ * everything the session has been doing. Grading text in isolation therefore
571
+ * answers a question the user did not ask, whichever branch it happens in.
572
+ *
573
+ * The history is cut from its **end**: the most recent turns are the ones being
574
+ * continued, so when the window overflows the oldest text is what goes first.
575
+ *
576
+ * Every part goes through {@link cleanEffortTaskText}: the history carries the
577
+ * same architecture/proof vocabulary the current turn does, and it is exactly
578
+ * that vocabulary that P9 showed must not leak into a decision as a raw keyword.
579
+ *
580
+ * @param task - the current turn input.
581
+ * @param history - earlier turns of this session, oldest first.
582
+ * @param previousLevel - the level the previous decision produced, when known.
583
+ * @returns the text to grade, and how much history and state were actually used.
584
+ */
585
+ export function composeEffortDecisionInput(task, history = [], previousLevel) {
586
+ const earlier = (level) => (level.trim().length === 0 ? '' : level.trim());
587
+ const fromState = earlier(previousLevel ?? '');
588
+ // The current turn is already recorded in the history by the time it is
589
+ // decided (`agent/pre-step` runs first), so it is dropped here: a session's
590
+ // own text must not be counted as its history, or the window would say it
591
+ // used a turn that says nothing new.
592
+ const current = cleanEffortTaskText(task).text;
593
+ // Newest first, bounded by the turn window, then joined oldest-first inside
594
+ // the window so the reading order matches the session's own.
595
+ const recent = history
596
+ .map((turn) => cleanEffortTaskText(turn.text).text)
597
+ .filter((text) => text.length > 0 && text !== current)
598
+ .slice(-EFFORT_CONTEXT_TURNS)
599
+ .reverse();
600
+ const kept = [];
601
+ let budget = EFFORT_CONTEXT_CHARS;
602
+ for (const text of recent) {
603
+ if (budget <= 0)
604
+ break;
605
+ // A turn longer than what is left contributes its tail: the end of a task
606
+ // description is the part a continuation is most likely about.
607
+ const slice = text.length > budget ? text.slice(text.length - budget) : text;
608
+ kept.push(slice);
609
+ budget -= slice.length + 1; // +1 for the newline joining it to the next entry
610
+ }
611
+ const context = kept.reverse().join('\n');
612
+ const parts = [formatPreviousLevelLine(fromState), context, task].filter((part) => part.length > 0);
613
+ return {
614
+ text: parts.join('\n'),
615
+ contextChars: context.length,
616
+ contextTurns: kept.length,
617
+ ...(fromState.length === 0 ? {} : { previousLevel: fromState })
618
+ };
619
+ }
418
620
  /**
419
621
  * Decide one turn's effort from cue words alone.
420
622
  *
@@ -475,6 +677,13 @@ export function classifyByCues(cues, fallback = 'medium', efforts) {
475
677
  * handed a keyword-scoring backend the exact words the cleanup had just removed
476
678
  * — the second half of the P9 regression.
477
679
  *
680
+ * g-063 adds a second neutral clause, and only when the input really opens with
681
+ * the previous level (see {@link composeEffortDecisionInput}): the line says the
682
+ * prior is there to be *considered*, and that a short reply to a larger task, or
683
+ * a new instruction inside a hard session, keeps the depth the session needs.
684
+ * Without that clause a text-reading backend can read `[previous level: high]`
685
+ * as the answer instead of as a hint.
686
+ *
478
687
  * @param task - the turn input captured before the request.
479
688
  * @param cues - its cue words (already cleaned).
480
689
  * @param efforts - effort ids the routed model declares; omitted keeps the whole ladder.
@@ -495,12 +704,28 @@ export function buildEffortChoice(task, cues, efforts) {
495
704
  // would reward whichever description happens to spell a level out.
496
705
  context = 'the routed model offers a bounded set of reasoning levels; choose the one this turn needs';
497
706
  }
707
+ const clauses = [];
708
+ if (context !== undefined)
709
+ clauses.push(context);
710
+ // The prefix line is judged, not obeyed: today's text is the task, the earlier
711
+ // turns and the previous level are only context for it.
712
+ if (hasPreviousLevelPrefix(cleaned.text) || hasPreviousLevelPrefix(task)) {
713
+ clauses.push('a leading [previous level: …] line is the level the last decision produced; weigh it with the task, do not copy it — a short reply or a short new instruction can still continue hard work');
714
+ }
498
715
  return {
499
716
  question,
500
717
  options,
501
- ...(context === undefined ? {} : { context })
718
+ ...(clauses.length === 0 ? {} : { context: clauses.join('; ') })
502
719
  };
503
720
  }
721
+ /**
722
+ * Whether a decision input opens with the previous-level line.
723
+ * @param text - the composed decision input.
724
+ * @returns whether the structured prefix is present.
725
+ */
726
+ export function hasPreviousLevelPrefix(text) {
727
+ return text.trimStart().startsWith(EFFORT_PREVIOUS_LEVEL_PREFIX);
728
+ }
504
729
  /**
505
730
  * Read the level out of one candidate option.
506
731
  * @param option - an option produced by {@link EFFORT_CHOICE_OPTIONS}.
@@ -658,18 +883,23 @@ export class EffortInterceptor {
658
883
  async #decideTurn(trigger, context) {
659
884
  const task = context.task ?? '';
660
885
  const started = this.#now();
886
+ // Every turn is graded on the previous level, the recent turns and its own
887
+ // text together (g-063). g-053 graded only continuation replies this way,
888
+ // which left a short *new* instruction ("改成这样") as undecided as "继续".
889
+ const decisionInput = composeEffortDecisionInput(task, context.history, context.previousLevel);
890
+ const graded = decisionInput.text;
661
891
  const support = await resolveSupport(context);
662
892
  const efforts = support.kind === 'declared' ? [...support.efforts] : undefined;
663
893
  if (support.kind === 'none') {
664
894
  // The model cannot think, so no System 1 round trip is worth buying: the
665
895
  // turn's level is still *reported* — the status row and the audit have to
666
896
  // say how deep the turn was — but the request must not carry the key.
667
- const decision = this.#decideByCues(readEffortCues(task), started, undefined, 'target model declares no reasoning; the level is reported but never sent');
668
- const status = buildEffortStatus(decision, { outcome: 'cleared' }, trigger, context, support);
897
+ const decision = this.#decideByCues(readEffortCues(graded), started, undefined, 'target model declares no reasoning; the level is reported but never sent');
898
+ const status = buildEffortStatus(decision, { outcome: 'cleared' }, trigger, context, support, decisionInput);
669
899
  this.#publish(decision, status, task);
670
900
  return { changed: context.requested !== undefined, outcome: 'cleared', trigger, decision, status };
671
901
  }
672
- const cues = readEffortCues(task);
902
+ const cues = readEffortCues(graded);
673
903
  // A restatement instruction is decided by its shape, not by its content: the
674
904
  // payload may be unquoted (`原文照抄:design the migration protocol`) and the
675
905
  // instruction's own phrasing may survive the negation cleanup (`不要优化…`).
@@ -677,10 +907,10 @@ export class EffortInterceptor {
677
907
  // false positive the cleanup exists to remove, so the cue verdict stands.
678
908
  const attempt = cleanEffortTaskText(task).verbatim
679
909
  ? { reason: 'the turn is a restatement instruction; the payload is a copy, not work to grade' }
680
- : await this.#askSystemOne(task, cues, started, efforts);
910
+ : await this.#askSystemOne(graded, cues, started, efforts);
681
911
  const decision = attempt.decision ?? this.#decideByCues(cues, started, efforts, attempt.reason);
682
912
  const projection = projectWithinSupport(decision.level, support);
683
- const status = buildEffortStatus(decision, projection, trigger, context, support);
913
+ const status = buildEffortStatus(decision, projection, trigger, context, support, decisionInput);
684
914
  this.#publish(decision, status, task);
685
915
  return {
686
916
  changed: projection.effort !== context.requested,
@@ -787,7 +1017,13 @@ export class EffortInterceptor {
787
1017
  ...(status.role ? { role: status.role } : {}),
788
1018
  ...(status.delegationDepth === undefined ? {} : { delegationDepth: status.delegationDepth }),
789
1019
  ...(status.turn === undefined ? {} : { turn: status.turn }),
790
- ...(status.step === undefined ? {} : { step: status.step })
1020
+ ...(status.step === undefined ? {} : { step: status.step }),
1021
+ // g-053: the ledger has to show *that* earlier context was used, not
1022
+ // just the level that came out of it.
1023
+ ...(status.contextChars === undefined ? {} : { contextChars: status.contextChars, contextTurns: status.contextTurns }),
1024
+ // g-063: the previous level is part of the evidence, so the ledger has
1025
+ // to name the prior the decision was given, not only the text it saw.
1026
+ ...(status.previousLevel === undefined ? {} : { previousLevel: status.previousLevel })
791
1027
  }
792
1028
  });
793
1029
  }
@@ -833,7 +1069,7 @@ function elapsed(now, started) {
833
1069
  * @param support - the routed model's declared vocabulary, when it was read.
834
1070
  * @returns the status payload.
835
1071
  */
836
- function buildEffortStatus(decision, projection, trigger, context, support) {
1072
+ function buildEffortStatus(decision, projection, trigger, context, support, decisionInput) {
837
1073
  const task = context.task?.trim() ?? '';
838
1074
  const status = {
839
1075
  level: decision.level,
@@ -860,7 +1096,13 @@ function buildEffortStatus(decision, projection, trigger, context, support) {
860
1096
  ...(context.switched === undefined ? {} : { switched: context.switched }),
861
1097
  ...(context.heldForCache === undefined ? {} : { heldForCache: context.heldForCache }),
862
1098
  ...(support?.kind === 'declared' ? { supportedEfforts: [...support.efforts] } : {}),
863
- ...(support?.kind === 'none' ? { supportedEfforts: [] } : {})
1099
+ ...(support?.kind === 'none' ? { supportedEfforts: [] } : {}),
1100
+ // Audit trail of the decision input: how much earlier-turn text the decision
1101
+ // actually saw. Absent when the session has no earlier turn to show, so the
1102
+ // status keeps the shape it had before g-053 on a cold session.
1103
+ ...(decisionInput?.contextChars ? { contextChars: decisionInput.contextChars, contextTurns: decisionInput.contextTurns } : {}),
1104
+ // g-063: which level this decision was told about beforehand.
1105
+ ...(decisionInput?.previousLevel === undefined ? {} : { previousLevel: decisionInput.previousLevel })
864
1106
  };
865
1107
  return { ...status, line: formatEffortStatusLine(status) };
866
1108
  }