invariant.ts 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. /** Package-owned hook invocation/result stream invariants. @module @deepseek-ai/dsh-hook-protocol/invariant */
  2. import type { Context } from '@deepseek-ai/cordis'
  3. import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
  4. import type { InvariantFailure, InvariantInstaller } from '@deepseek-ai/dsh-invariants'
  5. import type {} from './types.ts'
  6. const PACKAGE_NAME = '@deepseek-ai/dsh-hook-protocol'
  7. /** Cordis companion plugin name. */
  8. export const name = 'hook-protocol-invariant'
  9. /** Service required before the companion can reserve package ownership. */
  10. export const inject = ['invariants']
  11. interface HookTransition {
  12. key: string
  13. delta: 1 | -1
  14. }
  15. interface HookTrace {
  16. openTurn: number | null
  17. pending: Map<string, number>
  18. }
  19. /** Correlation key shared by an invoked/result pair. */
  20. function hookKey(data: { turn: number; point: string; handlerId: string }): string {
  21. return `${data.turn}\0${data.point}\0${data.handlerId}`
  22. }
  23. /** Validate one hook event against committed pending invocations. */
  24. function validateHookEvent(
  25. trace: HookTrace,
  26. event: SessionEvent,
  27. fail: InvariantFailure,
  28. ): HookTransition | undefined {
  29. if (event.type !== 'hook/invoked' && event.type !== 'hook/result') return undefined
  30. if (trace.openTurn === null) fail(`${event.type} appended outside any open turn`)
  31. if (event.data.turn !== trace.openTurn) {
  32. fail(`${event.type} names turn ${event.data.turn} but open turn is ${trace.openTurn}`)
  33. }
  34. if (event.type === 'hook/invoked') {
  35. if (event.data.point.length === 0 || event.data.handlerId.length === 0) {
  36. fail('hook/invoked point and handlerId must be non-empty')
  37. }
  38. const dialect: string = event.data.dialect
  39. if (dialect !== 'claude-code' && dialect !== 'codex') {
  40. fail(`hook/invoked carries unknown dialect ${JSON.stringify(dialect)}`)
  41. }
  42. return { key: hookKey(event.data), delta: 1 }
  43. }
  44. const key = hookKey(event.data)
  45. if ((trace.pending.get(key) ?? 0) === 0) {
  46. fail(`hook/result has no matching hook/invoked for ${JSON.stringify(event.data.handlerId)}`)
  47. }
  48. if (!Number.isFinite(event.data.durationMs) || event.data.durationMs < 0) {
  49. fail('hook/result durationMs must be a non-negative finite number')
  50. }
  51. return { key, delta: -1 }
  52. }
  53. /** Apply one committed hook-pair transition. */
  54. function applyHookTransition(pending: Map<string, number>, transition: HookTransition): void {
  55. const next = (pending.get(transition.key) ?? 0) + transition.delta
  56. if (next === 0) pending.delete(transition.key)
  57. else pending.set(transition.key, next)
  58. }
  59. /** Install hook invoked/result pairing checks. */
  60. // Event owners keep precommit staging local so their vocabularies never move into a central helper.
  61. /* jscpd:ignore-start */
  62. const install: InvariantInstaller = Object.assign((ctx: Context, fail: InvariantFailure) => {
  63. const traces = new WeakMap<Session, HookTrace>()
  64. const staged = new WeakMap<SessionEvent, { session: Session; transition: HookTransition }>()
  65. const seed = (session: Session): HookTrace => {
  66. const trace: HookTrace = { openTurn: null, pending: new Map() }
  67. traces.set(session, trace)
  68. for (const event of session.events) {
  69. if (event.type === 'turn/start') trace.openTurn = event.data.turn
  70. else if (event.type === 'turn/end') trace.openTurn = null
  71. const transition = validateHookEvent(trace, event, fail)
  72. if (transition !== undefined) applyHookTransition(trace.pending, transition)
  73. }
  74. return trace
  75. }
  76. const traceFor = (session: Session): HookTrace => traces.get(session) ?? seed(session)
  77. for (const session of ctx.sessions.list()) seed(session)
  78. ctx.on('session/created', (session) => { seed(session) }, { global: true })
  79. ctx.on('session/event', (session, event) => {
  80. const trace = traceFor(session)
  81. if (event.type === 'turn/start') {
  82. trace.openTurn = event.data.turn
  83. return
  84. }
  85. if (event.type === 'turn/end') {
  86. trace.openTurn = null
  87. return
  88. }
  89. if (event.type !== 'hook/invoked' && event.type !== 'hook/result') return
  90. const candidate = staged.get(event)
  91. /* v8 ignore next -- internal/dispatch stages every hook invocation/result event */
  92. if (candidate === undefined || candidate.session !== session) return fail('hook event published without pre-commit validation')
  93. staged.delete(event)
  94. applyHookTransition(trace.pending, candidate.transition)
  95. }, { global: true })
  96. ctx.on('internal/dispatch', (_mode, eventName, args) => {
  97. if (eventName !== 'session/event') return
  98. const [session, event] = args as [Session, SessionEvent]
  99. const transition = validateHookEvent(traceFor(session), event, fail)
  100. if (transition !== undefined) staged.set(event, { session, transition })
  101. }, { global: true })
  102. }, { inject: ['sessions'] })
  103. /* jscpd:ignore-end */
  104. /**
  105. * Register the hook-protocol invariant companion.
  106. * @param ctx - Cordis context carrying the invariant service.
  107. * @returns the installed registration's disposer after setup succeeds.
  108. */
  109. export const apply = (ctx: Context): Promise<() => void> =>
  110. Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))