@event4u/agent-config 15.0.0 → 16.0.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.
- package/.augment-plugin/marketplace.json +3 -3
- package/.augment-plugin/plugin.json +1 -1
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +142 -348
- package/dist/agent-src/commands/roadmap/create.md +3 -2
- package/dist/agent-src/contexts/communication/rules-auto/user-interaction-mechanics.md +50 -0
- package/dist/agent-src/rules/user-interaction.md +31 -30
- package/dist/agent-src/skills/error-handling-patterns/SKILL.md +9 -0
- package/dist/agent-src/templates/agents/agent-project-settings.example.yml +1 -1
- package/dist/cli-delegate/{chunk-HZ52BRGG.js → chunk-H32DGUJH.js} +14 -89
- package/dist/cli-delegate/chunk-NUHLI2RX.js +80 -0
- package/dist/cli-delegate/{chunk-TYSY33MD.js → chunk-QJWAUMJW.js} +12 -2
- package/dist/cli-delegate/{chunk-2KKXJW25.js → chunk-S3VFXMTM.js} +1 -1
- package/dist/cli-delegate/cmd_conformance.js +831 -272
- package/dist/cli-delegate/cmd_explain.js +4 -2
- package/dist/cli-delegate/cmd_handoff.js +2 -2
- package/dist/cli-delegate/cmd_packs_active.js +2 -1
- package/dist/cli-delegate/cmd_session_recycle.js +2 -2
- package/dist/cli-delegate/cmd_settings_set.js +13 -0
- package/dist/discovery/deprecation-report.md +1 -1
- package/dist/discovery/discovery-manifest.json +5 -5
- package/dist/discovery/discovery-manifest.json.sha256 +1 -1
- package/dist/discovery/discovery-manifest.summary.md +1 -1
- package/dist/discovery/dormancy-report.md +1 -1
- package/dist/discovery/orphan-report.md +1 -1
- package/dist/discovery/packs.json +2 -2
- package/dist/discovery/trust-report.md +1 -1
- package/dist/discovery/workspaces.json +2 -2
- package/dist/hooks/dispatch.js +1274 -571
- package/dist/install/install.mjs +1 -0
- package/dist/mcp/registry-manifest.json +2 -2
- package/dist/mcp/server.json +2 -2
- package/dist/mcp/server.mjs +1218 -632
- package/dist/scripts/_lib/installed_lock.js +1 -1
- package/dist/server/io/yamlIO.js +50 -0
- package/package.json +1 -1
- package/src/config/continuity-surface.json +7 -0
- package/src/config/gate-violation-baselines.json +3 -3
- package/src/config/host-injection-effect.json +1 -1
- package/src/config/preamble-payload-budget.json +12 -7
- package/src/config/preamble-payload-exceptions.json +28 -0
- package/src/scripts/_dispatch.bash +3 -1
- package/src/scripts/_lib/base_ref_payload.ts +315 -0
- package/src/scripts/_lib/dropped_decision.ts +142 -0
- package/src/scripts/_lib/installed_lock.ts +1 -1
- package/src/scripts/_lib/measured_payload_ceiling.ts +424 -0
- package/src/scripts/_lib/payload_catalogue_completeness.ts +211 -0
- package/src/scripts/_lib/release_findings_ingest.ts +324 -0
- package/src/scripts/_lib/release_tag_dispatch.ts +63 -0
- package/src/scripts/_lib/review_baseline.ts +254 -0
- package/src/scripts/_lib/review_skipped_record.ts +61 -1
- package/src/scripts/_lib/standing_bound_ratchet.ts +216 -103
- package/src/scripts/_lib/turn_end_refusals.ts +51 -4
- package/src/scripts/check_beta_review_markers.ts +35 -4
- package/src/scripts/check_finding_dispositions.ts +167 -16
- package/src/scripts/check_held_object_arrivals.ts +381 -0
- package/src/scripts/check_preamble_payload_budget.ts +399 -122
- package/src/scripts/check_release_published.ts +1 -1
- package/src/scripts/check_reply_consistency.ts +86 -17
- package/src/scripts/hook_manifest.json +1 -1
- package/src/scripts/hook_manifest.yaml +39 -3
- package/src/scripts/hooks/block_kernel_rule_writes.ts +12 -2
- package/src/scripts/hooks/concern_registry.ts +2 -0
- package/src/scripts/hooks/end_review_nudge_hook.ts +101 -21
- package/src/scripts/hooks/review_baseline_hook.ts +130 -0
- package/src/scripts/hooks/turn_end_gate_hook.ts +232 -14
- package/src/scripts/hooks_doctor.ts +4 -1
- package/src/scripts/install.ts +1 -1
- package/src/scripts/interruption_report.ts +8 -2
- package/src/scripts/janitor.ts +8 -1
- package/src/scripts/measure_turn_end_gate.ts +302 -5
- package/src/scripts/release.ts +52 -64
- package/src/scripts/release_drill.ts +193 -14
- package/src/scripts/release_env.ts +1 -1
- package/src/scripts/release_publication.ts +1 -1
- package/src/scripts/report_held_object_arrivals.ts +456 -0
- package/src/scripts/sync_agent_settings.ts +140 -18
- package/src/server/io/yamlIO.ts +48 -0
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Detector E of `turn-end-gate`, extracted so its prose costs nothing.
|
|
3
|
+
*
|
|
4
|
+
* It lives here rather than in the hook for one mechanical reason and one real
|
|
5
|
+
* one. The mechanical one: `turn_end_gate_hook.ts` sits past the 1500-line
|
|
6
|
+
* source ceiling, where every line is one unit of ratchet debt, and this module
|
|
7
|
+
* is under it. The real one: E is the only detector that reads a LIST of the
|
|
8
|
+
* turn's assistant texts rather than the single closing one, so it shares no
|
|
9
|
+
* input with A-D and F, and its dependencies are the reply-consistency parser
|
|
10
|
+
* rather than anything the hook owns.
|
|
11
|
+
*/
|
|
12
|
+
import {
|
|
13
|
+
find_option_blocks,
|
|
14
|
+
recommendationsUnder,
|
|
15
|
+
splitAndMask,
|
|
16
|
+
} from '../check_reply_consistency.js';
|
|
17
|
+
import type { RefusalDetectorId } from './turn_end_refusals.js';
|
|
18
|
+
|
|
19
|
+
/** The shape the gate collects. Kept structural so this module imports no hook. */
|
|
20
|
+
export interface DroppedDecisionFinding {
|
|
21
|
+
detector: RefusalDetectorId;
|
|
22
|
+
evidence: string;
|
|
23
|
+
reason: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Detector E — a decision put to the user in this turn, dropped before the turn
|
|
28
|
+
* ended.
|
|
29
|
+
*
|
|
30
|
+
* THE MEASURED FAILURE. An assistant turn put three numbered options and a
|
|
31
|
+
* recommendation line to the user. The `end-review-nudge` stop concern then
|
|
32
|
+
* produced a SECOND assistant execution with no intervening user message, and
|
|
33
|
+
* that second reply handled the nudge while demoting the open question to a
|
|
34
|
+
* subordinate clause — "bleibt davon unberührt und liegt bei Dir". From the
|
|
35
|
+
* user's side the conversation ended without a question. No rule stated this
|
|
36
|
+
* when the detector was written: `user-interaction` Iron Law 1 inspects a reply
|
|
37
|
+
* that HAS an options block, `check_reply_consistency` receives a draft and not
|
|
38
|
+
* a transcript, `active-remediation` governs findings rather than issued
|
|
39
|
+
* decisions, and `no-cheap-questions` guards the opposite direction. That gap
|
|
40
|
+
* is now closed from the other side — `user-interaction` Iron Law 3 states the
|
|
41
|
+
* continuity obligation, and the refusal below cites it — so this paragraph
|
|
42
|
+
* records why the detector exists, not a gap that is still open.
|
|
43
|
+
*
|
|
44
|
+
* WHAT IT READS. `assistantTurnTexts` — the assistant texts since the last
|
|
45
|
+
* GENUINE user prompt, with synthetic prompts and sidechain entries already
|
|
46
|
+
* filtered by `readTranscriptTail`. So a task notification, a system reminder or
|
|
47
|
+
* a subagent's own prompt does not read as an answer, which is the whole point:
|
|
48
|
+
* the failure is defined by the absence of a real user turn.
|
|
49
|
+
*
|
|
50
|
+
* WHAT IT DELIBERATELY DOES NOT DO. It does not model the decision — no id, no
|
|
51
|
+
* `pending → answered` lifecycle, no semantic matching of a free-text reply
|
|
52
|
+
* against an option. That object is grant-shaped and
|
|
53
|
+
* `road-to-decision-closure` owns its ownership routing; a second obligation
|
|
54
|
+
* ledger here would be the parallel taxonomy that roadmap exists to prevent.
|
|
55
|
+
* This is transcript adjacency and nothing above it.
|
|
56
|
+
*
|
|
57
|
+
* AN ASK IS A BLOCK **PLUS** ITS RECOMMENDATION LINE, and that qualifier is
|
|
58
|
+
* load-bearing rather than pedantic. `find_option_blocks` calls any run of two
|
|
59
|
+
* or more consecutive numbered lines a block — a plan, a findings list, an
|
|
60
|
+
* ordinary enumeration. Keyed on the block alone this detector fired on 29 of
|
|
61
|
+
* this repository's own 592 assistant turns, and 8 of those blocks carried no
|
|
62
|
+
* recommendation line anywhere near them: pure false positives on narrative
|
|
63
|
+
* lists, in a detector that can REFUSE a turn. `user-interaction` Iron Law 1
|
|
64
|
+
* already says the recommendation line is the ask, so requiring it removes that
|
|
65
|
+
* whole class by applying the rule this refusal cites rather than by bolting a
|
|
66
|
+
* heuristic beside it.
|
|
67
|
+
*
|
|
68
|
+
* The cost, stated rather than discovered: an options block whose recommendation
|
|
69
|
+
* line was omitted is invisible here. That reply is ALREADY a
|
|
70
|
+
* `check_reply_consistency` finding and a stated Iron Law 1 violation, so it is
|
|
71
|
+
* the malformed-ask problem rather than the dropped-ask problem — a different
|
|
72
|
+
* defect with a different owner.
|
|
73
|
+
*
|
|
74
|
+
* REUSE. `find_option_blocks` and `recommendationsUnder` are both the
|
|
75
|
+
* spec-backed readings behind `check_reply_consistency`, extracted rather than
|
|
76
|
+
* copied. `interruption_ledger_hook` carries its own `hasNumberedOptions` for
|
|
77
|
+
* the capture-only ledger; a third reading of the same rule would drift from
|
|
78
|
+
* both.
|
|
79
|
+
*
|
|
80
|
+
* TWO KNOWN FALSE-POSITIVE PATHS, named because a refusing detector owes its
|
|
81
|
+
* residual rather than only its fix:
|
|
82
|
+
*
|
|
83
|
+
* · A BLOCKQUOTED illustration of an ask — `> 1.` / `> 2.` plus a quoted
|
|
84
|
+
* recommendation line — reads as live. `OPTION_LINE_RE` accepts a leading
|
|
85
|
+
* `>` deliberately, because this suite's own documented ask shape is often
|
|
86
|
+
* blockquoted, so excluding it would miss real asks to avoid a quoted one.
|
|
87
|
+
* Fenced illustrations ARE excluded and tested; blockquoted ones are not,
|
|
88
|
+
* and narrowing the shared parser to fix that would change what
|
|
89
|
+
* `check_reply_consistency` enforces about Iron Law 1.
|
|
90
|
+
* · A genuine user turn carrying NO `type: 'text'` block — an image-only
|
|
91
|
+
* message — does not reset the turn, because `readTranscriptTail` skips an
|
|
92
|
+
* entry with no text before reaching the reset. Changing that would move
|
|
93
|
+
* `turnOrdinal` for all four other detectors on a shape none of them has
|
|
94
|
+
* been measured against.
|
|
95
|
+
*
|
|
96
|
+
* Both cost one extra line in a reply, once: the re-entrancy layers cap a turn
|
|
97
|
+
* at ONE refusal, so neither can wedge a session.
|
|
98
|
+
*/
|
|
99
|
+
export function detectDroppedDecision(
|
|
100
|
+
assistantTurnTexts: readonly string[],
|
|
101
|
+
closingFromPayload = false,
|
|
102
|
+
): DroppedDecisionFinding | null {
|
|
103
|
+
if (assistantTurnTexts.length < 2) return null;
|
|
104
|
+
// Masked once per text, not once per block: this runs on the stop path over
|
|
105
|
+
// every assistant text of the turn, and a reply with four numbered blocks
|
|
106
|
+
// would otherwise split and fence-mask the whole reply four times.
|
|
107
|
+
const asksIn = (text: string): ReturnType<typeof find_option_blocks> => {
|
|
108
|
+
const blocks = find_option_blocks(text);
|
|
109
|
+
if (blocks.length === 0) return blocks;
|
|
110
|
+
const masked = splitAndMask(text);
|
|
111
|
+
return blocks.filter((b) => recommendationsUnder(text, b, masked).length > 0);
|
|
112
|
+
};
|
|
113
|
+
const closing = assistantTurnTexts[assistantTurnTexts.length - 1]!;
|
|
114
|
+
if (asksIn(closing).length > 0) return null;
|
|
115
|
+
for (let i = assistantTurnTexts.length - 2; i >= 0; i -= 1) {
|
|
116
|
+
const earlier = assistantTurnTexts[i]!;
|
|
117
|
+
const blocks = asksIn(earlier);
|
|
118
|
+
if (blocks.length === 0) continue;
|
|
119
|
+
const block = blocks[blocks.length - 1]!;
|
|
120
|
+
return {
|
|
121
|
+
detector: 'pending-decision',
|
|
122
|
+
// The option NUMBERS and the line span, never the option text: the
|
|
123
|
+
// evidence is quoted into a refusal that reaches the transcript, and
|
|
124
|
+
// an options block can carry anything the reply carried.
|
|
125
|
+
evidence:
|
|
126
|
+
`options ${block.numbers.join('/')} at lines ${block.startLine}-${block.endLine} ` +
|
|
127
|
+
`of an earlier reply this turn (closing reply read from ` +
|
|
128
|
+
`${closingFromPayload ? 'the stop payload' : 'the transcript'})`,
|
|
129
|
+
reason:
|
|
130
|
+
'an earlier reply in THIS turn put numbered options to the user ' +
|
|
131
|
+
'and no user answer followed — this closing reply carries no ' +
|
|
132
|
+
'options block, so the decision disappeared without being ' +
|
|
133
|
+
'answered, cancelled or superseded. A hook nudge, a reviewer ' +
|
|
134
|
+
'result or a task notification may ADD to a turn; it may not ' +
|
|
135
|
+
'displace a question already asked (user-interaction Iron Law 3: ' +
|
|
136
|
+
'a decision handed to the user outlives the turn). ' +
|
|
137
|
+
'Re-present the block and its recommendation line at the end of ' +
|
|
138
|
+
'this reply',
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
return null;
|
|
142
|
+
}
|
|
@@ -0,0 +1,424 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The standing-payload ceiling, MEASURED at the base ref rather than stored.
|
|
3
|
+
*
|
|
4
|
+
* ceiling = max(design_ceiling, effective_base + active grant)
|
|
5
|
+
*
|
|
6
|
+
* WHY MEASURED
|
|
7
|
+
* ------------
|
|
8
|
+
* An AI council (2/2 convergent, 2026-09-10, under a written owner delegation)
|
|
9
|
+
* fixed the formula, and the reason for the move is one sentence from that
|
|
10
|
+
* verdict: a measured ceiling **captures every merged reduction
|
|
11
|
+
* automatically**, where a stored one stays at its last hand-written number —
|
|
12
|
+
* so payload a merge removed can be added straight back into the space it
|
|
13
|
+
* freed. That is the defect `ci_delivery.grace_ceiling` had for its whole life.
|
|
14
|
+
*
|
|
15
|
+
* WHY NO PER-PR HEADROOM. Both seats, without qualification: *"Neither a
|
|
16
|
+
* percentage nor a fixed token allowance is safe against a moving base: both
|
|
17
|
+
* authorize cumulative growth."* One seat put the arithmetic on it —
|
|
18
|
+
* 138,413 × 1.05^10 ≈ 225,000 after ten pull requests. `headroom_pct` derives
|
|
19
|
+
* the FIXED design ceiling from `baseline_tokens` and is never re-applied to a
|
|
20
|
+
* moving base. So the ordinary path is ZERO NET GROWTH while the tree is over
|
|
21
|
+
* design, and the design ceiling once it is at or below. 96.8 % of the last
|
|
22
|
+
* 250 merged pull requests already move this payload by zero or less.
|
|
23
|
+
*
|
|
24
|
+
* THE STORED TERM IS GONE — STAGE 2 LANDED 2026-09-11
|
|
25
|
+
* ----------------------------------------------------
|
|
26
|
+
* A second council round (2/2, 2026-09-11) refused to let the stored ceiling be
|
|
27
|
+
* removed in the change that INTRODUCED the measured one, on a structural
|
|
28
|
+
* ground rather than a cautious one. Under prerequisite 3 the gate runs AS IT
|
|
29
|
+
* EXISTS AT THE BASE REF, so — openai, verbatim — *"the new gate cannot safely
|
|
30
|
+
* validate its own introduction: while the implementation PR runs, the
|
|
31
|
+
* authoritative measuring code at the base ref is still the old
|
|
32
|
+
* implementation."*
|
|
33
|
+
*
|
|
34
|
+
* Stage 1 therefore landed the whole mechanism with the stored ceiling retained
|
|
35
|
+
* as an additional `max` term that could only widen the bound. Stage 2 removes
|
|
36
|
+
* it from a base that already carries this code — verified before the removal
|
|
37
|
+
* by running the base-ref copy of the gate against the head tree, which is the
|
|
38
|
+
* precondition the sequencing was about. `ci_delivery` now stores no ceiling at
|
|
39
|
+
* all, so the bound cannot be widened by editing a field. ADR-275 records the
|
|
40
|
+
* formula and its prerequisites; ADR-276 records this removal and the required
|
|
41
|
+
* status check that made it meaningful.
|
|
42
|
+
*
|
|
43
|
+
* THE EXCEPTION PATH, AND WHY THE WATERMARK IS THE LOAD-BEARING FIELD
|
|
44
|
+
* -------------------------------------------------------------------
|
|
45
|
+
* A change whose offsetting reduction is genuinely unsafe takes a recorded,
|
|
46
|
+
* approved, dated grant. Both seats specified the same six properties, and one
|
|
47
|
+
* is easy to lose: *"the exceptional measurement must NEVER become the next
|
|
48
|
+
* base."* Under a base-measured ceiling that is a mechanism, not a note —
|
|
49
|
+
* without it a grant of N tokens raises the measurement, the next pull request
|
|
50
|
+
* measures the raised base, and the grant is permanent one merge later.
|
|
51
|
+
* `effectiveBase` pins the base to the WATERMARK recorded at grant time for as
|
|
52
|
+
* long as the grant is live.
|
|
53
|
+
*
|
|
54
|
+
* SIX CONTRACT RULES, EACH FROM A BLOCKING FINDING OF THE 2026-09-11 ROUND
|
|
55
|
+
* ------------------------------------------------------------------------
|
|
56
|
+
* 1. AT MOST ONE ACTIVE GRANT. openai: overlapping grants are undefined, and
|
|
57
|
+
* *"'use the highest watermark' is not safe: a later watermark may already
|
|
58
|
+
* contain earlier exceptional growth, causing that growth to be counted both
|
|
59
|
+
* in the anchor and in summed grants."* anthropic preferred defined overlap
|
|
60
|
+
* rules to a ban but called defined semantics blocking either way, so the
|
|
61
|
+
* ban satisfies both seats and the permissive variant does not.
|
|
62
|
+
* 2. APPROVAL MUST BE AUTHENTICATED, NOT ASSERTED. Both seats' hardest
|
|
63
|
+
* pushback: `approved_by` in the pull request that requests the grant is
|
|
64
|
+
* self-asserted data authenticating nothing. A grant therefore carries an
|
|
65
|
+
* `approval_event` — a reference to a platform event outside the diff — and
|
|
66
|
+
* a grant whose approval is unverified is REFUSED rather than honoured.
|
|
67
|
+
* Verification is the CI step's job (it needs the platform); this module
|
|
68
|
+
* refuses anything it was not told is verified.
|
|
69
|
+
* 3. DELETION CANNOT DISCHARGE DEBT. A removed record is not a repaid one.
|
|
70
|
+
* Deletion is caught by the base-ref ratchet, which sees a grant that
|
|
71
|
+
* existed at the base and does not exist at head.
|
|
72
|
+
* 4. `repaid_at` IS A RECORD OF A MEASUREMENT, NOT A CLAIM. Repayment is
|
|
73
|
+
* established by the payload returning to the watermark. A record claiming
|
|
74
|
+
* repayment while the measurement says otherwise is refused.
|
|
75
|
+
* 5. CONSUMPTION IS DERIVED. There is no `consumed_tokens` field to edit:
|
|
76
|
+
* consumption is `measured − watermark`, computed here.
|
|
77
|
+
* 6. EXPIRY IS EVALUATED AT GATE TIME, which is merge time on a required
|
|
78
|
+
* check. A grant that expires while its pull request sits in review reds
|
|
79
|
+
* that pull request; the fix is a fresh approved grant, never an edit to the
|
|
80
|
+
* old one's date, which rule 3's ratchet refuses anyway.
|
|
81
|
+
*
|
|
82
|
+
* WHAT THIS IS NOT, STATED RATHER THAN IMPLIED
|
|
83
|
+
* ---------------------------------------------
|
|
84
|
+
* The ledger is editable by the pull request it governs, like the gate code.
|
|
85
|
+
* The council accepted that for the gate under prerequisite 3 in these terms:
|
|
86
|
+
* *"the mechanism does not prevent the exploit; it makes the exploit auditable
|
|
87
|
+
* … a forensic control, not a preventive one."* Rules 2 and 3 above are what
|
|
88
|
+
* keep the ledger from being weaker than that — an unverified grant buys
|
|
89
|
+
* nothing, and a deleted one is still owed.
|
|
90
|
+
*
|
|
91
|
+
* NO NUMERIC CAP IS ENFORCED, AND THAT IS A FINDING RATHER THAN AN OMISSION.
|
|
92
|
+
* Both seats refused to derive one from the 250-PR delta distribution
|
|
93
|
+
* (p50 0, p90 0, p95 0/+167, max +288): the sample is CENSORED by the very
|
|
94
|
+
* ratchet a cap would relax, so every percentile describes what got through
|
|
95
|
+
* rather than what was attempted. A p95 cap would license the top 5 % of
|
|
96
|
+
* ordinary work to use the break-glass routinely, which makes it not
|
|
97
|
+
* exceptional. The 2026-09-11 round added that the cap must eventually come
|
|
98
|
+
* from actual CONSUMED rather than granted tokens, which rule 5 makes
|
|
99
|
+
* measurable. Until then the approver is the cap.
|
|
100
|
+
*/
|
|
101
|
+
import * as fs from 'node:fs';
|
|
102
|
+
|
|
103
|
+
/** Repo-relative path of the break-glass ledger. */
|
|
104
|
+
export const EXCEPTIONS_CONFIG_PATH = 'src/config/preamble-payload-exceptions.json';
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* A grant's state at evaluation time. Derived, never stored — a stored status
|
|
108
|
+
* would be a second source of truth that drifts against `expires_at`.
|
|
109
|
+
*/
|
|
110
|
+
export type ExceptionState = 'active' | 'repaid' | 'expired';
|
|
111
|
+
|
|
112
|
+
export interface PayloadException {
|
|
113
|
+
id: string;
|
|
114
|
+
granted_tokens: number;
|
|
115
|
+
/** The measured payload immediately BEFORE the grant. The base is pinned here. */
|
|
116
|
+
watermark: number;
|
|
117
|
+
reason: string;
|
|
118
|
+
/**
|
|
119
|
+
* A reference to a platform event that authorised this grant, OUTSIDE the
|
|
120
|
+
* diff requesting it — the council's blocking finding #2. Shape is the CI
|
|
121
|
+
* step's business; this module only requires that one is named and that
|
|
122
|
+
* the caller has verified it.
|
|
123
|
+
*/
|
|
124
|
+
approval_event: string;
|
|
125
|
+
/** ISO date. */
|
|
126
|
+
approved_at: string;
|
|
127
|
+
/** ISO date. After it, an unrepaid grant is a hard refusal. */
|
|
128
|
+
expires_at: string;
|
|
129
|
+
/** ISO date once the payload has measurably returned to the watermark. */
|
|
130
|
+
repaid_at: string | null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export interface ExceptionsFile {
|
|
134
|
+
exceptions: PayloadException[];
|
|
135
|
+
/** Schema / parse problems. Non-empty means the file may not be trusted. */
|
|
136
|
+
errors: string[];
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isIsoDate(v: unknown): v is string {
|
|
140
|
+
return typeof v === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(v);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Read and VALIDATE the ledger. A malformed entry is an error, never a skip.
|
|
145
|
+
*
|
|
146
|
+
* An unreadable or invalid ledger must not silently evaluate as "no
|
|
147
|
+
* exceptions": that reading is permissive in one direction — a corrupted entry
|
|
148
|
+
* stops pinning the base to its watermark — and the caller cannot tell it from
|
|
149
|
+
* an honestly empty file. Callers refuse on `errors`.
|
|
150
|
+
*/
|
|
151
|
+
export function readExceptions(file: string): ExceptionsFile {
|
|
152
|
+
let raw: unknown;
|
|
153
|
+
try {
|
|
154
|
+
raw = JSON.parse(fs.readFileSync(file, 'utf-8'));
|
|
155
|
+
} catch (err) {
|
|
156
|
+
const e = err as NodeJS.ErrnoException;
|
|
157
|
+
if (e.code === 'ENOENT') return { exceptions: [], errors: [] };
|
|
158
|
+
return { exceptions: [], errors: [`${file} is not readable as JSON: ${(err as Error).message}`] };
|
|
159
|
+
}
|
|
160
|
+
const root = (raw ?? {}) as Record<string, unknown>;
|
|
161
|
+
const list = root['exceptions'];
|
|
162
|
+
if (list === undefined) return { exceptions: [], errors: [] };
|
|
163
|
+
if (!Array.isArray(list)) return { exceptions: [], errors: [`${file}: 'exceptions' must be an array`] };
|
|
164
|
+
|
|
165
|
+
const errors: string[] = [];
|
|
166
|
+
const out: PayloadException[] = [];
|
|
167
|
+
const ids = new Set<string>();
|
|
168
|
+
list.forEach((item, i) => {
|
|
169
|
+
const e = (item ?? {}) as Record<string, unknown>;
|
|
170
|
+
const where = `${file}: exceptions[${String(i)}]`;
|
|
171
|
+
const id = e['id'];
|
|
172
|
+
const granted = Number(e['granted_tokens']);
|
|
173
|
+
const watermark = Number(e['watermark']);
|
|
174
|
+
const repaid = e['repaid_at'] ?? null;
|
|
175
|
+
if (typeof id !== 'string' || id.trim() === '') errors.push(`${where}: 'id' must be a non-empty string`);
|
|
176
|
+
else if (ids.has(id)) errors.push(`${where}: duplicate id '${id}' — an id is the record's identity`);
|
|
177
|
+
else ids.add(id);
|
|
178
|
+
if (!Number.isInteger(granted) || granted <= 0) {
|
|
179
|
+
errors.push(`${where}: 'granted_tokens' must be a positive integer`);
|
|
180
|
+
}
|
|
181
|
+
if (!Number.isInteger(watermark) || watermark < 0) {
|
|
182
|
+
errors.push(`${where}: 'watermark' must be a non-negative integer — the payload measured at grant time`);
|
|
183
|
+
}
|
|
184
|
+
for (const k of ['reason', 'approval_event'] as const) {
|
|
185
|
+
if (typeof e[k] !== 'string' || (e[k] as string).trim() === '') {
|
|
186
|
+
errors.push(
|
|
187
|
+
`${where}: '${k}' must be a non-empty string` +
|
|
188
|
+
(k === 'approval_event'
|
|
189
|
+
? ". An approval recorded only by the diff requesting it authenticates nothing — name the platform event that authorised it."
|
|
190
|
+
: ''),
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
for (const k of ['approved_at', 'expires_at'] as const) {
|
|
195
|
+
if (!isIsoDate(e[k])) errors.push(`${where}: '${k}' must be a YYYY-MM-DD date`);
|
|
196
|
+
}
|
|
197
|
+
if (repaid !== null && !isIsoDate(repaid)) {
|
|
198
|
+
errors.push(`${where}: 'repaid_at' must be a YYYY-MM-DD date or null`);
|
|
199
|
+
}
|
|
200
|
+
if (e['consumed_tokens'] !== undefined) {
|
|
201
|
+
errors.push(
|
|
202
|
+
`${where}: 'consumed_tokens' is not a field. Consumption is DERIVED as measured − watermark; ` +
|
|
203
|
+
'a stored copy would be an editable assertion about a measurement, which is the shape ' +
|
|
204
|
+
'this ledger exists to avoid.',
|
|
205
|
+
);
|
|
206
|
+
}
|
|
207
|
+
out.push({
|
|
208
|
+
id: typeof id === 'string' ? id : `<entry ${String(i)}>`,
|
|
209
|
+
granted_tokens: Number.isFinite(granted) ? granted : 0,
|
|
210
|
+
watermark: Number.isFinite(watermark) ? watermark : 0,
|
|
211
|
+
reason: String(e['reason'] ?? ''),
|
|
212
|
+
approval_event: String(e['approval_event'] ?? ''),
|
|
213
|
+
approved_at: String(e['approved_at'] ?? ''),
|
|
214
|
+
expires_at: String(e['expires_at'] ?? ''),
|
|
215
|
+
repaid_at: repaid === null ? null : String(repaid),
|
|
216
|
+
});
|
|
217
|
+
});
|
|
218
|
+
return { exceptions: out, errors };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** `today` as `YYYY-MM-DD`, injectable so the expiry branch is testable. */
|
|
222
|
+
export function stateOf(e: PayloadException, today: string): ExceptionState {
|
|
223
|
+
if (e.repaid_at !== null) return 'repaid';
|
|
224
|
+
return e.expires_at < today ? 'expired' : 'active';
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
export interface CeilingReading {
|
|
228
|
+
/** The number the payload is compared against. */
|
|
229
|
+
ceiling: number;
|
|
230
|
+
/** `round(baseline_tokens * (1 + headroom_pct/100))`. The floor of the ceiling. */
|
|
231
|
+
designCeiling: number;
|
|
232
|
+
/** Payload measured at the base ref, or `null` when it could not be read. */
|
|
233
|
+
basePayload: number | null;
|
|
234
|
+
/** The base after watermark pinning, or `null` with `basePayload`. */
|
|
235
|
+
effectiveBase: number | null;
|
|
236
|
+
/** `granted_tokens` of the single active grant, else 0. */
|
|
237
|
+
activeGrants: number;
|
|
238
|
+
activeIds: string[];
|
|
239
|
+
/** Which term set the ceiling — the one thing a reader needs at a glance. */
|
|
240
|
+
boundBy: 'design' | 'base' | 'grant';
|
|
241
|
+
/** True when the ceiling rests on a base reading that was actually taken. */
|
|
242
|
+
verified: boolean;
|
|
243
|
+
ok: boolean;
|
|
244
|
+
violations: string[];
|
|
245
|
+
/** Printed on the passing path too, so a skip cannot pass for a check. */
|
|
246
|
+
note: string | null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export interface CeilingOptions {
|
|
250
|
+
designCeiling: number;
|
|
251
|
+
/** `null` = the base ref could not be measured. */
|
|
252
|
+
basePayload: number | null;
|
|
253
|
+
/** Why it could not be measured. Rendered verbatim. */
|
|
254
|
+
baseNote?: string | null;
|
|
255
|
+
/** The payload measured in THIS tree — needed to corroborate `repaid_at`. */
|
|
256
|
+
headPayload: number;
|
|
257
|
+
exceptions?: readonly PayloadException[];
|
|
258
|
+
exceptionErrors?: readonly string[];
|
|
259
|
+
/**
|
|
260
|
+
* Ids whose `approval_event` the caller VERIFIED against the platform.
|
|
261
|
+
*
|
|
262
|
+
* Absent means nothing was verified, which is the safe default: a grant is
|
|
263
|
+
* honoured only when someone with access to the platform said so.
|
|
264
|
+
*/
|
|
265
|
+
verifiedApprovals?: readonly string[];
|
|
266
|
+
/** `YYYY-MM-DD`. Injected so the expiry branch is testable. */
|
|
267
|
+
today: string;
|
|
268
|
+
/**
|
|
269
|
+
* Refuse instead of falling back when the base could not be measured.
|
|
270
|
+
*
|
|
271
|
+
* Advisory is the default and keeps a shallow clone, a first commit and a
|
|
272
|
+
* detached build usable — the same argument `standing_bound_ratchet` makes
|
|
273
|
+
* for its own mode gate, and the same reason the flag is the caller's
|
|
274
|
+
* rather than sniffed from an environment variable here.
|
|
275
|
+
*/
|
|
276
|
+
requireBase?: boolean;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Compute the effective ceiling and say whether it may be trusted.
|
|
281
|
+
*
|
|
282
|
+
* Pure: it takes a base reading rather than producing one, so every branch —
|
|
283
|
+
* expiry, watermark pinning, unverified approval, fail-closed base — is
|
|
284
|
+
* testable without git or a platform.
|
|
285
|
+
*/
|
|
286
|
+
export function computeCeiling(opts: CeilingOptions): CeilingReading {
|
|
287
|
+
const exceptions = opts.exceptions ?? [];
|
|
288
|
+
const verified = new Set(opts.verifiedApprovals ?? []);
|
|
289
|
+
const violations = [...(opts.exceptionErrors ?? [])];
|
|
290
|
+
|
|
291
|
+
const live = exceptions.filter((e) => stateOf(e, opts.today) !== 'repaid');
|
|
292
|
+
const expired = live.filter((e) => stateOf(e, opts.today) === 'expired');
|
|
293
|
+
const candidates = live.filter((e) => stateOf(e, opts.today) === 'active');
|
|
294
|
+
|
|
295
|
+
// Rule 1 — at most one active grant. Summing overlapping grants can count
|
|
296
|
+
// exceptional growth twice: in a later watermark that already contains it,
|
|
297
|
+
// and again in the sum.
|
|
298
|
+
if (candidates.length > 1) {
|
|
299
|
+
violations.push(
|
|
300
|
+
`${String(candidates.length)} standing-payload exceptions are active at once ` +
|
|
301
|
+
`(${candidates.map((e) => e.id).join(', ')}). At most one may be. Overlapping grants have no ` +
|
|
302
|
+
'defined composition: a later watermark can already contain an earlier grant\'s growth, so ' +
|
|
303
|
+
'summing counts it twice. Repay or expire one before recording the next.',
|
|
304
|
+
);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Rule 2 — an unverified approval buys nothing.
|
|
308
|
+
for (const e of candidates) {
|
|
309
|
+
if (!verified.has(e.id)) {
|
|
310
|
+
violations.push(
|
|
311
|
+
`standing-payload exception '${e.id}' has no VERIFIED approval. It names ` +
|
|
312
|
+
`'${e.approval_event}', and nothing in this run confirmed that event. An approval recorded ` +
|
|
313
|
+
'only by the change that requests it is self-asserted data: the same diff can claim the ' +
|
|
314
|
+
'grant, the approver and the date. The grant is refused until the platform event is ' +
|
|
315
|
+
'checked. This is not a payload problem — do not shrink the change to clear it.',
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// Rule 6 — expiry is evaluated now, which on a required check is merge time.
|
|
321
|
+
for (const e of expired) {
|
|
322
|
+
violations.push(
|
|
323
|
+
`standing-payload exception '${e.id}' expired on ${e.expires_at} and is not repaid. ` +
|
|
324
|
+
`It granted ${String(e.granted_tokens)} tok over a watermark of ${String(e.watermark)}. ` +
|
|
325
|
+
'Bring the payload back to the watermark and record repaid_at, or obtain a fresh approved ' +
|
|
326
|
+
"grant — editing this one's expiry is refused by the shrink-only ratchet, and an expiry " +
|
|
327
|
+
'that lapsed quietly would renew the grant by inaction.',
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
// Rule 4 — `repaid_at` records a measurement; it does not assert one.
|
|
332
|
+
for (const e of exceptions) {
|
|
333
|
+
if (e.repaid_at !== null && opts.headPayload > e.watermark) {
|
|
334
|
+
violations.push(
|
|
335
|
+
`standing-payload exception '${e.id}' is marked repaid on ${e.repaid_at}, but the payload ` +
|
|
336
|
+
`measures ${String(opts.headPayload)} against its watermark of ${String(e.watermark)} — ` +
|
|
337
|
+
`${String(opts.headPayload - e.watermark)} tok still outstanding. Repayment is established ` +
|
|
338
|
+
'by the measurement returning to the watermark; the field records that event and cannot ' +
|
|
339
|
+
'substitute for it.',
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
const activeGrants = candidates.length === 1 ? (candidates[0]?.granted_tokens ?? 0) : 0;
|
|
345
|
+
const activeIds = candidates.map((e) => e.id);
|
|
346
|
+
|
|
347
|
+
if (opts.basePayload === null) {
|
|
348
|
+
const why = opts.baseNote ?? 'the base ref could not be measured';
|
|
349
|
+
const fallback = opts.designCeiling;
|
|
350
|
+
if (opts.requireBase === true) {
|
|
351
|
+
violations.push(
|
|
352
|
+
`the standing-payload ceiling could not be measured: ${why}. This run is ENFORCING, so an ` +
|
|
353
|
+
'unmeasurable base refuses rather than falling back — a base that cannot be read would ' +
|
|
354
|
+
'otherwise grant an unbounded budget on an infrastructure failure. This is NOT payload ' +
|
|
355
|
+
'growth: fix the checkout (a full fetch of the base ref) rather than shrinking the change.',
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
return {
|
|
359
|
+
ceiling: fallback,
|
|
360
|
+
designCeiling: opts.designCeiling,
|
|
361
|
+
basePayload: null,
|
|
362
|
+
effectiveBase: null,
|
|
363
|
+
activeGrants,
|
|
364
|
+
activeIds,
|
|
365
|
+
boundBy: 'design',
|
|
366
|
+
verified: false,
|
|
367
|
+
ok: violations.length === 0 && opts.requireBase !== true,
|
|
368
|
+
note: `${why}, so the ceiling is NOT a base-measured reading`,
|
|
369
|
+
violations,
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
// The watermark pin. Without it a grant raises the measurement, the next
|
|
374
|
+
// pull request measures the raised base, and the grant is permanent.
|
|
375
|
+
const effectiveBase =
|
|
376
|
+
candidates.length === 1
|
|
377
|
+
? Math.min(opts.basePayload, candidates[0]?.watermark ?? opts.basePayload)
|
|
378
|
+
: opts.basePayload;
|
|
379
|
+
|
|
380
|
+
// An unverified or over-subscribed grant contributes ZERO, so a refused
|
|
381
|
+
// grant can never widen the bound it was refused for.
|
|
382
|
+
const honoured = violations.length === 0 ? activeGrants : 0;
|
|
383
|
+
const measuredTerm = effectiveBase + honoured;
|
|
384
|
+
const ceiling = Math.max(opts.designCeiling, measuredTerm);
|
|
385
|
+
|
|
386
|
+
let boundBy: CeilingReading['boundBy'] = 'design';
|
|
387
|
+
if (ceiling === measuredTerm && ceiling > opts.designCeiling) boundBy = honoured > 0 ? 'grant' : 'base';
|
|
388
|
+
|
|
389
|
+
return {
|
|
390
|
+
ceiling,
|
|
391
|
+
designCeiling: opts.designCeiling,
|
|
392
|
+
basePayload: opts.basePayload,
|
|
393
|
+
effectiveBase,
|
|
394
|
+
activeGrants: honoured,
|
|
395
|
+
activeIds,
|
|
396
|
+
boundBy,
|
|
397
|
+
verified: true,
|
|
398
|
+
ok: violations.length === 0,
|
|
399
|
+
violations,
|
|
400
|
+
note: null,
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** The human rendering, printed on BOTH paths — a check that only speaks when
|
|
405
|
+
* it fails is a check nobody audits until it is already load-bearing. */
|
|
406
|
+
export function renderCeiling(c: CeilingReading): string {
|
|
407
|
+
const lines: string[] = [];
|
|
408
|
+
if (!c.verified) {
|
|
409
|
+
lines.push(` ⚠️ ceiling NOT measured — ${c.note ?? 'no reason recorded'}\n`);
|
|
410
|
+
lines.push(` falling back to ${String(c.ceiling)} tok (design ${String(c.designCeiling)}).\n`);
|
|
411
|
+
} else {
|
|
412
|
+
const pinned = c.effectiveBase !== c.basePayload;
|
|
413
|
+
const how =
|
|
414
|
+
c.boundBy === 'design'
|
|
415
|
+
? `the DESIGN ceiling — the measured base (${String(c.basePayload ?? 0)}) is at or below it`
|
|
416
|
+
: `base ${String(c.effectiveBase ?? 0)}` +
|
|
417
|
+
(pinned ? ` (PINNED to an exception watermark; measured ${String(c.basePayload ?? 0)})` : '') +
|
|
418
|
+
(c.activeGrants > 0 ? ` + ${String(c.activeGrants)} granted` : '') +
|
|
419
|
+
` — zero net growth, design ${String(c.designCeiling)}`;
|
|
420
|
+
lines.push(` ✅ ceiling ${String(c.ceiling)} tok = ${how}.\n`);
|
|
421
|
+
}
|
|
422
|
+
if (c.activeIds.length > 0) lines.push(` active exception(s): ${c.activeIds.join(', ')}\n`);
|
|
423
|
+
return lines.join('');
|
|
424
|
+
}
|