Skip to content

zenstory-ai/oh-story-claudecode / skills/story-long-write

story-long-write

Unverified

长篇网文规划与写作。支持只讨论结构、只写大纲或指定细纲,明确要求正文后再写章节。触发方式:/story-long-write、/写长篇、「帮我开书」「定设定」「出卷纲」「规划剧情」「写大纲」「补细纲」「日更」「续写」「继续写」「修改第X章」「回炉」「重写第X章」。

FileKindSize
SKILL.mdskill md12.9 KB
references/agent-calls.mdmarkdown5.3 KB
references/artifact-protocols.mdmarkdown9.8 KB
references/author-memory.mdmarkdown6.6 KB
references/banned-words.mdmarkdown10.9 KB
references/benchmark-recall.mdmarkdown5.2 KB
references/character-basics.mdmarkdown12.3 KB
references/character-relations.mdmarkdown10.2 KB
references/cross-book-recall.mdmarkdown3.9 KB
references/dialogue-mastery.mdmarkdown11.0 KB
references/emotional-methods.mdmarkdown7.9 KB
references/female-audience-writing.mdmarkdown7.5 KB
references/genre-prose-cards.mdmarkdown7.0 KB
references/genre-prose-cards/东方仙侠.mdmarkdown2.3 KB
references/genre-prose-cards/传统玄幻.mdmarkdown1.9 KB
references/genre-prose-cards/历史古代.mdmarkdown1.7 KB
references/genre-prose-cards/历史脑洞.mdmarkdown2.0 KB
references/genre-prose-cards/双男主.mdmarkdown2.3 KB
references/genre-prose-cards/古言脑洞.mdmarkdown1.8 KB
references/genre-prose-cards/古风世情.mdmarkdown2.3 KB
references/genre-prose-cards/女频悬疑.mdmarkdown1.8 KB
references/genre-prose-cards/女频种田.mdmarkdown1.8 KB
references/genre-prose-cards/宫斗宅斗.mdmarkdown1.6 KB
references/genre-prose-cards/年代.mdmarkdown2.1 KB
references/genre-prose-cards/快穿.mdmarkdown1.9 KB
references/genre-prose-cards/悬疑灵异.mdmarkdown1.7 KB
references/genre-prose-cards/悬疑脑洞.mdmarkdown1.9 KB
references/genre-prose-cards/战神赘婿.mdmarkdown1.9 KB
references/genre-prose-cards/抗战谍战.mdmarkdown1.8 KB
references/genre-prose-cards/星光璀璨.mdmarkdown1.8 KB
references/genre-prose-cards/民国言情.mdmarkdown1.9 KB
references/genre-prose-cards/流派兜底.mdmarkdown8.4 KB
references/genre-prose-cards/游戏体育.mdmarkdown1.9 KB
references/genre-prose-cards/玄幻脑洞.mdmarkdown2.0 KB
references/genre-prose-cards/玄幻言情.mdmarkdown1.7 KB
references/genre-prose-cards/现言脑洞.mdmarkdown1.8 KB
references/genre-prose-cards/科幻末世.mdmarkdown1.7 KB
references/genre-prose-cards/职场婚恋.mdmarkdown1.7 KB
references/genre-prose-cards/西方奇幻.mdmarkdown1.9 KB
references/genre-prose-cards/豪门总裁.mdmarkdown2.3 KB
references/genre-prose-cards/都市修真.mdmarkdown1.7 KB
references/genre-prose-cards/都市日常.mdmarkdown2.8 KB
references/genre-prose-cards/都市种田.mdmarkdown1.7 KB
references/genre-prose-cards/都市脑洞.mdmarkdown2.4 KB
references/genre-prose-cards/都市高武.mdmarkdown2.0 KB
references/genre-prose-cards/青春甜宠.mdmarkdown1.8 KB
references/genre-readers.mdmarkdown6.9 KB
references/long-chapter-hooks.mdmarkdown6.5 KB
references/long-chapter-quality.mdmarkdown3.3 KB
references/long-format.mdmarkdown2.1 KB
references/long-genre-catalog.mdmarkdown11.9 KB
references/long-genre-mechanics.mdmarkdown8.3 KB
references/long-reversal.mdmarkdown12.3 KB
references/long-suspense.mdmarkdown9.2 KB
references/opening-design.mdmarkdown4.5 KB
references/outline-methods.mdmarkdown12.5 KB
references/outline-template.mdmarkdown7.9 KB
references/plot-core-methods.mdmarkdown5.3 KB
references/project-files.mdmarkdown4.7 KB
references/reader-contract-and-progression.mdmarkdown6.9 KB
references/revision-diagnosis.mdmarkdown3.6 KB
references/style-combat-face.mdmarkdown9.1 KB
references/tracking-initialization.mdmarkdown1.6 KB
references/tracking-transaction.mdmarkdown8.8 KB
references/workflow-chapter.mdmarkdown12.5 KB
references/workflow-daily.mdmarkdown6.3 KB
references/workflow-outline.mdmarkdown11.1 KB
references/workflow-revision.mdmarkdown6.5 KB
references/workflow-setup.mdmarkdown10.9 KB
references/workflow-volume.mdmarkdown6.4 KB
references/writing-craft.mdmarkdown23.6 KB
scripts/author_memory_commit.jsexecutablescript64.6 KB
scripts/build_architect_brief.jsexecutablescript20.0 KB
scripts/build_writer_prompt.jsexecutablescript34.9 KB
scripts/check-ai-patterns.jsexecutablescript79.8 KB
scripts/check-degeneration.jsscript15.4 KB
scripts/check-outline-contract.jsscript12.4 KB
scripts/check-outline-copy.jsscript13.4 KB
scripts/normalize-punctuation.jsexecutablescript19.0 KB
scripts/outline_view.jsexecutablescript15.1 KB
scripts/storyctl.jsexecutablescript32.8 KB
scripts/style-whitelist.jsscript1.1 KB
scripts/tracking_commit.jsexecutablescript84.7 KB
scripts/wordcount_core.jsexecutablescript20.3 KB

scripts/wordcount_core.js

View on GitHub
#!/usr/bin/env node
'use strict';
/**
 * Small deterministic wordcount core shared by storyctl, tracking_commit,
 * check-outline-contract, build_writer_prompt, and build_outline_brief.
 */

const crypto = require('node:crypto');
const fs = require('node:fs');
const path = require('node:path');

const WORDCOUNT_SCHEMA = 'story-wordcount-result/v1';
const MEASUREMENT_SCHEMA = 'story-wordcount-measurement/v1';
const CHECKPOINT_SCHEMA = 'story-wordcount-checkpoint/v1';
const METRIC = 'visible_chars_v1';
const RESOLUTIONS = new Set(['within_user_band', 'accepted_current_length']);

const _WHITE_SPACE_CODEPOINTS = new Set([
  0x0009, 0x000a, 0x000b, 0x000c, 0x000d,
  0x0020, 0x0085, 0x00a0, 0x1680,
  0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200a,
  0x2028, 0x2029, 0x202f, 0x205f, 0x3000,
]);

const _FRONTMATTER_KEY_RE = /^[A-Za-z_\u3400-\u9FFF][^:\n]{0,80}:[ \t]*(?:.*)$/;
const _LEADING_BLANK_RE = /^[\u0009\u0020\u3000]*$/;
const _ATX_HEADING_RE = /^[\u0009\u0020]{0,3}#{1,6}[\u0009\u0020]+\S/;
const _POSITIVE_INTEGER_RE = /^[1-9]\d*$/;

// 细纲「字数目标」「字数范围」「字数口径」的唯一写法语法;check-outline-contract.js 直接复用本模块。
// 值里一个数字都没有的目标/范围行(「字数目标:按卷规划」)是说明文字,不参与取值。
const _NUMBER = '([1-9][0-9]{0,2}(?:[,,][0-9]{3})+|[1-9][0-9]*)';
const _NOTE = '(?:[((][^()()]*[))])?';
const _TARGET_VALUE_RE = new RegExp(`^(?:约|大约)?[ \\t]*${_NUMBER}[ \\t]*字?(?:左右)?[ \\t]*${_NOTE}$`);
const _RANGE_VALUE_RE = new RegExp(
  `^${_NUMBER}[ \\t]*字?[ \\t]*(?:-|~|~|—|–|-|至|到)[ \\t]*${_NUMBER}[ \\t]*字?[ \\t]*${_NOTE}$`
);
const _METRIC_VALUE_RE = new RegExp(`^([A-Za-z0-9_-]+)[ \\t]*${_NOTE}$`);
const _HAS_DIGIT_RE = /[0-90-9]/;

const BOOK_DIRS = ['设定', '大纲', '正文', '追踪'];
const _RECORD_FIELDS = new Set(['metric', 'target', 'actual', 'status', 'resolution', 'body_sha256']);

class WordcountError extends Error {
  constructor(message) {
    super(message);
    this.name = 'WordcountError';
  }
}

function requireCondition(condition, message) {
  if (!condition) {
    throw new WordcountError(message);
  }
}

function normalizeNewlines(value) {
  return value.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
}

function stripBom(value) {
  return value.startsWith('\ufeff') ? value.slice(1) : value;
}

function _fieldValues(text, label) {
  const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  const pattern = new RegExp(
    `^[ \\t>]*(?:[-*+][ \\t]*)?(?:\\*\\*)?${escaped}(?:\\*\\*)?[ \\t]*[::][ \\t]*(.*?)[ \\t]*$`,
    'gm'
  );
  const values = [];
  let match;
  while ((match = pattern.exec(text)) !== null) {
    values.push(match[1].replace(/\*\*/g, '').trim());
  }
  return values;
}

function _numericFieldValues(text, label) {
  return _fieldValues(text, label).filter((raw) => _HAS_DIGIT_RE.test(raw));
}

function _number(raw) {
  return Number(raw.replace(/[,,]/g, ''));
}

function parseTargetField(text) {
  const raws = _numericFieldValues(stripBom(normalizeNewlines(text)), '字数目标');
  if (raws.length === 0) {
    return { status: 'missing', value: null, raw: raws };
  }
  const matches = raws.map((raw) => _TARGET_VALUE_RE.exec(raw));
  if (!matches.every(Boolean)) {
    return { status: 'invalid', value: null, raw: raws };
  }
  const values = [...new Set(matches.map((m) => _number(m[1])))].sort((a, b) => a - b);
  if (values.length !== 1) {
    return { status: 'conflict', value: null, raw: raws };
  }
  return { status: 'ok', value: values[0], raw: raws };
}

function parseRangeField(text) {
  const raws = _numericFieldValues(stripBom(normalizeNewlines(text)), '字数范围');
  if (raws.length === 0) {
    return { status: 'missing', value: null, raw: raws };
  }
  const matches = raws.map((raw) => _RANGE_VALUE_RE.exec(raw));
  if (!matches.every(Boolean)) {
    return { status: 'invalid', value: null, raw: raws };
  }
  const pairKeys = [...new Set(matches.map((m) => `${_number(m[1])}:${_number(m[2])}`))];
  if (pairKeys.length !== 1) {
    return { status: 'invalid', value: null, raw: raws };
  }
  const [low, high] = pairKeys[0].split(':').map(Number);
  if (low > high) {
    return { status: 'invalid', value: null, raw: raws };
  }
  return { status: 'ok', value: { min: low, max: high }, raw: raws };
}

function parseMetricField(text) {
  const raws = _fieldValues(stripBom(normalizeNewlines(text)), '字数口径');
  const matches = raws.map((raw) => _METRIC_VALUE_RE.exec(raw));
  const ok =
    raws.length === 0 ||
    (matches.every(Boolean) &&
      new Set(matches.map((m) => m[1])).size === 1 &&
      matches[0][1] === METRIC);
  return { ok, raw: raws };
}

function _isDir(targetPath) {
  try {
    return fs.statSync(targetPath).isDirectory();
  } catch {
    return false;
  }
}

function _isFile(targetPath) {
  try {
    return fs.statSync(targetPath).isFile();
  } catch {
    return false;
  }
}

function _realpathOrResolve(targetPath) {
  const resolved = path.resolve(targetPath);
  try {
    return fs.realpathSync(resolved);
  } catch {
    return resolved;
  }
}

function resolveBookDir(project) {
  const root = String(project);
  const marker = path.join(root, '.active-book');
  if (BOOK_DIRS.some((name) => _isDir(path.join(root, name))) || !_isFile(marker)) {
    return root;
  }
  const lines = fs.readFileSync(marker, 'utf8').split(/\r?\n/);
  const active = lines.length ? lines[0].trim() : '';
  const book = path.join(root, active);
  const realRoot = _realpathOrResolve(root);
  const realBook = _realpathOrResolve(book);
  const rel = path.relative(realRoot, realBook);
  const inside = rel === '' || (rel !== '..' && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
  requireCondition(
    Boolean(active) && inside && _isDir(book),
    `${marker} 没有指向工作区里的书目录(写的是「${active}」);--project 直接传书目录`
  );
  return book;
}

function stripRecognizableFrontmatter(value) {
  const lines = value.split('\n');
  if (!lines.length || lines[0] !== '---') {
    return value;
  }
  const limit = Math.min(lines.length, 201);
  let closing = -1;
  for (let index = 1; index < limit; index += 1) {
    if (lines[index] === '---' || lines[index] === '...') {
      closing = index;
      break;
    }
  }
  if (closing < 2 || !lines.slice(1, closing).some((line) => _FRONTMATTER_KEY_RE.test(line))) {
    return value;
  }
  return lines.slice(closing + 1).join('\n');
}

function visibleBody(value) {
  if (typeof value !== 'string') {
    throw new TypeError('body must be a string');
  }
  let text = normalizeNewlines(value);
  if (text.startsWith('\ufeff')) {
    text = text.slice(1);
  }
  const lines = stripRecognizableFrontmatter(text).split('\n');
  while (lines.length && _LEADING_BLANK_RE.test(lines[0])) {
    lines.shift();
  }
  if (lines.length && _ATX_HEADING_RE.test(lines[0])) {
    lines.shift();
  }
  return lines.join('\n');
}

function countVisibleChars(value) {
  const body = visibleBody(value);
  let count = 0;
  for (const ch of body) {
    if (!_WHITE_SPACE_CODEPOINTS.has(ch.codePointAt(0))) {
      count += 1;
    }
  }
  return count;
}

function parseTarget(value) {
  const raw = value === null || value === undefined ? '' : String(value);
  if (!_POSITIVE_INTEGER_RE.test(raw)) {
    throw new WordcountError('target must be a positive integer');
  }
  const big = BigInt(raw);
  requireCondition(big <= BigInt(Number.MAX_SAFE_INTEGER), 'target exceeds Number.MAX_SAFE_INTEGER');
  return Number(big);
}

function normalizeAuthorRange(value) {
  if (value === null || value === undefined) {
    return null;
  }
  requireCondition(
    typeof value === 'object' &&
      !Array.isArray(value) &&
      Object.keys(value).length === 2 &&
      Object.prototype.hasOwnProperty.call(value, 'min') &&
      Object.prototype.hasOwnProperty.call(value, 'max'),
    'author range must be {min, max}'
  );
  const { min: low, max: high } = value;
  requireCondition(
    Number.isInteger(low) && low >= 1 && Number.isInteger(high) && high >= 1,
    'author range bounds must be positive integers'
  );
  requireCondition(low <= high, 'author range min must not exceed max');
  return { min: low, max: high };
}

function computeWordcountBands(value, authorRange = null) {
  const target = parseTarget(value);
  const author = normalizeAuthorRange(authorRange);
  if (author !== null) {
    return { internal: { ...author }, user: { ...author } };
  }
  const bigTarget = BigInt(target);
  return {
    internal: {
      min: Number((bigTarget * 88n + 99n) / 100n),
      max: Number((bigTarget * 112n) / 100n),
    },
    user: {
      min: Number((bigTarget * 85n + 99n) / 100n),
      max: Number((bigTarget * 115n) / 100n),
    },
  };
}

function invalidWordcountResult(reason, opts = {}) {
  const { chapter = null, caseId = null, target = null, actual = null } = opts;
  return {
    schema: WORDCOUNT_SCHEMA,
    metric: METRIC,
    chapter,
    case_id: caseId,
    target,
    actual,
    internal_band: null,
    user_band: null,
    signed_error_pct: null,
    absolute_error_pct: null,
    band_source: null,
    status: 'invalid',
    invalid_reason: reason,
  };
}

function measureWordcount(value, opts = {}) {
  const { chapter = null, caseId = null } = opts;
  let actual;
  try {
    actual = countVisibleChars(value);
  } catch {
    return {
      schema: MEASUREMENT_SCHEMA,
      metric: METRIC,
      chapter,
      case_id: caseId,
      actual: null,
      status: 'invalid',
      invalid_reason: 'INVALID_BODY',
    };
  }
  return {
    schema: MEASUREMENT_SCHEMA,
    metric: METRIC,
    chapter,
    case_id: caseId,
    actual,
    status: 'measured',
    invalid_reason: null,
  };
}

function evaluateWordcount(value, targetValue, opts = {}) {
  const { chapter = null, caseId = null, authorRange = null } = opts;
  let target;
  try {
    target = parseTarget(targetValue);
  } catch {
    return invalidWordcountResult('INVALID_TARGET', { chapter, caseId });
  }
  let author;
  try {
    author = normalizeAuthorRange(authorRange);
  } catch {
    return invalidWordcountResult('INVALID_RANGE', { chapter, caseId, target });
  }
  let actual;
  try {
    actual = countVisibleChars(value);
  } catch {
    return invalidWordcountResult('INVALID_BODY', { chapter, caseId, target });
  }
  if (actual === 0) {
    return invalidWordcountResult('EMPTY_BODY', { chapter, caseId, target, actual });
  }
  const bands = computeWordcountBands(target, author);
  const internalPass = bands.internal.min <= actual && actual <= bands.internal.max;
  const userPass = bands.user.min <= actual && actual <= bands.user.max;
  const status = internalPass
    ? 'internal_pass'
    : userPass
      ? 'borderline'
      : actual < bands.user.min
        ? 'under'
        : 'over';
  const signedError = (actual - target) / target;
  return {
    schema: WORDCOUNT_SCHEMA,
    metric: METRIC,
    chapter,
    case_id: caseId,
    target,
    actual,
    internal_band: { ...bands.internal, status: internalPass ? 'pass' : 'fail' },
    user_band: { ...bands.user, status: userPass ? 'pass' : 'fail' },
    signed_error_pct: signedError,
    absolute_error_pct: Math.abs(signedError),
    band_source: author ? 'author' : 'default',
    status,
    invalid_reason: null,
  };
}

function checkpointWordcount(value, targetValue, opts = {}) {
  const { chapter = null, caseId = null, authorRange = null } = opts;
  const target = parseTarget(targetValue);
  const actual = countVisibleChars(value);
  const author = normalizeAuthorRange(authorRange);
  const user = computeWordcountBands(target, author).user;
  return {
    schema: CHECKPOINT_SCHEMA,
    metric: METRIC,
    chapter,
    case_id: caseId,
    target,
    actual,
    user_band: user,
    band_source: author ? 'author' : 'default',
    remaining_user_range: {
      min: Math.max(0, user.min - actual),
      max: Math.max(0, user.max - actual),
    },
  };
}

const _FIELD_ERRORS = {
  missing: 'is missing',
  invalid: 'is not a recognizable number (write e.g. 2300 字 / 约 2300 / 2,300)',
  conflict: 'has conflicting values',
};

function targetFromOutline(value) {
  const text = stripBom(normalizeNewlines(value));
  const parsed = parseTargetField(text);
  requireCondition(
    parsed.status === 'ok',
    `字数目标 ${_FIELD_ERRORS[parsed.status] || ''}: ${JSON.stringify(parsed.raw)}`
  );
  requireCondition(parseMetricField(text).ok, `字数口径 must be ${METRIC} when written`);
  return parseTarget(parsed.value);
}

function rangeFromOutline(value) {
  const parsed = parseRangeField(value);
  if (parsed.status === 'missing') {
    return null;
  }
  requireCondition(
    parsed.status === 'ok',
    `字数范围 must be one min-max pair with min <= max: ${JSON.stringify(parsed.raw)}`
  );
  return parsed.value;
}

function _chapterNumberFromName(name, { outline }) {
  if (!outline && name.includes('_原稿_')) {
    return null;
  }
  const pattern = outline
    ? /^细纲_第0*(\d+)章.*\.md$/
    : /^第0*(\d+)章(?:[_\-  ].*)?\.md$/;
  const match = pattern.exec(name);
  return match ? Number(match[1]) : null;
}

function findChapterFile(directory, chapter, { outline }) {
  requireCondition(Number.isInteger(chapter) && chapter >= 1, 'chapter must be >= 1');
  requireCondition(_isDir(directory), `chapter directory is missing: ${directory}`);
  const entries = fs.readdirSync(directory).sort();
  const matches = [];
  for (const name of entries) {
    const fullPath = path.join(directory, name);
    if (_isFile(fullPath) && _chapterNumberFromName(name, { outline }) === chapter) {
      matches.push(fullPath);
    }
  }
  const label = outline ? 'outline' : 'body';
  requireCondition(matches.length === 1, `chapter ${chapter} must have exactly one ${label} file`);
  return matches[0];
}

function readUtf8Strict(filePath) {
  const rawBytes = fs.readFileSync(filePath);
  const decoder = new TextDecoder('utf-8', { fatal: true });
  return { rawBytes, text: decoder.decode(rawBytes) };
}

function readChapterOutline(project, chapter) {
  const outlinePath = findChapterFile(path.join(path.resolve(String(project)), '大纲'), chapter, { outline: true });
  try {
    const { text } = readUtf8Strict(outlinePath);
    return { outlinePath, outline: text };
  } catch (err) {
    throw new WordcountError(`unable to read outline: ${err.message}`);
  }
}

function effectiveAuthorRange(outline, authorRange = null) {
  return authorRange !== null && authorRange !== undefined
    ? normalizeAuthorRange(authorRange)
    : rangeFromOutline(outline);
}

function readProjectChapter(project, chapter, authorRange = null) {
  const { outlinePath, outline } = readChapterOutline(project, chapter);
  const bodyPath = findChapterFile(path.join(path.resolve(String(project)), '正文'), chapter, { outline: false });
  return {
    outlinePath,
    bodyPath,
    target: targetFromOutline(outline),
    authorRange: effectiveAuthorRange(outline, authorRange),
  };
}

function buildProjectWordcountRecord(project, chapter, { resolution, authorRange = null }) {
  requireCondition(RESOLUTIONS.has(resolution), `unsupported wordcount resolution: ${resolution}`);
  const { bodyPath, target, authorRange: author } = readProjectChapter(project, chapter, authorRange);
  let rawBytes;
  let body;
  try {
    ({ rawBytes, text: body } = readUtf8Strict(bodyPath));
  } catch (err) {
    throw new WordcountError(`unable to read chapter files: ${err.message}`);
  }
  const result = evaluateWordcount(body, target, { chapter, authorRange: author });
  requireCondition(result.status !== 'invalid', `invalid chapter wordcount: ${result.invalid_reason}`);
  const inUserBand = result.status === 'internal_pass' || result.status === 'borderline';
  requireCondition(
    (resolution === 'within_user_band' && inUserBand) ||
      (resolution === 'accepted_current_length' && !inUserBand),
    'wordcount resolution does not match the current length'
  );
  const record = {
    metric: METRIC,
    target: result.target,
    actual: result.actual,
    status: result.status,
    resolution,
    body_sha256: crypto.createHash('sha256').update(rawBytes).digest('hex'),
  };
  if (author !== null) {
    record.author_range = { ...author };
  }
  return record;
}

function normalizeWordcountRecord(value) {
  requireCondition(
    value !== null && typeof value === 'object' && !Array.isArray(value),
    'wordcount record must be an object'
  );
  const keys = Object.keys(value);
  const validKeys =
    (keys.length === _RECORD_FIELDS.size && keys.every((k) => _RECORD_FIELDS.has(k))) ||
    (keys.length === _RECORD_FIELDS.size + 1 &&
      keys.every((k) => _RECORD_FIELDS.has(k) || k === 'author_range') &&
      Object.prototype.hasOwnProperty.call(value, 'author_range'));
  requireCondition(validKeys, 'wordcount record fields are invalid');
  requireCondition(value.metric === METRIC, 'wordcount metric is unsupported');
  const target = parseTarget(value.target);
  const author = normalizeAuthorRange(value.author_range);
  const actual = value.actual;
  requireCondition(Number.isInteger(actual) && actual >= 1, 'wordcount actual is invalid');
  const expected = evaluateWordcount('字'.repeat(actual), target, { authorRange: author });
  requireCondition(value.status === expected.status, 'wordcount status does not match target and actual');
  const resolution = value.resolution;
  requireCondition(RESOLUTIONS.has(resolution), 'wordcount resolution is unsupported');
  const inUserBand = expected.status === 'internal_pass' || expected.status === 'borderline';
  requireCondition((resolution === 'within_user_band') === inUserBand, 'wordcount resolution does not match status');
  const digest = value.body_sha256;
  requireCondition(typeof digest === 'string' && /^[0-9a-f]{64}$/.test(digest), 'body_sha256 is invalid');
  const out = {
    metric: value.metric,
    target: value.target,
    actual: value.actual,
    status: value.status,
    resolution: value.resolution,
    body_sha256: value.body_sha256,
  };
  if (Object.prototype.hasOwnProperty.call(value, 'author_range')) {
    out.author_range = value.author_range === null ? null : { ...author };
  }
  return out;
}

function wordcountRecordDrift(project, chapter, value) {
  const record = normalizeWordcountRecord(value);
  const root = path.resolve(String(project));
  const outlinePath = findChapterFile(path.join(root, '大纲'), chapter, { outline: true });
  const bodyPath = findChapterFile(path.join(root, '正文'), chapter, { outline: false });
  let outline;
  let bodyBytes;
  try {
    ({ text: outline } = readUtf8Strict(outlinePath));
    bodyBytes = fs.readFileSync(bodyPath);
  } catch (err) {
    throw new WordcountError(`unable to read chapter files: ${err.message}`);
  }
  const drift = [];
  if (crypto.createHash('sha256').update(bodyBytes).digest('hex') !== record.body_sha256) {
    drift.push('正文');
  }
  if (targetFromOutline(outline) !== record.target) {
    drift.push('字数目标');
  }
  return drift;
}

function _recordsEqual(a, b) {
  const aKeys = Object.keys(a).sort();
  const bKeys = Object.keys(b).sort();
  if (aKeys.length !== bKeys.length) return false;
  for (let i = 0; i < aKeys.length; i += 1) {
    const k = aKeys[i];
    if (k !== bKeys[i]) return false;
    const av = a[k];
    const bv = b[k];
    if (av && typeof av === 'object' && bv && typeof bv === 'object') {
      if (av.min !== bv.min || av.max !== bv.max) return false;
    } else if (av !== bv) {
      return false;
    }
  }
  return true;
}

function validateCurrentWordcountRecord(project, chapter, value) {
  const record = normalizeWordcountRecord(value);
  const current = buildProjectWordcountRecord(project, chapter, {
    resolution: record.resolution,
    authorRange: record.author_range ?? null,
  });
  requireCondition(_recordsEqual(record, current), 'wordcount record is stale for the current body or target');
  return record;
}

module.exports = {
  WORDCOUNT_SCHEMA,
  MEASUREMENT_SCHEMA,
  CHECKPOINT_SCHEMA,
  METRIC,
  RESOLUTIONS,
  BOOK_DIRS,
  WordcountError,
  require: requireCondition,
  normalizeNewlines,
  stripRecognizableFrontmatter,
  visibleBody,
  countVisibleChars,
  parseTarget,
  normalizeAuthorRange,
  computeWordcountBands,
  invalidWordcountResult,
  measureWordcount,
  evaluateWordcount,
  checkpointWordcount,
  parseTargetField,
  parseRangeField,
  parseMetricField,
  targetFromOutline,
  rangeFromOutline,
  effectiveAuthorRange,
  resolveBookDir,
  findChapterFile,
  readChapterOutline,
  readProjectChapter,
  readUtf8Strict,
  buildProjectWordcountRecord,
  normalizeWordcountRecord,
  wordcountRecordDrift,
  validateCurrentWordcountRecord,
};
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall