fix(payroll): require jamkning valid_to on every write path (#2058) (#2240)

* fix(payroll): require jamkning valid_to on every write path (#2058)

A jamkningsbeslut saved through the v1 API or MCP with a percentage and a
start date but no end date was stored and returned 200, yet the engine
(isJamkningValid) never applies a beslut without both dates: the payslip
and the AGI carried the table tax while the caller believed the beslut
was live.

One shared validator (lib/salary/jamkning-rules.ts) now requires both
dates whenever a percentage is set and checks their ordering. Every write
path runs it: CreateEmployeeSchema and UpdateEmployeeSchema, the web POST
and PATCH routes, the v1 PATCH route (its private copy is deleted), the
MCP create and update executors in employee-commands, and the MCP update
tool preflights the merged row at staging time so the agent sees the
error before approval. The update paths keep the existing touched gate, so
legacy rows stored without valid_to stay editable in unrelated ways.

The MCP tool descriptions state that both dates are required for the
beslut to apply. scripts/list-incomplete-jamkning.ts lists the existing
rows (percentage set, valid_to null) per company, read-only; setting an
end date or clearing the beslut is decided per company since either
changes the next payslip.

Declined: defaulting valid_to to 31 December of the from-year. It matches
most beslut but silently changes withholding on rows that today do
nothing.

Closes #2058

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0161fHpCX3rnWtidwwdGfCdB

* fix(payroll): keep the jamkning PR inside the type and tools/list budgets

CI on the first push failed on two ratchets this PR itself tripped:

- Typecheck ratchet: the three staging tests added here reused the
  untyped 'agent_chat' actor literal the file already carried, which
  raised that file's error count above its baseline. They now pass
  { type: 'user' }.
- tools/list payload budget: the first jamkning field descriptions on
  gnubok_create_employee and gnubok_update_employee pushed the projected
  catalog to 60 113 tokens against the 60 000 ceiling. The percentage
  fields keep a one-line "needs both dates or never applied" note; the
  date fields drop theirs.

Also acts on the compliance swarm's GDPR Art.32 note: the read-only
lister no longer selects employee names at all (the employee id is what
the per-company decision needs), so the script touches no PII.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0161fHpCX3rnWtidwwdGfCdB

* docs(mcp): say the jamkning percentage is rejected without both dates

CodeRabbit on #2240: "never applied" described the pre-fix engine
behaviour; the contract now is that a create or update with a percentage
and a missing date is rejected before staging. Same length, so the
tools/list payload budget is unchanged. The concurrency finding is
tracked in #2256 instead of this PR.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(mcp): keep tools/list under budget after proforma landed on main

After merging main (#2254 proforma fields) the projected tools/list
measured 60 010 tokens against the 60 000 ceiling with this PR's two
jamkning field notes. Per the budget test's own rule, demote a read tool
instead of bumping the ceiling: gnubok_list_arsredovisning_versions goes
search-only. Versions exist only once a report is rendered for signing
or filing, which is the same switched-off iXBRL path as its sibling
gnubok_get_arsredovisning_filing_status, already search-only since
2026-09-02. Still reachable via gnubok_call_tool.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-09-03 20:22:41 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent 22b98e0a3b
commit b07efcafd4
17 changed files with 706 additions and 117 deletions
@@ -401,6 +401,12 @@ describe('tools/list payload size guard', () => {
// gnubok_get_arsredovisning_filing_status to search-only: iXBRL
// filing is off until the Bolagsverket avtal exists, so no client
// polls it. Ceiling unchanged.
// * 2026-09-03, jamkning (#2240) landing on top of proforma (#2254):
// two one-line field notes on create/update_employee measured 60 010
// after merging main. Demoted gnubok_list_arsredovisning_versions to
// search-only: versions exist only once a report is rendered for
// signing or filing, which is the same switched-off iXBRL path as its
// sibling filing_status tool. Ceiling unchanged.
expect(approxTokens).toBeLessThan(60_000)
})
@@ -560,6 +560,16 @@ describe('gnubok_create_employee', () => {
).rejects.toThrow(/Invalid employee/)
})
it('rejects a jämkning percentage without an end date (#2058)', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
createEmployee.execute(
{ ...validArgs, jamkning_percentage: 15, jamkning_valid_from: '2026-01-01' },
'company-1', 'user-1', supabase as never, { type: 'user' },
),
).rejects.toThrow(/jamkning_valid_to/)
})
it('blocks EF owners on payroll (entity-type preflight)', async () => {
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { entity_type: 'ef' } }) // company_settings
@@ -624,6 +634,35 @@ describe('gnubok_update_employee', () => {
expect(inserted.params.patch.default_dimensions).toEqual({})
})
it('rejects a jämkning percentage without an end date at staging time (#2058)', async () => {
// Preflight on the merged row: the agent gets the error now, not at
// approval. The executor runs the same shared validator again.
const { supabase, enqueue } = createQueuedMockSupabase()
enqueue({ data: { ...EXISTING, jamkning_percentage: null, jamkning_valid_from: null, jamkning_valid_to: null } })
await expect(
updateEmployee.execute(
{ employee_id: 'emp-1', jamkning_percentage: 15, jamkning_valid_from: '2026-01-01' },
'company-1', 'user-1', supabase as never, { type: 'user' },
),
).rejects.toThrow(/jamkning_valid_to/)
})
it('stages an unrelated edit on a legacy row that lacks valid_to (touched gate)', async () => {
const supabaseMock = makeCapturingSupabase({
employees: { data: { ...EXISTING, jamkning_percentage: 15, jamkning_valid_from: '2026-01-01', jamkning_valid_to: null } },
fiscal_periods: { data: null },
company_settings: { data: null },
pending_operations: { data: { id: 'op-legacy' }, error: null },
})
const result = (await updateEmployee.execute(
{ employee_id: 'emp-1', monthly_salary: 38000 },
'company-1', 'user-1', supabaseMock as never, { type: 'user' },
)) as { staged: boolean }
expect(result.staged).toBe(true)
})
it('rejects personnummer changes at the tool boundary', async () => {
const { supabase } = createQueuedMockSupabase()
await expect(
+19 -2
View File
@@ -15774,7 +15774,7 @@ export const tools: McpTool[] = [
vaxa_stod_eligible: { type: 'boolean' },
vaxa_stod_start: { type: 'string' },
vaxa_stod_end: { type: 'string' },
jamkning_percentage: { type: 'number' },
jamkning_percentage: { type: 'number', description: 'Requires both dates, else rejected' },
jamkning_valid_from: { type: 'string' },
jamkning_valid_to: { type: 'string' },
default_dimensions: {
@@ -15888,7 +15888,7 @@ export const tools: McpTool[] = [
vaxa_stod_eligible: { type: 'boolean' },
vaxa_stod_start: { type: 'string' },
vaxa_stod_end: { type: 'string' },
jamkning_percentage: { type: ['number', 'null'], description: 'null clears the beslut' },
jamkning_percentage: { type: ['number', 'null'], description: 'null clears; else requires both dates' },
jamkning_valid_from: { type: ['string', 'null'] },
jamkning_valid_to: { type: ['string', 'null'] },
default_dimensions: {
@@ -15936,6 +15936,15 @@ export const tools: McpTool[] = [
if (error) throw dbError(error)
if (!existing) throw new Error('Employee not found')
// Preflight the jämkning contract on the merged row so the agent gets
// the error at staging time instead of at approval (#2058). The
// executor (updateEmployee) runs the same shared validator again.
const { touchesJamkning, validateJamkning } = await import('@/lib/salary/jamkning-rules')
if (touchesJamkning(patch)) {
const [issue] = validateJamkning({ ...(existing as Record<string, unknown>), ...patch })
if (issue) throw new Error(`${issue.field}: ${issue.message}`)
}
const changes = Object.entries(patch).map(([field, to]) => ({
field,
from: (existing as Record<string, unknown>)[field] ?? null,
@@ -19926,6 +19935,14 @@ export const tools: McpTool[] = [
const versions = await listAnnualReportVersions(supabase, companyId, fiscalPeriodId)
return { fiscal_period_id: fiscalPeriodId, versions }
},
// Search-only (2026-09-03): versions exist only once an annual report is
// rendered for signing or filing, and iXBRL filing is switched off until
// the Bolagsverket avtal and certificate exist (same reason its sibling
// gnubok_get_arsredovisning_filing_status below is search-only). Demoted
// to keep tools/list under the context budget after #2254 added the
// proforma fields and #2240 the jamkning field notes (see
// payload-size.bench.test.ts). Reachable via gnubok_call_tool.
catalogVisibility: 'search',
},
{