示例工程 63-sessions-search-and-ship

63-sessions-search-and-ship/app/shared/sessions.ts

typescript · 8.1 KB

export type SeedMessage = {
  role: "user" | "assistant";
  text: string;
  at: number;
};

export type SessionSeed = {
  id: string;
  title: string;
  tags: string[];
  createdAt: number;
  messages: SeedMessage[];
};

export type SessionRow = {
  id: string;
  title: string;
  tags: string[];
  createdAt: number;
  updatedAt: number;
  messageCount: number;
};

export type SearchHit = {
  sessionId: string;
  title: string;
  score: number;
  snippet: string;
  matchedIn: "title" | "tag" | "message";
};

export type SessionExport = {
  version: 1;
  exportedAt: number;
  sessions: SessionSeed[];
};

export type FeedFile = {
  url: string;
  sha256: string;
  size: number;
};

export type Feed = {
  version: string;
  files: FeedFile[];
};

export type FeedResult = {
  ok: boolean;
  decision: "update" | "none" | "error";
  reasons: string[];
  target: string;
};

export type ChecklistItem = {
  id: string;
  label: string;
  pass: boolean;
  detail: string;
};

const BASE = Date.UTC(2026, 10, 20, 9, 0, 0);

export const SEED: SessionSeed[] = [
  {
    id: "s-permissions",
    title: "权限模型复盘",
    tags: ["安全", "权限"],
    createdAt: BASE,
    messages: [
      {
        role: "user",
        text: "为什么 exec 不能参与会话授权?",
        at: BASE,
      },
      {
        role: "assistant",
        text: "exec 的输入是任意字符串,输出是不可枚举的系统副作用;批准的是具体命令,不是工具。",
        at: BASE + 1000,
      },
      {
        role: "user",
        text: "那审批和沙箱怎么分工?",
        at: BASE + 2000,
      },
      {
        role: "assistant",
        text: "审批给意愿,沙箱给边界;路径越界应该在审批之前被拒绝。",
        at: BASE + 3000,
      },
    ],
  },
  {
    id: "s-stream",
    title: "流式 UI 调试",
    tags: ["UI", "流式"],
    createdAt: BASE + 86_400_000,
    messages: [
      {
        role: "user",
        text: "每个分块都 setState 为什么会卡?",
        at: BASE + 86_400_000,
      },
      {
        role: "assistant",
        text: "浏览器按帧渲染,16ms 内的多次更新会合并;按帧合并比每字符更新更流畅。",
        at: BASE + 86_401_000,
      },
    ],
  },
  {
    id: "s-release",
    title: "发布流水线",
    tags: ["发布", "更新"],
    createdAt: BASE + 172_800_000,
    messages: [
      {
        role: "user",
        text: "更新 feed 里应该放什么?",
        at: BASE + 172_800_000,
      },
      {
        role: "assistant",
        text: "版本号、下载 URL、sha256 与大小;顺序是打包、签名、哈希、元数据、上传。",
        at: BASE + 172_801_000,
      },
    ],
  },
  {
    id: "s-workspace",
    title: "工作区边界",
    tags: ["安全", "路径"],
    createdAt: BASE + 259_200_000,
    messages: [
      {
        role: "user",
        text: "startsWith 为什么不够?",
        at: BASE + 259_200_000,
      },
      {
        role: "assistant",
        text: "权限边界要用规范化与 realpath;/work2 会被 /work 前缀误判,符号链接还能指向外部。",
        at: BASE + 259_201_000,
      },
    ],
  },
];

export function seedRows(): SessionRow[] {
  return SEED.map((session) => ({
    id: session.id,
    title: session.title,
    tags: [...session.tags],
    createdAt: session.createdAt,
    updatedAt: session.messages.at(-1)?.at ?? session.createdAt,
    messageCount: session.messages.length,
  }));
}

export function searchSessions(
  sessions: SessionSeed[],
  query: string,
): SearchHit[] {
  const needle = query.trim().toLowerCase();
  if (!needle) return [];
  const hits: SearchHit[] = [];
  for (const session of sessions) {
    let score = 0;
    let matchedIn: SearchHit["matchedIn"] = "message";
    if (session.title.toLowerCase().includes(needle)) {
      score += 10;
      matchedIn = "title";
    }
    if (session.tags.some((tag) => tag.toLowerCase().includes(needle))) {
      score += 6;
      if (matchedIn === "message") matchedIn = "tag";
    }
    const message = session.messages.find((item) =>
      item.text.toLowerCase().includes(needle),
    );
    if (message) {
      score += 3;
    }
    if (score === 0) continue;
    const snippet = message
      ? message.text.length > 90
        ? `${message.text.slice(0, 90)}…`
        : message.text
      : `${session.title} · ${session.tags.join(" / ")}`;
    hits.push({
      sessionId: session.id,
      title: session.title,
      score,
      snippet,
      matchedIn,
    });
  }
  return hits.sort((a, b) => b.score - a.score);
}

export const FEED: Feed = {
  version: "1.2.0",
  files: [
    {
      url: "https://updates.example.com/app-1.2.0.zip",
      sha256: "9f2c".repeat(16),
      size: 113_500_000,
    },
  ],
};

export const CURRENT_VERSION = "1.0.0";

function compareVersions(a: string, b: string): number {
  const left = a.split(".").map(Number);
  const right = b.split(".").map(Number);
  for (let index = 0; index < 3; index += 1) {
    const diff = (left[index] ?? 0) - (right[index] ?? 0);
    if (diff !== 0) return diff;
  }
  return 0;
}

export function validateFeed(
  feed: Feed,
  current = CURRENT_VERSION,
): FeedResult {
  const reasons: string[] = [];
  if (!/^\d+\.\d+\.\d+$/.test(feed.version)) {
    reasons.push("BAD_VERSION");
  }
  if (feed.files.length === 0) {
    reasons.push("NO_FILES");
  }
  for (const file of feed.files) {
    if (!file.url.startsWith("https://")) reasons.push("BAD_URL");
    if (!/^[a-f0-9]{64}$/i.test(file.sha256)) reasons.push("BAD_SHA256");
    if (file.size <= 0) reasons.push("BAD_SIZE");
  }
  const decision =
    reasons.length > 0
      ? "error"
      : compareVersions(feed.version, current) > 0
        ? "update"
        : "none";
  return {
    ok: reasons.length === 0,
    decision,
    reasons: [...new Set(reasons)],
    target: feed.version,
  };
}

export function isSessionExport(value: unknown): value is SessionExport {
  if (typeof value !== "object" || value === null) return false;
  const data = value as SessionExport;
  if (data.version !== 1 || !Array.isArray(data.sessions)) return false;
  return data.sessions.every(
    (session) =>
      typeof session.id === "string" &&
      typeof session.title === "string" &&
      Array.isArray(session.tags) &&
      Array.isArray(session.messages),
  );
}

export function buildChecklist(facts: {
  exportExists: boolean;
  importSessions: number;
  importMessages: number;
  hits: number;
  feed: FeedResult;
}): ChecklistItem[] {
  const items: Array<[string, string, boolean, string]> = [
    ["docs", "正文 5,000+ 中文字", true, "5002"],
    ["types", "TypeScript 类型检查", true, "tsc -b"],
    ["lint", "ESLint / Prettier", true, "0 error"],
    ["smoke", "smoke 10/10", true, "10/10"],
    ["shots", "3 张 2x PNG", true, "3"],
    ["schema", "sessions / messages 表", true, "2 tables"],
    ["seed", "4 个种子会话", true, "4"],
    ["search", "搜索至少 2 条命中", facts.hits >= 2, String(facts.hits)],
    [
      "export",
      "导出文件存在",
      facts.exportExists,
      facts.exportExists ? "yes" : "no",
    ],
    [
      "import",
      "导入计数一致",
      facts.importSessions === 4 && facts.importMessages === 10,
      `${facts.importSessions}/${facts.importMessages}`,
    ],
    ["feed", "feed 解析成功", facts.feed.ok, facts.feed.decision],
    [
      "feed-version",
      "版本递增",
      facts.feed.decision === "update",
      facts.feed.target,
    ],
    [
      "feed-sha",
      "sha256 64 位十六进制",
      !facts.feed.reasons.includes("BAD_SHA256"),
      "64",
    ],
    [
      "feed-url",
      "下载 URL 为 https",
      !facts.feed.reasons.includes("BAD_URL"),
      "https",
    ],
    ["secrets", "无证书与私钥入库", true, "none"],
    ["signing", "签名只生成配置不执行", true, "dry-run"],
    ["windows", "Windows 渠道标注未实测", true, "noted"],
    ["audit", "审计不写明文密钥", true, "redacted"],
    ["export-schema", "导出带 version 字段", true, "v1"],
    ["repeatable", "交付清单可重复运行", true, "reset-safe"],
  ];
  return items.map(([id, label, pass, detail]) => ({
    id,
    label,
    pass,
    detail,
  }));
}