// types.d.ts — dsh-checkpoint-rewind 类型契约（会话事件声明合并 + 消息来源声明
// 合并 + 配置类型）。

import type { Volatile } from '@deepseek-ai/cordis'
import type { ContextFormed } from '@deepseek-ai/dsh-llm'

/**
 * 检查点记录（与 lib/domain.mjs 的持久 schema 同构；存储领域记录为权威）。
 * 一体化三态模型：{id, 时间, 会话事件游标(seq), 工作区 git tree SHA(tree),
 * 配置快照(config), 备注(note), 来源(kind)}。
 */
export interface CheckpointRecord {
  id: string
  /**
   * 每会话短号（正整数，从 1 起；`/rewind 3` 的精确寻址目标）。
   * 单调、永不复用：prune 与 `/rewind clear` 都不回收号（高水位持久在
   * 'checkpoints' 领域的 global 槽里）。0.6.24 及更早写入的记录没有该字段，
   * 首次被本会话任何 /rewind、/checkpoint list 或捕获触达时按创建序补号并
   * 持久化（见 planShortNumbers）。
   */
  short?: number
  sessionId: string
  cwd: string
  /** 会话事件游标：捕获时会话日志 seq。 */
  seq: number
  time: number
  provider: 'git' | 'copy'
  /** 来源：manual（/checkpoint 与工具）· auto（间隔）· guard（回退保护）· mutation（变更安全网）。 */
  kind: 'manual' | 'auto' | 'guard' | 'mutation'
  triggerTool: string
  turn: number
  step: number
  files: number
  bytes: number
  /** provider 恢复句柄（git 提交对象 sha / copy 目录名）。 */
  ref: string
  /** 工作区 git tree SHA（copy provider 为 null）。 */
  tree?: string | null
  /** 配置快照（捕获时插件有效配置）。 */
  config?: Record<string, unknown>
  /** 备注（手动检查点；≤500 字符）。 */
  note?: string
  /** 捕获所在 step 的 step/end 事件 seq（补记；"/rewind step N" 映射）。 */
  stepEndSeq?: number
  /** 会话重放边界：游标之前最近一条 turn/end 的 seq（首轮检查点缺失）。 */
  sessionBoundary?: number
  /** doctor pass 标记：底层快照对象（如 gc 后的提交/树对象）已消亡、无法恢复。 */
  unrestorable?: boolean
  unrestorableReason?: string
}

declare module '@deepseek-ai/cordis' {
  interface Events {
    /**
     * fs 写入/编辑意图（宿主审批缝；本插件为旁路观察者——监听必须 next()
     * 直通，决策槽仍归策略插件）。返回值为决策槽（策略插件决定形状）。
     */
    'fs/write-intent'(target: { path?: string, key?: string }, actor: object | null, next: () => any): any
    'fs/edit-intent'(target: { path?: string, key?: string }, actor: object | null, next: () => any): any
  }
}

declare module '@deepseek-ai/dsh-llm' {
  interface MessageSourceMap {
    /**
     * 本插件注入的回退通知（user/message）。
     * 0.1.7-alpha.1 删除了 `kind: 'plugin'` catch-all（MessageSourceMap 只剩
     * user|model|tool|system-prompt），且会话格式 v3→v4 的物理行准入明确拒绝
     * `kind === 'plugin'`（as any 也拦得住）——生产者必须声明自己的 kind。
     * 形态与宿主 packages/jobs/tool-jobs 的做法一致：{ kind } & ContextFormed。
     */
    'dsh-checkpoint-rewind': { kind: 'dsh-checkpoint-rewind' } & ContextFormed
  }
}

declare module '@deepseek-ai/dsh-session' {
  interface SessionEventMap {
    /**
     * 一条三态检查点被捕获（log-only）。
     * 注意：宿主构建的 KNOWN_SESSION_EVENT_TYPES 至今未收录 checkpoint/*（新宿主
     * 新增的是 developer/message 与 workspace/changes），运行时经自适应门跳过
     * append；宿主收录该类型或 append 盖章 ignorable 信封后自动开启
     * （见 lib/gate.mjs 与 README「会话事件」）。
     */
    'checkpoint/snapshot': CheckpointRecord
    /**
     * 检查点边界补记（log-only）：step/end 到达补 stepEndSeq。
     */
    'checkpoint/bound': {
      id: string
      turn: number
      step?: number
      stepEndSeq?: number
    }
    /** 配额清理（log-only）：被删检查点 id 与触发原因。 */
    'checkpoint/prune': {
      ids: string[]
      reason: 'maxSnapshots' | 'maxSnapshotBytes' | 'turnEnd' | 'clear'
    }
    /**
     * /rewind 回退动作结果（log-only）：三态事务的关键字段。
     * outcome: denied（确认门拒绝）| failed（工作区恢复失败，其余未执行）
     * | partial（工作区已恢复，配置/会话至少一项失败）| restored（全成功）。
     * target: all | workspace | session | config。
     * preCheckpointId：本次回退前捕获的保护检查点（可用来撤销回退）。
     */
    'checkpoint/rewind': {
      checkpointId: string
      sessionId: string
      outcome: 'denied' | 'failed' | 'partial' | 'restored'
      target: 'all' | 'workspace' | 'session' | 'config'
      workspace?: { restored: number, mode: 'restore' | 'reset-hard' }
      config?: { durable: boolean, error?: string }
      session?: { childSessionId?: string, error?: string }
      preCheckpointId?: string
      error?: string
    }
  }
}

/**
 * 一条检查点的客户端 wire 记录（投影单元 view 输出；SessionProjectionMap
 * 与 SessionProjectionStateMap 共用同一形状——后者按 id 索引）。
 */
export interface CheckpointWireRecord {
  id: string
  /** 每会话短号（`/rewind <number>` 的寻址目标；旧事件载荷可能缺失）。 */
  short?: number
  turn: number
  step: number
  time: number
  provider: 'git' | 'copy'
  kind: 'manual' | 'auto' | 'guard' | 'mutation'
  triggerTool: string
  files: number
  bytes: number
  tree?: string | null
  note?: string
  seq: number
  stepEndSeq?: number
  sessionBoundary?: number
  rewindOutcome?: 'denied' | 'failed' | 'partial' | 'restored'
  preCheckpointId?: string
}

/**
 * `checkpoints` 会话投影的**整个 wire 值**：一行有界状态串，例如
 *
 * ```text
 * cp:7 | #1-7 | last #7 [manual] t3s2 | sess t2s4 | rw:restored
 * ```
 *
 * 它是字符串而不是对象，这是被渲染器逼出来的：一条检查点的紧凑 JSON 即使一个
 * 可选字段都不带、短号也没有，也要 151 码元（36 字符 UUID 是 id 下限），而微信桥
 * 把每个投影值渲染成一行并在 120 码元处截断 —— 也就是说对象（列表）形态对**任何**
 * 真实值都必然被劈断。格式与预算由 `lib/projection.mjs` 的
 * `renderCheckpointsLine` / `CHECKPOINTS_LINE_MAX` 独家持有。
 */
export type CheckpointsView = string

declare module '@deepseek-ai/dsh-session-projection' {
  interface SessionProjectionMap {
    /**
     * Web UI 检查点条 / 手机桥 `/status` 的整值：一行有界状态串
     * （`cp:<n> | #<lo>-<hi> | last #<short> [<kind>] t<turn>s<step>
     * [| sess t<turn>s<step>] [| rw:<outcome>]`）。
     * 折叠 checkpoint/snapshot|bound|prune|rewind 事件得到；宿主未收录该词汇
     * 且不支持 ignorable 信封时恒为 `cp:0`（见 README「会话事件」）。
     */
    checkpoints: CheckpointsView
  }
  interface SessionProjectionStateMap {
    /**
     * 检查点折叠状态：id → wire 记录（持久缓存前置条件 = 普通 JSON）。
     * ⚠️ 状态形状与 wire 值解耦：wire 换成单行字符串**不动**这份状态，因此
     * `stateVersion` 保持 0、旧持久行无需迁移（见 lib/projection.mjs 的推导）。
     */
    checkpoints: Record<string, CheckpointWireRecord>
  }
}

/**
 * 插件配置的纯值形态（cordis.yml 字面值；也是检查点 config 快照与设置页表单
 * 处理的值）。可选字段 = apply 之前用户层可能缺席，缺失由 schema 默认 /
 * resolveConfig 补齐。
 */
export interface CheckpointConfig {
  /** 总开关；false 时命令、监听器与 provider 全部卸载。 */
  enabled?: boolean
  /** 快照 provider：auto（git 可用则 git，否则 copy）· git · copy。 */
  provider?: 'auto' | 'git' | 'copy'
  /** git 可执行文件路径（仅 git provider 使用）。 */
  gitBin?: string
  /** copy provider 快照根目录（默认 $DSH_HOME/dsh-checkpoint-rewind）。 */
  snapshotDir?: string
  /** 每会话保留的检查点数（最旧优先清理，默认 50；有界存储·数量界）。 */
  maxSnapshots?: number
  /** 跨会话全局增量字节软配额（默认 512 MiB；有界存储·大小界；每会话最新一条总是保留）。 */
  maxSnapshotBytes?: number
  /** 轮次结束时执行配额清理（默认 true）。 */
  pruneOnTurnEnd?: boolean
  /** tools/pre-execute 上视为变更型的工具名（fs 工具由 fs/*-intent 覆盖）。 */
  mutationTools?: string[]
  /**
   * copy provider 排除的 glob 模式：`*` 段内任意字符、`?` 单字符、`**` 跨段；
   * 无 `/` 匹配任意深度段名，含 `/` 按相对路径匹配，命中目录排除整个子树。
   */
  excludeGlobs?: string[]
  /** 恢复确认通道：auto（userQuestions 优先）· userQuestions · approval。 */
  confirmVia?: 'auto' | 'userQuestions' | 'approval'
  /** 无参 /rewind 列出的检查点数（默认 10）。 */
  listLimit?: number
  /** 恢复前保护检查点：warn · require · off（默认 warn）。 */
  preRewindCheckpoint?: 'warn' | 'require' | 'off'
  /** copy provider 内容哈希校验（去重 + 恢复完整性，默认 false）。 */
  verifyByHash?: boolean
  /** 自动间隔快照：step/start 时检查；intervalMinutes=0 每步；enabled=false 关闭。 */
  autoCheckpoint?: {
    enabled?: boolean
    intervalMinutes?: number
  }
  /**
   * 工作区回滚实现：restore（默认安全覆盖，绝不删除检查点后新建的文件）·
   * reset-hard（CC 对标：git reset --hard <快照提交>，默认关，需显式开启）。
   */
  workspaceRestore?: 'restore' | 'reset-hard'
  /** 设置页两两 diff 的渲染器：pairwise（默认行级文本）· side-by-side（per-file 并排）。 */
  diffRenderer?: 'pairwise' | 'side-by-side'
  /** 逐文件勾选 + 选择性恢复（/rewind … --files）开关（默认 true）。 */
  selectiveRestore?: boolean
  /** 注入一句角色陈述式短提示词段落（默认 true，对齐官方 Minimal persona 风格）。 */
  promptSection?: boolean
  /** 注册 checkpoint 模型工具（默认 true）。 */
  checkpointTool?: boolean
}

/**
 * cordis 交给 apply 的配置形态：Config schema 里标了 volatile 的字段在
 * 0.1.7-alpha.1+ 宿主上解析为稳定的 Volatile 引用（设置页编辑时就地更新，
 * 插件不重挂），读值必须走 `.get()`；旧宿主行（schemastery 无 volatile 支持）
 * 与直接调用拿到的是纯值。index.mjs 的 resolveConfig 两种形态都接受。
 */
export type Config = {
  [K in keyof CheckpointConfig]-?: Volatile<NonNullable<CheckpointConfig[K]>>
}
