@litfamily/litclaude 1.0.43 → 1.0.45

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/README.md +8 -8
  3. package/README_ko-KR.md +8 -8
  4. package/bin/litclaude-ai.js +201 -5
  5. package/docs/assets/readme/badge-version.svg +1 -1
  6. package/package.json +1 -1
  7. package/plugins/litclaude/.claude-plugin/plugin.json +1 -1
  8. package/plugins/litclaude/agents/korean-prose-editor.md +2 -0
  9. package/plugins/litclaude/agents/korean-style-analyzer.md +2 -0
  10. package/plugins/litclaude/agents/librarian-researcher.md +2 -0
  11. package/plugins/litclaude/agents/lit-executor.md +2 -0
  12. package/plugins/litclaude/agents/lit-planner.md +2 -0
  13. package/plugins/litclaude/agents/lit-verifier.md +2 -0
  14. package/plugins/litclaude/agents/meaning-preservation-auditor.md +2 -0
  15. package/plugins/litclaude/agents/native-flow-reviewer.md +2 -0
  16. package/plugins/litclaude/agents/polish-orchestrator.md +2 -0
  17. package/plugins/litclaude/agents/qa-runner.md +2 -0
  18. package/plugins/litclaude/agents/quality-reviewer.md +2 -0
  19. package/plugins/litclaude/bin/litclaude-ai +1 -0
  20. package/plugins/litclaude/bin/litclaude-hook.js +31 -12
  21. package/plugins/litclaude/bin/litclaude-mcp.js +1 -1
  22. package/plugins/litclaude/commands/litgoal.md +3 -1
  23. package/plugins/litclaude/hooks/hooks.json +1 -1
  24. package/plugins/litclaude/lib/agent-file/apply.mjs +150 -0
  25. package/plugins/litclaude/lib/agent-file/attribution.mjs +62 -0
  26. package/plugins/litclaude/lib/agent-file/block.md +12 -0
  27. package/plugins/litclaude/lib/agent-file/cli.mjs +71 -0
  28. package/plugins/litclaude/lib/agent-file/managed-block.mjs +82 -0
  29. package/plugins/litclaude/lib/agent-file/project-block.md +9 -0
  30. package/plugins/litclaude/lib/canonical-runtime-commitments.mjs +6 -6
  31. package/plugins/litclaude/lib/canonical-skill-resources.mjs +51 -48
  32. package/plugins/litclaude/lib/litgoal/autoloop.mjs +57 -8
  33. package/plugins/litclaude/lib/litgoal/cli.mjs +62 -1
  34. package/plugins/litclaude/lib/litgoal/freshness.mjs +55 -0
  35. package/plugins/litclaude/lib/litgoal/ledger.mjs +1 -1
  36. package/plugins/litclaude/lib/litgoal/state.mjs +1 -1
  37. package/plugins/litclaude/lib/litgoal/unknowns.mjs +44 -0
  38. package/plugins/litclaude/lib/mark-logo.png +0 -0
  39. package/plugins/litclaude/lib/mark.mjs +392 -0
  40. package/plugins/litclaude/lib/official-build.mjs +22 -0
  41. package/plugins/litclaude/lib/output_mark.py +132 -0
  42. package/plugins/litclaude/lib/render_pages.py +16 -0
  43. package/plugins/litclaude/lib/rewind/brief.mjs +12 -2
  44. package/plugins/litclaude/lib/rewind/collect.mjs +83 -12
  45. package/plugins/litclaude/lib/rewind/next-step.mjs +21 -3
  46. package/plugins/litclaude/lib/start-work-lifecycle.mjs +6 -4
  47. package/plugins/litclaude/skills/autoconference/SKILL.md +2 -0
  48. package/plugins/litclaude/skills/autoresearch/SKILL.md +2 -0
  49. package/plugins/litclaude/skills/browser-drive/SKILL.md +2 -0
  50. package/plugins/litclaude/skills/comment-checker/SKILL.md +2 -0
  51. package/plugins/litclaude/skills/debugging/SKILL.md +2 -0
  52. package/plugins/litclaude/skills/deep-interview/SKILL.md +2 -0
  53. package/plugins/litclaude/skills/frontend-ui-ux/SKILL.md +2 -0
  54. package/plugins/litclaude/skills/lit-adhd/SKILL.md +8 -4
  55. package/plugins/litclaude/skills/lit-brainstorm/SKILL.md +2 -0
  56. package/plugins/litclaude/skills/lit-burnoff/SKILL.md +2 -0
  57. package/plugins/litclaude/skills/lit-burnoff-file/SKILL.md +2 -0
  58. package/plugins/litclaude/skills/lit-code/SKILL.md +2 -0
  59. package/plugins/litclaude/skills/lit-commit/SKILL.md +2 -0
  60. package/plugins/litclaude/skills/lit-comprehend/SKILL.md +2 -0
  61. package/plugins/litclaude/skills/lit-crucible/SKILL.md +2 -0
  62. package/plugins/litclaude/skills/lit-diagram-drawer/SKILL.md +3 -1
  63. package/plugins/litclaude/skills/lit-diagram-drawer/scripts/export.mjs +35 -1
  64. package/plugins/litclaude/skills/lit-docx/SKILL.md +2 -0
  65. package/plugins/litclaude/skills/lit-docx/scripts/convert_md_to_docx.py +4 -1
  66. package/plugins/litclaude/skills/lit-docx/scripts/convert_md_to_pdf.py +2 -0
  67. package/plugins/litclaude/skills/lit-handoff/SKILL.md +2 -0
  68. package/plugins/litclaude/skills/lit-hijack/SKILL.md +2 -0
  69. package/plugins/litclaude/skills/lit-humanizer/SKILL.md +2 -0
  70. package/plugins/litclaude/skills/lit-init/SKILL.md +14 -0
  71. package/plugins/litclaude/skills/lit-loop/SKILL.md +2 -0
  72. package/plugins/litclaude/skills/lit-plan/SKILL.md +2 -0
  73. package/plugins/litclaude/skills/lit-pptx/SKILL.md +2 -0
  74. package/plugins/litclaude/skills/lit-pptx/scripts/lib/render-adapter-pptx.js +6 -1
  75. package/plugins/litclaude/skills/lit-recap/SKILL.md +2 -0
  76. package/plugins/litclaude/skills/lit-schematic/SKILL.md +3 -1
  77. package/plugins/litclaude/skills/lit-schematic/scripts/lib/sheet.mjs +10 -0
  78. package/plugins/litclaude/skills/lit-schematic/scripts/lib/svg.mjs +4 -0
  79. package/plugins/litclaude/skills/lit-schematic/scripts/motion.mjs +5 -2
  80. package/plugins/litclaude/skills/lit-schematic/scripts/render.mjs +20 -2
  81. package/plugins/litclaude/skills/lit-scientific-visualization/SKILL.md +2 -0
  82. package/plugins/litclaude/skills/lit-team/SKILL.md +2 -0
  83. package/plugins/litclaude/skills/lit-typographic-motion/SKILL.md +2 -0
  84. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/chrome.mjs +23 -2
  85. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover-capture.mjs +14 -1
  86. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/cover.mjs +48 -2
  87. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/encode.mjs +8 -1
  88. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/end-card.mjs +128 -0
  89. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/pipeline.mjs +59 -14
  90. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/stage-gate.mjs +7 -4
  91. package/plugins/litclaude/skills/lit-typographic-motion/engine/node/stage.mjs +33 -8
  92. package/plugins/litclaude/skills/lit-typographic-motion/engine/stage/init.js +13 -0
  93. package/plugins/litclaude/skills/lit-typographic-motion/references/studio.md +11 -0
  94. package/plugins/litclaude/skills/litgoal/SKILL.md +53 -1
  95. package/plugins/litclaude/skills/litresearch/SKILL.md +2 -0
  96. package/plugins/litclaude/skills/litwork/SKILL.md +2 -0
  97. package/plugins/litclaude/skills/lsp/SKILL.md +2 -0
  98. package/plugins/litclaude/skills/lsp-setup/SKILL.md +2 -0
  99. package/plugins/litclaude/skills/readme-studio/SKILL.md +3 -1
  100. package/plugins/litclaude/skills/readme-studio/templates/cover-source.json +1 -0
  101. package/plugins/litclaude/skills/readme-studio/templates/hyperframes-cover/index.html +3 -2
  102. package/plugins/litclaude/skills/readme-studio/templates/hyperframes-cover/package-lock.json +4 -4
  103. package/plugins/litclaude/skills/readme-studio/templates/remotion-cover/package-lock.json +3 -3
  104. package/plugins/litclaude/skills/readme-studio/templates/remotion-cover/package.json +2 -1
  105. package/plugins/litclaude/skills/readme-studio/templates/remotion-cover/src/index.tsx +4 -3
  106. package/plugins/litclaude/skills/refactor/SKILL.md +2 -0
  107. package/plugins/litclaude/skills/review-work/SKILL.md +2 -0
  108. package/plugins/litclaude/skills/rules/SKILL.md +2 -0
  109. package/plugins/litclaude/skills/start-work/SKILL.md +2 -0
  110. package/plugins/litclaude/skills/structural-search/SKILL.md +2 -0
  111. package/plugins/litclaude/skills/visual-qa/SKILL.md +2 -0
  112. package/plugins/litclaude/skills/wikify/SKILL.md +2 -0
  113. package/scripts/doctor.mjs +3 -1
  114. package/scripts/prepublish-test-gate.mjs +75 -22
@@ -0,0 +1,55 @@
1
+ // Evidence freshness: a file existing is not proof that a pass is current. `record-evidence --inputs` (and
2
+ // `--reviewed` for the artifact a human review looked at) binds the pass to each file's SHA-256 at the moment
3
+ // it was observed; when one of those files changes or disappears, the pass reopens as `stale`.
4
+ import { createHash } from "node:crypto";
5
+ import { lstatSync, readFileSync } from "node:fs";
6
+ import { resolve } from "node:path";
7
+
8
+ import { LitgoalStateError } from "./state.mjs";
9
+
10
+ const MAX_INPUT_BYTES = 256 * 1024 * 1024;
11
+
12
+ const sha256Of = (path) => {
13
+ let info;
14
+ try {
15
+ info = lstatSync(path);
16
+ } catch {
17
+ return null;
18
+ }
19
+ if (!info.isFile() || info.size > MAX_INPUT_BYTES) return null;
20
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
21
+ };
22
+
23
+ /** Fingerprints each path (relative to `cwd`) as { path, role, sha256 }; a missing or non-regular file is refused. */
24
+ export const fingerprintInputs = (cwd, entries) =>
25
+ entries.map(({ path, role }) => {
26
+ const absolute = resolve(cwd, path);
27
+ const sha256 = sha256Of(absolute);
28
+ if (!sha256) throw new LitgoalStateError(`evidence input is not a readable regular file: ${path}`);
29
+ return { path: absolute, role, sha256 };
30
+ });
31
+
32
+ /** The inputs of an evidence record whose file changed or vanished since it was recorded. */
33
+ export const staleInputs = (record) =>
34
+ (Array.isArray(record?.inputs) ? record.inputs : []).flatMap(({ path, role, sha256 }) => {
35
+ const now = sha256Of(path);
36
+ if (now === sha256) return [];
37
+ return [{ path, role, reason: now === null ? "missing" : "changed" }];
38
+ });
39
+
40
+ /**
41
+ * Reopens every passing criterion whose latest evidence has a changed or missing input: its status becomes
42
+ * `stale` and `staleInputs` says which. Mutates `state`; returns one ledger entry per reopened criterion.
43
+ */
44
+ export const reopenStaleCriteria = (state) => {
45
+ const reopened = [];
46
+ for (const criterion of Array.isArray(state?.criteria) ? state.criteria : []) {
47
+ if (criterion?.status !== "pass") continue;
48
+ const stale = staleInputs(criterion.evidence?.at(-1));
49
+ if (!stale.length) continue;
50
+ criterion.status = "stale";
51
+ criterion.staleInputs = stale;
52
+ reopened.push({ event: "evidence.stale", criterionId: criterion.id, staleInputs: stale });
53
+ }
54
+ return reopened;
55
+ };
@@ -11,7 +11,7 @@ export const appendLitgoalLedger = (path, entry) => {
11
11
  };
12
12
  appendFileSync(path, `${JSON.stringify(record)}\n`, { flag: STATE_APPEND_FLAG });
13
13
  // Flush the appended record to disk for durability.
14
- const fd = openSync(path, "r");
14
+ const fd = openSync(path, "r+");
15
15
  fsyncSync(fd);
16
16
  closeSync(fd);
17
17
  return record;
@@ -26,7 +26,7 @@ export const writeLitgoalState = (path, state) => {
26
26
  const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
27
27
  writeFileSync(tmpPath, `${JSON.stringify(state, null, 2)}\n`, { flag: STATE_WRITE_FLAG });
28
28
  // Flush tmp file data to disk before rename so the rename is durable.
29
- const fd = openSync(tmpPath, "r");
29
+ const fd = openSync(tmpPath, "r+");
30
30
  fsyncSync(fd);
31
31
  closeSync(fd);
32
32
  renameSync(tmpPath, path);
@@ -0,0 +1,44 @@
1
+ // The unknown register: unknowns are reduced while the work runs, not only while it is planned. Each item is
2
+ // KK (known known: needs a source), KU (known unknown), UK (unknown known: something only the user can answer)
3
+ // or UU (unknown unknown). An open KU/UK/UU needs a deterministic probe, closing one needs evidence, and an
4
+ // open critical item blocks completion.
5
+ import { LitgoalStateError } from "./state.mjs";
6
+
7
+ export const UNKNOWN_KINDS = Object.freeze(["KK", "KU", "UK", "UU"]);
8
+
9
+ /** Adds an item to `state.unknowns`; returns the stored record. */
10
+ export const addUnknown = (state, { kind, text, source, probe, critical, now }) => {
11
+ if (!UNKNOWN_KINDS.includes(kind)) throw new LitgoalStateError(`unknown kind must be one of: ${UNKNOWN_KINDS.join(", ")}`, 64);
12
+ if (!text) throw new LitgoalStateError("missing text", 64);
13
+ if (kind === "KK" && !source) throw new LitgoalStateError("a KK item needs --source", 64);
14
+ if (kind !== "KK" && !probe) throw new LitgoalStateError(`an open ${kind} item needs --probe: how it will be checked`, 64);
15
+ const unknowns = Array.isArray(state.unknowns) ? state.unknowns : [];
16
+ const record = {
17
+ id: `unknown-${unknowns.length + 1}`,
18
+ kind,
19
+ text,
20
+ ...(source ? { source } : {}),
21
+ ...(probe ? { probe } : {}),
22
+ critical: Boolean(critical),
23
+ status: kind === "KK" ? "known" : "open",
24
+ createdAt: now,
25
+ };
26
+ state.unknowns = [...unknowns, record];
27
+ return record;
28
+ };
29
+
30
+ /** Closes an open item with the evidence that answered it; returns the updated record. */
31
+ export const resolveUnknown = (state, { id, evidence, now }) => {
32
+ const record = (Array.isArray(state.unknowns) ? state.unknowns : []).find((item) => item.id === id);
33
+ if (!record) throw new LitgoalStateError("unknown item not found");
34
+ if (record.status !== "open") throw new LitgoalStateError(`${id} is not open`);
35
+ if (!evidence) throw new LitgoalStateError("closing an unknown needs --evidence", 64);
36
+ record.status = "resolved";
37
+ record.evidence = evidence;
38
+ record.resolvedAt = now;
39
+ return record;
40
+ };
41
+
42
+ /** Open items marked critical: any one of them blocks completion. */
43
+ export const openCriticalUnknowns = (state) =>
44
+ (Array.isArray(state?.unknowns) ? state.unknowns : []).filter((item) => item?.status === "open" && item.critical === true);
@@ -0,0 +1,392 @@
1
+ // The `mark` setting: whether LitClaude's engines tag the files they make. `on` puts an invisible
2
+ // generator tag in every output and a small visible mark on showcase outputs (films, README covers,
3
+ // diagrams, schematics); `meta` keeps only the invisible tag; `off` leaves outputs unmarked.
4
+ // The value lives in LitClaude's own `<litHome>/config.json`, never in Claude Code's settings;
5
+ // LITCLAUDE_MARK overrides it for one run. Anything unreadable reads as `on`. No network, no clock.
6
+ // output_mark.py is the Python engines' copy of the same rules.
7
+
8
+ import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, readSync, renameSync, writeFileSync } from "node:fs";
9
+ import { homedir } from "node:os";
10
+ import { dirname, extname, join, resolve } from "node:path";
11
+ import { fileURLToPath } from "node:url";
12
+ import { crc32 } from "node:zlib";
13
+
14
+ import { STATE_WRITE_FLAG } from "./project-state-root.mjs";
15
+
16
+ export const MARK_MODES = Object.freeze(["on", "meta", "off"]);
17
+ const MAX_CONFIG_BYTES = 64 * 1024;
18
+ const manifestPath = join(dirname(fileURLToPath(import.meta.url)), "..", ".claude-plugin", "plugin.json");
19
+
20
+ export const markLitHome = (env = process.env) => resolve(env.LITCLAUDE_HOME || join(homedir(), ".litclaude"));
21
+ export const markConfigPath = (litHome = markLitHome()) => join(litHome, "config.json");
22
+
23
+ const readConfig = (path) => {
24
+ let fd;
25
+ try {
26
+ if (!lstatSync(path).isFile()) return null;
27
+ fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
28
+ const { size } = fstatSync(fd);
29
+ if (size > MAX_CONFIG_BYTES) return null;
30
+ const buffer = Buffer.alloc(size);
31
+ readSync(fd, buffer, 0, size, 0);
32
+ const parsed = JSON.parse(buffer.toString("utf8"));
33
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
34
+ } catch {
35
+ return null;
36
+ } finally {
37
+ if (fd !== undefined) closeSync(fd);
38
+ }
39
+ };
40
+
41
+ /** The mode for this run: LITCLAUDE_MARK when valid, else the stored value, else `on`. */
42
+ export const readMarkMode = ({ env = process.env, litHome = markLitHome(env) } = {}) => {
43
+ const override = String(env.LITCLAUDE_MARK ?? "").trim().toLowerCase();
44
+ if (MARK_MODES.includes(override)) return override;
45
+ const stored = readConfig(markConfigPath(litHome))?.mark;
46
+ return MARK_MODES.includes(stored) ? stored : "on";
47
+ };
48
+
49
+ /** One key of `<litHome>/config.json`, or undefined when the file or key is unreadable. */
50
+ export const readLitConfigKey = (litHome, key) => readConfig(markConfigPath(litHome))?.[key];
51
+
52
+ /** Stores one key, keeping the file's other keys; a symlinked config or home is refused, not followed. */
53
+ export const writeLitConfigKey = (litHome, key, value) => {
54
+ const path = markConfigPath(litHome);
55
+ for (const p of [litHome, path]) {
56
+ try {
57
+ if (lstatSync(p).isSymbolicLink()) throw new Error(`refusing to write the ${key} setting through a symlink: ${p}`);
58
+ } catch (error) {
59
+ if (error.code !== "ENOENT") throw error;
60
+ }
61
+ }
62
+ let current = {};
63
+ try {
64
+ lstatSync(path);
65
+ current = readConfig(path);
66
+ } catch (error) {
67
+ if (error.code !== "ENOENT") throw error;
68
+ }
69
+ // A config.json that exists but does not read as an object holds the user's other settings.
70
+ if (current === null) throw new Error(`refusing to overwrite ${path}: it is not readable JSON; fix or remove it first`);
71
+ mkdirSync(litHome, { recursive: true, mode: 0o700 });
72
+ const next = { ...current, [key]: value };
73
+ const staging = `${path}.${process.pid}.tmp`;
74
+ writeFileSync(staging, `${JSON.stringify(next, null, 2)}\n`, { flag: STATE_WRITE_FLAG, mode: 0o600 });
75
+ renameSync(staging, path);
76
+ return value;
77
+ };
78
+
79
+ /** Stores the mode, keeping the file's other keys; a symlinked config or home is refused, not followed. */
80
+ export const writeMarkMode = (litHome, mode) => {
81
+ if (!MARK_MODES.includes(mode)) throw new Error(`mark takes one of: ${MARK_MODES.join(", ")}`);
82
+ return writeLitConfigKey(litHome, "mark", mode);
83
+ };
84
+
85
+ /** `LitClaude <version> · github.com/wjgoarxiv/litclaude`, the version taken from the plugin manifest. */
86
+ export const generatorString = () => {
87
+ const { version } = JSON.parse(readFileSync(manifestPath, "utf8"));
88
+ return `LitClaude ${version} · github.com/wjgoarxiv/litclaude`;
89
+ };
90
+
91
+ const CUSTOM_PART = "docProps/custom.xml";
92
+ const CUSTOM_TYPE = "application/vnd.openxmlformats-officedocument.custom-properties+xml";
93
+ const CUSTOM_REL = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/custom-properties";
94
+ const FMTID = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
95
+ const xmlText = (value) => value.replace(/&/gu, "&amp;").replace(/</gu, "&lt;").replace(/>/gu, "&gt;");
96
+
97
+ /**
98
+ * The changed package parts that name `generator`: app.xml <Application> and a custom `Generator` property,
99
+ * with the content type and package relationship custom.xml needs. Same rules as output_mark.tag_ooxml_parts.
100
+ */
101
+ export const tagOoxmlParts = (parts, generator) => {
102
+ const text = xmlText(generator);
103
+ const out = {};
104
+ const app = parts["docProps/app.xml"];
105
+ if (app !== undefined) {
106
+ const tag = `<Application>${text}</Application>`;
107
+ out["docProps/app.xml"] = /<Application[>/]/u.test(app)
108
+ ? app.replace(/<Application>[^<]*<\/Application>|<Application\/>/u, tag)
109
+ : app.replace("</Properties>", `${tag}</Properties>`);
110
+ }
111
+ const prop = `<vt:lpwstr>${text}</vt:lpwstr></property>`;
112
+ const custom = parts[CUSTOM_PART];
113
+ if (custom === undefined) {
114
+ out[CUSTOM_PART] = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n'
115
+ + '<Properties xmlns="http://schemas.openxmlformats.org/officeDocument/2006/custom-properties" '
116
+ + 'xmlns:vt="http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes">'
117
+ + `<property fmtid="${FMTID}" pid="2" name="Generator">${prop}</Properties>`;
118
+ } else {
119
+ const existing = custom.match(/(<property [^>]*name="Generator"[^>]*>)[\s\S]*?<\/property>/u);
120
+ if (existing) out[CUSTOM_PART] = custom.replace(existing[0], existing[1] + prop);
121
+ else {
122
+ const pid = Math.max(1, ...[...custom.matchAll(/\bpid="(\d+)"/gu)].map((m) => Number(m[1]))) + 1;
123
+ out[CUSTOM_PART] = custom.replace("</Properties>", `<property fmtid="${FMTID}" pid="${pid}" name="Generator">${prop}</Properties>`);
124
+ }
125
+ }
126
+ const types = parts["[Content_Types].xml"];
127
+ if (!types.includes(`PartName="/${CUSTOM_PART}"`)) {
128
+ out["[Content_Types].xml"] = types.replace("</Types>", `<Override PartName="/${CUSTOM_PART}" ContentType="${CUSTOM_TYPE}"/></Types>`);
129
+ }
130
+ const rels = parts["_rels/.rels"];
131
+ if (!rels.includes(`Target="${CUSTOM_PART}"`) && !rels.includes(`Target="/${CUSTOM_PART}"`)) {
132
+ const rid = `rId${Math.max(0, ...[...rels.matchAll(/Id="rId(\d+)"/gu)].map((m) => Number(m[1]))) + 1}`;
133
+ out["_rels/.rels"] = rels.replace("</Relationships>", `<Relationship Id="${rid}" Type="${CUSTOM_REL}" Target="${CUSTOM_PART}"/></Relationships>`);
134
+ }
135
+ return out;
136
+ };
137
+
138
+ /** Tags an OOXML package held in a JSZip instance when this run's mode is `on` or `meta`. */
139
+ export const tagOoxmlZip = async (zip, options) => {
140
+ const { generator } = markPlan(options);
141
+ if (!generator) return;
142
+ const parts = {};
143
+ for (const name of ["docProps/app.xml", CUSTOM_PART, "[Content_Types].xml", "_rels/.rels"]) {
144
+ if (zip.file(name)) parts[name] = await zip.file(name).async("string");
145
+ }
146
+ for (const [name, xml] of Object.entries(tagOoxmlParts(parts, generator))) zip.file(name, xml);
147
+ };
148
+
149
+ /**
150
+ * The visible mark every showcase engine draws (approved by the user on 2026-10-28 from task-6-mock): the text,
151
+ * Pretendard 500 with 0.02 em tracking, a corner size of 1.6 % of the short side (never under 11 px) at 60 %
152
+ * opacity, a film end card of about 0.5 s after the last beat, and ink taken from the output's own ground,
153
+ * pushed 72 % toward black on a light ground or white on a dark one. The flame logo (lib/mark-logo.png, the plugin
154
+ * icon at 96 px; chosen by the user on 2026-10-30) sits left of the text at 1.3 x the font size, 0.35 em away,
155
+ * in its own colours at the same opacity.
156
+ */
157
+ export const WORDMARK = Object.freeze({
158
+ text: "made with LitClaude",
159
+ font: "Pretendard",
160
+ weight: 500,
161
+ tracking: 0.02,
162
+ cornerShare: 0.016,
163
+ minPx: 11,
164
+ insetShare: 0.025,
165
+ cornerOpacity: 0.6,
166
+ endCardSec: 0.5,
167
+ endCardFadeSec: 0.12,
168
+ endCardShare: 0.022,
169
+ inkPush: 0.72,
170
+ logoScale: 1.3,
171
+ logoGap: 0.35,
172
+ });
173
+
174
+ const logoPath = join(dirname(fileURLToPath(import.meta.url)), "mark-logo.png");
175
+ /** The flame logo as a `data:image/png` URI, so an SVG or a page carries it without a sibling file. */
176
+ export const markLogoDataUri = () => `data:image/png;base64,${readFileSync(logoPath).toString("base64")}`;
177
+
178
+ /**
179
+ * The logo's box for a mark whose text ends at `x` on baseline `y` with `fontSize` and `textWidth`:
180
+ * left of the text, centred on its x-height band.
181
+ */
182
+ export const markLogoBox = ({ x, y, fontSize, textWidth }) => {
183
+ const size = WORDMARK.logoScale * fontSize;
184
+ return { x: x - textWidth - WORDMARK.logoGap * fontSize - size, y: y - 0.36 * fontSize - size / 2, size };
185
+ };
186
+
187
+ /** An SVG <image> element for the logo box, at the mark's opacity. */
188
+ export const markLogoSvg = ({ x, y, size }) =>
189
+ `<image data-litclaude-mark-logo="1" x="${x.toFixed(2)}" y="${y.toFixed(2)}" width="${size.toFixed(2)}" height="${size.toFixed(2)}" opacity="${WORDMARK.cornerOpacity}" href="${markLogoDataUri()}"/>`;
190
+
191
+ /** The mark's ink for a ground colour [r, g, b] (0-255): the ground pushed toward black or white. */
192
+ export const markInk = ([r, g, b]) => {
193
+ const target = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255 > 0.5 ? 0 : 255;
194
+ return [r, g, b].map((v) => Math.round(v + (target - v) * WORDMARK.inkPush));
195
+ };
196
+
197
+ /**
198
+ * Where a corner mark of `boxW` x `boxH` pixels fits on a raster without touching anything drawn: the clear box
199
+ * (no pixel within `pad` that departs from the box's median luminance by more than 0.08) nearest the anchor
200
+ * (`bottom-right` or `bottom-centre`), searched over the bottom quarter and kept out of every `exclude` box.
201
+ * Returns { x, y (top-left of the text box), ground [r, g, b], ink } or null when no clear spot exists.
202
+ * `image` is { width, height, channels (3 or 4), pixels }.
203
+ */
204
+ // How far (in luminance, 0-1) a pixel may stray from the box's median and still count as ground: a quiet
205
+ // pattern such as soft stripes or a gradient stays under it; type and drawn art (0.3 and more) do not.
206
+ const GROUND_TOLERANCE = 0.2;
207
+ export const findClearSpot = (image, { boxW, boxH, inset, pad = 0, anchor = "bottom-right", exclude = [] }) => {
208
+ const { width, height, channels, pixels } = image;
209
+ const stats = (x0, y0, x1, y1) => {
210
+ const lums = [];
211
+ let r = 0, g = 0, b = 0;
212
+ for (let y = Math.max(0, Math.floor(y0)); y < Math.min(height, y1); y += 2) {
213
+ for (let x = Math.max(0, Math.floor(x0)); x < Math.min(width, x1); x += 2) {
214
+ const o = (y * width + x) * channels;
215
+ r += pixels[o]; g += pixels[o + 1]; b += pixels[o + 2];
216
+ lums.push((0.2126 * pixels[o] + 0.7152 * pixels[o + 1] + 0.0722 * pixels[o + 2]) / 255);
217
+ }
218
+ }
219
+ const median = [...lums].sort((p, q) => p - q)[lums.length >> 1];
220
+ return { ink: lums.filter((l) => Math.abs(l - median) > GROUND_TOLERANCE).length / lums.length, ground: [r, g, b].map((v) => Math.round(v / lums.length)) };
221
+ };
222
+ const ax = anchor === "bottom-right" ? width - inset - boxW / 2 : width / 2;
223
+ const ay = height - inset - boxH / 2;
224
+ let best = null;
225
+ const step = Math.max(2, Math.round(boxH / 4));
226
+ for (let y = height - inset - boxH; y >= height * 0.72; y -= step) {
227
+ for (let x = inset; x <= width - inset - boxW; x += step) {
228
+ const box = [x - pad, y - pad, x + boxW + pad, y + boxH + pad];
229
+ if (exclude.some((e) => e[0] < box[2] && e[2] > box[0] && e[1] < box[3] && e[3] > box[1])) continue;
230
+ const d = Math.hypot(x + boxW / 2 - ax, (y + boxH / 2 - ay) * 2);
231
+ if (best && d >= best.d) continue;
232
+ const s = stats(...box);
233
+ if (s.ink < 0.004) best = { x, y, d, ground: s.ground };
234
+ }
235
+ }
236
+ return best ? { x: best.x, y: best.y, ground: best.ground, ink: markInk(best.ground) } : null;
237
+ };
238
+
239
+ /** What an engine should do for this run: `meta` (invisible tag) and `visible` (showcase mark). */
240
+ export const markPlan = (options) => {
241
+ const mode = readMarkMode(options);
242
+ return { mode, meta: mode !== "off", visible: mode === "on", generator: mode === "off" ? null : generatorString() };
243
+ };
244
+
245
+ // ── Media outputs ───────────────────────────────────────────────────────────
246
+ // Every tag is a fixed string: no time, no random value, so deterministic renders stay deterministic.
247
+
248
+ const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
249
+ const pngChunk = (type, data) => {
250
+ const head = Buffer.alloc(8);
251
+ head.writeUInt32BE(data.length, 0);
252
+ head.write(type, 4, "latin1");
253
+ const crc = Buffer.alloc(4);
254
+ crc.writeUInt32BE(crc32(Buffer.concat([head.subarray(4), data])) >>> 0, 0);
255
+ return Buffer.concat([head, data, crc]);
256
+ };
257
+
258
+ /** A PNG with one `tEXt` `Software` chunk naming `generator`, just before IEND (an earlier one is replaced). */
259
+ export const tagPngBuffer = (buf, generator) => {
260
+ if (buf.length < 8 || !buf.subarray(0, 8).equals(PNG_SIGNATURE)) throw new Error("not a PNG file");
261
+ const kept = [];
262
+ let end = null;
263
+ for (let o = 8; o + 12 <= buf.length;) {
264
+ const len = buf.readUInt32BE(o);
265
+ if (o + 12 + len > buf.length) throw new Error("not a PNG file (a chunk runs past the end)");
266
+ const type = buf.toString("latin1", o + 4, o + 8);
267
+ const whole = buf.subarray(o, o + 12 + len);
268
+ if (type === "IEND") { end = whole; break; }
269
+ const software = type === "tEXt" && buf.toString("latin1", o + 8, o + 17) === "Software\0";
270
+ if (!software) kept.push(whole);
271
+ o += 12 + len;
272
+ }
273
+ if (!end) throw new Error("not a PNG file (no IEND)");
274
+ return Buffer.concat([PNG_SIGNATURE, ...kept, pngChunk("tEXt", Buffer.from(`Software\0${generator}`, "latin1")), end]);
275
+ };
276
+
277
+ /** A GIF with one comment extension naming `generator`, right after the header and global colour table. */
278
+ export const tagGifBuffer = (buf, generator) => {
279
+ if (buf.length < 13 || !/^GIF8[79]a$/u.test(buf.toString("latin1", 0, 6))) throw new Error("not a GIF file");
280
+ const flags = buf[10];
281
+ const head = 13 + (flags & 0x80 ? 3 * 2 ** ((flags & 0x07) + 1) : 0);
282
+ const text = Buffer.from(generator, "utf8");
283
+ const blocks = [];
284
+ for (let o = 0; o < text.length; o += 255) {
285
+ const part = text.subarray(o, o + 255);
286
+ blocks.push(Buffer.from([part.length]), part);
287
+ }
288
+ const comment = Buffer.concat([Buffer.from([0x21, 0xfe]), ...blocks, Buffer.from([0])]);
289
+ const rest = buf.subarray(head);
290
+ if (rest.subarray(0, comment.length).equals(comment)) return buf;
291
+ return Buffer.concat([buf.subarray(0, head), comment, rest]);
292
+ };
293
+
294
+ const xmpPacket = (generator) => Buffer.from(
295
+ `<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?><x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">`
296
+ + `<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/"><xmp:CreatorTool>${xmlText(generator)}</xmp:CreatorTool></rdf:Description>`
297
+ + "</rdf:RDF></x:xmpmeta><?xpacket end=\"r\"?>", "utf8");
298
+
299
+ /**
300
+ * An extended (VP8X) WebP — every animated WebP the engines write — with an `XMP ` chunk naming `generator`
301
+ * and the XMP flag set; an earlier XMP chunk is replaced. A simple-format still has no room for metadata
302
+ * without re-encoding its header, so it is returned unchanged.
303
+ */
304
+ export const tagWebpBuffer = (buf, generator) => {
305
+ if (buf.length < 20 || buf.toString("latin1", 0, 4) !== "RIFF" || buf.toString("latin1", 8, 12) !== "WEBP") throw new Error("not a WebP file");
306
+ if (buf.toString("latin1", 12, 16) !== "VP8X") return buf;
307
+ const chunks = [];
308
+ for (let o = 12; o + 8 <= buf.length;) {
309
+ const size = buf.readUInt32LE(o + 4);
310
+ const type = buf.toString("latin1", o, o + 4);
311
+ if (type !== "XMP ") chunks.push(Buffer.from(buf.subarray(o, o + 8 + size + (size & 1))));
312
+ o += 8 + size + (size & 1);
313
+ }
314
+ chunks[0][8] |= 0x04;
315
+ const xmp = xmpPacket(generator);
316
+ const head = Buffer.alloc(8);
317
+ head.write("XMP ", 0, "latin1");
318
+ head.writeUInt32LE(xmp.length, 4);
319
+ chunks.push(head, xmp, xmp.length & 1 ? Buffer.alloc(1) : Buffer.alloc(0));
320
+ const body = Buffer.concat(chunks);
321
+ const riff = Buffer.alloc(12);
322
+ riff.write("RIFF", 0, "latin1");
323
+ riff.writeUInt32LE(4 + body.length, 4);
324
+ riff.write("WEBP", 8, "latin1");
325
+ const out = Buffer.concat([riff, body]);
326
+ return out.equals(buf) ? buf : out;
327
+ };
328
+
329
+ /** An SVG with one `<metadata id="litclaude-generator">` right after its root element (an earlier one is replaced). */
330
+ export const svgWithMetadata = (svg, generator) => {
331
+ const tag = `<metadata id="litclaude-generator">${xmlText(generator)}</metadata>`;
332
+ const cleaned = svg.replace(/<metadata id="litclaude-generator">[^<]*<\/metadata>/u, "");
333
+ return cleaned.replace(/<svg\b[^>]*>/u, (root) => root + tag);
334
+ };
335
+
336
+ /** ffmpeg arguments that name the generator in a video container's `comment`; none when the mode is off. */
337
+ export const ffmpegMetadataArgs = (options) => {
338
+ const { generator } = markPlan(options);
339
+ return generator ? ["-metadata", `comment=${generator}`] : [];
340
+ };
341
+
342
+ const pdfText = (value) => `<FEFF${Buffer.from(value, "utf16le").swap16().toString("hex").toUpperCase()}>`;
343
+
344
+ /**
345
+ * A PDF whose Info dictionary names `generator` as Creator and Producer, added as a standard incremental
346
+ * update (new Info object, xref section, trailer with /Prev); the original bytes stay in front unchanged.
347
+ * Only a file whose last cross-reference is a classic `xref` table is updated: one that ends in a
348
+ * cross-reference stream is returned unchanged. A file already carrying this generator is returned as it is.
349
+ */
350
+ export const tagPdfBuffer = (buf, generator) => {
351
+ if (buf.toString("latin1", 0, 5) !== "%PDF-") throw new Error("not a PDF file");
352
+ const tail = buf.toString("latin1", Math.max(0, buf.length - 4096));
353
+ const prev = Number(tail.match(/startxref\s+(\d+)\s+%%EOF\s*$/u)?.[1]);
354
+ if (!Number.isInteger(prev) || buf.toString("latin1", prev, prev + 4) !== "xref") return buf;
355
+ const value = pdfText(generator);
356
+ const trailer = buf.toString("latin1", prev).match(/trailer\s*<<([\s\S]*?)>>\s*startxref/u)?.[1];
357
+ if (!trailer) return buf;
358
+ const size = Number(trailer.match(/\/Size\s+(\d+)/u)?.[1]);
359
+ const root = trailer.match(/\/Root\s+(\d+\s+\d+\s+R)/u)?.[1];
360
+ if (!size || !root) return buf;
361
+ const info = trailer.match(/\/Info\s+(\d+)\s+0\s+R/u)?.[1];
362
+ if (info && buf.toString("latin1").includes(`${info} 0 obj\n<</Creator ${value} /Producer ${value}>>`)) return buf;
363
+ const id = trailer.match(/\/ID\s*(\[[^\]]*\])/u)?.[1];
364
+ const sep = buf.at(-1) === 0x0a ? "" : "\n";
365
+ const object = `${sep}${size} 0 obj\n<</Creator ${value} /Producer ${value}>>\nendobj\n`;
366
+ const objectAt = buf.length + Buffer.byteLength(sep);
367
+ const xrefAt = buf.length + Buffer.byteLength(object);
368
+ const update = `${object}xref\n${size} 1\n${String(objectAt).padStart(10, "0")} 00000 n \ntrailer\n<</Size ${size + 1} /Root ${root} /Info ${size} 0 R${id ? ` /ID ${id}` : ""} /Prev ${prev}>>\nstartxref\n${xrefAt}\n%%EOF\n`;
369
+ return Buffer.concat([buf, Buffer.from(update, "latin1")]);
370
+ };
371
+
372
+ const TAGGERS = { ".png": tagPngBuffer, ".gif": tagGifBuffer, ".webp": tagWebpBuffer, ".pdf": tagPdfBuffer };
373
+
374
+ // `node lib/mark.mjs` prints this run's plan as JSON, for skills whose outputs are assembled outside an engine
375
+ // (readme-studio covers): { mode, visible, generator, text, logo, logoScale, logoGap }, where `logo` is the flame
376
+ // PNG's path. It reads only the setting; it writes nothing.
377
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
378
+ const { mode, visible, generator } = markPlan();
379
+ process.stdout.write(`${JSON.stringify({ mode, visible, generator, text: WORDMARK.text, logo: logoPath, logoScale: WORDMARK.logoScale, logoGap: WORDMARK.logoGap })}\n`);
380
+ }
381
+
382
+ /** Tags a file the engine just wrote (png, gif, webp, svg) in place; returns whether the mode asked for it. */
383
+ export const tagFile = (file, options) => {
384
+ const { generator } = markPlan(options);
385
+ if (!generator) return false;
386
+ const ext = extname(file).toLowerCase();
387
+ const before = readFileSync(file);
388
+ const after = ext === ".svg" ? Buffer.from(svgWithMetadata(before.toString("utf8"), generator), "utf8") : TAGGERS[ext]?.(before, generator);
389
+ if (!after) return false;
390
+ if (!after.equals(before)) writeFileSync(file, after);
391
+ return true;
392
+ };
@@ -0,0 +1,22 @@
1
+ // How a user tells the official LitClaude from a renamed or re-hosted copy: doctor prints the official package
2
+ // and repository, and warns when the running copy's package name or repository field differs. Local data only.
3
+
4
+ export const OFFICIAL_BUILD = Object.freeze({ packageName: "@litfamily/litclaude", repo: "wjgoarxiv/litclaude" });
5
+
6
+ /** `github.com/<owner>/<name>` from a package.json repository field, or null. */
7
+ const repoOf = (repository) => {
8
+ const url = typeof repository === "string" ? repository : repository?.url;
9
+ const m = /github\.com[/:]([^/\s]+)\/([^/\s#]+?)(?:\.git)?(?:[#/].*)?$/u.exec(String(url ?? ""));
10
+ return m ? `${m[1]}/${m[2]}` : null;
11
+ };
12
+
13
+ /** Doctor lines for a package.json: OFFICIAL_BUILD always, OFFICIAL_BUILD_WARNING when name or repo differ. */
14
+ export const officialBuildLines = (pkg) => {
15
+ const repo = repoOf(pkg.repository);
16
+ const official = `${OFFICIAL_BUILD.packageName} from github.com/${OFFICIAL_BUILD.repo}`;
17
+ const lines = [`OFFICIAL_BUILD: ${official} (this copy: ${pkg.name} ${pkg.version})`];
18
+ if (pkg.name !== OFFICIAL_BUILD.packageName || repo !== OFFICIAL_BUILD.repo) {
19
+ lines.push(`OFFICIAL_BUILD_WARNING: this copy is ${pkg.name} from ${repo ? `github.com/${repo}` : "an unnamed repository"}; the official build is ${official}. Install it with npx ${OFFICIAL_BUILD.packageName}@latest install`);
20
+ }
21
+ return lines;
22
+ };